LLVM API Documentation

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