LLVM API Documentation

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