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