LLVM API Documentation

SimplifyCFG.cpp
Go to the documentation of this file.
00001 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Peephole optimize the CFG.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Transforms/Utils/Local.h"
00015 #include "llvm/ADT/DenseMap.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Analysis/ConstantFolding.h"
00022 #include "llvm/Analysis/InstructionSimplify.h"
00023 #include "llvm/Analysis/TargetTransformInfo.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/IR/CFG.h"
00026 #include "llvm/IR/ConstantRange.h"
00027 #include "llvm/IR/Constants.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/DerivedTypes.h"
00030 #include "llvm/IR/GlobalVariable.h"
00031 #include "llvm/IR/IRBuilder.h"
00032 #include "llvm/IR/Instructions.h"
00033 #include "llvm/IR/IntrinsicInst.h"
00034 #include "llvm/IR/LLVMContext.h"
00035 #include "llvm/IR/MDBuilder.h"
00036 #include "llvm/IR/Metadata.h"
00037 #include "llvm/IR/Module.h"
00038 #include "llvm/IR/NoFolder.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/IR/PatternMatch.h"
00041 #include "llvm/IR/Type.h"
00042 #include "llvm/Support/CommandLine.h"
00043 #include "llvm/Support/Debug.h"
00044 #include "llvm/Support/raw_ostream.h"
00045 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 #include "llvm/Transforms/Utils/ValueMapper.h"
00048 #include <algorithm>
00049 #include <map>
00050 #include <set>
00051 using namespace llvm;
00052 using namespace PatternMatch;
00053 
00054 #define DEBUG_TYPE "simplifycfg"
00055 
00056 static cl::opt<unsigned>
00057 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
00058    cl::desc("Control the amount of phi node folding to perform (default = 1)"));
00059 
00060 static cl::opt<bool>
00061 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
00062        cl::desc("Duplicate return instructions into unconditional branches"));
00063 
00064 static cl::opt<bool>
00065 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
00066        cl::desc("Sink common instructions down to the end block"));
00067 
00068 static cl::opt<bool> HoistCondStores(
00069     "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
00070     cl::desc("Hoist conditional stores if an unconditional store precedes"));
00071 
00072 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
00073 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
00074 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
00075 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
00076 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
00077 
00078 namespace {
00079   // The first field contains the value that the switch produces when a certain
00080   // case group is selected, and the second field is a vector containing the cases
00081   // composing the case group.
00082   typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
00083     SwitchCaseResultVectorTy;
00084   // The first field contains the phi node that generates a result of the switch
00085   // and the second field contains the value generated for a certain case in the switch
00086   // for that PHI.
00087   typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
00088 
00089   /// ValueEqualityComparisonCase - Represents a case of a switch.
00090   struct ValueEqualityComparisonCase {
00091     ConstantInt *Value;
00092     BasicBlock *Dest;
00093 
00094     ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
00095       : Value(Value), Dest(Dest) {}
00096 
00097     bool operator<(ValueEqualityComparisonCase RHS) const {
00098       // Comparing pointers is ok as we only rely on the order for uniquing.
00099       return Value < RHS.Value;
00100     }
00101 
00102     bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
00103   };
00104 
00105 class SimplifyCFGOpt {
00106   const TargetTransformInfo &TTI;
00107   unsigned BonusInstThreshold;
00108   const DataLayout *const DL;
00109   AssumptionTracker *AT;
00110   Value *isValueEqualityComparison(TerminatorInst *TI);
00111   BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
00112                                std::vector<ValueEqualityComparisonCase> &Cases);
00113   bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00114                                                      BasicBlock *Pred,
00115                                                      IRBuilder<> &Builder);
00116   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
00117                                            IRBuilder<> &Builder);
00118 
00119   bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
00120   bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
00121   bool SimplifyUnreachable(UnreachableInst *UI);
00122   bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
00123   bool SimplifyIndirectBr(IndirectBrInst *IBI);
00124   bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
00125   bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
00126 
00127 public:
00128   SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
00129                  const DataLayout *DL, AssumptionTracker *AT)
00130       : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
00131   bool run(BasicBlock *BB);
00132 };
00133 }
00134 
00135 /// SafeToMergeTerminators - Return true if it is safe to merge these two
00136 /// terminator instructions together.
00137 ///
00138 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
00139   if (SI1 == SI2) return false;  // Can't merge with self!
00140 
00141   // It is not safe to merge these two switch instructions if they have a common
00142   // successor, and if that successor has a PHI node, and if *that* PHI node has
00143   // conflicting incoming values from the two switch blocks.
00144   BasicBlock *SI1BB = SI1->getParent();
00145   BasicBlock *SI2BB = SI2->getParent();
00146   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00147 
00148   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00149     if (SI1Succs.count(*I))
00150       for (BasicBlock::iterator BBI = (*I)->begin();
00151            isa<PHINode>(BBI); ++BBI) {
00152         PHINode *PN = cast<PHINode>(BBI);
00153         if (PN->getIncomingValueForBlock(SI1BB) !=
00154             PN->getIncomingValueForBlock(SI2BB))
00155           return false;
00156       }
00157 
00158   return true;
00159 }
00160 
00161 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
00162 /// to merge these two terminator instructions together, where SI1 is an
00163 /// unconditional branch. PhiNodes will store all PHI nodes in common
00164 /// successors.
00165 ///
00166 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
00167                                           BranchInst *SI2,
00168                                           Instruction *Cond,
00169                                           SmallVectorImpl<PHINode*> &PhiNodes) {
00170   if (SI1 == SI2) return false;  // Can't merge with self!
00171   assert(SI1->isUnconditional() && SI2->isConditional());
00172 
00173   // We fold the unconditional branch if we can easily update all PHI nodes in
00174   // common successors:
00175   // 1> We have a constant incoming value for the conditional branch;
00176   // 2> We have "Cond" as the incoming value for the unconditional branch;
00177   // 3> SI2->getCondition() and Cond have same operands.
00178   CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
00179   if (!Ci2) return false;
00180   if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
00181         Cond->getOperand(1) == Ci2->getOperand(1)) &&
00182       !(Cond->getOperand(0) == Ci2->getOperand(1) &&
00183         Cond->getOperand(1) == Ci2->getOperand(0)))
00184     return false;
00185 
00186   BasicBlock *SI1BB = SI1->getParent();
00187   BasicBlock *SI2BB = SI2->getParent();
00188   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00189   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00190     if (SI1Succs.count(*I))
00191       for (BasicBlock::iterator BBI = (*I)->begin();
00192            isa<PHINode>(BBI); ++BBI) {
00193         PHINode *PN = cast<PHINode>(BBI);
00194         if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
00195             !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
00196           return false;
00197         PhiNodes.push_back(PN);
00198       }
00199   return true;
00200 }
00201 
00202 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
00203 /// now be entries in it from the 'NewPred' block.  The values that will be
00204 /// flowing into the PHI nodes will be the same as those coming in from
00205 /// ExistPred, an existing predecessor of Succ.
00206 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
00207                                   BasicBlock *ExistPred) {
00208   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
00209 
00210   PHINode *PN;
00211   for (BasicBlock::iterator I = Succ->begin();
00212        (PN = dyn_cast<PHINode>(I)); ++I)
00213     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
00214 }
00215 
00216 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
00217 /// given instruction, which is assumed to be safe to speculate. 1 means
00218 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
00219 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
00220   assert(isSafeToSpeculativelyExecute(I, DL) &&
00221          "Instruction is not safe to speculatively execute!");
00222   switch (Operator::getOpcode(I)) {
00223   default:
00224     // In doubt, be conservative.
00225     return UINT_MAX;
00226   case Instruction::GetElementPtr:
00227     // GEPs are cheap if all indices are constant.
00228     if (!cast<GEPOperator>(I)->hasAllConstantIndices())
00229       return UINT_MAX;
00230     return 1;
00231   case Instruction::ExtractValue:
00232   case Instruction::Load:
00233   case Instruction::Add:
00234   case Instruction::Sub:
00235   case Instruction::And:
00236   case Instruction::Or:
00237   case Instruction::Xor:
00238   case Instruction::Shl:
00239   case Instruction::LShr:
00240   case Instruction::AShr:
00241   case Instruction::ICmp:
00242   case Instruction::Trunc:
00243   case Instruction::ZExt:
00244   case Instruction::SExt:
00245   case Instruction::BitCast:
00246   case Instruction::ExtractElement:
00247   case Instruction::InsertElement:
00248     return 1; // These are all cheap.
00249 
00250   case Instruction::Call:
00251   case Instruction::Select:
00252     return 2;
00253   }
00254 }
00255 
00256 /// DominatesMergePoint - If we have a merge point of an "if condition" as
00257 /// accepted above, return true if the specified value dominates the block.  We
00258 /// don't handle the true generality of domination here, just a special case
00259 /// which works well enough for us.
00260 ///
00261 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
00262 /// see if V (which must be an instruction) and its recursive operands
00263 /// that do not dominate BB have a combined cost lower than CostRemaining and
00264 /// are non-trapping.  If both are true, the instruction is inserted into the
00265 /// set and true is returned.
00266 ///
00267 /// The cost for most non-trapping instructions is defined as 1 except for
00268 /// Select whose cost is 2.
00269 ///
00270 /// After this function returns, CostRemaining is decreased by the cost of
00271 /// V plus its non-dominating operands.  If that cost is greater than
00272 /// CostRemaining, false is returned and CostRemaining is undefined.
00273 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
00274                                 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
00275                                 unsigned &CostRemaining,
00276                                 const DataLayout *DL) {
00277   Instruction *I = dyn_cast<Instruction>(V);
00278   if (!I) {
00279     // Non-instructions all dominate instructions, but not all constantexprs
00280     // can be executed unconditionally.
00281     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
00282       if (C->canTrap())
00283         return false;
00284     return true;
00285   }
00286   BasicBlock *PBB = I->getParent();
00287 
00288   // We don't want to allow weird loops that might have the "if condition" in
00289   // the bottom of this block.
00290   if (PBB == BB) return false;
00291 
00292   // If this instruction is defined in a block that contains an unconditional
00293   // branch to BB, then it must be in the 'conditional' part of the "if
00294   // statement".  If not, it definitely dominates the region.
00295   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
00296   if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
00297     return true;
00298 
00299   // If we aren't allowing aggressive promotion anymore, then don't consider
00300   // instructions in the 'if region'.
00301   if (!AggressiveInsts) return false;
00302 
00303   // If we have seen this instruction before, don't count it again.
00304   if (AggressiveInsts->count(I)) return true;
00305 
00306   // Okay, it looks like the instruction IS in the "condition".  Check to
00307   // see if it's a cheap instruction to unconditionally compute, and if it
00308   // only uses stuff defined outside of the condition.  If so, hoist it out.
00309   if (!isSafeToSpeculativelyExecute(I, DL))
00310     return false;
00311 
00312   unsigned Cost = ComputeSpeculationCost(I, DL);
00313 
00314   if (Cost > CostRemaining)
00315     return false;
00316 
00317   CostRemaining -= Cost;
00318 
00319   // Okay, we can only really hoist these out if their operands do
00320   // not take us over the cost threshold.
00321   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
00322     if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
00323       return false;
00324   // Okay, it's safe to do this!  Remember this instruction.
00325   AggressiveInsts->insert(I);
00326   return true;
00327 }
00328 
00329 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
00330 /// and PointerNullValue. Return NULL if value is not a constant int.
00331 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
00332   // Normal constant int.
00333   ConstantInt *CI = dyn_cast<ConstantInt>(V);
00334   if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
00335     return CI;
00336 
00337   // This is some kind of pointer constant. Turn it into a pointer-sized
00338   // ConstantInt if possible.
00339   IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
00340 
00341   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
00342   if (isa<ConstantPointerNull>(V))
00343     return ConstantInt::get(PtrTy, 0);
00344 
00345   // IntToPtr const int.
00346   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00347     if (CE->getOpcode() == Instruction::IntToPtr)
00348       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
00349         // The constant is very likely to have the right type already.
00350         if (CI->getType() == PtrTy)
00351           return CI;
00352         else
00353           return cast<ConstantInt>
00354             (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
00355       }
00356   return nullptr;
00357 }
00358 
00359 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
00360 /// collection of icmp eq/ne instructions that compare a value against a
00361 /// constant, return the value being compared, and stick the constant into the
00362 /// Values vector.
00363 static Value *
00364 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
00365                        const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
00366   Instruction *I = dyn_cast<Instruction>(V);
00367   if (!I) return nullptr;
00368 
00369   // If this is an icmp against a constant, handle this as one of the cases.
00370   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
00371     if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
00372       Value *RHSVal;
00373       ConstantInt *RHSC;
00374 
00375       if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
00376         // (x & ~2^x) == y --> x == y || x == y|2^x
00377         // This undoes a transformation done by instcombine to fuse 2 compares.
00378         if (match(ICI->getOperand(0),
00379                   m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
00380           APInt Not = ~RHSC->getValue();
00381           if (Not.isPowerOf2()) {
00382             Vals.push_back(C);
00383             Vals.push_back(
00384                 ConstantInt::get(C->getContext(), C->getValue() | Not));
00385             UsedICmps++;
00386             return RHSVal;
00387           }
00388         }
00389 
00390         UsedICmps++;
00391         Vals.push_back(C);
00392         return I->getOperand(0);
00393       }
00394 
00395       // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
00396       // the set.
00397       ConstantRange Span =
00398         ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
00399 
00400       // Shift the range if the compare is fed by an add. This is the range
00401       // compare idiom as emitted by instcombine.
00402       bool hasAdd =
00403           match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
00404       if (hasAdd)
00405         Span = Span.subtract(RHSC->getValue());
00406 
00407       // If this is an and/!= check then we want to optimize "x ugt 2" into
00408       // x != 0 && x != 1.
00409       if (!isEQ)
00410         Span = Span.inverse();
00411 
00412       // If there are a ton of values, we don't want to make a ginormous switch.
00413       if (Span.getSetSize().ugt(8) || Span.isEmptySet())
00414         return nullptr;
00415 
00416       for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
00417         Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
00418       UsedICmps++;
00419       return hasAdd ? RHSVal : I->getOperand(0);
00420     }
00421     return nullptr;
00422   }
00423 
00424   // Otherwise, we can only handle an | or &, depending on isEQ.
00425   if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
00426     return nullptr;
00427 
00428   unsigned NumValsBeforeLHS = Vals.size();
00429   unsigned UsedICmpsBeforeLHS = UsedICmps;
00430   if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
00431                                           isEQ, UsedICmps)) {
00432     unsigned NumVals = Vals.size();
00433     unsigned UsedICmpsBeforeRHS = UsedICmps;
00434     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
00435                                             isEQ, UsedICmps)) {
00436       if (LHS == RHS)
00437         return LHS;
00438       Vals.resize(NumVals);
00439       UsedICmps = UsedICmpsBeforeRHS;
00440     }
00441 
00442     // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
00443     // set it and return success.
00444     if (Extra == nullptr || Extra == I->getOperand(1)) {
00445       Extra = I->getOperand(1);
00446       return LHS;
00447     }
00448 
00449     Vals.resize(NumValsBeforeLHS);
00450     UsedICmps = UsedICmpsBeforeLHS;
00451     return nullptr;
00452   }
00453 
00454   // If the LHS can't be folded in, but Extra is available and RHS can, try to
00455   // use LHS as Extra.
00456   if (Extra == nullptr || Extra == I->getOperand(0)) {
00457     Value *OldExtra = Extra;
00458     Extra = I->getOperand(0);
00459     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
00460                                             isEQ, UsedICmps))
00461       return RHS;
00462     assert(Vals.size() == NumValsBeforeLHS);
00463     Extra = OldExtra;
00464   }
00465 
00466   return nullptr;
00467 }
00468 
00469 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
00470   Instruction *Cond = nullptr;
00471   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00472     Cond = dyn_cast<Instruction>(SI->getCondition());
00473   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00474     if (BI->isConditional())
00475       Cond = dyn_cast<Instruction>(BI->getCondition());
00476   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
00477     Cond = dyn_cast<Instruction>(IBI->getAddress());
00478   }
00479 
00480   TI->eraseFromParent();
00481   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
00482 }
00483 
00484 /// isValueEqualityComparison - Return true if the specified terminator checks
00485 /// to see if a value is equal to constant integer value.
00486 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
00487   Value *CV = nullptr;
00488   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00489     // Do not permit merging of large switch instructions into their
00490     // predecessors unless there is only one predecessor.
00491     if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
00492                                              pred_end(SI->getParent())) <= 128)
00493       CV = SI->getCondition();
00494   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
00495     if (BI->isConditional() && BI->getCondition()->hasOneUse())
00496       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
00497         if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
00498           CV = ICI->getOperand(0);
00499 
00500   // Unwrap any lossless ptrtoint cast.
00501   if (DL && CV) {
00502     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
00503       Value *Ptr = PTII->getPointerOperand();
00504       if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
00505         CV = Ptr;
00506     }
00507   }
00508   return CV;
00509 }
00510 
00511 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
00512 /// decode all of the 'cases' that it represents and return the 'default' block.
00513 BasicBlock *SimplifyCFGOpt::
00514 GetValueEqualityComparisonCases(TerminatorInst *TI,
00515                                 std::vector<ValueEqualityComparisonCase>
00516                                                                        &Cases) {
00517   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00518     Cases.reserve(SI->getNumCases());
00519     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
00520       Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
00521                                                   i.getCaseSuccessor()));
00522     return SI->getDefaultDest();
00523   }
00524 
00525   BranchInst *BI = cast<BranchInst>(TI);
00526   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
00527   BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
00528   Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
00529                                                              DL),
00530                                               Succ));
00531   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
00532 }
00533 
00534 
00535 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
00536 /// in the list that match the specified block.
00537 static void EliminateBlockCases(BasicBlock *BB,
00538                               std::vector<ValueEqualityComparisonCase> &Cases) {
00539   Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
00540 }
00541 
00542 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
00543 /// well.
00544 static bool
00545 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
00546               std::vector<ValueEqualityComparisonCase > &C2) {
00547   std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
00548 
00549   // Make V1 be smaller than V2.
00550   if (V1->size() > V2->size())
00551     std::swap(V1, V2);
00552 
00553   if (V1->size() == 0) return false;
00554   if (V1->size() == 1) {
00555     // Just scan V2.
00556     ConstantInt *TheVal = (*V1)[0].Value;
00557     for (unsigned i = 0, e = V2->size(); i != e; ++i)
00558       if (TheVal == (*V2)[i].Value)
00559         return true;
00560   }
00561 
00562   // Otherwise, just sort both lists and compare element by element.
00563   array_pod_sort(V1->begin(), V1->end());
00564   array_pod_sort(V2->begin(), V2->end());
00565   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
00566   while (i1 != e1 && i2 != e2) {
00567     if ((*V1)[i1].Value == (*V2)[i2].Value)
00568       return true;
00569     if ((*V1)[i1].Value < (*V2)[i2].Value)
00570       ++i1;
00571     else
00572       ++i2;
00573   }
00574   return false;
00575 }
00576 
00577 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
00578 /// terminator instruction and its block is known to only have a single
00579 /// predecessor block, check to see if that predecessor is also a value
00580 /// comparison with the same value, and if that comparison determines the
00581 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
00582 /// form of jump threading.
00583 bool SimplifyCFGOpt::
00584 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00585                                               BasicBlock *Pred,
00586                                               IRBuilder<> &Builder) {
00587   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
00588   if (!PredVal) return false;  // Not a value comparison in predecessor.
00589 
00590   Value *ThisVal = isValueEqualityComparison(TI);
00591   assert(ThisVal && "This isn't a value comparison!!");
00592   if (ThisVal != PredVal) return false;  // Different predicates.
00593 
00594   // TODO: Preserve branch weight metadata, similarly to how
00595   // FoldValueComparisonIntoPredecessors preserves it.
00596 
00597   // Find out information about when control will move from Pred to TI's block.
00598   std::vector<ValueEqualityComparisonCase> PredCases;
00599   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
00600                                                         PredCases);
00601   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
00602 
00603   // Find information about how control leaves this block.
00604   std::vector<ValueEqualityComparisonCase> ThisCases;
00605   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
00606   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
00607 
00608   // If TI's block is the default block from Pred's comparison, potentially
00609   // simplify TI based on this knowledge.
00610   if (PredDef == TI->getParent()) {
00611     // If we are here, we know that the value is none of those cases listed in
00612     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
00613     // can simplify TI.
00614     if (!ValuesOverlap(PredCases, ThisCases))
00615       return false;
00616 
00617     if (isa<BranchInst>(TI)) {
00618       // Okay, one of the successors of this condbr is dead.  Convert it to a
00619       // uncond br.
00620       assert(ThisCases.size() == 1 && "Branch can only have one case!");
00621       // Insert the new branch.
00622       Instruction *NI = Builder.CreateBr(ThisDef);
00623       (void) NI;
00624 
00625       // Remove PHI node entries for the dead edge.
00626       ThisCases[0].Dest->removePredecessor(TI->getParent());
00627 
00628       DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00629            << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00630 
00631       EraseTerminatorInstAndDCECond(TI);
00632       return true;
00633     }
00634 
00635     SwitchInst *SI = cast<SwitchInst>(TI);
00636     // Okay, TI has cases that are statically dead, prune them away.
00637     SmallPtrSet<Constant*, 16> DeadCases;
00638     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00639       DeadCases.insert(PredCases[i].Value);
00640 
00641     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00642                  << "Through successor TI: " << *TI);
00643 
00644     // Collect branch weights into a vector.
00645     SmallVector<uint32_t, 8> Weights;
00646     MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
00647     bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
00648     if (HasWeight)
00649       for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
00650            ++MD_i) {
00651         ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
00652         assert(CI);
00653         Weights.push_back(CI->getValue().getZExtValue());
00654       }
00655     for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
00656       --i;
00657       if (DeadCases.count(i.getCaseValue())) {
00658         if (HasWeight) {
00659           std::swap(Weights[i.getCaseIndex()+1], Weights.back());
00660           Weights.pop_back();
00661         }
00662         i.getCaseSuccessor()->removePredecessor(TI->getParent());
00663         SI->removeCase(i);
00664       }
00665     }
00666     if (HasWeight && Weights.size() >= 2)
00667       SI->setMetadata(LLVMContext::MD_prof,
00668                       MDBuilder(SI->getParent()->getContext()).
00669                       createBranchWeights(Weights));
00670 
00671     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
00672     return true;
00673   }
00674 
00675   // Otherwise, TI's block must correspond to some matched value.  Find out
00676   // which value (or set of values) this is.
00677   ConstantInt *TIV = nullptr;
00678   BasicBlock *TIBB = TI->getParent();
00679   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00680     if (PredCases[i].Dest == TIBB) {
00681       if (TIV)
00682         return false;  // Cannot handle multiple values coming to this block.
00683       TIV = PredCases[i].Value;
00684     }
00685   assert(TIV && "No edge from pred to succ?");
00686 
00687   // Okay, we found the one constant that our value can be if we get into TI's
00688   // BB.  Find out which successor will unconditionally be branched to.
00689   BasicBlock *TheRealDest = nullptr;
00690   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
00691     if (ThisCases[i].Value == TIV) {
00692       TheRealDest = ThisCases[i].Dest;
00693       break;
00694     }
00695 
00696   // If not handled by any explicit cases, it is handled by the default case.
00697   if (!TheRealDest) TheRealDest = ThisDef;
00698 
00699   // Remove PHI node entries for dead edges.
00700   BasicBlock *CheckEdge = TheRealDest;
00701   for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
00702     if (*SI != CheckEdge)
00703       (*SI)->removePredecessor(TIBB);
00704     else
00705       CheckEdge = nullptr;
00706 
00707   // Insert the new branch.
00708   Instruction *NI = Builder.CreateBr(TheRealDest);
00709   (void) NI;
00710 
00711   DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00712             << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00713 
00714   EraseTerminatorInstAndDCECond(TI);
00715   return true;
00716 }
00717 
00718 namespace {
00719   /// ConstantIntOrdering - This class implements a stable ordering of constant
00720   /// integers that does not depend on their address.  This is important for
00721   /// applications that sort ConstantInt's to ensure uniqueness.
00722   struct ConstantIntOrdering {
00723     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
00724       return LHS->getValue().ult(RHS->getValue());
00725     }
00726   };
00727 }
00728 
00729 static int ConstantIntSortPredicate(ConstantInt *const *P1,
00730                                     ConstantInt *const *P2) {
00731   const ConstantInt *LHS = *P1;
00732   const ConstantInt *RHS = *P2;
00733   if (LHS->getValue().ult(RHS->getValue()))
00734     return 1;
00735   if (LHS->getValue() == RHS->getValue())
00736     return 0;
00737   return -1;
00738 }
00739 
00740 static inline bool HasBranchWeights(const Instruction* I) {
00741   MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
00742   if (ProfMD && ProfMD->getOperand(0))
00743     if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
00744       return MDS->getString().equals("branch_weights");
00745 
00746   return false;
00747 }
00748 
00749 /// Get Weights of a given TerminatorInst, the default weight is at the front
00750 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
00751 /// metadata.
00752 static void GetBranchWeights(TerminatorInst *TI,
00753                              SmallVectorImpl<uint64_t> &Weights) {
00754   MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
00755   assert(MD);
00756   for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
00757     ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
00758     Weights.push_back(CI->getValue().getZExtValue());
00759   }
00760 
00761   // If TI is a conditional eq, the default case is the false case,
00762   // and the corresponding branch-weight data is at index 2. We swap the
00763   // default weight to be the first entry.
00764   if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
00765     assert(Weights.size() == 2);
00766     ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
00767     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
00768       std::swap(Weights.front(), Weights.back());
00769   }
00770 }
00771 
00772 /// Keep halving the weights until all can fit in uint32_t.
00773 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
00774   uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
00775   if (Max > UINT_MAX) {
00776     unsigned Offset = 32 - countLeadingZeros(Max);
00777     for (uint64_t &I : Weights)
00778       I >>= Offset;
00779   }
00780 }
00781 
00782 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
00783 /// equality comparison instruction (either a switch or a branch on "X == c").
00784 /// See if any of the predecessors of the terminator block are value comparisons
00785 /// on the same value.  If so, and if safe to do so, fold them together.
00786 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
00787                                                          IRBuilder<> &Builder) {
00788   BasicBlock *BB = TI->getParent();
00789   Value *CV = isValueEqualityComparison(TI);  // CondVal
00790   assert(CV && "Not a comparison?");
00791   bool Changed = false;
00792 
00793   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
00794   while (!Preds.empty()) {
00795     BasicBlock *Pred = Preds.pop_back_val();
00796 
00797     // See if the predecessor is a comparison with the same value.
00798     TerminatorInst *PTI = Pred->getTerminator();
00799     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
00800 
00801     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
00802       // Figure out which 'cases' to copy from SI to PSI.
00803       std::vector<ValueEqualityComparisonCase> BBCases;
00804       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
00805 
00806       std::vector<ValueEqualityComparisonCase> PredCases;
00807       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
00808 
00809       // Based on whether the default edge from PTI goes to BB or not, fill in
00810       // PredCases and PredDefault with the new switch cases we would like to
00811       // build.
00812       SmallVector<BasicBlock*, 8> NewSuccessors;
00813 
00814       // Update the branch weight metadata along the way
00815       SmallVector<uint64_t, 8> Weights;
00816       bool PredHasWeights = HasBranchWeights(PTI);
00817       bool SuccHasWeights = HasBranchWeights(TI);
00818 
00819       if (PredHasWeights) {
00820         GetBranchWeights(PTI, Weights);
00821         // branch-weight metadata is inconsistent here.
00822         if (Weights.size() != 1 + PredCases.size())
00823           PredHasWeights = SuccHasWeights = false;
00824       } else if (SuccHasWeights)
00825         // If there are no predecessor weights but there are successor weights,
00826         // populate Weights with 1, which will later be scaled to the sum of
00827         // successor's weights
00828         Weights.assign(1 + PredCases.size(), 1);
00829 
00830       SmallVector<uint64_t, 8> SuccWeights;
00831       if (SuccHasWeights) {
00832         GetBranchWeights(TI, SuccWeights);
00833         // branch-weight metadata is inconsistent here.
00834         if (SuccWeights.size() != 1 + BBCases.size())
00835           PredHasWeights = SuccHasWeights = false;
00836       } else if (PredHasWeights)
00837         SuccWeights.assign(1 + BBCases.size(), 1);
00838 
00839       if (PredDefault == BB) {
00840         // If this is the default destination from PTI, only the edges in TI
00841         // that don't occur in PTI, or that branch to BB will be activated.
00842         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
00843         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00844           if (PredCases[i].Dest != BB)
00845             PTIHandled.insert(PredCases[i].Value);
00846           else {
00847             // The default destination is BB, we don't need explicit targets.
00848             std::swap(PredCases[i], PredCases.back());
00849 
00850             if (PredHasWeights || SuccHasWeights) {
00851               // Increase weight for the default case.
00852               Weights[0] += Weights[i+1];
00853               std::swap(Weights[i+1], Weights.back());
00854               Weights.pop_back();
00855             }
00856 
00857             PredCases.pop_back();
00858             --i; --e;
00859           }
00860 
00861         // Reconstruct the new switch statement we will be building.
00862         if (PredDefault != BBDefault) {
00863           PredDefault->removePredecessor(Pred);
00864           PredDefault = BBDefault;
00865           NewSuccessors.push_back(BBDefault);
00866         }
00867 
00868         unsigned CasesFromPred = Weights.size();
00869         uint64_t ValidTotalSuccWeight = 0;
00870         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00871           if (!PTIHandled.count(BBCases[i].Value) &&
00872               BBCases[i].Dest != BBDefault) {
00873             PredCases.push_back(BBCases[i]);
00874             NewSuccessors.push_back(BBCases[i].Dest);
00875             if (SuccHasWeights || PredHasWeights) {
00876               // The default weight is at index 0, so weight for the ith case
00877               // should be at index i+1. Scale the cases from successor by
00878               // PredDefaultWeight (Weights[0]).
00879               Weights.push_back(Weights[0] * SuccWeights[i+1]);
00880               ValidTotalSuccWeight += SuccWeights[i+1];
00881             }
00882           }
00883 
00884         if (SuccHasWeights || PredHasWeights) {
00885           ValidTotalSuccWeight += SuccWeights[0];
00886           // Scale the cases from predecessor by ValidTotalSuccWeight.
00887           for (unsigned i = 1; i < CasesFromPred; ++i)
00888             Weights[i] *= ValidTotalSuccWeight;
00889           // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
00890           Weights[0] *= SuccWeights[0];
00891         }
00892       } else {
00893         // If this is not the default destination from PSI, only the edges
00894         // in SI that occur in PSI with a destination of BB will be
00895         // activated.
00896         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
00897         std::map<ConstantInt*, uint64_t> WeightsForHandled;
00898         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00899           if (PredCases[i].Dest == BB) {
00900             PTIHandled.insert(PredCases[i].Value);
00901 
00902             if (PredHasWeights || SuccHasWeights) {
00903               WeightsForHandled[PredCases[i].Value] = Weights[i+1];
00904               std::swap(Weights[i+1], Weights.back());
00905               Weights.pop_back();
00906             }
00907 
00908             std::swap(PredCases[i], PredCases.back());
00909             PredCases.pop_back();
00910             --i; --e;
00911           }
00912 
00913         // Okay, now we know which constants were sent to BB from the
00914         // predecessor.  Figure out where they will all go now.
00915         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00916           if (PTIHandled.count(BBCases[i].Value)) {
00917             // If this is one we are capable of getting...
00918             if (PredHasWeights || SuccHasWeights)
00919               Weights.push_back(WeightsForHandled[BBCases[i].Value]);
00920             PredCases.push_back(BBCases[i]);
00921             NewSuccessors.push_back(BBCases[i].Dest);
00922             PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
00923           }
00924 
00925         // If there are any constants vectored to BB that TI doesn't handle,
00926         // they must go to the default destination of TI.
00927         for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
00928                                     PTIHandled.begin(),
00929                E = PTIHandled.end(); I != E; ++I) {
00930           if (PredHasWeights || SuccHasWeights)
00931             Weights.push_back(WeightsForHandled[*I]);
00932           PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
00933           NewSuccessors.push_back(BBDefault);
00934         }
00935       }
00936 
00937       // Okay, at this point, we know which new successor Pred will get.  Make
00938       // sure we update the number of entries in the PHI nodes for these
00939       // successors.
00940       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
00941         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
00942 
00943       Builder.SetInsertPoint(PTI);
00944       // Convert pointer to int before we switch.
00945       if (CV->getType()->isPointerTy()) {
00946         assert(DL && "Cannot switch on pointer without DataLayout");
00947         CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
00948                                     "magicptr");
00949       }
00950 
00951       // Now that the successors are updated, create the new Switch instruction.
00952       SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
00953                                                PredCases.size());
00954       NewSI->setDebugLoc(PTI->getDebugLoc());
00955       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00956         NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
00957 
00958       if (PredHasWeights || SuccHasWeights) {
00959         // Halve the weights if any of them cannot fit in an uint32_t
00960         FitWeights(Weights);
00961 
00962         SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
00963 
00964         NewSI->setMetadata(LLVMContext::MD_prof,
00965                            MDBuilder(BB->getContext()).
00966                            createBranchWeights(MDWeights));
00967       }
00968 
00969       EraseTerminatorInstAndDCECond(PTI);
00970 
00971       // Okay, last check.  If BB is still a successor of PSI, then we must
00972       // have an infinite loop case.  If so, add an infinitely looping block
00973       // to handle the case to preserve the behavior of the code.
00974       BasicBlock *InfLoopBlock = nullptr;
00975       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
00976         if (NewSI->getSuccessor(i) == BB) {
00977           if (!InfLoopBlock) {
00978             // Insert it at the end of the function, because it's either code,
00979             // or it won't matter if it's hot. :)
00980             InfLoopBlock = BasicBlock::Create(BB->getContext(),
00981                                               "infloop", BB->getParent());
00982             BranchInst::Create(InfLoopBlock, InfLoopBlock);
00983           }
00984           NewSI->setSuccessor(i, InfLoopBlock);
00985         }
00986 
00987       Changed = true;
00988     }
00989   }
00990   return Changed;
00991 }
00992 
00993 // isSafeToHoistInvoke - If we would need to insert a select that uses the
00994 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
00995 // would need to do this), we can't hoist the invoke, as there is nowhere
00996 // to put the select in this case.
00997 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
00998                                 Instruction *I1, Instruction *I2) {
00999   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
01000     PHINode *PN;
01001     for (BasicBlock::iterator BBI = SI->begin();
01002          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01003       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01004       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01005       if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
01006         return false;
01007       }
01008     }
01009   }
01010   return true;
01011 }
01012 
01013 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
01014 
01015 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
01016 /// BB2, hoist any common code in the two blocks up into the branch block.  The
01017 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
01018 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
01019   // This does very trivial matching, with limited scanning, to find identical
01020   // instructions in the two blocks.  In particular, we don't want to get into
01021   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
01022   // such, we currently just scan for obviously identical instructions in an
01023   // identical order.
01024   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
01025   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
01026 
01027   BasicBlock::iterator BB1_Itr = BB1->begin();
01028   BasicBlock::iterator BB2_Itr = BB2->begin();
01029 
01030   Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
01031   // Skip debug info if it is not identical.
01032   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
01033   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
01034   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
01035     while (isa<DbgInfoIntrinsic>(I1))
01036       I1 = BB1_Itr++;
01037     while (isa<DbgInfoIntrinsic>(I2))
01038       I2 = BB2_Itr++;
01039   }
01040   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
01041       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
01042     return false;
01043 
01044   BasicBlock *BIParent = BI->getParent();
01045 
01046   bool Changed = false;
01047   do {
01048     // If we are hoisting the terminator instruction, don't move one (making a
01049     // broken BB), instead clone it, and remove BI.
01050     if (isa<TerminatorInst>(I1))
01051       goto HoistTerminator;
01052 
01053     // For a normal instruction, we just move one to right before the branch,
01054     // then replace all uses of the other with the first.  Finally, we remove
01055     // the now redundant second instruction.
01056     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
01057     if (!I2->use_empty())
01058       I2->replaceAllUsesWith(I1);
01059     I1->intersectOptionalDataWith(I2);
01060     unsigned KnownIDs[] = {
01061       LLVMContext::MD_tbaa,
01062       LLVMContext::MD_range,
01063       LLVMContext::MD_fpmath,
01064       LLVMContext::MD_invariant_load
01065     };
01066     combineMetadata(I1, I2, KnownIDs);
01067     I2->eraseFromParent();
01068     Changed = true;
01069 
01070     I1 = BB1_Itr++;
01071     I2 = BB2_Itr++;
01072     // Skip debug info if it is not identical.
01073     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
01074     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
01075     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
01076       while (isa<DbgInfoIntrinsic>(I1))
01077         I1 = BB1_Itr++;
01078       while (isa<DbgInfoIntrinsic>(I2))
01079         I2 = BB2_Itr++;
01080     }
01081   } while (I1->isIdenticalToWhenDefined(I2));
01082 
01083   return true;
01084 
01085 HoistTerminator:
01086   // It may not be possible to hoist an invoke.
01087   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
01088     return Changed;
01089 
01090   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
01091     PHINode *PN;
01092     for (BasicBlock::iterator BBI = SI->begin();
01093          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01094       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01095       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01096       if (BB1V == BB2V)
01097         continue;
01098 
01099       // Check for passingValueIsAlwaysUndefined here because we would rather
01100       // eliminate undefined control flow then converting it to a select.
01101       if (passingValueIsAlwaysUndefined(BB1V, PN) ||
01102           passingValueIsAlwaysUndefined(BB2V, PN))
01103        return Changed;
01104 
01105       if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
01106         return Changed;
01107       if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
01108         return Changed;
01109     }
01110   }
01111 
01112   // Okay, it is safe to hoist the terminator.
01113   Instruction *NT = I1->clone();
01114   BIParent->getInstList().insert(BI, NT);
01115   if (!NT->getType()->isVoidTy()) {
01116     I1->replaceAllUsesWith(NT);
01117     I2->replaceAllUsesWith(NT);
01118     NT->takeName(I1);
01119   }
01120 
01121   IRBuilder<true, NoFolder> Builder(NT);
01122   // Hoisting one of the terminators from our successor is a great thing.
01123   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
01124   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
01125   // nodes, so we insert select instruction to compute the final result.
01126   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
01127   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
01128     PHINode *PN;
01129     for (BasicBlock::iterator BBI = SI->begin();
01130          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01131       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01132       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01133       if (BB1V == BB2V) continue;
01134 
01135       // These values do not agree.  Insert a select instruction before NT
01136       // that determines the right value.
01137       SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
01138       if (!SI)
01139         SI = cast<SelectInst>
01140           (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
01141                                 BB1V->getName()+"."+BB2V->getName()));
01142 
01143       // Make the PHI node use the select for all incoming values for BB1/BB2
01144       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01145         if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
01146           PN->setIncomingValue(i, SI);
01147     }
01148   }
01149 
01150   // Update any PHI nodes in our new successors.
01151   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
01152     AddPredecessorToBlock(*SI, BIParent, BB1);
01153 
01154   EraseTerminatorInstAndDCECond(BI);
01155   return true;
01156 }
01157 
01158 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
01159 /// check whether BBEnd has only two predecessors and the other predecessor
01160 /// ends with an unconditional branch. If it is true, sink any common code
01161 /// in the two predecessors to BBEnd.
01162 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
01163   assert(BI1->isUnconditional());
01164   BasicBlock *BB1 = BI1->getParent();
01165   BasicBlock *BBEnd = BI1->getSuccessor(0);
01166 
01167   // Check that BBEnd has two predecessors and the other predecessor ends with
01168   // an unconditional branch.
01169   pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
01170   BasicBlock *Pred0 = *PI++;
01171   if (PI == PE) // Only one predecessor.
01172     return false;
01173   BasicBlock *Pred1 = *PI++;
01174   if (PI != PE) // More than two predecessors.
01175     return false;
01176   BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
01177   BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
01178   if (!BI2 || !BI2->isUnconditional())
01179     return false;
01180 
01181   // Gather the PHI nodes in BBEnd.
01182   std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
01183   Instruction *FirstNonPhiInBBEnd = nullptr;
01184   for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
01185        I != E; ++I) {
01186     if (PHINode *PN = dyn_cast<PHINode>(I)) {
01187       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01188       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01189       MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
01190     } else {
01191       FirstNonPhiInBBEnd = &*I;
01192       break;
01193     }
01194   }
01195   if (!FirstNonPhiInBBEnd)
01196     return false;
01197 
01198 
01199   // This does very trivial matching, with limited scanning, to find identical
01200   // instructions in the two blocks.  We scan backward for obviously identical
01201   // instructions in an identical order.
01202   BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
01203       RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
01204       RE2 = BB2->getInstList().rend();
01205   // Skip debug info.
01206   while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
01207   if (RI1 == RE1)
01208     return false;
01209   while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
01210   if (RI2 == RE2)
01211     return false;
01212   // Skip the unconditional branches.
01213   ++RI1;
01214   ++RI2;
01215 
01216   bool Changed = false;
01217   while (RI1 != RE1 && RI2 != RE2) {
01218     // Skip debug info.
01219     while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
01220     if (RI1 == RE1)
01221       return Changed;
01222     while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
01223     if (RI2 == RE2)
01224       return Changed;
01225 
01226     Instruction *I1 = &*RI1, *I2 = &*RI2;
01227     // I1 and I2 should have a single use in the same PHI node, and they
01228     // perform the same operation.
01229     // Cannot move control-flow-involving, volatile loads, vaarg, etc.
01230     if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
01231         isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
01232         isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
01233         isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
01234         I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
01235         I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
01236         !I1->hasOneUse() || !I2->hasOneUse() ||
01237         MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
01238         MapValueFromBB1ToBB2[I1].first != I2)
01239       return Changed;
01240 
01241     // Check whether we should swap the operands of ICmpInst.
01242     ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
01243     bool SwapOpnds = false;
01244     if (ICmp1 && ICmp2 &&
01245         ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
01246         ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
01247         (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
01248          ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
01249       ICmp2->swapOperands();
01250       SwapOpnds = true;
01251     }
01252     if (!I1->isSameOperationAs(I2)) {
01253       if (SwapOpnds)
01254         ICmp2->swapOperands();
01255       return Changed;
01256     }
01257 
01258     // The operands should be either the same or they need to be generated
01259     // with a PHI node after sinking. We only handle the case where there is
01260     // a single pair of different operands.
01261     Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
01262     unsigned Op1Idx = 0;
01263     for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
01264       if (I1->getOperand(I) == I2->getOperand(I))
01265         continue;
01266       // Early exit if we have more-than one pair of different operands or
01267       // the different operand is already in MapValueFromBB1ToBB2.
01268       // Early exit if we need a PHI node to replace a constant.
01269       if (DifferentOp1 ||
01270           MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
01271           MapValueFromBB1ToBB2.end() ||
01272           isa<Constant>(I1->getOperand(I)) ||
01273           isa<Constant>(I2->getOperand(I))) {
01274         // If we can't sink the instructions, undo the swapping.
01275         if (SwapOpnds)
01276           ICmp2->swapOperands();
01277         return Changed;
01278       }
01279       DifferentOp1 = I1->getOperand(I);
01280       Op1Idx = I;
01281       DifferentOp2 = I2->getOperand(I);
01282     }
01283 
01284     // We insert the pair of different operands to MapValueFromBB1ToBB2 and
01285     // remove (I1, I2) from MapValueFromBB1ToBB2.
01286     if (DifferentOp1) {
01287       PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
01288                                        DifferentOp1->getName() + ".sink",
01289                                        BBEnd->begin());
01290       MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
01291       // I1 should use NewPN instead of DifferentOp1.
01292       I1->setOperand(Op1Idx, NewPN);
01293       NewPN->addIncoming(DifferentOp1, BB1);
01294       NewPN->addIncoming(DifferentOp2, BB2);
01295       DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
01296     }
01297     PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
01298     MapValueFromBB1ToBB2.erase(I1);
01299 
01300     DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
01301     DEBUG(dbgs() << "                         " << *I2 << "\n";);
01302     // We need to update RE1 and RE2 if we are going to sink the first
01303     // instruction in the basic block down.
01304     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
01305     // Sink the instruction.
01306     BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
01307     if (!OldPN->use_empty())
01308       OldPN->replaceAllUsesWith(I1);
01309     OldPN->eraseFromParent();
01310 
01311     if (!I2->use_empty())
01312       I2->replaceAllUsesWith(I1);
01313     I1->intersectOptionalDataWith(I2);
01314     I2->eraseFromParent();
01315 
01316     if (UpdateRE1)
01317       RE1 = BB1->getInstList().rend();
01318     if (UpdateRE2)
01319       RE2 = BB2->getInstList().rend();
01320     FirstNonPhiInBBEnd = I1;
01321     NumSinkCommons++;
01322     Changed = true;
01323   }
01324   return Changed;
01325 }
01326 
01327 /// \brief Determine if we can hoist sink a sole store instruction out of a
01328 /// conditional block.
01329 ///
01330 /// We are looking for code like the following:
01331 ///   BrBB:
01332 ///     store i32 %add, i32* %arrayidx2
01333 ///     ... // No other stores or function calls (we could be calling a memory
01334 ///     ... // function).
01335 ///     %cmp = icmp ult %x, %y
01336 ///     br i1 %cmp, label %EndBB, label %ThenBB
01337 ///   ThenBB:
01338 ///     store i32 %add5, i32* %arrayidx2
01339 ///     br label EndBB
01340 ///   EndBB:
01341 ///     ...
01342 ///   We are going to transform this into:
01343 ///   BrBB:
01344 ///     store i32 %add, i32* %arrayidx2
01345 ///     ... //
01346 ///     %cmp = icmp ult %x, %y
01347 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
01348 ///     store i32 %add.add5, i32* %arrayidx2
01349 ///     ...
01350 ///
01351 /// \return The pointer to the value of the previous store if the store can be
01352 ///         hoisted into the predecessor block. 0 otherwise.
01353 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
01354                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
01355   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
01356   if (!StoreToHoist)
01357     return nullptr;
01358 
01359   // Volatile or atomic.
01360   if (!StoreToHoist->isSimple())
01361     return nullptr;
01362 
01363   Value *StorePtr = StoreToHoist->getPointerOperand();
01364 
01365   // Look for a store to the same pointer in BrBB.
01366   unsigned MaxNumInstToLookAt = 10;
01367   for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
01368        RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
01369     Instruction *CurI = &*RI;
01370 
01371     // Could be calling an instruction that effects memory like free().
01372     if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
01373       return nullptr;
01374 
01375     StoreInst *SI = dyn_cast<StoreInst>(CurI);
01376     // Found the previous store make sure it stores to the same location.
01377     if (SI && SI->getPointerOperand() == StorePtr)
01378       // Found the previous store, return its value operand.
01379       return SI->getValueOperand();
01380     else if (SI)
01381       return nullptr; // Unknown store.
01382   }
01383 
01384   return nullptr;
01385 }
01386 
01387 /// \brief Speculate a conditional basic block flattening the CFG.
01388 ///
01389 /// Note that this is a very risky transform currently. Speculating
01390 /// instructions like this is most often not desirable. Instead, there is an MI
01391 /// pass which can do it with full awareness of the resource constraints.
01392 /// However, some cases are "obvious" and we should do directly. An example of
01393 /// this is speculating a single, reasonably cheap instruction.
01394 ///
01395 /// There is only one distinct advantage to flattening the CFG at the IR level:
01396 /// it makes very common but simplistic optimizations such as are common in
01397 /// instcombine and the DAG combiner more powerful by removing CFG edges and
01398 /// modeling their effects with easier to reason about SSA value graphs.
01399 ///
01400 ///
01401 /// An illustration of this transform is turning this IR:
01402 /// \code
01403 ///   BB:
01404 ///     %cmp = icmp ult %x, %y
01405 ///     br i1 %cmp, label %EndBB, label %ThenBB
01406 ///   ThenBB:
01407 ///     %sub = sub %x, %y
01408 ///     br label BB2
01409 ///   EndBB:
01410 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
01411 ///     ...
01412 /// \endcode
01413 ///
01414 /// Into this IR:
01415 /// \code
01416 ///   BB:
01417 ///     %cmp = icmp ult %x, %y
01418 ///     %sub = sub %x, %y
01419 ///     %cond = select i1 %cmp, 0, %sub
01420 ///     ...
01421 /// \endcode
01422 ///
01423 /// \returns true if the conditional block is removed.
01424 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
01425                                    const DataLayout *DL) {
01426   // Be conservative for now. FP select instruction can often be expensive.
01427   Value *BrCond = BI->getCondition();
01428   if (isa<FCmpInst>(BrCond))
01429     return false;
01430 
01431   BasicBlock *BB = BI->getParent();
01432   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
01433 
01434   // If ThenBB is actually on the false edge of the conditional branch, remember
01435   // to swap the select operands later.
01436   bool Invert = false;
01437   if (ThenBB != BI->getSuccessor(0)) {
01438     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
01439     Invert = true;
01440   }
01441   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
01442 
01443   // Keep a count of how many times instructions are used within CondBB when
01444   // they are candidates for sinking into CondBB. Specifically:
01445   // - They are defined in BB, and
01446   // - They have no side effects, and
01447   // - All of their uses are in CondBB.
01448   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
01449 
01450   unsigned SpeculationCost = 0;
01451   Value *SpeculatedStoreValue = nullptr;
01452   StoreInst *SpeculatedStore = nullptr;
01453   for (BasicBlock::iterator BBI = ThenBB->begin(),
01454                             BBE = std::prev(ThenBB->end());
01455        BBI != BBE; ++BBI) {
01456     Instruction *I = BBI;
01457     // Skip debug info.
01458     if (isa<DbgInfoIntrinsic>(I))
01459       continue;
01460 
01461     // Only speculatively execution a single instruction (not counting the
01462     // terminator) for now.
01463     ++SpeculationCost;
01464     if (SpeculationCost > 1)
01465       return false;
01466 
01467     // Don't hoist the instruction if it's unsafe or expensive.
01468     if (!isSafeToSpeculativelyExecute(I, DL) &&
01469         !(HoistCondStores &&
01470           (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
01471                                                          EndBB))))
01472       return false;
01473     if (!SpeculatedStoreValue &&
01474         ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
01475       return false;
01476 
01477     // Store the store speculation candidate.
01478     if (SpeculatedStoreValue)
01479       SpeculatedStore = cast<StoreInst>(I);
01480 
01481     // Do not hoist the instruction if any of its operands are defined but not
01482     // used in BB. The transformation will prevent the operand from
01483     // being sunk into the use block.
01484     for (User::op_iterator i = I->op_begin(), e = I->op_end();
01485          i != e; ++i) {
01486       Instruction *OpI = dyn_cast<Instruction>(*i);
01487       if (!OpI || OpI->getParent() != BB ||
01488           OpI->mayHaveSideEffects())
01489         continue; // Not a candidate for sinking.
01490 
01491       ++SinkCandidateUseCounts[OpI];
01492     }
01493   }
01494 
01495   // Consider any sink candidates which are only used in CondBB as costs for
01496   // speculation. Note, while we iterate over a DenseMap here, we are summing
01497   // and so iteration order isn't significant.
01498   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
01499            SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
01500        I != E; ++I)
01501     if (I->first->getNumUses() == I->second) {
01502       ++SpeculationCost;
01503       if (SpeculationCost > 1)
01504         return false;
01505     }
01506 
01507   // Check that the PHI nodes can be converted to selects.
01508   bool HaveRewritablePHIs = false;
01509   for (BasicBlock::iterator I = EndBB->begin();
01510        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01511     Value *OrigV = PN->getIncomingValueForBlock(BB);
01512     Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
01513 
01514     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
01515     // Skip PHIs which are trivial.
01516     if (ThenV == OrigV)
01517       continue;
01518 
01519     // Don't convert to selects if we could remove undefined behavior instead.
01520     if (passingValueIsAlwaysUndefined(OrigV, PN) ||
01521         passingValueIsAlwaysUndefined(ThenV, PN))
01522       return false;
01523 
01524     HaveRewritablePHIs = true;
01525     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
01526     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
01527     if (!OrigCE && !ThenCE)
01528       continue; // Known safe and cheap.
01529 
01530     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
01531         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
01532       return false;
01533     unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
01534     unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
01535     if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
01536       return false;
01537 
01538     // Account for the cost of an unfolded ConstantExpr which could end up
01539     // getting expanded into Instructions.
01540     // FIXME: This doesn't account for how many operations are combined in the
01541     // constant expression.
01542     ++SpeculationCost;
01543     if (SpeculationCost > 1)
01544       return false;
01545   }
01546 
01547   // If there are no PHIs to process, bail early. This helps ensure idempotence
01548   // as well.
01549   if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
01550     return false;
01551 
01552   // If we get here, we can hoist the instruction and if-convert.
01553   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
01554 
01555   // Insert a select of the value of the speculated store.
01556   if (SpeculatedStoreValue) {
01557     IRBuilder<true, NoFolder> Builder(BI);
01558     Value *TrueV = SpeculatedStore->getValueOperand();
01559     Value *FalseV = SpeculatedStoreValue;
01560     if (Invert)
01561       std::swap(TrueV, FalseV);
01562     Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
01563                                     "." + FalseV->getName());
01564     SpeculatedStore->setOperand(0, S);
01565   }
01566 
01567   // Hoist the instructions.
01568   BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
01569                            std::prev(ThenBB->end()));
01570 
01571   // Insert selects and rewrite the PHI operands.
01572   IRBuilder<true, NoFolder> Builder(BI);
01573   for (BasicBlock::iterator I = EndBB->begin();
01574        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01575     unsigned OrigI = PN->getBasicBlockIndex(BB);
01576     unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
01577     Value *OrigV = PN->getIncomingValue(OrigI);
01578     Value *ThenV = PN->getIncomingValue(ThenI);
01579 
01580     // Skip PHIs which are trivial.
01581     if (OrigV == ThenV)
01582       continue;
01583 
01584     // Create a select whose true value is the speculatively executed value and
01585     // false value is the preexisting value. Swap them if the branch
01586     // destinations were inverted.
01587     Value *TrueV = ThenV, *FalseV = OrigV;
01588     if (Invert)
01589       std::swap(TrueV, FalseV);
01590     Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
01591                                     TrueV->getName() + "." + FalseV->getName());
01592     PN->setIncomingValue(OrigI, V);
01593     PN->setIncomingValue(ThenI, V);
01594   }
01595 
01596   ++NumSpeculations;
01597   return true;
01598 }
01599 
01600 /// \returns True if this block contains a CallInst with the NoDuplicate
01601 /// attribute.
01602 static bool HasNoDuplicateCall(const BasicBlock *BB) {
01603   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01604     const CallInst *CI = dyn_cast<CallInst>(I);
01605     if (!CI)
01606       continue;
01607     if (CI->cannotDuplicate())
01608       return true;
01609   }
01610   return false;
01611 }
01612 
01613 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
01614 /// across this block.
01615 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
01616   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
01617   unsigned Size = 0;
01618 
01619   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
01620     if (isa<DbgInfoIntrinsic>(BBI))
01621       continue;
01622     if (Size > 10) return false;  // Don't clone large BB's.
01623     ++Size;
01624 
01625     // We can only support instructions that do not define values that are
01626     // live outside of the current basic block.
01627     for (User *U : BBI->users()) {
01628       Instruction *UI = cast<Instruction>(U);
01629       if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
01630     }
01631 
01632     // Looks ok, continue checking.
01633   }
01634 
01635   return true;
01636 }
01637 
01638 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
01639 /// that is defined in the same block as the branch and if any PHI entries are
01640 /// constants, thread edges corresponding to that entry to be branches to their
01641 /// ultimate destination.
01642 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
01643   BasicBlock *BB = BI->getParent();
01644   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
01645   // NOTE: we currently cannot transform this case if the PHI node is used
01646   // outside of the block.
01647   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
01648     return false;
01649 
01650   // Degenerate case of a single entry PHI.
01651   if (PN->getNumIncomingValues() == 1) {
01652     FoldSingleEntryPHINodes(PN->getParent());
01653     return true;
01654   }
01655 
01656   // Now we know that this block has multiple preds and two succs.
01657   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
01658 
01659   if (HasNoDuplicateCall(BB)) return false;
01660 
01661   // Okay, this is a simple enough basic block.  See if any phi values are
01662   // constants.
01663   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01664     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
01665     if (!CB || !CB->getType()->isIntegerTy(1)) continue;
01666 
01667     // Okay, we now know that all edges from PredBB should be revectored to
01668     // branch to RealDest.
01669     BasicBlock *PredBB = PN->getIncomingBlock(i);
01670     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
01671 
01672     if (RealDest == BB) continue;  // Skip self loops.
01673     // Skip if the predecessor's terminator is an indirect branch.
01674     if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
01675 
01676     // The dest block might have PHI nodes, other predecessors and other
01677     // difficult cases.  Instead of being smart about this, just insert a new
01678     // block that jumps to the destination block, effectively splitting
01679     // the edge we are about to create.
01680     BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
01681                                             RealDest->getName()+".critedge",
01682                                             RealDest->getParent(), RealDest);
01683     BranchInst::Create(RealDest, EdgeBB);
01684 
01685     // Update PHI nodes.
01686     AddPredecessorToBlock(RealDest, EdgeBB, BB);
01687 
01688     // BB may have instructions that are being threaded over.  Clone these
01689     // instructions into EdgeBB.  We know that there will be no uses of the
01690     // cloned instructions outside of EdgeBB.
01691     BasicBlock::iterator InsertPt = EdgeBB->begin();
01692     DenseMap<Value*, Value*> TranslateMap;  // Track translated values.
01693     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
01694       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
01695         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
01696         continue;
01697       }
01698       // Clone the instruction.
01699       Instruction *N = BBI->clone();
01700       if (BBI->hasName()) N->setName(BBI->getName()+".c");
01701 
01702       // Update operands due to translation.
01703       for (User::op_iterator i = N->op_begin(), e = N->op_end();
01704            i != e; ++i) {
01705         DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
01706         if (PI != TranslateMap.end())
01707           *i = PI->second;
01708       }
01709 
01710       // Check for trivial simplification.
01711       if (Value *V = SimplifyInstruction(N, DL)) {
01712         TranslateMap[BBI] = V;
01713         delete N;   // Instruction folded away, don't need actual inst
01714       } else {
01715         // Insert the new instruction into its new home.
01716         EdgeBB->getInstList().insert(InsertPt, N);
01717         if (!BBI->use_empty())
01718           TranslateMap[BBI] = N;
01719       }
01720     }
01721 
01722     // Loop over all of the edges from PredBB to BB, changing them to branch
01723     // to EdgeBB instead.
01724     TerminatorInst *PredBBTI = PredBB->getTerminator();
01725     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
01726       if (PredBBTI->getSuccessor(i) == BB) {
01727         BB->removePredecessor(PredBB);
01728         PredBBTI->setSuccessor(i, EdgeBB);
01729       }
01730 
01731     // Recurse, simplifying any other constants.
01732     return FoldCondBranchOnPHI(BI, DL) | true;
01733   }
01734 
01735   return false;
01736 }
01737 
01738 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
01739 /// PHI node, see if we can eliminate it.
01740 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
01741   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
01742   // statement", which has a very simple dominance structure.  Basically, we
01743   // are trying to find the condition that is being branched on, which
01744   // subsequently causes this merge to happen.  We really want control
01745   // dependence information for this check, but simplifycfg can't keep it up
01746   // to date, and this catches most of the cases we care about anyway.
01747   BasicBlock *BB = PN->getParent();
01748   BasicBlock *IfTrue, *IfFalse;
01749   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
01750   if (!IfCond ||
01751       // Don't bother if the branch will be constant folded trivially.
01752       isa<ConstantInt>(IfCond))
01753     return false;
01754 
01755   // Okay, we found that we can merge this two-entry phi node into a select.
01756   // Doing so would require us to fold *all* two entry phi nodes in this block.
01757   // At some point this becomes non-profitable (particularly if the target
01758   // doesn't support cmov's).  Only do this transformation if there are two or
01759   // fewer PHI nodes in this block.
01760   unsigned NumPhis = 0;
01761   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
01762     if (NumPhis > 2)
01763       return false;
01764 
01765   // Loop over the PHI's seeing if we can promote them all to select
01766   // instructions.  While we are at it, keep track of the instructions
01767   // that need to be moved to the dominating block.
01768   SmallPtrSet<Instruction*, 4> AggressiveInsts;
01769   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
01770            MaxCostVal1 = PHINodeFoldingThreshold;
01771 
01772   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
01773     PHINode *PN = cast<PHINode>(II++);
01774     if (Value *V = SimplifyInstruction(PN, DL)) {
01775       PN->replaceAllUsesWith(V);
01776       PN->eraseFromParent();
01777       continue;
01778     }
01779 
01780     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
01781                              MaxCostVal0, DL) ||
01782         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
01783                              MaxCostVal1, DL))
01784       return false;
01785   }
01786 
01787   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
01788   // we ran out of PHIs then we simplified them all.
01789   PN = dyn_cast<PHINode>(BB->begin());
01790   if (!PN) return true;
01791 
01792   // Don't fold i1 branches on PHIs which contain binary operators.  These can
01793   // often be turned into switches and other things.
01794   if (PN->getType()->isIntegerTy(1) &&
01795       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
01796        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
01797        isa<BinaryOperator>(IfCond)))
01798     return false;
01799 
01800   // If we all PHI nodes are promotable, check to make sure that all
01801   // instructions in the predecessor blocks can be promoted as well.  If
01802   // not, we won't be able to get rid of the control flow, so it's not
01803   // worth promoting to select instructions.
01804   BasicBlock *DomBlock = nullptr;
01805   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
01806   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
01807   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
01808     IfBlock1 = nullptr;
01809   } else {
01810     DomBlock = *pred_begin(IfBlock1);
01811     for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
01812       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
01813         // This is not an aggressive instruction that we can promote.
01814         // Because of this, we won't be able to get rid of the control
01815         // flow, so the xform is not worth it.
01816         return false;
01817       }
01818   }
01819 
01820   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
01821     IfBlock2 = nullptr;
01822   } else {
01823     DomBlock = *pred_begin(IfBlock2);
01824     for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
01825       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
01826         // This is not an aggressive instruction that we can promote.
01827         // Because of this, we won't be able to get rid of the control
01828         // flow, so the xform is not worth it.
01829         return false;
01830       }
01831   }
01832 
01833   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
01834                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
01835 
01836   // If we can still promote the PHI nodes after this gauntlet of tests,
01837   // do all of the PHI's now.
01838   Instruction *InsertPt = DomBlock->getTerminator();
01839   IRBuilder<true, NoFolder> Builder(InsertPt);
01840 
01841   // Move all 'aggressive' instructions, which are defined in the
01842   // conditional parts of the if's up to the dominating block.
01843   if (IfBlock1)
01844     DomBlock->getInstList().splice(InsertPt,
01845                                    IfBlock1->getInstList(), IfBlock1->begin(),
01846                                    IfBlock1->getTerminator());
01847   if (IfBlock2)
01848     DomBlock->getInstList().splice(InsertPt,
01849                                    IfBlock2->getInstList(), IfBlock2->begin(),
01850                                    IfBlock2->getTerminator());
01851 
01852   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
01853     // Change the PHI node into a select instruction.
01854     Value *TrueVal  = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
01855     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
01856 
01857     SelectInst *NV =
01858       cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
01859     PN->replaceAllUsesWith(NV);
01860     NV->takeName(PN);
01861     PN->eraseFromParent();
01862   }
01863 
01864   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
01865   // has been flattened.  Change DomBlock to jump directly to our new block to
01866   // avoid other simplifycfg's kicking in on the diamond.
01867   TerminatorInst *OldTI = DomBlock->getTerminator();
01868   Builder.SetInsertPoint(OldTI);
01869   Builder.CreateBr(BB);
01870   OldTI->eraseFromParent();
01871   return true;
01872 }
01873 
01874 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
01875 /// to two returning blocks, try to merge them together into one return,
01876 /// introducing a select if the return values disagree.
01877 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
01878                                            IRBuilder<> &Builder) {
01879   assert(BI->isConditional() && "Must be a conditional branch");
01880   BasicBlock *TrueSucc = BI->getSuccessor(0);
01881   BasicBlock *FalseSucc = BI->getSuccessor(1);
01882   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
01883   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
01884 
01885   // Check to ensure both blocks are empty (just a return) or optionally empty
01886   // with PHI nodes.  If there are other instructions, merging would cause extra
01887   // computation on one path or the other.
01888   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
01889     return false;
01890   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
01891     return false;
01892 
01893   Builder.SetInsertPoint(BI);
01894   // Okay, we found a branch that is going to two return nodes.  If
01895   // there is no return value for this function, just change the
01896   // branch into a return.
01897   if (FalseRet->getNumOperands() == 0) {
01898     TrueSucc->removePredecessor(BI->getParent());
01899     FalseSucc->removePredecessor(BI->getParent());
01900     Builder.CreateRetVoid();
01901     EraseTerminatorInstAndDCECond(BI);
01902     return true;
01903   }
01904 
01905   // Otherwise, figure out what the true and false return values are
01906   // so we can insert a new select instruction.
01907   Value *TrueValue = TrueRet->getReturnValue();
01908   Value *FalseValue = FalseRet->getReturnValue();
01909 
01910   // Unwrap any PHI nodes in the return blocks.
01911   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
01912     if (TVPN->getParent() == TrueSucc)
01913       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
01914   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
01915     if (FVPN->getParent() == FalseSucc)
01916       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
01917 
01918   // In order for this transformation to be safe, we must be able to
01919   // unconditionally execute both operands to the return.  This is
01920   // normally the case, but we could have a potentially-trapping
01921   // constant expression that prevents this transformation from being
01922   // safe.
01923   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
01924     if (TCV->canTrap())
01925       return false;
01926   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
01927     if (FCV->canTrap())
01928       return false;
01929 
01930   // Okay, we collected all the mapped values and checked them for sanity, and
01931   // defined to really do this transformation.  First, update the CFG.
01932   TrueSucc->removePredecessor(BI->getParent());
01933   FalseSucc->removePredecessor(BI->getParent());
01934 
01935   // Insert select instructions where needed.
01936   Value *BrCond = BI->getCondition();
01937   if (TrueValue) {
01938     // Insert a select if the results differ.
01939     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
01940     } else if (isa<UndefValue>(TrueValue)) {
01941       TrueValue = FalseValue;
01942     } else {
01943       TrueValue = Builder.CreateSelect(BrCond, TrueValue,
01944                                        FalseValue, "retval");
01945     }
01946   }
01947 
01948   Value *RI = !TrueValue ?
01949     Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
01950 
01951   (void) RI;
01952 
01953   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
01954                << "\n  " << *BI << "NewRet = " << *RI
01955                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
01956 
01957   EraseTerminatorInstAndDCECond(BI);
01958 
01959   return true;
01960 }
01961 
01962 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
01963 /// probabilities of the branch taking each edge. Fills in the two APInt
01964 /// parameters and return true, or returns false if no or invalid metadata was
01965 /// found.
01966 static bool ExtractBranchMetadata(BranchInst *BI,
01967                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
01968   assert(BI->isConditional() &&
01969          "Looking for probabilities on unconditional branch?");
01970   MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
01971   if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
01972   ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
01973   ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
01974   if (!CITrue || !CIFalse) return false;
01975   ProbTrue = CITrue->getValue().getZExtValue();
01976   ProbFalse = CIFalse->getValue().getZExtValue();
01977   return true;
01978 }
01979 
01980 /// checkCSEInPredecessor - Return true if the given instruction is available
01981 /// in its predecessor block. If yes, the instruction will be removed.
01982 ///
01983 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
01984   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
01985     return false;
01986   for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
01987     Instruction *PBI = &*I;
01988     // Check whether Inst and PBI generate the same value.
01989     if (Inst->isIdenticalTo(PBI)) {
01990       Inst->replaceAllUsesWith(PBI);
01991       Inst->eraseFromParent();
01992       return true;
01993     }
01994   }
01995   return false;
01996 }
01997 
01998 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
01999 /// predecessor branches to us and one of our successors, fold the block into
02000 /// the predecessor and use logical operations to pick the right destination.
02001 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
02002                                   unsigned BonusInstThreshold) {
02003   BasicBlock *BB = BI->getParent();
02004 
02005   Instruction *Cond = nullptr;
02006   if (BI->isConditional())
02007     Cond = dyn_cast<Instruction>(BI->getCondition());
02008   else {
02009     // For unconditional branch, check for a simple CFG pattern, where
02010     // BB has a single predecessor and BB's successor is also its predecessor's
02011     // successor. If such pattern exisits, check for CSE between BB and its
02012     // predecessor.
02013     if (BasicBlock *PB = BB->getSinglePredecessor())
02014       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
02015         if (PBI->isConditional() &&
02016             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
02017              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
02018           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
02019                I != E; ) {
02020             Instruction *Curr = I++;
02021             if (isa<CmpInst>(Curr)) {
02022               Cond = Curr;
02023               break;
02024             }
02025             // Quit if we can't remove this instruction.
02026             if (!checkCSEInPredecessor(Curr, PB))
02027               return false;
02028           }
02029         }
02030 
02031     if (!Cond)
02032       return false;
02033   }
02034 
02035   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
02036       Cond->getParent() != BB || !Cond->hasOneUse())
02037   return false;
02038 
02039   // Make sure the instruction after the condition is the cond branch.
02040   BasicBlock::iterator CondIt = Cond; ++CondIt;
02041 
02042   // Ignore dbg intrinsics.
02043   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
02044 
02045   if (&*CondIt != BI)
02046     return false;
02047 
02048   // Only allow this transformation if computing the condition doesn't involve
02049   // too many instructions and these involved instructions can be executed
02050   // unconditionally. We denote all involved instructions except the condition
02051   // as "bonus instructions", and only allow this transformation when the
02052   // number of the bonus instructions does not exceed a certain threshold.
02053   unsigned NumBonusInsts = 0;
02054   for (auto I = BB->begin(); Cond != I; ++I) {
02055     // Ignore dbg intrinsics.
02056     if (isa<DbgInfoIntrinsic>(I))
02057       continue;
02058     if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
02059       return false;
02060     // I has only one use and can be executed unconditionally.
02061     Instruction *User = dyn_cast<Instruction>(I->user_back());
02062     if (User == nullptr || User->getParent() != BB)
02063       return false;
02064     // I is used in the same BB. Since BI uses Cond and doesn't have more slots
02065     // to use any other instruction, User must be an instruction between next(I)
02066     // and Cond.
02067     ++NumBonusInsts;
02068     // Early exits once we reach the limit.
02069     if (NumBonusInsts > BonusInstThreshold)
02070       return false;
02071   }
02072 
02073   // Cond is known to be a compare or binary operator.  Check to make sure that
02074   // neither operand is a potentially-trapping constant expression.
02075   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
02076     if (CE->canTrap())
02077       return false;
02078   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
02079     if (CE->canTrap())
02080       return false;
02081 
02082   // Finally, don't infinitely unroll conditional loops.
02083   BasicBlock *TrueDest  = BI->getSuccessor(0);
02084   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
02085   if (TrueDest == BB || FalseDest == BB)
02086     return false;
02087 
02088   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
02089     BasicBlock *PredBlock = *PI;
02090     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
02091 
02092     // Check that we have two conditional branches.  If there is a PHI node in
02093     // the common successor, verify that the same value flows in from both
02094     // blocks.
02095     SmallVector<PHINode*, 4> PHIs;
02096     if (!PBI || PBI->isUnconditional() ||
02097         (BI->isConditional() &&
02098          !SafeToMergeTerminators(BI, PBI)) ||
02099         (!BI->isConditional() &&
02100          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
02101       continue;
02102 
02103     // Determine if the two branches share a common destination.
02104     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
02105     bool InvertPredCond = false;
02106 
02107     if (BI->isConditional()) {
02108       if (PBI->getSuccessor(0) == TrueDest)
02109         Opc = Instruction::Or;
02110       else if (PBI->getSuccessor(1) == FalseDest)
02111         Opc = Instruction::And;
02112       else if (PBI->getSuccessor(0) == FalseDest)
02113         Opc = Instruction::And, InvertPredCond = true;
02114       else if (PBI->getSuccessor(1) == TrueDest)
02115         Opc = Instruction::Or, InvertPredCond = true;
02116       else
02117         continue;
02118     } else {
02119       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
02120         continue;
02121     }
02122 
02123     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
02124     IRBuilder<> Builder(PBI);
02125 
02126     // If we need to invert the condition in the pred block to match, do so now.
02127     if (InvertPredCond) {
02128       Value *NewCond = PBI->getCondition();
02129 
02130       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
02131         CmpInst *CI = cast<CmpInst>(NewCond);
02132         CI->setPredicate(CI->getInversePredicate());
02133       } else {
02134         NewCond = Builder.CreateNot(NewCond,
02135                                     PBI->getCondition()->getName()+".not");
02136       }
02137 
02138       PBI->setCondition(NewCond);
02139       PBI->swapSuccessors();
02140     }
02141 
02142     // If we have bonus instructions, clone them into the predecessor block.
02143     // Note that there may be mutliple predecessor blocks, so we cannot move
02144     // bonus instructions to a predecessor block.
02145     ValueToValueMapTy VMap; // maps original values to cloned values
02146     // We already make sure Cond is the last instruction before BI. Therefore,
02147     // every instructions before Cond other than DbgInfoIntrinsic are bonus
02148     // instructions.
02149     for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
02150       if (isa<DbgInfoIntrinsic>(BonusInst))
02151         continue;
02152       Instruction *NewBonusInst = BonusInst->clone();
02153       RemapInstruction(NewBonusInst, VMap,
02154                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
02155       VMap[BonusInst] = NewBonusInst;
02156 
02157       // If we moved a load, we cannot any longer claim any knowledge about
02158       // its potential value. The previous information might have been valid
02159       // only given the branch precondition.
02160       // For an analogous reason, we must also drop all the metadata whose
02161       // semantics we don't understand.
02162       NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
02163 
02164       PredBlock->getInstList().insert(PBI, NewBonusInst);
02165       NewBonusInst->takeName(BonusInst);
02166       BonusInst->setName(BonusInst->getName() + ".old");
02167     }
02168 
02169     // Clone Cond into the predecessor basic block, and or/and the
02170     // two conditions together.
02171     Instruction *New = Cond->clone();
02172     RemapInstruction(New, VMap,
02173                      RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
02174     PredBlock->getInstList().insert(PBI, New);
02175     New->takeName(Cond);
02176     Cond->setName(New->getName() + ".old");
02177 
02178     if (BI->isConditional()) {
02179       Instruction *NewCond =
02180         cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
02181                                             New, "or.cond"));
02182       PBI->setCondition(NewCond);
02183 
02184       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
02185       bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
02186                                                   PredFalseWeight);
02187       bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
02188                                                   SuccFalseWeight);
02189       SmallVector<uint64_t, 8> NewWeights;
02190 
02191       if (PBI->getSuccessor(0) == BB) {
02192         if (PredHasWeights && SuccHasWeights) {
02193           // PBI: br i1 %x, BB, FalseDest
02194           // BI:  br i1 %y, TrueDest, FalseDest
02195           //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
02196           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
02197           //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
02198           //               TrueWeight for PBI * FalseWeight for BI.
02199           // We assume that total weights of a BranchInst can fit into 32 bits.
02200           // Therefore, we will not have overflow using 64-bit arithmetic.
02201           NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
02202                SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
02203         }
02204         AddPredecessorToBlock(TrueDest, PredBlock, BB);
02205         PBI->setSuccessor(0, TrueDest);
02206       }
02207       if (PBI->getSuccessor(1) == BB) {
02208         if (PredHasWeights && SuccHasWeights) {
02209           // PBI: br i1 %x, TrueDest, BB
02210           // BI:  br i1 %y, TrueDest, FalseDest
02211           //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
02212           //              FalseWeight for PBI * TrueWeight for BI.
02213           NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
02214               SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
02215           //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
02216           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
02217         }
02218         AddPredecessorToBlock(FalseDest, PredBlock, BB);
02219         PBI->setSuccessor(1, FalseDest);
02220       }
02221       if (NewWeights.size() == 2) {
02222         // Halve the weights if any of them cannot fit in an uint32_t
02223         FitWeights(NewWeights);
02224 
02225         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
02226         PBI->setMetadata(LLVMContext::MD_prof,
02227                          MDBuilder(BI->getContext()).
02228                          createBranchWeights(MDWeights));
02229       } else
02230         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
02231     } else {
02232       // Update PHI nodes in the common successors.
02233       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
02234         ConstantInt *PBI_C = cast<ConstantInt>(
02235           PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
02236         assert(PBI_C->getType()->isIntegerTy(1));
02237         Instruction *MergedCond = nullptr;
02238         if (PBI->getSuccessor(0) == TrueDest) {
02239           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
02240           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
02241           //       is false: !PBI_Cond and BI_Value
02242           Instruction *NotCond =
02243             cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
02244                                 "not.cond"));
02245           MergedCond =
02246             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
02247                                 NotCond, New,
02248                                 "and.cond"));
02249           if (PBI_C->isOne())
02250             MergedCond =
02251               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
02252                                   PBI->getCondition(), MergedCond,
02253                                   "or.cond"));
02254         } else {
02255           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
02256           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
02257           //       is false: PBI_Cond and BI_Value
02258           MergedCond =
02259             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
02260                                 PBI->getCondition(), New,
02261                                 "and.cond"));
02262           if (PBI_C->isOne()) {
02263             Instruction *NotCond =
02264               cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
02265                                   "not.cond"));
02266             MergedCond =
02267               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
02268                                   NotCond, MergedCond,
02269                                   "or.cond"));
02270           }
02271         }
02272         // Update PHI Node.
02273         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
02274                                   MergedCond);
02275       }
02276       // Change PBI from Conditional to Unconditional.
02277       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
02278       EraseTerminatorInstAndDCECond(PBI);
02279       PBI = New_PBI;
02280     }
02281 
02282     // TODO: If BB is reachable from all paths through PredBlock, then we
02283     // could replace PBI's branch probabilities with BI's.
02284 
02285     // Copy any debug value intrinsics into the end of PredBlock.
02286     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
02287       if (isa<DbgInfoIntrinsic>(*I))
02288         I->clone()->insertBefore(PBI);
02289 
02290     return true;
02291   }
02292   return false;
02293 }
02294 
02295 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
02296 /// predecessor of another block, this function tries to simplify it.  We know
02297 /// that PBI and BI are both conditional branches, and BI is in one of the
02298 /// successor blocks of PBI - PBI branches to BI.
02299 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
02300   assert(PBI->isConditional() && BI->isConditional());
02301   BasicBlock *BB = BI->getParent();
02302 
02303   // If this block ends with a branch instruction, and if there is a
02304   // predecessor that ends on a branch of the same condition, make
02305   // this conditional branch redundant.
02306   if (PBI->getCondition() == BI->getCondition() &&
02307       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
02308     // Okay, the outcome of this conditional branch is statically
02309     // knowable.  If this block had a single pred, handle specially.
02310     if (BB->getSinglePredecessor()) {
02311       // Turn this into a branch on constant.
02312       bool CondIsTrue = PBI->getSuccessor(0) == BB;
02313       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
02314                                         CondIsTrue));
02315       return true;  // Nuke the branch on constant.
02316     }
02317 
02318     // Otherwise, if there are multiple predecessors, insert a PHI that merges
02319     // in the constant and simplify the block result.  Subsequent passes of
02320     // simplifycfg will thread the block.
02321     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
02322       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
02323       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
02324                                        std::distance(PB, PE),
02325                                        BI->getCondition()->getName() + ".pr",
02326                                        BB->begin());
02327       // Okay, we're going to insert the PHI node.  Since PBI is not the only
02328       // predecessor, compute the PHI'd conditional value for all of the preds.
02329       // Any predecessor where the condition is not computable we keep symbolic.
02330       for (pred_iterator PI = PB; PI != PE; ++PI) {
02331         BasicBlock *P = *PI;
02332         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
02333             PBI != BI && PBI->isConditional() &&
02334             PBI->getCondition() == BI->getCondition() &&
02335             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
02336           bool CondIsTrue = PBI->getSuccessor(0) == BB;
02337           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
02338                                               CondIsTrue), P);
02339         } else {
02340           NewPN->addIncoming(BI->getCondition(), P);
02341         }
02342       }
02343 
02344       BI->setCondition(NewPN);
02345       return true;
02346     }
02347   }
02348 
02349   // If this is a conditional branch in an empty block, and if any
02350   // predecessors are a conditional branch to one of our destinations,
02351   // fold the conditions into logical ops and one cond br.
02352   BasicBlock::iterator BBI = BB->begin();
02353   // Ignore dbg intrinsics.
02354   while (isa<DbgInfoIntrinsic>(BBI))
02355     ++BBI;
02356   if (&*BBI != BI)
02357     return false;
02358 
02359 
02360   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
02361     if (CE->canTrap())
02362       return false;
02363 
02364   int PBIOp, BIOp;
02365   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
02366     PBIOp = BIOp = 0;
02367   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
02368     PBIOp = 0, BIOp = 1;
02369   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
02370     PBIOp = 1, BIOp = 0;
02371   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
02372     PBIOp = BIOp = 1;
02373   else
02374     return false;
02375 
02376   // Check to make sure that the other destination of this branch
02377   // isn't BB itself.  If so, this is an infinite loop that will
02378   // keep getting unwound.
02379   if (PBI->getSuccessor(PBIOp) == BB)
02380     return false;
02381 
02382   // Do not perform this transformation if it would require
02383   // insertion of a large number of select instructions. For targets
02384   // without predication/cmovs, this is a big pessimization.
02385 
02386   // Also do not perform this transformation if any phi node in the common
02387   // destination block can trap when reached by BB or PBB (PR17073). In that
02388   // case, it would be unsafe to hoist the operation into a select instruction.
02389 
02390   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
02391   unsigned NumPhis = 0;
02392   for (BasicBlock::iterator II = CommonDest->begin();
02393        isa<PHINode>(II); ++II, ++NumPhis) {
02394     if (NumPhis > 2) // Disable this xform.
02395       return false;
02396 
02397     PHINode *PN = cast<PHINode>(II);
02398     Value *BIV = PN->getIncomingValueForBlock(BB);
02399     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
02400       if (CE->canTrap())
02401         return false;
02402 
02403     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
02404     Value *PBIV = PN->getIncomingValue(PBBIdx);
02405     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
02406       if (CE->canTrap())
02407         return false;
02408   }
02409 
02410   // Finally, if everything is ok, fold the branches to logical ops.
02411   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
02412 
02413   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
02414                << "AND: " << *BI->getParent());
02415 
02416 
02417   // If OtherDest *is* BB, then BB is a basic block with a single conditional
02418   // branch in it, where one edge (OtherDest) goes back to itself but the other
02419   // exits.  We don't *know* that the program avoids the infinite loop
02420   // (even though that seems likely).  If we do this xform naively, we'll end up
02421   // recursively unpeeling the loop.  Since we know that (after the xform is
02422   // done) that the block *is* infinite if reached, we just make it an obviously
02423   // infinite loop with no cond branch.
02424   if (OtherDest == BB) {
02425     // Insert it at the end of the function, because it's either code,
02426     // or it won't matter if it's hot. :)
02427     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
02428                                                   "infloop", BB->getParent());
02429     BranchInst::Create(InfLoopBlock, InfLoopBlock);
02430     OtherDest = InfLoopBlock;
02431   }
02432 
02433   DEBUG(dbgs() << *PBI->getParent()->getParent());
02434 
02435   // BI may have other predecessors.  Because of this, we leave
02436   // it alone, but modify PBI.
02437 
02438   // Make sure we get to CommonDest on True&True directions.
02439   Value *PBICond = PBI->getCondition();
02440   IRBuilder<true, NoFolder> Builder(PBI);
02441   if (PBIOp)
02442     PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
02443 
02444   Value *BICond = BI->getCondition();
02445   if (BIOp)
02446     BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
02447 
02448   // Merge the conditions.
02449   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
02450 
02451   // Modify PBI to branch on the new condition to the new dests.
02452   PBI->setCondition(Cond);
02453   PBI->setSuccessor(0, CommonDest);
02454   PBI->setSuccessor(1, OtherDest);
02455 
02456   // Update branch weight for PBI.
02457   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
02458   bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
02459                                               PredFalseWeight);
02460   bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
02461                                               SuccFalseWeight);
02462   if (PredHasWeights && SuccHasWeights) {
02463     uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
02464     uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
02465     uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
02466     uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
02467     // The weight to CommonDest should be PredCommon * SuccTotal +
02468     //                                    PredOther * SuccCommon.
02469     // The weight to OtherDest should be PredOther * SuccOther.
02470     SmallVector<uint64_t, 2> NewWeights;
02471     NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
02472                          PredOther * SuccCommon);
02473     NewWeights.push_back(PredOther * SuccOther);
02474     // Halve the weights if any of them cannot fit in an uint32_t
02475     FitWeights(NewWeights);
02476 
02477     SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
02478     PBI->setMetadata(LLVMContext::MD_prof,
02479                      MDBuilder(BI->getContext()).
02480                      createBranchWeights(MDWeights));
02481   }
02482 
02483   // OtherDest may have phi nodes.  If so, add an entry from PBI's
02484   // block that are identical to the entries for BI's block.
02485   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
02486 
02487   // We know that the CommonDest already had an edge from PBI to
02488   // it.  If it has PHIs though, the PHIs may have different
02489   // entries for BB and PBI's BB.  If so, insert a select to make
02490   // them agree.
02491   PHINode *PN;
02492   for (BasicBlock::iterator II = CommonDest->begin();
02493        (PN = dyn_cast<PHINode>(II)); ++II) {
02494     Value *BIV = PN->getIncomingValueForBlock(BB);
02495     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
02496     Value *PBIV = PN->getIncomingValue(PBBIdx);
02497     if (BIV != PBIV) {
02498       // Insert a select in PBI to pick the right value.
02499       Value *NV = cast<SelectInst>
02500         (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
02501       PN->setIncomingValue(PBBIdx, NV);
02502     }
02503   }
02504 
02505   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
02506   DEBUG(dbgs() << *PBI->getParent()->getParent());
02507 
02508   // This basic block is probably dead.  We know it has at least
02509   // one fewer predecessor.
02510   return true;
02511 }
02512 
02513 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
02514 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
02515 // Takes care of updating the successors and removing the old terminator.
02516 // Also makes sure not to introduce new successors by assuming that edges to
02517 // non-successor TrueBBs and FalseBBs aren't reachable.
02518 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
02519                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
02520                                        uint32_t TrueWeight,
02521                                        uint32_t FalseWeight){
02522   // Remove any superfluous successor edges from the CFG.
02523   // First, figure out which successors to preserve.
02524   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
02525   // successor.
02526   BasicBlock *KeepEdge1 = TrueBB;
02527   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
02528 
02529   // Then remove the rest.
02530   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
02531     BasicBlock *Succ = OldTerm->getSuccessor(I);
02532     // Make sure only to keep exactly one copy of each edge.
02533     if (Succ == KeepEdge1)
02534       KeepEdge1 = nullptr;
02535     else if (Succ == KeepEdge2)
02536       KeepEdge2 = nullptr;
02537     else
02538       Succ->removePredecessor(OldTerm->getParent());
02539   }
02540 
02541   IRBuilder<> Builder(OldTerm);
02542   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
02543 
02544   // Insert an appropriate new terminator.
02545   if (!KeepEdge1 && !KeepEdge2) {
02546     if (TrueBB == FalseBB)
02547       // We were only looking for one successor, and it was present.
02548       // Create an unconditional branch to it.
02549       Builder.CreateBr(TrueBB);
02550     else {
02551       // We found both of the successors we were looking for.
02552       // Create a conditional branch sharing the condition of the select.
02553       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
02554       if (TrueWeight != FalseWeight)
02555         NewBI->setMetadata(LLVMContext::MD_prof,
02556                            MDBuilder(OldTerm->getContext()).
02557                            createBranchWeights(TrueWeight, FalseWeight));
02558     }
02559   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
02560     // Neither of the selected blocks were successors, so this
02561     // terminator must be unreachable.
02562     new UnreachableInst(OldTerm->getContext(), OldTerm);
02563   } else {
02564     // One of the selected values was a successor, but the other wasn't.
02565     // Insert an unconditional branch to the one that was found;
02566     // the edge to the one that wasn't must be unreachable.
02567     if (!KeepEdge1)
02568       // Only TrueBB was found.
02569       Builder.CreateBr(TrueBB);
02570     else
02571       // Only FalseBB was found.
02572       Builder.CreateBr(FalseBB);
02573   }
02574 
02575   EraseTerminatorInstAndDCECond(OldTerm);
02576   return true;
02577 }
02578 
02579 // SimplifySwitchOnSelect - Replaces
02580 //   (switch (select cond, X, Y)) on constant X, Y
02581 // with a branch - conditional if X and Y lead to distinct BBs,
02582 // unconditional otherwise.
02583 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
02584   // Check for constant integer values in the select.
02585   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
02586   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
02587   if (!TrueVal || !FalseVal)
02588     return false;
02589 
02590   // Find the relevant condition and destinations.
02591   Value *Condition = Select->getCondition();
02592   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
02593   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
02594 
02595   // Get weight for TrueBB and FalseBB.
02596   uint32_t TrueWeight = 0, FalseWeight = 0;
02597   SmallVector<uint64_t, 8> Weights;
02598   bool HasWeights = HasBranchWeights(SI);
02599   if (HasWeights) {
02600     GetBranchWeights(SI, Weights);
02601     if (Weights.size() == 1 + SI->getNumCases()) {
02602       TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
02603                                      getSuccessorIndex()];
02604       FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
02605                                       getSuccessorIndex()];
02606     }
02607   }
02608 
02609   // Perform the actual simplification.
02610   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
02611                                     TrueWeight, FalseWeight);
02612 }
02613 
02614 // SimplifyIndirectBrOnSelect - Replaces
02615 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
02616 //                             blockaddress(@fn, BlockB)))
02617 // with
02618 //   (br cond, BlockA, BlockB).
02619 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
02620   // Check that both operands of the select are block addresses.
02621   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
02622   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
02623   if (!TBA || !FBA)
02624     return false;
02625 
02626   // Extract the actual blocks.
02627   BasicBlock *TrueBB = TBA->getBasicBlock();
02628   BasicBlock *FalseBB = FBA->getBasicBlock();
02629 
02630   // Perform the actual simplification.
02631   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
02632                                     0, 0);
02633 }
02634 
02635 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
02636 /// instruction (a seteq/setne with a constant) as the only instruction in a
02637 /// block that ends with an uncond branch.  We are looking for a very specific
02638 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
02639 /// this case, we merge the first two "or's of icmp" into a switch, but then the
02640 /// default value goes to an uncond block with a seteq in it, we get something
02641 /// like:
02642 ///
02643 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
02644 /// DEFAULT:
02645 ///   %tmp = icmp eq i8 %A, 92
02646 ///   br label %end
02647 /// end:
02648 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
02649 ///
02650 /// We prefer to split the edge to 'end' so that there is a true/false entry to
02651 /// the PHI, merging the third icmp into the switch.
02652 static bool TryToSimplifyUncondBranchWithICmpInIt(
02653     ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
02654     unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
02655   BasicBlock *BB = ICI->getParent();
02656 
02657   // If the block has any PHIs in it or the icmp has multiple uses, it is too
02658   // complex.
02659   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
02660 
02661   Value *V = ICI->getOperand(0);
02662   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
02663 
02664   // The pattern we're looking for is where our only predecessor is a switch on
02665   // 'V' and this block is the default case for the switch.  In this case we can
02666   // fold the compared value into the switch to simplify things.
02667   BasicBlock *Pred = BB->getSinglePredecessor();
02668   if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
02669 
02670   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
02671   if (SI->getCondition() != V)
02672     return false;
02673 
02674   // If BB is reachable on a non-default case, then we simply know the value of
02675   // V in this block.  Substitute it and constant fold the icmp instruction
02676   // away.
02677   if (SI->getDefaultDest() != BB) {
02678     ConstantInt *VVal = SI->findCaseDest(BB);
02679     assert(VVal && "Should have a unique destination value");
02680     ICI->setOperand(0, VVal);
02681 
02682     if (Value *V = SimplifyInstruction(ICI, DL)) {
02683       ICI->replaceAllUsesWith(V);
02684       ICI->eraseFromParent();
02685     }
02686     // BB is now empty, so it is likely to simplify away.
02687     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
02688   }
02689 
02690   // Ok, the block is reachable from the default dest.  If the constant we're
02691   // comparing exists in one of the other edges, then we can constant fold ICI
02692   // and zap it.
02693   if (SI->findCaseValue(Cst) != SI->case_default()) {
02694     Value *V;
02695     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
02696       V = ConstantInt::getFalse(BB->getContext());
02697     else
02698       V = ConstantInt::getTrue(BB->getContext());
02699 
02700     ICI->replaceAllUsesWith(V);
02701     ICI->eraseFromParent();
02702     // BB is now empty, so it is likely to simplify away.
02703     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
02704   }
02705 
02706   // The use of the icmp has to be in the 'end' block, by the only PHI node in
02707   // the block.
02708   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
02709   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
02710   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
02711       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
02712     return false;
02713 
02714   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
02715   // true in the PHI.
02716   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
02717   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
02718 
02719   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
02720     std::swap(DefaultCst, NewCst);
02721 
02722   // Replace ICI (which is used by the PHI for the default value) with true or
02723   // false depending on if it is EQ or NE.
02724   ICI->replaceAllUsesWith(DefaultCst);
02725   ICI->eraseFromParent();
02726 
02727   // Okay, the switch goes to this block on a default value.  Add an edge from
02728   // the switch to the merge point on the compared value.
02729   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
02730                                          BB->getParent(), BB);
02731   SmallVector<uint64_t, 8> Weights;
02732   bool HasWeights = HasBranchWeights(SI);
02733   if (HasWeights) {
02734     GetBranchWeights(SI, Weights);
02735     if (Weights.size() == 1 + SI->getNumCases()) {
02736       // Split weight for default case to case for "Cst".
02737       Weights[0] = (Weights[0]+1) >> 1;
02738       Weights.push_back(Weights[0]);
02739 
02740       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
02741       SI->setMetadata(LLVMContext::MD_prof,
02742                       MDBuilder(SI->getContext()).
02743                       createBranchWeights(MDWeights));
02744     }
02745   }
02746   SI->addCase(Cst, NewBB);
02747 
02748   // NewBB branches to the phi block, add the uncond branch and the phi entry.
02749   Builder.SetInsertPoint(NewBB);
02750   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
02751   Builder.CreateBr(SuccBlock);
02752   PHIUse->addIncoming(NewCst, NewBB);
02753   return true;
02754 }
02755 
02756 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
02757 /// Check to see if it is branching on an or/and chain of icmp instructions, and
02758 /// fold it into a switch instruction if so.
02759 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
02760                                       IRBuilder<> &Builder) {
02761   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
02762   if (!Cond) return false;
02763 
02764 
02765   // Change br (X == 0 | X == 1), T, F into a switch instruction.
02766   // If this is a bunch of seteq's or'd together, or if it's a bunch of
02767   // 'setne's and'ed together, collect them.
02768   Value *CompVal = nullptr;
02769   std::vector<ConstantInt*> Values;
02770   bool TrueWhenEqual = true;
02771   Value *ExtraCase = nullptr;
02772   unsigned UsedICmps = 0;
02773 
02774   if (Cond->getOpcode() == Instruction::Or) {
02775     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
02776                                      UsedICmps);
02777   } else if (Cond->getOpcode() == Instruction::And) {
02778     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
02779                                      UsedICmps);
02780     TrueWhenEqual = false;
02781   }
02782 
02783   // If we didn't have a multiply compared value, fail.
02784   if (!CompVal) return false;
02785 
02786   // Avoid turning single icmps into a switch.
02787   if (UsedICmps <= 1)
02788     return false;
02789 
02790   // There might be duplicate constants in the list, which the switch
02791   // instruction can't handle, remove them now.
02792   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
02793   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
02794 
02795   // If Extra was used, we require at least two switch values to do the
02796   // transformation.  A switch with one value is just an cond branch.
02797   if (ExtraCase && Values.size() < 2) return false;
02798 
02799   // TODO: Preserve branch weight metadata, similarly to how
02800   // FoldValueComparisonIntoPredecessors preserves it.
02801 
02802   // Figure out which block is which destination.
02803   BasicBlock *DefaultBB = BI->getSuccessor(1);
02804   BasicBlock *EdgeBB    = BI->getSuccessor(0);
02805   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
02806 
02807   BasicBlock *BB = BI->getParent();
02808 
02809   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
02810                << " cases into SWITCH.  BB is:\n" << *BB);
02811 
02812   // If there are any extra values that couldn't be folded into the switch
02813   // then we evaluate them with an explicit branch first.  Split the block
02814   // right before the condbr to handle it.
02815   if (ExtraCase) {
02816     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
02817     // Remove the uncond branch added to the old block.
02818     TerminatorInst *OldTI = BB->getTerminator();
02819     Builder.SetInsertPoint(OldTI);
02820 
02821     if (TrueWhenEqual)
02822       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
02823     else
02824       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
02825 
02826     OldTI->eraseFromParent();
02827 
02828     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
02829     // for the edge we just added.
02830     AddPredecessorToBlock(EdgeBB, BB, NewBB);
02831 
02832     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
02833           << "\nEXTRABB = " << *BB);
02834     BB = NewBB;
02835   }
02836 
02837   Builder.SetInsertPoint(BI);
02838   // Convert pointer to int before we switch.
02839   if (CompVal->getType()->isPointerTy()) {
02840     assert(DL && "Cannot switch on pointer without DataLayout");
02841     CompVal = Builder.CreatePtrToInt(CompVal,
02842                                      DL->getIntPtrType(CompVal->getType()),
02843                                      "magicptr");
02844   }
02845 
02846   // Create the new switch instruction now.
02847   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
02848 
02849   // Add all of the 'cases' to the switch instruction.
02850   for (unsigned i = 0, e = Values.size(); i != e; ++i)
02851     New->addCase(Values[i], EdgeBB);
02852 
02853   // We added edges from PI to the EdgeBB.  As such, if there were any
02854   // PHI nodes in EdgeBB, they need entries to be added corresponding to
02855   // the number of edges added.
02856   for (BasicBlock::iterator BBI = EdgeBB->begin();
02857        isa<PHINode>(BBI); ++BBI) {
02858     PHINode *PN = cast<PHINode>(BBI);
02859     Value *InVal = PN->getIncomingValueForBlock(BB);
02860     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
02861       PN->addIncoming(InVal, BB);
02862   }
02863 
02864   // Erase the old branch instruction.
02865   EraseTerminatorInstAndDCECond(BI);
02866 
02867   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
02868   return true;
02869 }
02870 
02871 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
02872   // If this is a trivial landing pad that just continues unwinding the caught
02873   // exception then zap the landing pad, turning its invokes into calls.
02874   BasicBlock *BB = RI->getParent();
02875   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
02876   if (RI->getValue() != LPInst)
02877     // Not a landing pad, or the resume is not unwinding the exception that
02878     // caused control to branch here.
02879     return false;
02880 
02881   // Check that there are no other instructions except for debug intrinsics.
02882   BasicBlock::iterator I = LPInst, E = RI;
02883   while (++I != E)
02884     if (!isa<DbgInfoIntrinsic>(I))
02885       return false;
02886 
02887   // Turn all invokes that unwind here into calls and delete the basic block.
02888   bool InvokeRequiresTableEntry = false;
02889   bool Changed = false;
02890   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
02891     InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
02892 
02893     if (II->hasFnAttr(Attribute::UWTable)) {
02894       // Don't remove an `invoke' instruction if the ABI requires an entry into
02895       // the table.
02896       InvokeRequiresTableEntry = true;
02897       continue;
02898     }
02899 
02900     SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
02901 
02902     // Insert a call instruction before the invoke.
02903     CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
02904     Call->takeName(II);
02905     Call->setCallingConv(II->getCallingConv());
02906     Call->setAttributes(II->getAttributes());
02907     Call->setDebugLoc(II->getDebugLoc());
02908 
02909     // Anything that used the value produced by the invoke instruction now uses
02910     // the value produced by the call instruction.  Note that we do this even
02911     // for void functions and calls with no uses so that the callgraph edge is
02912     // updated.
02913     II->replaceAllUsesWith(Call);
02914     BB->removePredecessor(II->getParent());
02915 
02916     // Insert a branch to the normal destination right before the invoke.
02917     BranchInst::Create(II->getNormalDest(), II);
02918 
02919     // Finally, delete the invoke instruction!
02920     II->eraseFromParent();
02921     Changed = true;
02922   }
02923 
02924   if (!InvokeRequiresTableEntry)
02925     // The landingpad is now unreachable.  Zap it.
02926     BB->eraseFromParent();
02927 
02928   return Changed;
02929 }
02930 
02931 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
02932   BasicBlock *BB = RI->getParent();
02933   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
02934 
02935   // Find predecessors that end with branches.
02936   SmallVector<BasicBlock*, 8> UncondBranchPreds;
02937   SmallVector<BranchInst*, 8> CondBranchPreds;
02938   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
02939     BasicBlock *P = *PI;
02940     TerminatorInst *PTI = P->getTerminator();
02941     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
02942       if (BI->isUnconditional())
02943         UncondBranchPreds.push_back(P);
02944       else
02945         CondBranchPreds.push_back(BI);
02946     }
02947   }
02948 
02949   // If we found some, do the transformation!
02950   if (!UncondBranchPreds.empty() && DupRet) {
02951     while (!UncondBranchPreds.empty()) {
02952       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
02953       DEBUG(dbgs() << "FOLDING: " << *BB
02954             << "INTO UNCOND BRANCH PRED: " << *Pred);
02955       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
02956     }
02957 
02958     // If we eliminated all predecessors of the block, delete the block now.
02959     if (pred_begin(BB) == pred_end(BB))
02960       // We know there are no successors, so just nuke the block.
02961       BB->eraseFromParent();
02962 
02963     return true;
02964   }
02965 
02966   // Check out all of the conditional branches going to this return
02967   // instruction.  If any of them just select between returns, change the
02968   // branch itself into a select/return pair.
02969   while (!CondBranchPreds.empty()) {
02970     BranchInst *BI = CondBranchPreds.pop_back_val();
02971 
02972     // Check to see if the non-BB successor is also a return block.
02973     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
02974         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
02975         SimplifyCondBranchToTwoReturns(BI, Builder))
02976       return true;
02977   }
02978   return false;
02979 }
02980 
02981 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
02982   BasicBlock *BB = UI->getParent();
02983 
02984   bool Changed = false;
02985 
02986   // If there are any instructions immediately before the unreachable that can
02987   // be removed, do so.
02988   while (UI != BB->begin()) {
02989     BasicBlock::iterator BBI = UI;
02990     --BBI;
02991     // Do not delete instructions that can have side effects which might cause
02992     // the unreachable to not be reachable; specifically, calls and volatile
02993     // operations may have this effect.
02994     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
02995 
02996     if (BBI->mayHaveSideEffects()) {
02997       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
02998         if (SI->isVolatile())
02999           break;
03000       } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
03001         if (LI->isVolatile())
03002           break;
03003       } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
03004         if (RMWI->isVolatile())
03005           break;
03006       } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
03007         if (CXI->isVolatile())
03008           break;
03009       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
03010                  !isa<LandingPadInst>(BBI)) {
03011         break;
03012       }
03013       // Note that deleting LandingPad's here is in fact okay, although it
03014       // involves a bit of subtle reasoning. If this inst is a LandingPad,
03015       // all the predecessors of this block will be the unwind edges of Invokes,
03016       // and we can therefore guarantee this block will be erased.
03017     }
03018 
03019     // Delete this instruction (any uses are guaranteed to be dead)
03020     if (!BBI->use_empty())
03021       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
03022     BBI->eraseFromParent();
03023     Changed = true;
03024   }
03025 
03026   // If the unreachable instruction is the first in the block, take a gander
03027   // at all of the predecessors of this instruction, and simplify them.
03028   if (&BB->front() != UI) return Changed;
03029 
03030   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
03031   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
03032     TerminatorInst *TI = Preds[i]->getTerminator();
03033     IRBuilder<> Builder(TI);
03034     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
03035       if (BI->isUnconditional()) {
03036         if (BI->getSuccessor(0) == BB) {
03037           new UnreachableInst(TI->getContext(), TI);
03038           TI->eraseFromParent();
03039           Changed = true;
03040         }
03041       } else {
03042         if (BI->getSuccessor(0) == BB) {
03043           Builder.CreateBr(BI->getSuccessor(1));
03044           EraseTerminatorInstAndDCECond(BI);
03045         } else if (BI->getSuccessor(1) == BB) {
03046           Builder.CreateBr(BI->getSuccessor(0));
03047           EraseTerminatorInstAndDCECond(BI);
03048           Changed = true;
03049         }
03050       }
03051     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
03052       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03053            i != e; ++i)
03054         if (i.getCaseSuccessor() == BB) {
03055           BB->removePredecessor(SI->getParent());
03056           SI->removeCase(i);
03057           --i; --e;
03058           Changed = true;
03059         }
03060       // If the default value is unreachable, figure out the most popular
03061       // destination and make it the default.
03062       if (SI->getDefaultDest() == BB) {
03063         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
03064         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03065              i != e; ++i) {
03066           std::pair<unsigned, unsigned> &entry =
03067               Popularity[i.getCaseSuccessor()];
03068           if (entry.first == 0) {
03069             entry.first = 1;
03070             entry.second = i.getCaseIndex();
03071           } else {
03072             entry.first++;
03073           }
03074         }
03075 
03076         // Find the most popular block.
03077         unsigned MaxPop = 0;
03078         unsigned MaxIndex = 0;
03079         BasicBlock *MaxBlock = nullptr;
03080         for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
03081              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
03082           if (I->second.first > MaxPop ||
03083               (I->second.first == MaxPop && MaxIndex > I->second.second)) {
03084             MaxPop = I->second.first;
03085             MaxIndex = I->second.second;
03086             MaxBlock = I->first;
03087           }
03088         }
03089         if (MaxBlock) {
03090           // Make this the new default, allowing us to delete any explicit
03091           // edges to it.
03092           SI->setDefaultDest(MaxBlock);
03093           Changed = true;
03094 
03095           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
03096           // it.
03097           if (isa<PHINode>(MaxBlock->begin()))
03098             for (unsigned i = 0; i != MaxPop-1; ++i)
03099               MaxBlock->removePredecessor(SI->getParent());
03100 
03101           for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03102                i != e; ++i)
03103             if (i.getCaseSuccessor() == MaxBlock) {
03104               SI->removeCase(i);
03105               --i; --e;
03106             }
03107         }
03108       }
03109     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
03110       if (II->getUnwindDest() == BB) {
03111         // Convert the invoke to a call instruction.  This would be a good
03112         // place to note that the call does not throw though.
03113         BranchInst *BI = Builder.CreateBr(II->getNormalDest());
03114         II->removeFromParent();   // Take out of symbol table
03115 
03116         // Insert the call now...
03117         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
03118         Builder.SetInsertPoint(BI);
03119         CallInst *CI = Builder.CreateCall(II->getCalledValue(),
03120                                           Args, II->getName());
03121         CI->setCallingConv(II->getCallingConv());
03122         CI->setAttributes(II->getAttributes());
03123         // If the invoke produced a value, the call does now instead.
03124         II->replaceAllUsesWith(CI);
03125         delete II;
03126         Changed = true;
03127       }
03128     }
03129   }
03130 
03131   // If this block is now dead, remove it.
03132   if (pred_begin(BB) == pred_end(BB) &&
03133       BB != &BB->getParent()->getEntryBlock()) {
03134     // We know there are no successors, so just nuke the block.
03135     BB->eraseFromParent();
03136     return true;
03137   }
03138 
03139   return Changed;
03140 }
03141 
03142 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
03143 /// integer range comparison into a sub, an icmp and a branch.
03144 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
03145   assert(SI->getNumCases() > 1 && "Degenerate switch?");
03146 
03147   // Make sure all cases point to the same destination and gather the values.
03148   SmallVector<ConstantInt *, 16> Cases;
03149   SwitchInst::CaseIt I = SI->case_begin();
03150   Cases.push_back(I.getCaseValue());
03151   SwitchInst::CaseIt PrevI = I++;
03152   for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
03153     if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
03154       return false;
03155     Cases.push_back(I.getCaseValue());
03156   }
03157   assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
03158 
03159   // Sort the case values, then check if they form a range we can transform.
03160   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
03161   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
03162     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
03163       return false;
03164   }
03165 
03166   Constant *Offset = ConstantExpr::getNeg(Cases.back());
03167   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
03168 
03169   Value *Sub = SI->getCondition();
03170   if (!Offset->isNullValue())
03171     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
03172   Value *Cmp;
03173   // If NumCases overflowed, then all possible values jump to the successor.
03174   if (NumCases->isNullValue() && SI->getNumCases() != 0)
03175     Cmp = ConstantInt::getTrue(SI->getContext());
03176   else
03177     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
03178   BranchInst *NewBI = Builder.CreateCondBr(
03179       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
03180 
03181   // Update weight for the newly-created conditional branch.
03182   SmallVector<uint64_t, 8> Weights;
03183   bool HasWeights = HasBranchWeights(SI);
03184   if (HasWeights) {
03185     GetBranchWeights(SI, Weights);
03186     if (Weights.size() == 1 + SI->getNumCases()) {
03187       // Combine all weights for the cases to be the true weight of NewBI.
03188       // We assume that the sum of all weights for a Terminator can fit into 32
03189       // bits.
03190       uint32_t NewTrueWeight = 0;
03191       for (unsigned I = 1, E = Weights.size(); I != E; ++I)
03192         NewTrueWeight += (uint32_t)Weights[I];
03193       NewBI->setMetadata(LLVMContext::MD_prof,
03194                          MDBuilder(SI->getContext()).
03195                          createBranchWeights(NewTrueWeight,
03196                                              (uint32_t)Weights[0]));
03197     }
03198   }
03199 
03200   // Prune obsolete incoming values off the successor's PHI nodes.
03201   for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
03202        isa<PHINode>(BBI); ++BBI) {
03203     for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
03204       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
03205   }
03206   SI->eraseFromParent();
03207 
03208   return true;
03209 }
03210 
03211 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
03212 /// and use it to remove dead cases.
03213 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
03214                                      AssumptionTracker *AT) {
03215   Value *Cond = SI->getCondition();
03216   unsigned Bits = Cond->getType()->getIntegerBitWidth();
03217   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
03218   computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
03219 
03220   // Gather dead cases.
03221   SmallVector<ConstantInt*, 8> DeadCases;
03222   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
03223     if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
03224         (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
03225       DeadCases.push_back(I.getCaseValue());
03226       DEBUG(dbgs() << "SimplifyCFG: switch case '"
03227                    << I.getCaseValue() << "' is dead.\n");
03228     }
03229   }
03230 
03231   SmallVector<uint64_t, 8> Weights;
03232   bool HasWeight = HasBranchWeights(SI);
03233   if (HasWeight) {
03234     GetBranchWeights(SI, Weights);
03235     HasWeight = (Weights.size() == 1 + SI->getNumCases());
03236   }
03237 
03238   // Remove dead cases from the switch.
03239   for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
03240     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
03241     assert(Case != SI->case_default() &&
03242            "Case was not found. Probably mistake in DeadCases forming.");
03243     if (HasWeight) {
03244       std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
03245       Weights.pop_back();
03246     }
03247 
03248     // Prune unused values from PHI nodes.
03249     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
03250     SI->removeCase(Case);
03251   }
03252   if (HasWeight && Weights.size() >= 2) {
03253     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
03254     SI->setMetadata(LLVMContext::MD_prof,
03255                     MDBuilder(SI->getParent()->getContext()).
03256                     createBranchWeights(MDWeights));
03257   }
03258 
03259   return !DeadCases.empty();
03260 }
03261 
03262 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
03263 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
03264 /// by an unconditional branch), look at the phi node for BB in the successor
03265 /// block and see if the incoming value is equal to CaseValue. If so, return
03266 /// the phi node, and set PhiIndex to BB's index in the phi node.
03267 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
03268                                               BasicBlock *BB,
03269                                               int *PhiIndex) {
03270   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
03271     return nullptr; // BB must be empty to be a candidate for simplification.
03272   if (!BB->getSinglePredecessor())
03273     return nullptr; // BB must be dominated by the switch.
03274 
03275   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
03276   if (!Branch || !Branch->isUnconditional())
03277     return nullptr; // Terminator must be unconditional branch.
03278 
03279   BasicBlock *Succ = Branch->getSuccessor(0);
03280 
03281   BasicBlock::iterator I = Succ->begin();
03282   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
03283     int Idx = PHI->getBasicBlockIndex(BB);
03284     assert(Idx >= 0 && "PHI has no entry for predecessor?");
03285 
03286     Value *InValue = PHI->getIncomingValue(Idx);
03287     if (InValue != CaseValue) continue;
03288 
03289     *PhiIndex = Idx;
03290     return PHI;
03291   }
03292 
03293   return nullptr;
03294 }
03295 
03296 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
03297 /// instruction to a phi node dominated by the switch, if that would mean that
03298 /// some of the destination blocks of the switch can be folded away.
03299 /// Returns true if a change is made.
03300 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
03301   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
03302   ForwardingNodesMap ForwardingNodes;
03303 
03304   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
03305     ConstantInt *CaseValue = I.getCaseValue();
03306     BasicBlock *CaseDest = I.getCaseSuccessor();
03307 
03308     int PhiIndex;
03309     PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
03310                                                  &PhiIndex);
03311     if (!PHI) continue;
03312 
03313     ForwardingNodes[PHI].push_back(PhiIndex);
03314   }
03315 
03316   bool Changed = false;
03317 
03318   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
03319        E = ForwardingNodes.end(); I != E; ++I) {
03320     PHINode *Phi = I->first;
03321     SmallVectorImpl<int> &Indexes = I->second;
03322 
03323     if (Indexes.size() < 2) continue;
03324 
03325     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
03326       Phi->setIncomingValue(Indexes[I], SI->getCondition());
03327     Changed = true;
03328   }
03329 
03330   return Changed;
03331 }
03332 
03333 /// ValidLookupTableConstant - Return true if the backend will be able to handle
03334 /// initializing an array of constants like C.
03335 static bool ValidLookupTableConstant(Constant *C) {
03336   if (C->isThreadDependent())
03337     return false;
03338   if (C->isDLLImportDependent())
03339     return false;
03340 
03341   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
03342     return CE->isGEPWithNoNotionalOverIndexing();
03343 
03344   return isa<ConstantFP>(C) ||
03345       isa<ConstantInt>(C) ||
03346       isa<ConstantPointerNull>(C) ||
03347       isa<GlobalValue>(C) ||
03348       isa<UndefValue>(C);
03349 }
03350 
03351 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
03352 /// its constant value in ConstantPool, returning 0 if it's not there.
03353 static Constant *LookupConstant(Value *V,
03354                          const SmallDenseMap<Value*, Constant*>& ConstantPool) {
03355   if (Constant *C = dyn_cast<Constant>(V))
03356     return C;
03357   return ConstantPool.lookup(V);
03358 }
03359 
03360 /// ConstantFold - Try to fold instruction I into a constant. This works for
03361 /// simple instructions such as binary operations where both operands are
03362 /// constant or can be replaced by constants from the ConstantPool. Returns the
03363 /// resulting constant on success, 0 otherwise.
03364 static Constant *
03365 ConstantFold(Instruction *I,
03366              const SmallDenseMap<Value *, Constant *> &ConstantPool,
03367              const DataLayout *DL) {
03368   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
03369     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
03370     if (!A)
03371       return nullptr;
03372     if (A->isAllOnesValue())
03373       return LookupConstant(Select->getTrueValue(), ConstantPool);
03374     if (A->isNullValue())
03375       return LookupConstant(Select->getFalseValue(), ConstantPool);
03376     return nullptr;
03377   }
03378 
03379   SmallVector<Constant *, 4> COps;
03380   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
03381     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
03382       COps.push_back(A);
03383     else
03384       return nullptr;
03385   }
03386 
03387   if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
03388     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
03389                                            COps[1], DL);
03390 
03391   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
03392 }
03393 
03394 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
03395 /// at the common destination basic block, *CommonDest, for one of the case
03396 /// destionations CaseDest corresponding to value CaseVal (0 for the default
03397 /// case), of a switch instruction SI.
03398 static bool
03399 GetCaseResults(SwitchInst *SI,
03400                ConstantInt *CaseVal,
03401                BasicBlock *CaseDest,
03402                BasicBlock **CommonDest,
03403                SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
03404                const DataLayout *DL) {
03405   // The block from which we enter the common destination.
03406   BasicBlock *Pred = SI->getParent();
03407 
03408   // If CaseDest is empty except for some side-effect free instructions through
03409   // which we can constant-propagate the CaseVal, continue to its successor.
03410   SmallDenseMap<Value*, Constant*> ConstantPool;
03411   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
03412   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
03413        ++I) {
03414     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
03415       // If the terminator is a simple branch, continue to the next block.
03416       if (T->getNumSuccessors() != 1)
03417         return false;
03418       Pred = CaseDest;
03419       CaseDest = T->getSuccessor(0);
03420     } else if (isa<DbgInfoIntrinsic>(I)) {
03421       // Skip debug intrinsic.
03422       continue;
03423     } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
03424       // Instruction is side-effect free and constant.
03425       ConstantPool.insert(std::make_pair(I, C));
03426     } else {
03427       break;
03428     }
03429   }
03430 
03431   // If we did not have a CommonDest before, use the current one.
03432   if (!*CommonDest)
03433     *CommonDest = CaseDest;
03434   // If the destination isn't the common one, abort.
03435   if (CaseDest != *CommonDest)
03436     return false;
03437 
03438   // Get the values for this case from phi nodes in the destination block.
03439   BasicBlock::iterator I = (*CommonDest)->begin();
03440   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
03441     int Idx = PHI->getBasicBlockIndex(Pred);
03442     if (Idx == -1)
03443       continue;
03444 
03445     Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
03446                                         ConstantPool);
03447     if (!ConstVal)
03448       return false;
03449 
03450     // Note: If the constant comes from constant-propagating the case value
03451     // through the CaseDest basic block, it will be safe to remove the
03452     // instructions in that block. They cannot be used (except in the phi nodes
03453     // we visit) outside CaseDest, because that block does not dominate its
03454     // successor. If it did, we would not be in this phi node.
03455 
03456     // Be conservative about which kinds of constants we support.
03457     if (!ValidLookupTableConstant(ConstVal))
03458       return false;
03459 
03460     Res.push_back(std::make_pair(PHI, ConstVal));
03461   }
03462 
03463   return Res.size() > 0;
03464 }
03465 
03466 // MapCaseToResult - Helper function used to
03467 // add CaseVal to the list of cases that generate Result.
03468 static void MapCaseToResult(ConstantInt *CaseVal,
03469     SwitchCaseResultVectorTy &UniqueResults,
03470     Constant *Result) {
03471   for (auto &I : UniqueResults) {
03472     if (I.first == Result) {
03473       I.second.push_back(CaseVal);
03474       return;
03475     }
03476   }
03477   UniqueResults.push_back(std::make_pair(Result,
03478         SmallVector<ConstantInt*, 4>(1, CaseVal)));
03479 }
03480 
03481 // InitializeUniqueCases - Helper function that initializes a map containing
03482 // results for the PHI node of the common destination block for a switch
03483 // instruction. Returns false if multiple PHI nodes have been found or if
03484 // there is not a common destination block for the switch.
03485 static bool InitializeUniqueCases(
03486     SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
03487     BasicBlock *&CommonDest,
03488     SwitchCaseResultVectorTy &UniqueResults,
03489     Constant *&DefaultResult) {
03490   for (auto &I : SI->cases()) {
03491     ConstantInt *CaseVal = I.getCaseValue();
03492 
03493     // Resulting value at phi nodes for this case value.
03494     SwitchCaseResultsTy Results;
03495     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
03496                         DL))
03497       return false;
03498 
03499     // Only one value per case is permitted
03500     if (Results.size() > 1)
03501       return false;
03502     MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
03503 
03504     // Check the PHI consistency.
03505     if (!PHI)
03506       PHI = Results[0].first;
03507     else if (PHI != Results[0].first)
03508       return false;
03509   }
03510   // Find the default result value.
03511   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
03512   BasicBlock *DefaultDest = SI->getDefaultDest();
03513   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
03514                  DL);
03515   // If the default value is not found abort unless the default destination
03516   // is unreachable.
03517   DefaultResult =
03518       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
03519   if ((!DefaultResult &&
03520         !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
03521     return false;
03522 
03523   return true;
03524 }
03525 
03526 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
03527 // transform a switch with only two cases (or two cases + default)
03528 // that produces a result into a value select.
03529 // Example:
03530 // switch (a) {
03531 //   case 10:                %0 = icmp eq i32 %a, 10
03532 //     return 10;            %1 = select i1 %0, i32 10, i32 4
03533 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
03534 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
03535 //   default:
03536 //     return 4;
03537 // }
03538 static Value *
03539 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
03540                      Constant *DefaultResult, Value *Condition,
03541                      IRBuilder<> &Builder) {
03542   assert(ResultVector.size() == 2 &&
03543       "We should have exactly two unique results at this point");
03544   // If we are selecting between only two cases transform into a simple
03545   // select or a two-way select if default is possible.
03546   if (ResultVector[0].second.size() == 1 &&
03547       ResultVector[1].second.size() == 1) {
03548     ConstantInt *const FirstCase = ResultVector[0].second[0];
03549     ConstantInt *const SecondCase = ResultVector[1].second[0];
03550 
03551     bool DefaultCanTrigger = DefaultResult;
03552     Value *SelectValue = ResultVector[1].first;
03553     if (DefaultCanTrigger) {
03554       Value *const ValueCompare =
03555           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
03556       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
03557                                          DefaultResult, "switch.select");
03558     }
03559     Value *const ValueCompare =
03560         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
03561     return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
03562                                 "switch.select");
03563   }
03564 
03565   return nullptr;
03566 }
03567 
03568 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
03569 // instruction that has been converted into a select, fixing up PHI nodes and
03570 // basic blocks.
03571 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
03572                                               Value *SelectValue,
03573                                               IRBuilder<> &Builder) {
03574   BasicBlock *SelectBB = SI->getParent();
03575   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
03576     PHI->removeIncomingValue(SelectBB);
03577   PHI->addIncoming(SelectValue, SelectBB);
03578 
03579   Builder.CreateBr(PHI->getParent());
03580 
03581   // Remove the switch.
03582   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
03583     BasicBlock *Succ = SI->getSuccessor(i);
03584 
03585     if (Succ == PHI->getParent())
03586       continue;
03587     Succ->removePredecessor(SelectBB);
03588   }
03589   SI->eraseFromParent();
03590 }
03591 
03592 /// SwitchToSelect - If the switch is only used to initialize one or more
03593 /// phi nodes in a common successor block with only two different
03594 /// constant values, replace the switch with select.
03595 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
03596                            const DataLayout *DL, AssumptionTracker *AT) {
03597   Value *const Cond = SI->getCondition();
03598   PHINode *PHI = nullptr;
03599   BasicBlock *CommonDest = nullptr;
03600   Constant *DefaultResult;
03601   SwitchCaseResultVectorTy UniqueResults;
03602   // Collect all the cases that will deliver the same value from the switch.
03603   if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
03604                              DefaultResult))
03605     return false;
03606   // Selects choose between maximum two values.
03607   if (UniqueResults.size() != 2)
03608     return false;
03609   assert(PHI != nullptr && "PHI for value select not found");
03610 
03611   Builder.SetInsertPoint(SI);
03612   Value *SelectValue = ConvertTwoCaseSwitch(
03613       UniqueResults,
03614       DefaultResult, Cond, Builder);
03615   if (SelectValue) {
03616     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
03617     return true;
03618   }
03619   // The switch couldn't be converted into a select.
03620   return false;
03621 }
03622 
03623 namespace {
03624   /// SwitchLookupTable - This class represents a lookup table that can be used
03625   /// to replace a switch.
03626   class SwitchLookupTable {
03627   public:
03628     /// SwitchLookupTable - Create a lookup table to use as a switch replacement
03629     /// with the contents of Values, using DefaultValue to fill any holes in the
03630     /// table.
03631     SwitchLookupTable(Module &M,
03632                       uint64_t TableSize,
03633                       ConstantInt *Offset,
03634              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
03635                       Constant *DefaultValue,
03636                       const DataLayout *DL);
03637 
03638     /// BuildLookup - Build instructions with Builder to retrieve the value at
03639     /// the position given by Index in the lookup table.
03640     Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
03641 
03642     /// WouldFitInRegister - Return true if a table with TableSize elements of
03643     /// type ElementType would fit in a target-legal register.
03644     static bool WouldFitInRegister(const DataLayout *DL,
03645                                    uint64_t TableSize,
03646                                    const Type *ElementType);
03647 
03648   private:
03649     // Depending on the contents of the table, it can be represented in
03650     // different ways.
03651     enum {
03652       // For tables where each element contains the same value, we just have to
03653       // store that single value and return it for each lookup.
03654       SingleValueKind,
03655 
03656       // For small tables with integer elements, we can pack them into a bitmap
03657       // that fits into a target-legal register. Values are retrieved by
03658       // shift and mask operations.
03659       BitMapKind,
03660 
03661       // The table is stored as an array of values. Values are retrieved by load
03662       // instructions from the table.
03663       ArrayKind
03664     } Kind;
03665 
03666     // For SingleValueKind, this is the single value.
03667     Constant *SingleValue;
03668 
03669     // For BitMapKind, this is the bitmap.
03670     ConstantInt *BitMap;
03671     IntegerType *BitMapElementTy;
03672 
03673     // For ArrayKind, this is the array.
03674     GlobalVariable *Array;
03675   };
03676 }
03677 
03678 SwitchLookupTable::SwitchLookupTable(Module &M,
03679                                      uint64_t TableSize,
03680                                      ConstantInt *Offset,
03681              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
03682                                      Constant *DefaultValue,
03683                                      const DataLayout *DL)
03684     : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
03685       Array(nullptr) {
03686   assert(Values.size() && "Can't build lookup table without values!");
03687   assert(TableSize >= Values.size() && "Can't fit values in table!");
03688 
03689   // If all values in the table are equal, this is that value.
03690   SingleValue = Values.begin()->second;
03691 
03692   Type *ValueType = Values.begin()->second->getType();
03693 
03694   // Build up the table contents.
03695   SmallVector<Constant*, 64> TableContents(TableSize);
03696   for (size_t I = 0, E = Values.size(); I != E; ++I) {
03697     ConstantInt *CaseVal = Values[I].first;
03698     Constant *CaseRes = Values[I].second;
03699     assert(CaseRes->getType() == ValueType);
03700 
03701     uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
03702                    .getLimitedValue();
03703     TableContents[Idx] = CaseRes;
03704 
03705     if (CaseRes != SingleValue)
03706       SingleValue = nullptr;
03707   }
03708 
03709   // Fill in any holes in the table with the default result.
03710   if (Values.size() < TableSize) {
03711     assert(DefaultValue &&
03712            "Need a default value to fill the lookup table holes.");
03713     assert(DefaultValue->getType() == ValueType);
03714     for (uint64_t I = 0; I < TableSize; ++I) {
03715       if (!TableContents[I])
03716         TableContents[I] = DefaultValue;
03717     }
03718 
03719     if (DefaultValue != SingleValue)
03720       SingleValue = nullptr;
03721   }
03722 
03723   // If each element in the table contains the same value, we only need to store
03724   // that single value.
03725   if (SingleValue) {
03726     Kind = SingleValueKind;
03727     return;
03728   }
03729 
03730   // If the type is integer and the table fits in a register, build a bitmap.
03731   if (WouldFitInRegister(DL, TableSize, ValueType)) {
03732     IntegerType *IT = cast<IntegerType>(ValueType);
03733     APInt TableInt(TableSize * IT->getBitWidth(), 0);
03734     for (uint64_t I = TableSize; I > 0; --I) {
03735       TableInt <<= IT->getBitWidth();
03736       // Insert values into the bitmap. Undef values are set to zero.
03737       if (!isa<UndefValue>(TableContents[I - 1])) {
03738         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
03739         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
03740       }
03741     }
03742     BitMap = ConstantInt::get(M.getContext(), TableInt);
03743     BitMapElementTy = IT;
03744     Kind = BitMapKind;
03745     ++NumBitMaps;
03746     return;
03747   }
03748 
03749   // Store the table in an array.
03750   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
03751   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
03752 
03753   Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
03754                              GlobalVariable::PrivateLinkage,
03755                              Initializer,
03756                              "switch.table");
03757   Array->setUnnamedAddr(true);
03758   Kind = ArrayKind;
03759 }
03760 
03761 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
03762   switch (Kind) {
03763     case SingleValueKind:
03764       return SingleValue;
03765     case BitMapKind: {
03766       // Type of the bitmap (e.g. i59).
03767       IntegerType *MapTy = BitMap->getType();
03768 
03769       // Cast Index to the same type as the bitmap.
03770       // Note: The Index is <= the number of elements in the table, so
03771       // truncating it to the width of the bitmask is safe.
03772       Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
03773 
03774       // Multiply the shift amount by the element width.
03775       ShiftAmt = Builder.CreateMul(ShiftAmt,
03776                       ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
03777                                    "switch.shiftamt");
03778 
03779       // Shift down.
03780       Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
03781                                               "switch.downshift");
03782       // Mask off.
03783       return Builder.CreateTrunc(DownShifted, BitMapElementTy,
03784                                  "switch.masked");
03785     }
03786     case ArrayKind: {
03787       // Make sure the table index will not overflow when treated as signed.
03788       IntegerType *IT = cast<IntegerType>(Index->getType());
03789       uint64_t TableSize = Array->getInitializer()->getType()
03790                                 ->getArrayNumElements();
03791       if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
03792         Index = Builder.CreateZExt(Index,
03793                                    IntegerType::get(IT->getContext(),
03794                                                     IT->getBitWidth() + 1),
03795                                    "switch.tableidx.zext");
03796 
03797       Value *GEPIndices[] = { Builder.getInt32(0), Index };
03798       Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
03799                                              "switch.gep");
03800       return Builder.CreateLoad(GEP, "switch.load");
03801     }
03802   }
03803   llvm_unreachable("Unknown lookup table kind!");
03804 }
03805 
03806 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
03807                                            uint64_t TableSize,
03808                                            const Type *ElementType) {
03809   if (!DL)
03810     return false;
03811   const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
03812   if (!IT)
03813     return false;
03814   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
03815   // are <= 15, we could try to narrow the type.
03816 
03817   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
03818   if (TableSize >= UINT_MAX/IT->getBitWidth())
03819     return false;
03820   return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
03821 }
03822 
03823 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
03824 /// for this switch, based on the number of cases, size of the table and the
03825 /// types of the results.
03826 static bool ShouldBuildLookupTable(SwitchInst *SI,
03827                                    uint64_t TableSize,
03828                                    const TargetTransformInfo &TTI,
03829                                    const DataLayout *DL,
03830                             const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
03831   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
03832     return false; // TableSize overflowed, or mul below might overflow.
03833 
03834   bool AllTablesFitInRegister = true;
03835   bool HasIllegalType = false;
03836   for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
03837        E = ResultTypes.end(); I != E; ++I) {
03838     Type *Ty = I->second;
03839 
03840     // Saturate this flag to true.
03841     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
03842 
03843     // Saturate this flag to false.
03844     AllTablesFitInRegister = AllTablesFitInRegister &&
03845       SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
03846 
03847     // If both flags saturate, we're done. NOTE: This *only* works with
03848     // saturating flags, and all flags have to saturate first due to the
03849     // non-deterministic behavior of iterating over a dense map.
03850     if (HasIllegalType && !AllTablesFitInRegister)
03851       break;
03852   }
03853 
03854   // If each table would fit in a register, we should build it anyway.
03855   if (AllTablesFitInRegister)
03856     return true;
03857 
03858   // Don't build a table that doesn't fit in-register if it has illegal types.
03859   if (HasIllegalType)
03860     return false;
03861 
03862   // The table density should be at least 40%. This is the same criterion as for
03863   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
03864   // FIXME: Find the best cut-off.
03865   return SI->getNumCases() * 10 >= TableSize * 4;
03866 }
03867 
03868 /// SwitchToLookupTable - If the switch is only used to initialize one or more
03869 /// phi nodes in a common successor block with different constant values,
03870 /// replace the switch with lookup tables.
03871 static bool SwitchToLookupTable(SwitchInst *SI,
03872                                 IRBuilder<> &Builder,
03873                                 const TargetTransformInfo &TTI,
03874                                 const DataLayout* DL) {
03875   assert(SI->getNumCases() > 1 && "Degenerate switch?");
03876 
03877   // Only build lookup table when we have a target that supports it.
03878   if (!TTI.shouldBuildLookupTables())
03879     return false;
03880 
03881   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
03882   // split off a dense part and build a lookup table for that.
03883 
03884   // FIXME: This creates arrays of GEPs to constant strings, which means each
03885   // GEP needs a runtime relocation in PIC code. We should just build one big
03886   // string and lookup indices into that.
03887 
03888   // Ignore switches with less than three cases. Lookup tables will not make them
03889   // faster, so we don't analyze them.
03890   if (SI->getNumCases() < 3)
03891     return false;
03892 
03893   // Figure out the corresponding result for each case value and phi node in the
03894   // common destination, as well as the the min and max case values.
03895   assert(SI->case_begin() != SI->case_end());
03896   SwitchInst::CaseIt CI = SI->case_begin();
03897   ConstantInt *MinCaseVal = CI.getCaseValue();
03898   ConstantInt *MaxCaseVal = CI.getCaseValue();
03899 
03900   BasicBlock *CommonDest = nullptr;
03901   typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
03902   SmallDenseMap<PHINode*, ResultListTy> ResultLists;
03903   SmallDenseMap<PHINode*, Constant*> DefaultResults;
03904   SmallDenseMap<PHINode*, Type*> ResultTypes;
03905   SmallVector<PHINode*, 4> PHIs;
03906 
03907   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
03908     ConstantInt *CaseVal = CI.getCaseValue();
03909     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
03910       MinCaseVal = CaseVal;
03911     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
03912       MaxCaseVal = CaseVal;
03913 
03914     // Resulting value at phi nodes for this case value.
03915     typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
03916     ResultsTy Results;
03917     if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
03918                         Results, DL))
03919       return false;
03920 
03921     // Append the result from this case to the list for each phi.
03922     for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
03923       if (!ResultLists.count(I->first))
03924         PHIs.push_back(I->first);
03925       ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
03926     }
03927   }
03928 
03929   // Keep track of the result types.
03930   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
03931     PHINode *PHI = PHIs[I];
03932     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
03933   }
03934 
03935   uint64_t NumResults = ResultLists[PHIs[0]].size();
03936   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
03937   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
03938   bool TableHasHoles = (NumResults < TableSize);
03939 
03940   // If the table has holes, we need a constant result for the default case
03941   // or a bitmask that fits in a register.
03942   SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
03943   bool HasDefaultResults = false;
03944   if (TableHasHoles) {
03945     HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
03946                                        &CommonDest, DefaultResultsList, DL);
03947   }
03948   bool NeedMask = (TableHasHoles && !HasDefaultResults);
03949   if (NeedMask) {
03950     // As an extra penalty for the validity test we require more cases.
03951     if (SI->getNumCases() < 4)  // FIXME: Find best threshold value (benchmark).
03952       return false;
03953     if (!(DL && DL->fitsInLegalInteger(TableSize)))
03954       return false;
03955   }
03956 
03957   for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
03958     PHINode *PHI = DefaultResultsList[I].first;
03959     Constant *Result = DefaultResultsList[I].second;
03960     DefaultResults[PHI] = Result;
03961   }
03962 
03963   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
03964     return false;
03965 
03966   // Create the BB that does the lookups.
03967   Module &Mod = *CommonDest->getParent()->getParent();
03968   BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
03969                                             "switch.lookup",
03970                                             CommonDest->getParent(),
03971                                             CommonDest);
03972 
03973   // Compute the table index value.
03974   Builder.SetInsertPoint(SI);
03975   Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
03976                                         "switch.tableidx");
03977 
03978   // Compute the maximum table size representable by the integer type we are
03979   // switching upon.
03980   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
03981   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
03982   assert(MaxTableSize >= TableSize &&
03983          "It is impossible for a switch to have more entries than the max "
03984          "representable value of its input integer type's size.");
03985 
03986   // If we have a fully covered lookup table, unconditionally branch to the
03987   // lookup table BB. Otherwise, check if the condition value is within the case
03988   // range. If it is so, branch to the new BB. Otherwise branch to SI's default
03989   // destination.
03990   const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
03991   if (GeneratingCoveredLookupTable) {
03992     Builder.CreateBr(LookupBB);
03993     // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
03994     // do not delete PHINodes here.
03995     SI->getDefaultDest()->removePredecessor(SI->getParent(),
03996                                             true/*DontDeleteUselessPHIs*/);
03997   } else {
03998     Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
03999                                        MinCaseVal->getType(), TableSize));
04000     Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
04001   }
04002 
04003   // Populate the BB that does the lookups.
04004   Builder.SetInsertPoint(LookupBB);
04005 
04006   if (NeedMask) {
04007     // Before doing the lookup we do the hole check.
04008     // The LookupBB is therefore re-purposed to do the hole check
04009     // and we create a new LookupBB.
04010     BasicBlock *MaskBB = LookupBB;
04011     MaskBB->setName("switch.hole_check");
04012     LookupBB = BasicBlock::Create(Mod.getContext(),
04013                                   "switch.lookup",
04014                                   CommonDest->getParent(),
04015                                   CommonDest);
04016 
04017     // Build bitmask; fill in a 1 bit for every case.
04018     APInt MaskInt(TableSize, 0);
04019     APInt One(TableSize, 1);
04020     const ResultListTy &ResultList = ResultLists[PHIs[0]];
04021     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
04022       uint64_t Idx = (ResultList[I].first->getValue() -
04023                       MinCaseVal->getValue()).getLimitedValue();
04024       MaskInt |= One << Idx;
04025     }
04026     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
04027 
04028     // Get the TableIndex'th bit of the bitmask.
04029     // If this bit is 0 (meaning hole) jump to the default destination,
04030     // else continue with table lookup.
04031     IntegerType *MapTy = TableMask->getType();
04032     Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
04033                                                  "switch.maskindex");
04034     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
04035                                         "switch.shifted");
04036     Value *LoBit = Builder.CreateTrunc(Shifted,
04037                                        Type::getInt1Ty(Mod.getContext()),
04038                                        "switch.lobit");
04039     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
04040 
04041     Builder.SetInsertPoint(LookupBB);
04042     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
04043   }
04044 
04045   bool ReturnedEarly = false;
04046   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
04047     PHINode *PHI = PHIs[I];
04048 
04049     // If using a bitmask, use any value to fill the lookup table holes.
04050     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
04051     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
04052                             DV, DL);
04053 
04054     Value *Result = Table.BuildLookup(TableIndex, Builder);
04055 
04056     // If the result is used to return immediately from the function, we want to
04057     // do that right here.
04058     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
04059         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
04060       Builder.CreateRet(Result);
04061       ReturnedEarly = true;
04062       break;
04063     }
04064 
04065     PHI->addIncoming(Result, LookupBB);
04066   }
04067 
04068   if (!ReturnedEarly)
04069     Builder.CreateBr(CommonDest);
04070 
04071   // Remove the switch.
04072   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
04073     BasicBlock *Succ = SI->getSuccessor(i);
04074 
04075     if (Succ == SI->getDefaultDest())
04076       continue;
04077     Succ->removePredecessor(SI->getParent());
04078   }
04079   SI->eraseFromParent();
04080 
04081   ++NumLookupTables;
04082   if (NeedMask)
04083     ++NumLookupTablesHoles;
04084   return true;
04085 }
04086 
04087 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
04088   BasicBlock *BB = SI->getParent();
04089 
04090   if (isValueEqualityComparison(SI)) {
04091     // If we only have one predecessor, and if it is a branch on this value,
04092     // see if that predecessor totally determines the outcome of this switch.
04093     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
04094       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
04095         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04096 
04097     Value *Cond = SI->getCondition();
04098     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
04099       if (SimplifySwitchOnSelect(SI, Select))
04100         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04101 
04102     // If the block only contains the switch, see if we can fold the block
04103     // away into any preds.
04104     BasicBlock::iterator BBI = BB->begin();
04105     // Ignore dbg intrinsics.
04106     while (isa<DbgInfoIntrinsic>(BBI))
04107       ++BBI;
04108     if (SI == &*BBI)
04109       if (FoldValueComparisonIntoPredecessors(SI, Builder))
04110         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04111   }
04112 
04113   // Try to transform the switch into an icmp and a branch.
04114   if (TurnSwitchRangeIntoICmp(SI, Builder))
04115     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04116 
04117   // Remove unreachable cases.
04118   if (EliminateDeadSwitchCases(SI, DL, AT))
04119     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04120 
04121   if (SwitchToSelect(SI, Builder, DL, AT))
04122     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04123 
04124   if (ForwardSwitchConditionToPHI(SI))
04125     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04126 
04127   if (SwitchToLookupTable(SI, Builder, TTI, DL))
04128     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04129 
04130   return false;
04131 }
04132 
04133 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
04134   BasicBlock *BB = IBI->getParent();
04135   bool Changed = false;
04136 
04137   // Eliminate redundant destinations.
04138   SmallPtrSet<Value *, 8> Succs;
04139   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
04140     BasicBlock *Dest = IBI->getDestination(i);
04141     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
04142       Dest->removePredecessor(BB);
04143       IBI->removeDestination(i);
04144       --i; --e;
04145       Changed = true;
04146     }
04147   }
04148 
04149   if (IBI->getNumDestinations() == 0) {
04150     // If the indirectbr has no successors, change it to unreachable.
04151     new UnreachableInst(IBI->getContext(), IBI);
04152     EraseTerminatorInstAndDCECond(IBI);
04153     return true;
04154   }
04155 
04156   if (IBI->getNumDestinations() == 1) {
04157     // If the indirectbr has one successor, change it to a direct branch.
04158     BranchInst::Create(IBI->getDestination(0), IBI);
04159     EraseTerminatorInstAndDCECond(IBI);
04160     return true;
04161   }
04162 
04163   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
04164     if (SimplifyIndirectBrOnSelect(IBI, SI))
04165       return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04166   }
04167   return Changed;
04168 }
04169 
04170 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
04171   BasicBlock *BB = BI->getParent();
04172 
04173   if (SinkCommon && SinkThenElseCodeToEnd(BI))
04174     return true;
04175 
04176   // If the Terminator is the only non-phi instruction, simplify the block.
04177   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
04178   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
04179       TryToSimplifyUncondBranchFromEmptyBlock(BB))
04180     return true;
04181 
04182   // If the only instruction in the block is a seteq/setne comparison
04183   // against a constant, try to simplify the block.
04184   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
04185     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
04186       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
04187         ;
04188       if (I->isTerminator() &&
04189           TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
04190                                                 BonusInstThreshold, DL, AT))
04191         return true;
04192     }
04193 
04194   // If this basic block is ONLY a compare and a branch, and if a predecessor
04195   // branches to us and our successor, fold the comparison into the
04196   // predecessor and use logical operations to update the incoming value
04197   // for PHI nodes in common successor.
04198   if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
04199     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04200   return false;
04201 }
04202 
04203 
04204 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
04205   BasicBlock *BB = BI->getParent();
04206 
04207   // Conditional branch
04208   if (isValueEqualityComparison(BI)) {
04209     // If we only have one predecessor, and if it is a branch on this value,
04210     // see if that predecessor totally determines the outcome of this
04211     // switch.
04212     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
04213       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
04214         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04215 
04216     // This block must be empty, except for the setcond inst, if it exists.
04217     // Ignore dbg intrinsics.
04218     BasicBlock::iterator I = BB->begin();
04219     // Ignore dbg intrinsics.
04220     while (isa<DbgInfoIntrinsic>(I))
04221       ++I;
04222     if (&*I == BI) {
04223       if (FoldValueComparisonIntoPredecessors(BI, Builder))
04224         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04225     } else if (&*I == cast<Instruction>(BI->getCondition())){
04226       ++I;
04227       // Ignore dbg intrinsics.
04228       while (isa<DbgInfoIntrinsic>(I))
04229         ++I;
04230       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
04231         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04232     }
04233   }
04234 
04235   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
04236   if (SimplifyBranchOnICmpChain(BI, DL, Builder))
04237     return true;
04238 
04239   // If this basic block is ONLY a compare and a branch, and if a predecessor
04240   // branches to us and one of our successors, fold the comparison into the
04241   // predecessor and use logical operations to pick the right destination.
04242   if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
04243     return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04244 
04245   // We have a conditional branch to two blocks that are only reachable
04246   // from BI.  We know that the condbr dominates the two blocks, so see if
04247   // there is any identical code in the "then" and "else" blocks.  If so, we
04248   // can hoist it up to the branching block.
04249   if (BI->getSuccessor(0)->getSinglePredecessor()) {
04250     if (BI->getSuccessor(1)->getSinglePredecessor()) {
04251       if (HoistThenElseCodeToIf(BI, DL))
04252         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04253     } else {
04254       // If Successor #1 has multiple preds, we may be able to conditionally
04255       // execute Successor #0 if it branches to Successor #1.
04256       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
04257       if (Succ0TI->getNumSuccessors() == 1 &&
04258           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
04259         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
04260           return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04261     }
04262   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
04263     // If Successor #0 has multiple preds, we may be able to conditionally
04264     // execute Successor #1 if it branches to Successor #0.
04265     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
04266     if (Succ1TI->getNumSuccessors() == 1 &&
04267         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
04268       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
04269         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04270   }
04271 
04272   // If this is a branch on a phi node in the current block, thread control
04273   // through this block if any PHI node entries are constants.
04274   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
04275     if (PN->getParent() == BI->getParent())
04276       if (FoldCondBranchOnPHI(BI, DL))
04277         return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04278 
04279   // Scan predecessor blocks for conditional branches.
04280   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
04281     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
04282       if (PBI != BI && PBI->isConditional())
04283         if (SimplifyCondBranchToCondBranch(PBI, BI))
04284           return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
04285 
04286   return false;
04287 }
04288 
04289 /// Check if passing a value to an instruction will cause undefined behavior.
04290 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
04291   Constant *C = dyn_cast<Constant>(V);
04292   if (!C)
04293     return false;
04294 
04295   if (I->use_empty())
04296     return false;
04297 
04298   if (C->isNullValue()) {
04299     // Only look at the first use, avoid hurting compile time with long uselists
04300     User *Use = *I->user_begin();
04301 
04302     // Now make sure that there are no instructions in between that can alter
04303     // control flow (eg. calls)
04304     for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
04305       if (i == I->getParent()->end() || i->mayHaveSideEffects())
04306         return false;
04307 
04308     // Look through GEPs. A load from a GEP derived from NULL is still undefined
04309     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
04310       if (GEP->getPointerOperand() == I)
04311         return passingValueIsAlwaysUndefined(V, GEP);
04312 
04313     // Look through bitcasts.
04314     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
04315       return passingValueIsAlwaysUndefined(V, BC);
04316 
04317     // Load from null is undefined.
04318     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
04319       if (!LI->isVolatile())
04320         return LI->getPointerAddressSpace() == 0;
04321 
04322     // Store to null is undefined.
04323     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
04324       if (!SI->isVolatile())
04325         return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
04326   }
04327   return false;
04328 }
04329 
04330 /// If BB has an incoming value that will always trigger undefined behavior
04331 /// (eg. null pointer dereference), remove the branch leading here.
04332 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
04333   for (BasicBlock::iterator i = BB->begin();
04334        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
04335     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
04336       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
04337         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
04338         IRBuilder<> Builder(T);
04339         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
04340           BB->removePredecessor(PHI->getIncomingBlock(i));
04341           // Turn uncoditional branches into unreachables and remove the dead
04342           // destination from conditional branches.
04343           if (BI->isUnconditional())
04344             Builder.CreateUnreachable();
04345           else
04346             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
04347                                                          BI->getSuccessor(0));
04348           BI->eraseFromParent();
04349           return true;
04350         }
04351         // TODO: SwitchInst.
04352       }
04353 
04354   return false;
04355 }
04356 
04357 bool SimplifyCFGOpt::run(BasicBlock *BB) {
04358   bool Changed = false;
04359 
04360   assert(BB && BB->getParent() && "Block not embedded in function!");
04361   assert(BB->getTerminator() && "Degenerate basic block encountered!");
04362 
04363   // Remove basic blocks that have no predecessors (except the entry block)...
04364   // or that just have themself as a predecessor.  These are unreachable.
04365   if ((pred_begin(BB) == pred_end(BB) &&
04366        BB != &BB->getParent()->getEntryBlock()) ||
04367       BB->getSinglePredecessor() == BB) {
04368     DEBUG(dbgs() << "Removing BB: \n" << *BB);
04369     DeleteDeadBlock(BB);
04370     return true;
04371   }
04372 
04373   // Check to see if we can constant propagate this terminator instruction
04374   // away...
04375   Changed |= ConstantFoldTerminator(BB, true);
04376 
04377   // Check for and eliminate duplicate PHI nodes in this block.
04378   Changed |= EliminateDuplicatePHINodes(BB);
04379 
04380   // Check for and remove branches that will always cause undefined behavior.
04381   Changed |= removeUndefIntroducingPredecessor(BB);
04382 
04383   // Merge basic blocks into their predecessor if there is only one distinct
04384   // pred, and if there is only one distinct successor of the predecessor, and
04385   // if there are no PHI nodes.
04386   //
04387   if (MergeBlockIntoPredecessor(BB))
04388     return true;
04389 
04390   IRBuilder<> Builder(BB);
04391 
04392   // If there is a trivial two-entry PHI node in this basic block, and we can
04393   // eliminate it, do so now.
04394   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
04395     if (PN->getNumIncomingValues() == 2)
04396       Changed |= FoldTwoEntryPHINode(PN, DL);
04397 
04398   Builder.SetInsertPoint(BB->getTerminator());
04399   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
04400     if (BI->isUnconditional()) {
04401       if (SimplifyUncondBranch(BI, Builder)) return true;
04402     } else {
04403       if (SimplifyCondBranch(BI, Builder)) return true;
04404     }
04405   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
04406     if (SimplifyReturn(RI, Builder)) return true;
04407   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
04408     if (SimplifyResume(RI, Builder)) return true;
04409   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
04410     if (SimplifySwitch(SI, Builder)) return true;
04411   } else if (UnreachableInst *UI =
04412                dyn_cast<UnreachableInst>(BB->getTerminator())) {
04413     if (SimplifyUnreachable(UI)) return true;
04414   } else if (IndirectBrInst *IBI =
04415                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
04416     if (SimplifyIndirectBr(IBI)) return true;
04417   }
04418 
04419   return Changed;
04420 }
04421 
04422 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
04423 /// example, it adjusts branches to branches to eliminate the extra hop, it
04424 /// eliminates unreachable basic blocks, and does other "peephole" optimization
04425 /// of the CFG.  It returns true if a modification was made.
04426 ///
04427 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
04428                        unsigned BonusInstThreshold,
04429                        const DataLayout *DL, AssumptionTracker *AT) {
04430   return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
04431 }