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