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