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