Don't build switch lookup tables for dllimport or TLS variables
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Peephole optimize the CFG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include <algorithm>
47 #include <map>
48 #include <set>
49 using namespace llvm;
50 using namespace PatternMatch;
51
52 #define DEBUG_TYPE "simplifycfg"
53
54 static cl::opt<unsigned>
55 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
56    cl::desc("Control the amount of phi node folding to perform (default = 1)"));
57
58 static cl::opt<bool>
59 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
60        cl::desc("Duplicate return instructions into unconditional branches"));
61
62 static cl::opt<bool>
63 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
64        cl::desc("Sink common instructions down to the end block"));
65
66 static cl::opt<bool> HoistCondStores(
67     "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
68     cl::desc("Hoist conditional stores if an unconditional store precedes"));
69
70 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
71 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
72 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
73 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
74 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
75
76 namespace {
77   /// ValueEqualityComparisonCase - Represents a case of a switch.
78   struct ValueEqualityComparisonCase {
79     ConstantInt *Value;
80     BasicBlock *Dest;
81
82     ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
83       : Value(Value), Dest(Dest) {}
84
85     bool operator<(ValueEqualityComparisonCase RHS) const {
86       // Comparing pointers is ok as we only rely on the order for uniquing.
87       return Value < RHS.Value;
88     }
89
90     bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
91   };
92
93 class SimplifyCFGOpt {
94   const TargetTransformInfo &TTI;
95   const DataLayout *const DL;
96   Value *isValueEqualityComparison(TerminatorInst *TI);
97   BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
98                                std::vector<ValueEqualityComparisonCase> &Cases);
99   bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
100                                                      BasicBlock *Pred,
101                                                      IRBuilder<> &Builder);
102   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
103                                            IRBuilder<> &Builder);
104
105   bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
106   bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
107   bool SimplifyUnreachable(UnreachableInst *UI);
108   bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
109   bool SimplifyIndirectBr(IndirectBrInst *IBI);
110   bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
111   bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
112
113 public:
114   SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL)
115       : TTI(TTI), DL(DL) {}
116   bool run(BasicBlock *BB);
117 };
118 }
119
120 /// SafeToMergeTerminators - Return true if it is safe to merge these two
121 /// terminator instructions together.
122 ///
123 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
124   if (SI1 == SI2) return false;  // Can't merge with self!
125
126   // It is not safe to merge these two switch instructions if they have a common
127   // successor, and if that successor has a PHI node, and if *that* PHI node has
128   // conflicting incoming values from the two switch blocks.
129   BasicBlock *SI1BB = SI1->getParent();
130   BasicBlock *SI2BB = SI2->getParent();
131   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
132
133   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
134     if (SI1Succs.count(*I))
135       for (BasicBlock::iterator BBI = (*I)->begin();
136            isa<PHINode>(BBI); ++BBI) {
137         PHINode *PN = cast<PHINode>(BBI);
138         if (PN->getIncomingValueForBlock(SI1BB) !=
139             PN->getIncomingValueForBlock(SI2BB))
140           return false;
141       }
142
143   return true;
144 }
145
146 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
147 /// to merge these two terminator instructions together, where SI1 is an
148 /// unconditional branch. PhiNodes will store all PHI nodes in common
149 /// successors.
150 ///
151 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
152                                           BranchInst *SI2,
153                                           Instruction *Cond,
154                                           SmallVectorImpl<PHINode*> &PhiNodes) {
155   if (SI1 == SI2) return false;  // Can't merge with self!
156   assert(SI1->isUnconditional() && SI2->isConditional());
157
158   // We fold the unconditional branch if we can easily update all PHI nodes in
159   // common successors:
160   // 1> We have a constant incoming value for the conditional branch;
161   // 2> We have "Cond" as the incoming value for the unconditional branch;
162   // 3> SI2->getCondition() and Cond have same operands.
163   CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
164   if (!Ci2) return false;
165   if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
166         Cond->getOperand(1) == Ci2->getOperand(1)) &&
167       !(Cond->getOperand(0) == Ci2->getOperand(1) &&
168         Cond->getOperand(1) == Ci2->getOperand(0)))
169     return false;
170
171   BasicBlock *SI1BB = SI1->getParent();
172   BasicBlock *SI2BB = SI2->getParent();
173   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
174   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
175     if (SI1Succs.count(*I))
176       for (BasicBlock::iterator BBI = (*I)->begin();
177            isa<PHINode>(BBI); ++BBI) {
178         PHINode *PN = cast<PHINode>(BBI);
179         if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
180             !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
181           return false;
182         PhiNodes.push_back(PN);
183       }
184   return true;
185 }
186
187 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
188 /// now be entries in it from the 'NewPred' block.  The values that will be
189 /// flowing into the PHI nodes will be the same as those coming in from
190 /// ExistPred, an existing predecessor of Succ.
191 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
192                                   BasicBlock *ExistPred) {
193   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
194
195   PHINode *PN;
196   for (BasicBlock::iterator I = Succ->begin();
197        (PN = dyn_cast<PHINode>(I)); ++I)
198     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
199 }
200
201 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
202 /// given instruction, which is assumed to be safe to speculate. 1 means
203 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
204 static unsigned ComputeSpeculationCost(const User *I) {
205   assert(isSafeToSpeculativelyExecute(I) &&
206          "Instruction is not safe to speculatively execute!");
207   switch (Operator::getOpcode(I)) {
208   default:
209     // In doubt, be conservative.
210     return UINT_MAX;
211   case Instruction::GetElementPtr:
212     // GEPs are cheap if all indices are constant.
213     if (!cast<GEPOperator>(I)->hasAllConstantIndices())
214       return UINT_MAX;
215     return 1;
216   case Instruction::ExtractValue:
217   case Instruction::Load:
218   case Instruction::Add:
219   case Instruction::Sub:
220   case Instruction::And:
221   case Instruction::Or:
222   case Instruction::Xor:
223   case Instruction::Shl:
224   case Instruction::LShr:
225   case Instruction::AShr:
226   case Instruction::ICmp:
227   case Instruction::Trunc:
228   case Instruction::ZExt:
229   case Instruction::SExt:
230   case Instruction::BitCast:
231   case Instruction::ExtractElement:
232   case Instruction::InsertElement:
233     return 1; // These are all cheap.
234
235   case Instruction::Call:
236   case Instruction::Select:
237     return 2;
238   }
239 }
240
241 /// DominatesMergePoint - If we have a merge point of an "if condition" as
242 /// accepted above, return true if the specified value dominates the block.  We
243 /// don't handle the true generality of domination here, just a special case
244 /// which works well enough for us.
245 ///
246 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
247 /// see if V (which must be an instruction) and its recursive operands
248 /// that do not dominate BB have a combined cost lower than CostRemaining and
249 /// are non-trapping.  If both are true, the instruction is inserted into the
250 /// set and true is returned.
251 ///
252 /// The cost for most non-trapping instructions is defined as 1 except for
253 /// Select whose cost is 2.
254 ///
255 /// After this function returns, CostRemaining is decreased by the cost of
256 /// V plus its non-dominating operands.  If that cost is greater than
257 /// CostRemaining, false is returned and CostRemaining is undefined.
258 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
259                                 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
260                                 unsigned &CostRemaining) {
261   Instruction *I = dyn_cast<Instruction>(V);
262   if (!I) {
263     // Non-instructions all dominate instructions, but not all constantexprs
264     // can be executed unconditionally.
265     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
266       if (C->canTrap())
267         return false;
268     return true;
269   }
270   BasicBlock *PBB = I->getParent();
271
272   // We don't want to allow weird loops that might have the "if condition" in
273   // the bottom of this block.
274   if (PBB == BB) return false;
275
276   // If this instruction is defined in a block that contains an unconditional
277   // branch to BB, then it must be in the 'conditional' part of the "if
278   // statement".  If not, it definitely dominates the region.
279   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
280   if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
281     return true;
282
283   // If we aren't allowing aggressive promotion anymore, then don't consider
284   // instructions in the 'if region'.
285   if (!AggressiveInsts) return false;
286
287   // If we have seen this instruction before, don't count it again.
288   if (AggressiveInsts->count(I)) return true;
289
290   // Okay, it looks like the instruction IS in the "condition".  Check to
291   // see if it's a cheap instruction to unconditionally compute, and if it
292   // only uses stuff defined outside of the condition.  If so, hoist it out.
293   if (!isSafeToSpeculativelyExecute(I))
294     return false;
295
296   unsigned Cost = ComputeSpeculationCost(I);
297
298   if (Cost > CostRemaining)
299     return false;
300
301   CostRemaining -= Cost;
302
303   // Okay, we can only really hoist these out if their operands do
304   // not take us over the cost threshold.
305   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
306     if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
307       return false;
308   // Okay, it's safe to do this!  Remember this instruction.
309   AggressiveInsts->insert(I);
310   return true;
311 }
312
313 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
314 /// and PointerNullValue. Return NULL if value is not a constant int.
315 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
316   // Normal constant int.
317   ConstantInt *CI = dyn_cast<ConstantInt>(V);
318   if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
319     return CI;
320
321   // This is some kind of pointer constant. Turn it into a pointer-sized
322   // ConstantInt if possible.
323   IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
324
325   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
326   if (isa<ConstantPointerNull>(V))
327     return ConstantInt::get(PtrTy, 0);
328
329   // IntToPtr const int.
330   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
331     if (CE->getOpcode() == Instruction::IntToPtr)
332       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
333         // The constant is very likely to have the right type already.
334         if (CI->getType() == PtrTy)
335           return CI;
336         else
337           return cast<ConstantInt>
338             (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
339       }
340   return nullptr;
341 }
342
343 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
344 /// collection of icmp eq/ne instructions that compare a value against a
345 /// constant, return the value being compared, and stick the constant into the
346 /// Values vector.
347 static Value *
348 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
349                        const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
350   Instruction *I = dyn_cast<Instruction>(V);
351   if (!I) return nullptr;
352
353   // If this is an icmp against a constant, handle this as one of the cases.
354   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
355     if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
356       Value *RHSVal;
357       ConstantInt *RHSC;
358
359       if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
360         // (x & ~2^x) == y --> x == y || x == y|2^x
361         // This undoes a transformation done by instcombine to fuse 2 compares.
362         if (match(ICI->getOperand(0),
363                   m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
364           APInt Not = ~RHSC->getValue();
365           if (Not.isPowerOf2()) {
366             Vals.push_back(C);
367             Vals.push_back(
368                 ConstantInt::get(C->getContext(), C->getValue() | Not));
369             UsedICmps++;
370             return RHSVal;
371           }
372         }
373
374         UsedICmps++;
375         Vals.push_back(C);
376         return I->getOperand(0);
377       }
378
379       // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
380       // the set.
381       ConstantRange Span =
382         ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
383
384       // Shift the range if the compare is fed by an add. This is the range
385       // compare idiom as emitted by instcombine.
386       bool hasAdd =
387           match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
388       if (hasAdd)
389         Span = Span.subtract(RHSC->getValue());
390
391       // If this is an and/!= check then we want to optimize "x ugt 2" into
392       // x != 0 && x != 1.
393       if (!isEQ)
394         Span = Span.inverse();
395
396       // If there are a ton of values, we don't want to make a ginormous switch.
397       if (Span.getSetSize().ugt(8) || Span.isEmptySet())
398         return nullptr;
399
400       for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
401         Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
402       UsedICmps++;
403       return hasAdd ? RHSVal : I->getOperand(0);
404     }
405     return nullptr;
406   }
407
408   // Otherwise, we can only handle an | or &, depending on isEQ.
409   if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
410     return nullptr;
411
412   unsigned NumValsBeforeLHS = Vals.size();
413   unsigned UsedICmpsBeforeLHS = UsedICmps;
414   if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
415                                           isEQ, UsedICmps)) {
416     unsigned NumVals = Vals.size();
417     unsigned UsedICmpsBeforeRHS = UsedICmps;
418     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
419                                             isEQ, UsedICmps)) {
420       if (LHS == RHS)
421         return LHS;
422       Vals.resize(NumVals);
423       UsedICmps = UsedICmpsBeforeRHS;
424     }
425
426     // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
427     // set it and return success.
428     if (Extra == nullptr || Extra == I->getOperand(1)) {
429       Extra = I->getOperand(1);
430       return LHS;
431     }
432
433     Vals.resize(NumValsBeforeLHS);
434     UsedICmps = UsedICmpsBeforeLHS;
435     return nullptr;
436   }
437
438   // If the LHS can't be folded in, but Extra is available and RHS can, try to
439   // use LHS as Extra.
440   if (Extra == nullptr || Extra == I->getOperand(0)) {
441     Value *OldExtra = Extra;
442     Extra = I->getOperand(0);
443     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
444                                             isEQ, UsedICmps))
445       return RHS;
446     assert(Vals.size() == NumValsBeforeLHS);
447     Extra = OldExtra;
448   }
449
450   return nullptr;
451 }
452
453 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
454   Instruction *Cond = nullptr;
455   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
456     Cond = dyn_cast<Instruction>(SI->getCondition());
457   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
458     if (BI->isConditional())
459       Cond = dyn_cast<Instruction>(BI->getCondition());
460   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
461     Cond = dyn_cast<Instruction>(IBI->getAddress());
462   }
463
464   TI->eraseFromParent();
465   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
466 }
467
468 /// isValueEqualityComparison - Return true if the specified terminator checks
469 /// to see if a value is equal to constant integer value.
470 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
471   Value *CV = nullptr;
472   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473     // Do not permit merging of large switch instructions into their
474     // predecessors unless there is only one predecessor.
475     if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
476                                              pred_end(SI->getParent())) <= 128)
477       CV = SI->getCondition();
478   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
479     if (BI->isConditional() && BI->getCondition()->hasOneUse())
480       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
481         if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
482           CV = ICI->getOperand(0);
483
484   // Unwrap any lossless ptrtoint cast.
485   if (DL && CV) {
486     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
487       Value *Ptr = PTII->getPointerOperand();
488       if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
489         CV = Ptr;
490     }
491   }
492   return CV;
493 }
494
495 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
496 /// decode all of the 'cases' that it represents and return the 'default' block.
497 BasicBlock *SimplifyCFGOpt::
498 GetValueEqualityComparisonCases(TerminatorInst *TI,
499                                 std::vector<ValueEqualityComparisonCase>
500                                                                        &Cases) {
501   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
502     Cases.reserve(SI->getNumCases());
503     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
504       Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
505                                                   i.getCaseSuccessor()));
506     return SI->getDefaultDest();
507   }
508
509   BranchInst *BI = cast<BranchInst>(TI);
510   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
511   BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
512   Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
513                                                              DL),
514                                               Succ));
515   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
516 }
517
518
519 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
520 /// in the list that match the specified block.
521 static void EliminateBlockCases(BasicBlock *BB,
522                               std::vector<ValueEqualityComparisonCase> &Cases) {
523   Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
524 }
525
526 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
527 /// well.
528 static bool
529 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
530               std::vector<ValueEqualityComparisonCase > &C2) {
531   std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
532
533   // Make V1 be smaller than V2.
534   if (V1->size() > V2->size())
535     std::swap(V1, V2);
536
537   if (V1->size() == 0) return false;
538   if (V1->size() == 1) {
539     // Just scan V2.
540     ConstantInt *TheVal = (*V1)[0].Value;
541     for (unsigned i = 0, e = V2->size(); i != e; ++i)
542       if (TheVal == (*V2)[i].Value)
543         return true;
544   }
545
546   // Otherwise, just sort both lists and compare element by element.
547   array_pod_sort(V1->begin(), V1->end());
548   array_pod_sort(V2->begin(), V2->end());
549   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
550   while (i1 != e1 && i2 != e2) {
551     if ((*V1)[i1].Value == (*V2)[i2].Value)
552       return true;
553     if ((*V1)[i1].Value < (*V2)[i2].Value)
554       ++i1;
555     else
556       ++i2;
557   }
558   return false;
559 }
560
561 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
562 /// terminator instruction and its block is known to only have a single
563 /// predecessor block, check to see if that predecessor is also a value
564 /// comparison with the same value, and if that comparison determines the
565 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
566 /// form of jump threading.
567 bool SimplifyCFGOpt::
568 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
569                                               BasicBlock *Pred,
570                                               IRBuilder<> &Builder) {
571   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
572   if (!PredVal) return false;  // Not a value comparison in predecessor.
573
574   Value *ThisVal = isValueEqualityComparison(TI);
575   assert(ThisVal && "This isn't a value comparison!!");
576   if (ThisVal != PredVal) return false;  // Different predicates.
577
578   // TODO: Preserve branch weight metadata, similarly to how
579   // FoldValueComparisonIntoPredecessors preserves it.
580
581   // Find out information about when control will move from Pred to TI's block.
582   std::vector<ValueEqualityComparisonCase> PredCases;
583   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
584                                                         PredCases);
585   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
586
587   // Find information about how control leaves this block.
588   std::vector<ValueEqualityComparisonCase> ThisCases;
589   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
590   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
591
592   // If TI's block is the default block from Pred's comparison, potentially
593   // simplify TI based on this knowledge.
594   if (PredDef == TI->getParent()) {
595     // If we are here, we know that the value is none of those cases listed in
596     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
597     // can simplify TI.
598     if (!ValuesOverlap(PredCases, ThisCases))
599       return false;
600
601     if (isa<BranchInst>(TI)) {
602       // Okay, one of the successors of this condbr is dead.  Convert it to a
603       // uncond br.
604       assert(ThisCases.size() == 1 && "Branch can only have one case!");
605       // Insert the new branch.
606       Instruction *NI = Builder.CreateBr(ThisDef);
607       (void) NI;
608
609       // Remove PHI node entries for the dead edge.
610       ThisCases[0].Dest->removePredecessor(TI->getParent());
611
612       DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
613            << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
614
615       EraseTerminatorInstAndDCECond(TI);
616       return true;
617     }
618
619     SwitchInst *SI = cast<SwitchInst>(TI);
620     // Okay, TI has cases that are statically dead, prune them away.
621     SmallPtrSet<Constant*, 16> DeadCases;
622     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
623       DeadCases.insert(PredCases[i].Value);
624
625     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
626                  << "Through successor TI: " << *TI);
627
628     // Collect branch weights into a vector.
629     SmallVector<uint32_t, 8> Weights;
630     MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
631     bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
632     if (HasWeight)
633       for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
634            ++MD_i) {
635         ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
636         assert(CI);
637         Weights.push_back(CI->getValue().getZExtValue());
638       }
639     for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
640       --i;
641       if (DeadCases.count(i.getCaseValue())) {
642         if (HasWeight) {
643           std::swap(Weights[i.getCaseIndex()+1], Weights.back());
644           Weights.pop_back();
645         }
646         i.getCaseSuccessor()->removePredecessor(TI->getParent());
647         SI->removeCase(i);
648       }
649     }
650     if (HasWeight && Weights.size() >= 2)
651       SI->setMetadata(LLVMContext::MD_prof,
652                       MDBuilder(SI->getParent()->getContext()).
653                       createBranchWeights(Weights));
654
655     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
656     return true;
657   }
658
659   // Otherwise, TI's block must correspond to some matched value.  Find out
660   // which value (or set of values) this is.
661   ConstantInt *TIV = nullptr;
662   BasicBlock *TIBB = TI->getParent();
663   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
664     if (PredCases[i].Dest == TIBB) {
665       if (TIV)
666         return false;  // Cannot handle multiple values coming to this block.
667       TIV = PredCases[i].Value;
668     }
669   assert(TIV && "No edge from pred to succ?");
670
671   // Okay, we found the one constant that our value can be if we get into TI's
672   // BB.  Find out which successor will unconditionally be branched to.
673   BasicBlock *TheRealDest = nullptr;
674   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
675     if (ThisCases[i].Value == TIV) {
676       TheRealDest = ThisCases[i].Dest;
677       break;
678     }
679
680   // If not handled by any explicit cases, it is handled by the default case.
681   if (!TheRealDest) TheRealDest = ThisDef;
682
683   // Remove PHI node entries for dead edges.
684   BasicBlock *CheckEdge = TheRealDest;
685   for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
686     if (*SI != CheckEdge)
687       (*SI)->removePredecessor(TIBB);
688     else
689       CheckEdge = nullptr;
690
691   // Insert the new branch.
692   Instruction *NI = Builder.CreateBr(TheRealDest);
693   (void) NI;
694
695   DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
696             << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
697
698   EraseTerminatorInstAndDCECond(TI);
699   return true;
700 }
701
702 namespace {
703   /// ConstantIntOrdering - This class implements a stable ordering of constant
704   /// integers that does not depend on their address.  This is important for
705   /// applications that sort ConstantInt's to ensure uniqueness.
706   struct ConstantIntOrdering {
707     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
708       return LHS->getValue().ult(RHS->getValue());
709     }
710   };
711 }
712
713 static int ConstantIntSortPredicate(ConstantInt *const *P1,
714                                     ConstantInt *const *P2) {
715   const ConstantInt *LHS = *P1;
716   const ConstantInt *RHS = *P2;
717   if (LHS->getValue().ult(RHS->getValue()))
718     return 1;
719   if (LHS->getValue() == RHS->getValue())
720     return 0;
721   return -1;
722 }
723
724 static inline bool HasBranchWeights(const Instruction* I) {
725   MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
726   if (ProfMD && ProfMD->getOperand(0))
727     if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
728       return MDS->getString().equals("branch_weights");
729
730   return false;
731 }
732
733 /// Get Weights of a given TerminatorInst, the default weight is at the front
734 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
735 /// metadata.
736 static void GetBranchWeights(TerminatorInst *TI,
737                              SmallVectorImpl<uint64_t> &Weights) {
738   MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
739   assert(MD);
740   for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
741     ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
742     Weights.push_back(CI->getValue().getZExtValue());
743   }
744
745   // If TI is a conditional eq, the default case is the false case,
746   // and the corresponding branch-weight data is at index 2. We swap the
747   // default weight to be the first entry.
748   if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
749     assert(Weights.size() == 2);
750     ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
751     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
752       std::swap(Weights.front(), Weights.back());
753   }
754 }
755
756 /// Keep halving the weights until all can fit in uint32_t.
757 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
758   uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
759   if (Max > UINT_MAX) {
760     unsigned Offset = 32 - countLeadingZeros(Max);
761     for (uint64_t &I : Weights)
762       I >>= Offset;
763   }
764 }
765
766 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
767 /// equality comparison instruction (either a switch or a branch on "X == c").
768 /// See if any of the predecessors of the terminator block are value comparisons
769 /// on the same value.  If so, and if safe to do so, fold them together.
770 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
771                                                          IRBuilder<> &Builder) {
772   BasicBlock *BB = TI->getParent();
773   Value *CV = isValueEqualityComparison(TI);  // CondVal
774   assert(CV && "Not a comparison?");
775   bool Changed = false;
776
777   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
778   while (!Preds.empty()) {
779     BasicBlock *Pred = Preds.pop_back_val();
780
781     // See if the predecessor is a comparison with the same value.
782     TerminatorInst *PTI = Pred->getTerminator();
783     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
784
785     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
786       // Figure out which 'cases' to copy from SI to PSI.
787       std::vector<ValueEqualityComparisonCase> BBCases;
788       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
789
790       std::vector<ValueEqualityComparisonCase> PredCases;
791       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
792
793       // Based on whether the default edge from PTI goes to BB or not, fill in
794       // PredCases and PredDefault with the new switch cases we would like to
795       // build.
796       SmallVector<BasicBlock*, 8> NewSuccessors;
797
798       // Update the branch weight metadata along the way
799       SmallVector<uint64_t, 8> Weights;
800       bool PredHasWeights = HasBranchWeights(PTI);
801       bool SuccHasWeights = HasBranchWeights(TI);
802
803       if (PredHasWeights) {
804         GetBranchWeights(PTI, Weights);
805         // branch-weight metadata is inconsistent here.
806         if (Weights.size() != 1 + PredCases.size())
807           PredHasWeights = SuccHasWeights = false;
808       } else if (SuccHasWeights)
809         // If there are no predecessor weights but there are successor weights,
810         // populate Weights with 1, which will later be scaled to the sum of
811         // successor's weights
812         Weights.assign(1 + PredCases.size(), 1);
813
814       SmallVector<uint64_t, 8> SuccWeights;
815       if (SuccHasWeights) {
816         GetBranchWeights(TI, SuccWeights);
817         // branch-weight metadata is inconsistent here.
818         if (SuccWeights.size() != 1 + BBCases.size())
819           PredHasWeights = SuccHasWeights = false;
820       } else if (PredHasWeights)
821         SuccWeights.assign(1 + BBCases.size(), 1);
822
823       if (PredDefault == BB) {
824         // If this is the default destination from PTI, only the edges in TI
825         // that don't occur in PTI, or that branch to BB will be activated.
826         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
827         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
828           if (PredCases[i].Dest != BB)
829             PTIHandled.insert(PredCases[i].Value);
830           else {
831             // The default destination is BB, we don't need explicit targets.
832             std::swap(PredCases[i], PredCases.back());
833
834             if (PredHasWeights || SuccHasWeights) {
835               // Increase weight for the default case.
836               Weights[0] += Weights[i+1];
837               std::swap(Weights[i+1], Weights.back());
838               Weights.pop_back();
839             }
840
841             PredCases.pop_back();
842             --i; --e;
843           }
844
845         // Reconstruct the new switch statement we will be building.
846         if (PredDefault != BBDefault) {
847           PredDefault->removePredecessor(Pred);
848           PredDefault = BBDefault;
849           NewSuccessors.push_back(BBDefault);
850         }
851
852         unsigned CasesFromPred = Weights.size();
853         uint64_t ValidTotalSuccWeight = 0;
854         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
855           if (!PTIHandled.count(BBCases[i].Value) &&
856               BBCases[i].Dest != BBDefault) {
857             PredCases.push_back(BBCases[i]);
858             NewSuccessors.push_back(BBCases[i].Dest);
859             if (SuccHasWeights || PredHasWeights) {
860               // The default weight is at index 0, so weight for the ith case
861               // should be at index i+1. Scale the cases from successor by
862               // PredDefaultWeight (Weights[0]).
863               Weights.push_back(Weights[0] * SuccWeights[i+1]);
864               ValidTotalSuccWeight += SuccWeights[i+1];
865             }
866           }
867
868         if (SuccHasWeights || PredHasWeights) {
869           ValidTotalSuccWeight += SuccWeights[0];
870           // Scale the cases from predecessor by ValidTotalSuccWeight.
871           for (unsigned i = 1; i < CasesFromPred; ++i)
872             Weights[i] *= ValidTotalSuccWeight;
873           // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
874           Weights[0] *= SuccWeights[0];
875         }
876       } else {
877         // If this is not the default destination from PSI, only the edges
878         // in SI that occur in PSI with a destination of BB will be
879         // activated.
880         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
881         std::map<ConstantInt*, uint64_t> WeightsForHandled;
882         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
883           if (PredCases[i].Dest == BB) {
884             PTIHandled.insert(PredCases[i].Value);
885
886             if (PredHasWeights || SuccHasWeights) {
887               WeightsForHandled[PredCases[i].Value] = Weights[i+1];
888               std::swap(Weights[i+1], Weights.back());
889               Weights.pop_back();
890             }
891
892             std::swap(PredCases[i], PredCases.back());
893             PredCases.pop_back();
894             --i; --e;
895           }
896
897         // Okay, now we know which constants were sent to BB from the
898         // predecessor.  Figure out where they will all go now.
899         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
900           if (PTIHandled.count(BBCases[i].Value)) {
901             // If this is one we are capable of getting...
902             if (PredHasWeights || SuccHasWeights)
903               Weights.push_back(WeightsForHandled[BBCases[i].Value]);
904             PredCases.push_back(BBCases[i]);
905             NewSuccessors.push_back(BBCases[i].Dest);
906             PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
907           }
908
909         // If there are any constants vectored to BB that TI doesn't handle,
910         // they must go to the default destination of TI.
911         for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
912                                     PTIHandled.begin(),
913                E = PTIHandled.end(); I != E; ++I) {
914           if (PredHasWeights || SuccHasWeights)
915             Weights.push_back(WeightsForHandled[*I]);
916           PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
917           NewSuccessors.push_back(BBDefault);
918         }
919       }
920
921       // Okay, at this point, we know which new successor Pred will get.  Make
922       // sure we update the number of entries in the PHI nodes for these
923       // successors.
924       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
925         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
926
927       Builder.SetInsertPoint(PTI);
928       // Convert pointer to int before we switch.
929       if (CV->getType()->isPointerTy()) {
930         assert(DL && "Cannot switch on pointer without DataLayout");
931         CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
932                                     "magicptr");
933       }
934
935       // Now that the successors are updated, create the new Switch instruction.
936       SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
937                                                PredCases.size());
938       NewSI->setDebugLoc(PTI->getDebugLoc());
939       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
940         NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
941
942       if (PredHasWeights || SuccHasWeights) {
943         // Halve the weights if any of them cannot fit in an uint32_t
944         FitWeights(Weights);
945
946         SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
947
948         NewSI->setMetadata(LLVMContext::MD_prof,
949                            MDBuilder(BB->getContext()).
950                            createBranchWeights(MDWeights));
951       }
952
953       EraseTerminatorInstAndDCECond(PTI);
954
955       // Okay, last check.  If BB is still a successor of PSI, then we must
956       // have an infinite loop case.  If so, add an infinitely looping block
957       // to handle the case to preserve the behavior of the code.
958       BasicBlock *InfLoopBlock = nullptr;
959       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
960         if (NewSI->getSuccessor(i) == BB) {
961           if (!InfLoopBlock) {
962             // Insert it at the end of the function, because it's either code,
963             // or it won't matter if it's hot. :)
964             InfLoopBlock = BasicBlock::Create(BB->getContext(),
965                                               "infloop", BB->getParent());
966             BranchInst::Create(InfLoopBlock, InfLoopBlock);
967           }
968           NewSI->setSuccessor(i, InfLoopBlock);
969         }
970
971       Changed = true;
972     }
973   }
974   return Changed;
975 }
976
977 // isSafeToHoistInvoke - If we would need to insert a select that uses the
978 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
979 // would need to do this), we can't hoist the invoke, as there is nowhere
980 // to put the select in this case.
981 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
982                                 Instruction *I1, Instruction *I2) {
983   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
984     PHINode *PN;
985     for (BasicBlock::iterator BBI = SI->begin();
986          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
987       Value *BB1V = PN->getIncomingValueForBlock(BB1);
988       Value *BB2V = PN->getIncomingValueForBlock(BB2);
989       if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
990         return false;
991       }
992     }
993   }
994   return true;
995 }
996
997 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
998 /// BB2, hoist any common code in the two blocks up into the branch block.  The
999 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1000 static bool HoistThenElseCodeToIf(BranchInst *BI) {
1001   // This does very trivial matching, with limited scanning, to find identical
1002   // instructions in the two blocks.  In particular, we don't want to get into
1003   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
1004   // such, we currently just scan for obviously identical instructions in an
1005   // identical order.
1006   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
1007   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
1008
1009   BasicBlock::iterator BB1_Itr = BB1->begin();
1010   BasicBlock::iterator BB2_Itr = BB2->begin();
1011
1012   Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1013   // Skip debug info if it is not identical.
1014   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1015   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1016   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1017     while (isa<DbgInfoIntrinsic>(I1))
1018       I1 = BB1_Itr++;
1019     while (isa<DbgInfoIntrinsic>(I2))
1020       I2 = BB2_Itr++;
1021   }
1022   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1023       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1024     return false;
1025
1026   BasicBlock *BIParent = BI->getParent();
1027
1028   bool Changed = false;
1029   do {
1030     // If we are hoisting the terminator instruction, don't move one (making a
1031     // broken BB), instead clone it, and remove BI.
1032     if (isa<TerminatorInst>(I1))
1033       goto HoistTerminator;
1034
1035     // For a normal instruction, we just move one to right before the branch,
1036     // then replace all uses of the other with the first.  Finally, we remove
1037     // the now redundant second instruction.
1038     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1039     if (!I2->use_empty())
1040       I2->replaceAllUsesWith(I1);
1041     I1->intersectOptionalDataWith(I2);
1042     I2->eraseFromParent();
1043     Changed = true;
1044
1045     I1 = BB1_Itr++;
1046     I2 = BB2_Itr++;
1047     // Skip debug info if it is not identical.
1048     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1049     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1050     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1051       while (isa<DbgInfoIntrinsic>(I1))
1052         I1 = BB1_Itr++;
1053       while (isa<DbgInfoIntrinsic>(I2))
1054         I2 = BB2_Itr++;
1055     }
1056   } while (I1->isIdenticalToWhenDefined(I2));
1057
1058   return true;
1059
1060 HoistTerminator:
1061   // It may not be possible to hoist an invoke.
1062   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1063     return Changed;
1064
1065   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1066     PHINode *PN;
1067     for (BasicBlock::iterator BBI = SI->begin();
1068          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1069       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1070       Value *BB2V = PN->getIncomingValueForBlock(BB2);
1071       if (BB1V == BB2V)
1072         continue;
1073
1074       if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1075         return Changed;
1076       if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1077         return Changed;
1078     }
1079   }
1080
1081   // Okay, it is safe to hoist the terminator.
1082   Instruction *NT = I1->clone();
1083   BIParent->getInstList().insert(BI, NT);
1084   if (!NT->getType()->isVoidTy()) {
1085     I1->replaceAllUsesWith(NT);
1086     I2->replaceAllUsesWith(NT);
1087     NT->takeName(I1);
1088   }
1089
1090   IRBuilder<true, NoFolder> Builder(NT);
1091   // Hoisting one of the terminators from our successor is a great thing.
1092   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1093   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
1094   // nodes, so we insert select instruction to compute the final result.
1095   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1096   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1097     PHINode *PN;
1098     for (BasicBlock::iterator BBI = SI->begin();
1099          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1100       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1101       Value *BB2V = PN->getIncomingValueForBlock(BB2);
1102       if (BB1V == BB2V) continue;
1103
1104       // These values do not agree.  Insert a select instruction before NT
1105       // that determines the right value.
1106       SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1107       if (!SI)
1108         SI = cast<SelectInst>
1109           (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1110                                 BB1V->getName()+"."+BB2V->getName()));
1111
1112       // Make the PHI node use the select for all incoming values for BB1/BB2
1113       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1114         if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1115           PN->setIncomingValue(i, SI);
1116     }
1117   }
1118
1119   // Update any PHI nodes in our new successors.
1120   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1121     AddPredecessorToBlock(*SI, BIParent, BB1);
1122
1123   EraseTerminatorInstAndDCECond(BI);
1124   return true;
1125 }
1126
1127 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1128 /// check whether BBEnd has only two predecessors and the other predecessor
1129 /// ends with an unconditional branch. If it is true, sink any common code
1130 /// in the two predecessors to BBEnd.
1131 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1132   assert(BI1->isUnconditional());
1133   BasicBlock *BB1 = BI1->getParent();
1134   BasicBlock *BBEnd = BI1->getSuccessor(0);
1135
1136   // Check that BBEnd has two predecessors and the other predecessor ends with
1137   // an unconditional branch.
1138   pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1139   BasicBlock *Pred0 = *PI++;
1140   if (PI == PE) // Only one predecessor.
1141     return false;
1142   BasicBlock *Pred1 = *PI++;
1143   if (PI != PE) // More than two predecessors.
1144     return false;
1145   BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1146   BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1147   if (!BI2 || !BI2->isUnconditional())
1148     return false;
1149
1150   // Gather the PHI nodes in BBEnd.
1151   std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1152   Instruction *FirstNonPhiInBBEnd = nullptr;
1153   for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1154        I != E; ++I) {
1155     if (PHINode *PN = dyn_cast<PHINode>(I)) {
1156       Value *BB1V = PN->getIncomingValueForBlock(BB1);
1157       Value *BB2V = PN->getIncomingValueForBlock(BB2);
1158       MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1159     } else {
1160       FirstNonPhiInBBEnd = &*I;
1161       break;
1162     }
1163   }
1164   if (!FirstNonPhiInBBEnd)
1165     return false;
1166
1167
1168   // This does very trivial matching, with limited scanning, to find identical
1169   // instructions in the two blocks.  We scan backward for obviously identical
1170   // instructions in an identical order.
1171   BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1172       RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1173       RE2 = BB2->getInstList().rend();
1174   // Skip debug info.
1175   while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1176   if (RI1 == RE1)
1177     return false;
1178   while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1179   if (RI2 == RE2)
1180     return false;
1181   // Skip the unconditional branches.
1182   ++RI1;
1183   ++RI2;
1184
1185   bool Changed = false;
1186   while (RI1 != RE1 && RI2 != RE2) {
1187     // Skip debug info.
1188     while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1189     if (RI1 == RE1)
1190       return Changed;
1191     while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1192     if (RI2 == RE2)
1193       return Changed;
1194
1195     Instruction *I1 = &*RI1, *I2 = &*RI2;
1196     // I1 and I2 should have a single use in the same PHI node, and they
1197     // perform the same operation.
1198     // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1199     if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1200         isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1201         isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1202         isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1203         I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1204         I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1205         !I1->hasOneUse() || !I2->hasOneUse() ||
1206         MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1207         MapValueFromBB1ToBB2[I1].first != I2)
1208       return Changed;
1209
1210     // Check whether we should swap the operands of ICmpInst.
1211     ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1212     bool SwapOpnds = false;
1213     if (ICmp1 && ICmp2 &&
1214         ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1215         ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1216         (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1217          ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1218       ICmp2->swapOperands();
1219       SwapOpnds = true;
1220     }
1221     if (!I1->isSameOperationAs(I2)) {
1222       if (SwapOpnds)
1223         ICmp2->swapOperands();
1224       return Changed;
1225     }
1226
1227     // The operands should be either the same or they need to be generated
1228     // with a PHI node after sinking. We only handle the case where there is
1229     // a single pair of different operands.
1230     Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1231     unsigned Op1Idx = 0;
1232     for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1233       if (I1->getOperand(I) == I2->getOperand(I))
1234         continue;
1235       // Early exit if we have more-than one pair of different operands or
1236       // the different operand is already in MapValueFromBB1ToBB2.
1237       // Early exit if we need a PHI node to replace a constant.
1238       if (DifferentOp1 ||
1239           MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1240           MapValueFromBB1ToBB2.end() ||
1241           isa<Constant>(I1->getOperand(I)) ||
1242           isa<Constant>(I2->getOperand(I))) {
1243         // If we can't sink the instructions, undo the swapping.
1244         if (SwapOpnds)
1245           ICmp2->swapOperands();
1246         return Changed;
1247       }
1248       DifferentOp1 = I1->getOperand(I);
1249       Op1Idx = I;
1250       DifferentOp2 = I2->getOperand(I);
1251     }
1252
1253     // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1254     // remove (I1, I2) from MapValueFromBB1ToBB2.
1255     if (DifferentOp1) {
1256       PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1257                                        DifferentOp1->getName() + ".sink",
1258                                        BBEnd->begin());
1259       MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1260       // I1 should use NewPN instead of DifferentOp1.
1261       I1->setOperand(Op1Idx, NewPN);
1262       NewPN->addIncoming(DifferentOp1, BB1);
1263       NewPN->addIncoming(DifferentOp2, BB2);
1264       DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1265     }
1266     PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1267     MapValueFromBB1ToBB2.erase(I1);
1268
1269     DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1270     DEBUG(dbgs() << "                         " << *I2 << "\n";);
1271     // We need to update RE1 and RE2 if we are going to sink the first
1272     // instruction in the basic block down.
1273     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1274     // Sink the instruction.
1275     BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1276     if (!OldPN->use_empty())
1277       OldPN->replaceAllUsesWith(I1);
1278     OldPN->eraseFromParent();
1279
1280     if (!I2->use_empty())
1281       I2->replaceAllUsesWith(I1);
1282     I1->intersectOptionalDataWith(I2);
1283     I2->eraseFromParent();
1284
1285     if (UpdateRE1)
1286       RE1 = BB1->getInstList().rend();
1287     if (UpdateRE2)
1288       RE2 = BB2->getInstList().rend();
1289     FirstNonPhiInBBEnd = I1;
1290     NumSinkCommons++;
1291     Changed = true;
1292   }
1293   return Changed;
1294 }
1295
1296 /// \brief Determine if we can hoist sink a sole store instruction out of a
1297 /// conditional block.
1298 ///
1299 /// We are looking for code like the following:
1300 ///   BrBB:
1301 ///     store i32 %add, i32* %arrayidx2
1302 ///     ... // No other stores or function calls (we could be calling a memory
1303 ///     ... // function).
1304 ///     %cmp = icmp ult %x, %y
1305 ///     br i1 %cmp, label %EndBB, label %ThenBB
1306 ///   ThenBB:
1307 ///     store i32 %add5, i32* %arrayidx2
1308 ///     br label EndBB
1309 ///   EndBB:
1310 ///     ...
1311 ///   We are going to transform this into:
1312 ///   BrBB:
1313 ///     store i32 %add, i32* %arrayidx2
1314 ///     ... //
1315 ///     %cmp = icmp ult %x, %y
1316 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
1317 ///     store i32 %add.add5, i32* %arrayidx2
1318 ///     ...
1319 ///
1320 /// \return The pointer to the value of the previous store if the store can be
1321 ///         hoisted into the predecessor block. 0 otherwise.
1322 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1323                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
1324   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1325   if (!StoreToHoist)
1326     return nullptr;
1327
1328   // Volatile or atomic.
1329   if (!StoreToHoist->isSimple())
1330     return nullptr;
1331
1332   Value *StorePtr = StoreToHoist->getPointerOperand();
1333
1334   // Look for a store to the same pointer in BrBB.
1335   unsigned MaxNumInstToLookAt = 10;
1336   for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1337        RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1338     Instruction *CurI = &*RI;
1339
1340     // Could be calling an instruction that effects memory like free().
1341     if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1342       return nullptr;
1343
1344     StoreInst *SI = dyn_cast<StoreInst>(CurI);
1345     // Found the previous store make sure it stores to the same location.
1346     if (SI && SI->getPointerOperand() == StorePtr)
1347       // Found the previous store, return its value operand.
1348       return SI->getValueOperand();
1349     else if (SI)
1350       return nullptr; // Unknown store.
1351   }
1352
1353   return nullptr;
1354 }
1355
1356 /// \brief Speculate a conditional basic block flattening the CFG.
1357 ///
1358 /// Note that this is a very risky transform currently. Speculating
1359 /// instructions like this is most often not desirable. Instead, there is an MI
1360 /// pass which can do it with full awareness of the resource constraints.
1361 /// However, some cases are "obvious" and we should do directly. An example of
1362 /// this is speculating a single, reasonably cheap instruction.
1363 ///
1364 /// There is only one distinct advantage to flattening the CFG at the IR level:
1365 /// it makes very common but simplistic optimizations such as are common in
1366 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1367 /// modeling their effects with easier to reason about SSA value graphs.
1368 ///
1369 ///
1370 /// An illustration of this transform is turning this IR:
1371 /// \code
1372 ///   BB:
1373 ///     %cmp = icmp ult %x, %y
1374 ///     br i1 %cmp, label %EndBB, label %ThenBB
1375 ///   ThenBB:
1376 ///     %sub = sub %x, %y
1377 ///     br label BB2
1378 ///   EndBB:
1379 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1380 ///     ...
1381 /// \endcode
1382 ///
1383 /// Into this IR:
1384 /// \code
1385 ///   BB:
1386 ///     %cmp = icmp ult %x, %y
1387 ///     %sub = sub %x, %y
1388 ///     %cond = select i1 %cmp, 0, %sub
1389 ///     ...
1390 /// \endcode
1391 ///
1392 /// \returns true if the conditional block is removed.
1393 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB) {
1394   // Be conservative for now. FP select instruction can often be expensive.
1395   Value *BrCond = BI->getCondition();
1396   if (isa<FCmpInst>(BrCond))
1397     return false;
1398
1399   BasicBlock *BB = BI->getParent();
1400   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1401
1402   // If ThenBB is actually on the false edge of the conditional branch, remember
1403   // to swap the select operands later.
1404   bool Invert = false;
1405   if (ThenBB != BI->getSuccessor(0)) {
1406     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1407     Invert = true;
1408   }
1409   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1410
1411   // Keep a count of how many times instructions are used within CondBB when
1412   // they are candidates for sinking into CondBB. Specifically:
1413   // - They are defined in BB, and
1414   // - They have no side effects, and
1415   // - All of their uses are in CondBB.
1416   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1417
1418   unsigned SpeculationCost = 0;
1419   Value *SpeculatedStoreValue = nullptr;
1420   StoreInst *SpeculatedStore = nullptr;
1421   for (BasicBlock::iterator BBI = ThenBB->begin(),
1422                             BBE = std::prev(ThenBB->end());
1423        BBI != BBE; ++BBI) {
1424     Instruction *I = BBI;
1425     // Skip debug info.
1426     if (isa<DbgInfoIntrinsic>(I))
1427       continue;
1428
1429     // Only speculatively execution a single instruction (not counting the
1430     // terminator) for now.
1431     ++SpeculationCost;
1432     if (SpeculationCost > 1)
1433       return false;
1434
1435     // Don't hoist the instruction if it's unsafe or expensive.
1436     if (!isSafeToSpeculativelyExecute(I) &&
1437         !(HoistCondStores &&
1438           (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1439                                                          EndBB))))
1440       return false;
1441     if (!SpeculatedStoreValue &&
1442         ComputeSpeculationCost(I) > PHINodeFoldingThreshold)
1443       return false;
1444
1445     // Store the store speculation candidate.
1446     if (SpeculatedStoreValue)
1447       SpeculatedStore = cast<StoreInst>(I);
1448
1449     // Do not hoist the instruction if any of its operands are defined but not
1450     // used in BB. The transformation will prevent the operand from
1451     // being sunk into the use block.
1452     for (User::op_iterator i = I->op_begin(), e = I->op_end();
1453          i != e; ++i) {
1454       Instruction *OpI = dyn_cast<Instruction>(*i);
1455       if (!OpI || OpI->getParent() != BB ||
1456           OpI->mayHaveSideEffects())
1457         continue; // Not a candidate for sinking.
1458
1459       ++SinkCandidateUseCounts[OpI];
1460     }
1461   }
1462
1463   // Consider any sink candidates which are only used in CondBB as costs for
1464   // speculation. Note, while we iterate over a DenseMap here, we are summing
1465   // and so iteration order isn't significant.
1466   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1467            SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1468        I != E; ++I)
1469     if (I->first->getNumUses() == I->second) {
1470       ++SpeculationCost;
1471       if (SpeculationCost > 1)
1472         return false;
1473     }
1474
1475   // Check that the PHI nodes can be converted to selects.
1476   bool HaveRewritablePHIs = false;
1477   for (BasicBlock::iterator I = EndBB->begin();
1478        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1479     Value *OrigV = PN->getIncomingValueForBlock(BB);
1480     Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1481
1482     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1483     // Skip PHIs which are trivial.
1484     if (ThenV == OrigV)
1485       continue;
1486
1487     HaveRewritablePHIs = true;
1488     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1489     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1490     if (!OrigCE && !ThenCE)
1491       continue; // Known safe and cheap.
1492
1493     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1494         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1495       return false;
1496     unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE) : 0;
1497     unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE) : 0;
1498     if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1499       return false;
1500
1501     // Account for the cost of an unfolded ConstantExpr which could end up
1502     // getting expanded into Instructions.
1503     // FIXME: This doesn't account for how many operations are combined in the
1504     // constant expression.
1505     ++SpeculationCost;
1506     if (SpeculationCost > 1)
1507       return false;
1508   }
1509
1510   // If there are no PHIs to process, bail early. This helps ensure idempotence
1511   // as well.
1512   if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1513     return false;
1514
1515   // If we get here, we can hoist the instruction and if-convert.
1516   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1517
1518   // Insert a select of the value of the speculated store.
1519   if (SpeculatedStoreValue) {
1520     IRBuilder<true, NoFolder> Builder(BI);
1521     Value *TrueV = SpeculatedStore->getValueOperand();
1522     Value *FalseV = SpeculatedStoreValue;
1523     if (Invert)
1524       std::swap(TrueV, FalseV);
1525     Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1526                                     "." + FalseV->getName());
1527     SpeculatedStore->setOperand(0, S);
1528   }
1529
1530   // Hoist the instructions.
1531   BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1532                            std::prev(ThenBB->end()));
1533
1534   // Insert selects and rewrite the PHI operands.
1535   IRBuilder<true, NoFolder> Builder(BI);
1536   for (BasicBlock::iterator I = EndBB->begin();
1537        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1538     unsigned OrigI = PN->getBasicBlockIndex(BB);
1539     unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1540     Value *OrigV = PN->getIncomingValue(OrigI);
1541     Value *ThenV = PN->getIncomingValue(ThenI);
1542
1543     // Skip PHIs which are trivial.
1544     if (OrigV == ThenV)
1545       continue;
1546
1547     // Create a select whose true value is the speculatively executed value and
1548     // false value is the preexisting value. Swap them if the branch
1549     // destinations were inverted.
1550     Value *TrueV = ThenV, *FalseV = OrigV;
1551     if (Invert)
1552       std::swap(TrueV, FalseV);
1553     Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1554                                     TrueV->getName() + "." + FalseV->getName());
1555     PN->setIncomingValue(OrigI, V);
1556     PN->setIncomingValue(ThenI, V);
1557   }
1558
1559   ++NumSpeculations;
1560   return true;
1561 }
1562
1563 /// \returns True if this block contains a CallInst with the NoDuplicate
1564 /// attribute.
1565 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1566   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1567     const CallInst *CI = dyn_cast<CallInst>(I);
1568     if (!CI)
1569       continue;
1570     if (CI->cannotDuplicate())
1571       return true;
1572   }
1573   return false;
1574 }
1575
1576 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1577 /// across this block.
1578 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1579   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1580   unsigned Size = 0;
1581
1582   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1583     if (isa<DbgInfoIntrinsic>(BBI))
1584       continue;
1585     if (Size > 10) return false;  // Don't clone large BB's.
1586     ++Size;
1587
1588     // We can only support instructions that do not define values that are
1589     // live outside of the current basic block.
1590     for (User *U : BBI->users()) {
1591       Instruction *UI = cast<Instruction>(U);
1592       if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1593     }
1594
1595     // Looks ok, continue checking.
1596   }
1597
1598   return true;
1599 }
1600
1601 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1602 /// that is defined in the same block as the branch and if any PHI entries are
1603 /// constants, thread edges corresponding to that entry to be branches to their
1604 /// ultimate destination.
1605 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1606   BasicBlock *BB = BI->getParent();
1607   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1608   // NOTE: we currently cannot transform this case if the PHI node is used
1609   // outside of the block.
1610   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1611     return false;
1612
1613   // Degenerate case of a single entry PHI.
1614   if (PN->getNumIncomingValues() == 1) {
1615     FoldSingleEntryPHINodes(PN->getParent());
1616     return true;
1617   }
1618
1619   // Now we know that this block has multiple preds and two succs.
1620   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1621
1622   if (HasNoDuplicateCall(BB)) return false;
1623
1624   // Okay, this is a simple enough basic block.  See if any phi values are
1625   // constants.
1626   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1627     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1628     if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1629
1630     // Okay, we now know that all edges from PredBB should be revectored to
1631     // branch to RealDest.
1632     BasicBlock *PredBB = PN->getIncomingBlock(i);
1633     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1634
1635     if (RealDest == BB) continue;  // Skip self loops.
1636     // Skip if the predecessor's terminator is an indirect branch.
1637     if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1638
1639     // The dest block might have PHI nodes, other predecessors and other
1640     // difficult cases.  Instead of being smart about this, just insert a new
1641     // block that jumps to the destination block, effectively splitting
1642     // the edge we are about to create.
1643     BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1644                                             RealDest->getName()+".critedge",
1645                                             RealDest->getParent(), RealDest);
1646     BranchInst::Create(RealDest, EdgeBB);
1647
1648     // Update PHI nodes.
1649     AddPredecessorToBlock(RealDest, EdgeBB, BB);
1650
1651     // BB may have instructions that are being threaded over.  Clone these
1652     // instructions into EdgeBB.  We know that there will be no uses of the
1653     // cloned instructions outside of EdgeBB.
1654     BasicBlock::iterator InsertPt = EdgeBB->begin();
1655     DenseMap<Value*, Value*> TranslateMap;  // Track translated values.
1656     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1657       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1658         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1659         continue;
1660       }
1661       // Clone the instruction.
1662       Instruction *N = BBI->clone();
1663       if (BBI->hasName()) N->setName(BBI->getName()+".c");
1664
1665       // Update operands due to translation.
1666       for (User::op_iterator i = N->op_begin(), e = N->op_end();
1667            i != e; ++i) {
1668         DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1669         if (PI != TranslateMap.end())
1670           *i = PI->second;
1671       }
1672
1673       // Check for trivial simplification.
1674       if (Value *V = SimplifyInstruction(N, DL)) {
1675         TranslateMap[BBI] = V;
1676         delete N;   // Instruction folded away, don't need actual inst
1677       } else {
1678         // Insert the new instruction into its new home.
1679         EdgeBB->getInstList().insert(InsertPt, N);
1680         if (!BBI->use_empty())
1681           TranslateMap[BBI] = N;
1682       }
1683     }
1684
1685     // Loop over all of the edges from PredBB to BB, changing them to branch
1686     // to EdgeBB instead.
1687     TerminatorInst *PredBBTI = PredBB->getTerminator();
1688     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1689       if (PredBBTI->getSuccessor(i) == BB) {
1690         BB->removePredecessor(PredBB);
1691         PredBBTI->setSuccessor(i, EdgeBB);
1692       }
1693
1694     // Recurse, simplifying any other constants.
1695     return FoldCondBranchOnPHI(BI, DL) | true;
1696   }
1697
1698   return false;
1699 }
1700
1701 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1702 /// PHI node, see if we can eliminate it.
1703 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1704   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1705   // statement", which has a very simple dominance structure.  Basically, we
1706   // are trying to find the condition that is being branched on, which
1707   // subsequently causes this merge to happen.  We really want control
1708   // dependence information for this check, but simplifycfg can't keep it up
1709   // to date, and this catches most of the cases we care about anyway.
1710   BasicBlock *BB = PN->getParent();
1711   BasicBlock *IfTrue, *IfFalse;
1712   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1713   if (!IfCond ||
1714       // Don't bother if the branch will be constant folded trivially.
1715       isa<ConstantInt>(IfCond))
1716     return false;
1717
1718   // Okay, we found that we can merge this two-entry phi node into a select.
1719   // Doing so would require us to fold *all* two entry phi nodes in this block.
1720   // At some point this becomes non-profitable (particularly if the target
1721   // doesn't support cmov's).  Only do this transformation if there are two or
1722   // fewer PHI nodes in this block.
1723   unsigned NumPhis = 0;
1724   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1725     if (NumPhis > 2)
1726       return false;
1727
1728   // Loop over the PHI's seeing if we can promote them all to select
1729   // instructions.  While we are at it, keep track of the instructions
1730   // that need to be moved to the dominating block.
1731   SmallPtrSet<Instruction*, 4> AggressiveInsts;
1732   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1733            MaxCostVal1 = PHINodeFoldingThreshold;
1734
1735   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1736     PHINode *PN = cast<PHINode>(II++);
1737     if (Value *V = SimplifyInstruction(PN, DL)) {
1738       PN->replaceAllUsesWith(V);
1739       PN->eraseFromParent();
1740       continue;
1741     }
1742
1743     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1744                              MaxCostVal0) ||
1745         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1746                              MaxCostVal1))
1747       return false;
1748   }
1749
1750   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
1751   // we ran out of PHIs then we simplified them all.
1752   PN = dyn_cast<PHINode>(BB->begin());
1753   if (!PN) return true;
1754
1755   // Don't fold i1 branches on PHIs which contain binary operators.  These can
1756   // often be turned into switches and other things.
1757   if (PN->getType()->isIntegerTy(1) &&
1758       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1759        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1760        isa<BinaryOperator>(IfCond)))
1761     return false;
1762
1763   // If we all PHI nodes are promotable, check to make sure that all
1764   // instructions in the predecessor blocks can be promoted as well.  If
1765   // not, we won't be able to get rid of the control flow, so it's not
1766   // worth promoting to select instructions.
1767   BasicBlock *DomBlock = nullptr;
1768   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1769   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1770   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1771     IfBlock1 = nullptr;
1772   } else {
1773     DomBlock = *pred_begin(IfBlock1);
1774     for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1775       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1776         // This is not an aggressive instruction that we can promote.
1777         // Because of this, we won't be able to get rid of the control
1778         // flow, so the xform is not worth it.
1779         return false;
1780       }
1781   }
1782
1783   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1784     IfBlock2 = nullptr;
1785   } else {
1786     DomBlock = *pred_begin(IfBlock2);
1787     for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1788       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1789         // This is not an aggressive instruction that we can promote.
1790         // Because of this, we won't be able to get rid of the control
1791         // flow, so the xform is not worth it.
1792         return false;
1793       }
1794   }
1795
1796   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1797                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
1798
1799   // If we can still promote the PHI nodes after this gauntlet of tests,
1800   // do all of the PHI's now.
1801   Instruction *InsertPt = DomBlock->getTerminator();
1802   IRBuilder<true, NoFolder> Builder(InsertPt);
1803
1804   // Move all 'aggressive' instructions, which are defined in the
1805   // conditional parts of the if's up to the dominating block.
1806   if (IfBlock1)
1807     DomBlock->getInstList().splice(InsertPt,
1808                                    IfBlock1->getInstList(), IfBlock1->begin(),
1809                                    IfBlock1->getTerminator());
1810   if (IfBlock2)
1811     DomBlock->getInstList().splice(InsertPt,
1812                                    IfBlock2->getInstList(), IfBlock2->begin(),
1813                                    IfBlock2->getTerminator());
1814
1815   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1816     // Change the PHI node into a select instruction.
1817     Value *TrueVal  = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1818     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1819
1820     SelectInst *NV =
1821       cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1822     PN->replaceAllUsesWith(NV);
1823     NV->takeName(PN);
1824     PN->eraseFromParent();
1825   }
1826
1827   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1828   // has been flattened.  Change DomBlock to jump directly to our new block to
1829   // avoid other simplifycfg's kicking in on the diamond.
1830   TerminatorInst *OldTI = DomBlock->getTerminator();
1831   Builder.SetInsertPoint(OldTI);
1832   Builder.CreateBr(BB);
1833   OldTI->eraseFromParent();
1834   return true;
1835 }
1836
1837 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1838 /// to two returning blocks, try to merge them together into one return,
1839 /// introducing a select if the return values disagree.
1840 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1841                                            IRBuilder<> &Builder) {
1842   assert(BI->isConditional() && "Must be a conditional branch");
1843   BasicBlock *TrueSucc = BI->getSuccessor(0);
1844   BasicBlock *FalseSucc = BI->getSuccessor(1);
1845   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1846   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1847
1848   // Check to ensure both blocks are empty (just a return) or optionally empty
1849   // with PHI nodes.  If there are other instructions, merging would cause extra
1850   // computation on one path or the other.
1851   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1852     return false;
1853   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1854     return false;
1855
1856   Builder.SetInsertPoint(BI);
1857   // Okay, we found a branch that is going to two return nodes.  If
1858   // there is no return value for this function, just change the
1859   // branch into a return.
1860   if (FalseRet->getNumOperands() == 0) {
1861     TrueSucc->removePredecessor(BI->getParent());
1862     FalseSucc->removePredecessor(BI->getParent());
1863     Builder.CreateRetVoid();
1864     EraseTerminatorInstAndDCECond(BI);
1865     return true;
1866   }
1867
1868   // Otherwise, figure out what the true and false return values are
1869   // so we can insert a new select instruction.
1870   Value *TrueValue = TrueRet->getReturnValue();
1871   Value *FalseValue = FalseRet->getReturnValue();
1872
1873   // Unwrap any PHI nodes in the return blocks.
1874   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1875     if (TVPN->getParent() == TrueSucc)
1876       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1877   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1878     if (FVPN->getParent() == FalseSucc)
1879       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1880
1881   // In order for this transformation to be safe, we must be able to
1882   // unconditionally execute both operands to the return.  This is
1883   // normally the case, but we could have a potentially-trapping
1884   // constant expression that prevents this transformation from being
1885   // safe.
1886   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1887     if (TCV->canTrap())
1888       return false;
1889   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1890     if (FCV->canTrap())
1891       return false;
1892
1893   // Okay, we collected all the mapped values and checked them for sanity, and
1894   // defined to really do this transformation.  First, update the CFG.
1895   TrueSucc->removePredecessor(BI->getParent());
1896   FalseSucc->removePredecessor(BI->getParent());
1897
1898   // Insert select instructions where needed.
1899   Value *BrCond = BI->getCondition();
1900   if (TrueValue) {
1901     // Insert a select if the results differ.
1902     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1903     } else if (isa<UndefValue>(TrueValue)) {
1904       TrueValue = FalseValue;
1905     } else {
1906       TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1907                                        FalseValue, "retval");
1908     }
1909   }
1910
1911   Value *RI = !TrueValue ?
1912     Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1913
1914   (void) RI;
1915
1916   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1917                << "\n  " << *BI << "NewRet = " << *RI
1918                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1919
1920   EraseTerminatorInstAndDCECond(BI);
1921
1922   return true;
1923 }
1924
1925 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1926 /// probabilities of the branch taking each edge. Fills in the two APInt
1927 /// parameters and return true, or returns false if no or invalid metadata was
1928 /// found.
1929 static bool ExtractBranchMetadata(BranchInst *BI,
1930                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
1931   assert(BI->isConditional() &&
1932          "Looking for probabilities on unconditional branch?");
1933   MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1934   if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1935   ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1936   ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1937   if (!CITrue || !CIFalse) return false;
1938   ProbTrue = CITrue->getValue().getZExtValue();
1939   ProbFalse = CIFalse->getValue().getZExtValue();
1940   return true;
1941 }
1942
1943 /// checkCSEInPredecessor - Return true if the given instruction is available
1944 /// in its predecessor block. If yes, the instruction will be removed.
1945 ///
1946 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1947   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1948     return false;
1949   for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1950     Instruction *PBI = &*I;
1951     // Check whether Inst and PBI generate the same value.
1952     if (Inst->isIdenticalTo(PBI)) {
1953       Inst->replaceAllUsesWith(PBI);
1954       Inst->eraseFromParent();
1955       return true;
1956     }
1957   }
1958   return false;
1959 }
1960
1961 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1962 /// predecessor branches to us and one of our successors, fold the block into
1963 /// the predecessor and use logical operations to pick the right destination.
1964 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1965   BasicBlock *BB = BI->getParent();
1966
1967   Instruction *Cond = nullptr;
1968   if (BI->isConditional())
1969     Cond = dyn_cast<Instruction>(BI->getCondition());
1970   else {
1971     // For unconditional branch, check for a simple CFG pattern, where
1972     // BB has a single predecessor and BB's successor is also its predecessor's
1973     // successor. If such pattern exisits, check for CSE between BB and its
1974     // predecessor.
1975     if (BasicBlock *PB = BB->getSinglePredecessor())
1976       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1977         if (PBI->isConditional() &&
1978             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1979              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1980           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1981                I != E; ) {
1982             Instruction *Curr = I++;
1983             if (isa<CmpInst>(Curr)) {
1984               Cond = Curr;
1985               break;
1986             }
1987             // Quit if we can't remove this instruction.
1988             if (!checkCSEInPredecessor(Curr, PB))
1989               return false;
1990           }
1991         }
1992
1993     if (!Cond)
1994       return false;
1995   }
1996
1997   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1998       Cond->getParent() != BB || !Cond->hasOneUse())
1999   return false;
2000
2001   // Only allow this if the condition is a simple instruction that can be
2002   // executed unconditionally.  It must be in the same block as the branch, and
2003   // must be at the front of the block.
2004   BasicBlock::iterator FrontIt = BB->front();
2005
2006   // Ignore dbg intrinsics.
2007   while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2008
2009   // Allow a single instruction to be hoisted in addition to the compare
2010   // that feeds the branch.  We later ensure that any values that _it_ uses
2011   // were also live in the predecessor, so that we don't unnecessarily create
2012   // register pressure or inhibit out-of-order execution.
2013   Instruction *BonusInst = nullptr;
2014   if (&*FrontIt != Cond &&
2015       FrontIt->hasOneUse() && FrontIt->user_back() == Cond &&
2016       isSafeToSpeculativelyExecute(FrontIt)) {
2017     BonusInst = &*FrontIt;
2018     ++FrontIt;
2019
2020     // Ignore dbg intrinsics.
2021     while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2022   }
2023
2024   // Only a single bonus inst is allowed.
2025   if (&*FrontIt != Cond)
2026     return false;
2027
2028   // Make sure the instruction after the condition is the cond branch.
2029   BasicBlock::iterator CondIt = Cond; ++CondIt;
2030
2031   // Ingore dbg intrinsics.
2032   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2033
2034   if (&*CondIt != BI)
2035     return false;
2036
2037   // Cond is known to be a compare or binary operator.  Check to make sure that
2038   // neither operand is a potentially-trapping constant expression.
2039   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2040     if (CE->canTrap())
2041       return false;
2042   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2043     if (CE->canTrap())
2044       return false;
2045
2046   // Finally, don't infinitely unroll conditional loops.
2047   BasicBlock *TrueDest  = BI->getSuccessor(0);
2048   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2049   if (TrueDest == BB || FalseDest == BB)
2050     return false;
2051
2052   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2053     BasicBlock *PredBlock = *PI;
2054     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2055
2056     // Check that we have two conditional branches.  If there is a PHI node in
2057     // the common successor, verify that the same value flows in from both
2058     // blocks.
2059     SmallVector<PHINode*, 4> PHIs;
2060     if (!PBI || PBI->isUnconditional() ||
2061         (BI->isConditional() &&
2062          !SafeToMergeTerminators(BI, PBI)) ||
2063         (!BI->isConditional() &&
2064          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2065       continue;
2066
2067     // Determine if the two branches share a common destination.
2068     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2069     bool InvertPredCond = false;
2070
2071     if (BI->isConditional()) {
2072       if (PBI->getSuccessor(0) == TrueDest)
2073         Opc = Instruction::Or;
2074       else if (PBI->getSuccessor(1) == FalseDest)
2075         Opc = Instruction::And;
2076       else if (PBI->getSuccessor(0) == FalseDest)
2077         Opc = Instruction::And, InvertPredCond = true;
2078       else if (PBI->getSuccessor(1) == TrueDest)
2079         Opc = Instruction::Or, InvertPredCond = true;
2080       else
2081         continue;
2082     } else {
2083       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2084         continue;
2085     }
2086
2087     // Ensure that any values used in the bonus instruction are also used
2088     // by the terminator of the predecessor.  This means that those values
2089     // must already have been resolved, so we won't be inhibiting the
2090     // out-of-order core by speculating them earlier. We also allow
2091     // instructions that are used by the terminator's condition because it
2092     // exposes more merging opportunities.
2093     bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() &&
2094                          BonusInst->user_back() == Cond);
2095
2096     if (BonusInst && !UsedByBranch) {
2097       // Collect the values used by the bonus inst
2098       SmallPtrSet<Value*, 4> UsedValues;
2099       for (Instruction::op_iterator OI = BonusInst->op_begin(),
2100            OE = BonusInst->op_end(); OI != OE; ++OI) {
2101         Value *V = *OI;
2102         if (!isa<Constant>(V) && !isa<Argument>(V))
2103           UsedValues.insert(V);
2104       }
2105
2106       SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2107       Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
2108
2109       // Walk up to four levels back up the use-def chain of the predecessor's
2110       // terminator to see if all those values were used.  The choice of four
2111       // levels is arbitrary, to provide a compile-time-cost bound.
2112       while (!Worklist.empty()) {
2113         std::pair<Value*, unsigned> Pair = Worklist.back();
2114         Worklist.pop_back();
2115
2116         if (Pair.second >= 4) continue;
2117         UsedValues.erase(Pair.first);
2118         if (UsedValues.empty()) break;
2119
2120         if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
2121           for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2122                OI != OE; ++OI)
2123             Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
2124         }
2125       }
2126
2127       if (!UsedValues.empty()) return false;
2128     }
2129
2130     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2131     IRBuilder<> Builder(PBI);
2132
2133     // If we need to invert the condition in the pred block to match, do so now.
2134     if (InvertPredCond) {
2135       Value *NewCond = PBI->getCondition();
2136
2137       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2138         CmpInst *CI = cast<CmpInst>(NewCond);
2139         CI->setPredicate(CI->getInversePredicate());
2140       } else {
2141         NewCond = Builder.CreateNot(NewCond,
2142                                     PBI->getCondition()->getName()+".not");
2143       }
2144
2145       PBI->setCondition(NewCond);
2146       PBI->swapSuccessors();
2147     }
2148
2149     // If we have a bonus inst, clone it into the predecessor block.
2150     Instruction *NewBonus = nullptr;
2151     if (BonusInst) {
2152       NewBonus = BonusInst->clone();
2153
2154       // If we moved a load, we cannot any longer claim any knowledge about
2155       // its potential value. The previous information might have been valid
2156       // only given the branch precondition.
2157       // For an analogous reason, we must also drop all the metadata whose
2158       // semantics we don't understand.
2159       NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
2160
2161       PredBlock->getInstList().insert(PBI, NewBonus);
2162       NewBonus->takeName(BonusInst);
2163       BonusInst->setName(BonusInst->getName()+".old");
2164     }
2165
2166     // Clone Cond into the predecessor basic block, and or/and the
2167     // two conditions together.
2168     Instruction *New = Cond->clone();
2169     if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
2170     PredBlock->getInstList().insert(PBI, New);
2171     New->takeName(Cond);
2172     Cond->setName(New->getName()+".old");
2173
2174     if (BI->isConditional()) {
2175       Instruction *NewCond =
2176         cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2177                                             New, "or.cond"));
2178       PBI->setCondition(NewCond);
2179
2180       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2181       bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2182                                                   PredFalseWeight);
2183       bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2184                                                   SuccFalseWeight);
2185       SmallVector<uint64_t, 8> NewWeights;
2186
2187       if (PBI->getSuccessor(0) == BB) {
2188         if (PredHasWeights && SuccHasWeights) {
2189           // PBI: br i1 %x, BB, FalseDest
2190           // BI:  br i1 %y, TrueDest, FalseDest
2191           //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2192           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2193           //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2194           //               TrueWeight for PBI * FalseWeight for BI.
2195           // We assume that total weights of a BranchInst can fit into 32 bits.
2196           // Therefore, we will not have overflow using 64-bit arithmetic.
2197           NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2198                SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2199         }
2200         AddPredecessorToBlock(TrueDest, PredBlock, BB);
2201         PBI->setSuccessor(0, TrueDest);
2202       }
2203       if (PBI->getSuccessor(1) == BB) {
2204         if (PredHasWeights && SuccHasWeights) {
2205           // PBI: br i1 %x, TrueDest, BB
2206           // BI:  br i1 %y, TrueDest, FalseDest
2207           //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2208           //              FalseWeight for PBI * TrueWeight for BI.
2209           NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2210               SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2211           //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2212           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2213         }
2214         AddPredecessorToBlock(FalseDest, PredBlock, BB);
2215         PBI->setSuccessor(1, FalseDest);
2216       }
2217       if (NewWeights.size() == 2) {
2218         // Halve the weights if any of them cannot fit in an uint32_t
2219         FitWeights(NewWeights);
2220
2221         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2222         PBI->setMetadata(LLVMContext::MD_prof,
2223                          MDBuilder(BI->getContext()).
2224                          createBranchWeights(MDWeights));
2225       } else
2226         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2227     } else {
2228       // Update PHI nodes in the common successors.
2229       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2230         ConstantInt *PBI_C = cast<ConstantInt>(
2231           PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2232         assert(PBI_C->getType()->isIntegerTy(1));
2233         Instruction *MergedCond = nullptr;
2234         if (PBI->getSuccessor(0) == TrueDest) {
2235           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2236           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2237           //       is false: !PBI_Cond and BI_Value
2238           Instruction *NotCond =
2239             cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2240                                 "not.cond"));
2241           MergedCond =
2242             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2243                                 NotCond, New,
2244                                 "and.cond"));
2245           if (PBI_C->isOne())
2246             MergedCond =
2247               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2248                                   PBI->getCondition(), MergedCond,
2249                                   "or.cond"));
2250         } else {
2251           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2252           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2253           //       is false: PBI_Cond and BI_Value
2254           MergedCond =
2255             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2256                                 PBI->getCondition(), New,
2257                                 "and.cond"));
2258           if (PBI_C->isOne()) {
2259             Instruction *NotCond =
2260               cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2261                                   "not.cond"));
2262             MergedCond =
2263               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2264                                   NotCond, MergedCond,
2265                                   "or.cond"));
2266           }
2267         }
2268         // Update PHI Node.
2269         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2270                                   MergedCond);
2271       }
2272       // Change PBI from Conditional to Unconditional.
2273       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2274       EraseTerminatorInstAndDCECond(PBI);
2275       PBI = New_PBI;
2276     }
2277
2278     // TODO: If BB is reachable from all paths through PredBlock, then we
2279     // could replace PBI's branch probabilities with BI's.
2280
2281     // Copy any debug value intrinsics into the end of PredBlock.
2282     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2283       if (isa<DbgInfoIntrinsic>(*I))
2284         I->clone()->insertBefore(PBI);
2285
2286     return true;
2287   }
2288   return false;
2289 }
2290
2291 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2292 /// predecessor of another block, this function tries to simplify it.  We know
2293 /// that PBI and BI are both conditional branches, and BI is in one of the
2294 /// successor blocks of PBI - PBI branches to BI.
2295 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2296   assert(PBI->isConditional() && BI->isConditional());
2297   BasicBlock *BB = BI->getParent();
2298
2299   // If this block ends with a branch instruction, and if there is a
2300   // predecessor that ends on a branch of the same condition, make
2301   // this conditional branch redundant.
2302   if (PBI->getCondition() == BI->getCondition() &&
2303       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2304     // Okay, the outcome of this conditional branch is statically
2305     // knowable.  If this block had a single pred, handle specially.
2306     if (BB->getSinglePredecessor()) {
2307       // Turn this into a branch on constant.
2308       bool CondIsTrue = PBI->getSuccessor(0) == BB;
2309       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2310                                         CondIsTrue));
2311       return true;  // Nuke the branch on constant.
2312     }
2313
2314     // Otherwise, if there are multiple predecessors, insert a PHI that merges
2315     // in the constant and simplify the block result.  Subsequent passes of
2316     // simplifycfg will thread the block.
2317     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2318       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2319       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2320                                        std::distance(PB, PE),
2321                                        BI->getCondition()->getName() + ".pr",
2322                                        BB->begin());
2323       // Okay, we're going to insert the PHI node.  Since PBI is not the only
2324       // predecessor, compute the PHI'd conditional value for all of the preds.
2325       // Any predecessor where the condition is not computable we keep symbolic.
2326       for (pred_iterator PI = PB; PI != PE; ++PI) {
2327         BasicBlock *P = *PI;
2328         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2329             PBI != BI && PBI->isConditional() &&
2330             PBI->getCondition() == BI->getCondition() &&
2331             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2332           bool CondIsTrue = PBI->getSuccessor(0) == BB;
2333           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2334                                               CondIsTrue), P);
2335         } else {
2336           NewPN->addIncoming(BI->getCondition(), P);
2337         }
2338       }
2339
2340       BI->setCondition(NewPN);
2341       return true;
2342     }
2343   }
2344
2345   // If this is a conditional branch in an empty block, and if any
2346   // predecessors is a conditional branch to one of our destinations,
2347   // fold the conditions into logical ops and one cond br.
2348   BasicBlock::iterator BBI = BB->begin();
2349   // Ignore dbg intrinsics.
2350   while (isa<DbgInfoIntrinsic>(BBI))
2351     ++BBI;
2352   if (&*BBI != BI)
2353     return false;
2354
2355
2356   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2357     if (CE->canTrap())
2358       return false;
2359
2360   int PBIOp, BIOp;
2361   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2362     PBIOp = BIOp = 0;
2363   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2364     PBIOp = 0, BIOp = 1;
2365   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2366     PBIOp = 1, BIOp = 0;
2367   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2368     PBIOp = BIOp = 1;
2369   else
2370     return false;
2371
2372   // Check to make sure that the other destination of this branch
2373   // isn't BB itself.  If so, this is an infinite loop that will
2374   // keep getting unwound.
2375   if (PBI->getSuccessor(PBIOp) == BB)
2376     return false;
2377
2378   // Do not perform this transformation if it would require
2379   // insertion of a large number of select instructions. For targets
2380   // without predication/cmovs, this is a big pessimization.
2381   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2382
2383   unsigned NumPhis = 0;
2384   for (BasicBlock::iterator II = CommonDest->begin();
2385        isa<PHINode>(II); ++II, ++NumPhis)
2386     if (NumPhis > 2) // Disable this xform.
2387       return false;
2388
2389   // Finally, if everything is ok, fold the branches to logical ops.
2390   BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
2391
2392   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2393                << "AND: " << *BI->getParent());
2394
2395
2396   // If OtherDest *is* BB, then BB is a basic block with a single conditional
2397   // branch in it, where one edge (OtherDest) goes back to itself but the other
2398   // exits.  We don't *know* that the program avoids the infinite loop
2399   // (even though that seems likely).  If we do this xform naively, we'll end up
2400   // recursively unpeeling the loop.  Since we know that (after the xform is
2401   // done) that the block *is* infinite if reached, we just make it an obviously
2402   // infinite loop with no cond branch.
2403   if (OtherDest == BB) {
2404     // Insert it at the end of the function, because it's either code,
2405     // or it won't matter if it's hot. :)
2406     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2407                                                   "infloop", BB->getParent());
2408     BranchInst::Create(InfLoopBlock, InfLoopBlock);
2409     OtherDest = InfLoopBlock;
2410   }
2411
2412   DEBUG(dbgs() << *PBI->getParent()->getParent());
2413
2414   // BI may have other predecessors.  Because of this, we leave
2415   // it alone, but modify PBI.
2416
2417   // Make sure we get to CommonDest on True&True directions.
2418   Value *PBICond = PBI->getCondition();
2419   IRBuilder<true, NoFolder> Builder(PBI);
2420   if (PBIOp)
2421     PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2422
2423   Value *BICond = BI->getCondition();
2424   if (BIOp)
2425     BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2426
2427   // Merge the conditions.
2428   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2429
2430   // Modify PBI to branch on the new condition to the new dests.
2431   PBI->setCondition(Cond);
2432   PBI->setSuccessor(0, CommonDest);
2433   PBI->setSuccessor(1, OtherDest);
2434
2435   // Update branch weight for PBI.
2436   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2437   bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2438                                               PredFalseWeight);
2439   bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2440                                               SuccFalseWeight);
2441   if (PredHasWeights && SuccHasWeights) {
2442     uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2443     uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2444     uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2445     uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2446     // The weight to CommonDest should be PredCommon * SuccTotal +
2447     //                                    PredOther * SuccCommon.
2448     // The weight to OtherDest should be PredOther * SuccOther.
2449     SmallVector<uint64_t, 2> NewWeights;
2450     NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2451                          PredOther * SuccCommon);
2452     NewWeights.push_back(PredOther * SuccOther);
2453     // Halve the weights if any of them cannot fit in an uint32_t
2454     FitWeights(NewWeights);
2455
2456     SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2457     PBI->setMetadata(LLVMContext::MD_prof,
2458                      MDBuilder(BI->getContext()).
2459                      createBranchWeights(MDWeights));
2460   }
2461
2462   // OtherDest may have phi nodes.  If so, add an entry from PBI's
2463   // block that are identical to the entries for BI's block.
2464   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2465
2466   // We know that the CommonDest already had an edge from PBI to
2467   // it.  If it has PHIs though, the PHIs may have different
2468   // entries for BB and PBI's BB.  If so, insert a select to make
2469   // them agree.
2470   PHINode *PN;
2471   for (BasicBlock::iterator II = CommonDest->begin();
2472        (PN = dyn_cast<PHINode>(II)); ++II) {
2473     Value *BIV = PN->getIncomingValueForBlock(BB);
2474     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2475     Value *PBIV = PN->getIncomingValue(PBBIdx);
2476     if (BIV != PBIV) {
2477       // Insert a select in PBI to pick the right value.
2478       Value *NV = cast<SelectInst>
2479         (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2480       PN->setIncomingValue(PBBIdx, NV);
2481     }
2482   }
2483
2484   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2485   DEBUG(dbgs() << *PBI->getParent()->getParent());
2486
2487   // This basic block is probably dead.  We know it has at least
2488   // one fewer predecessor.
2489   return true;
2490 }
2491
2492 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2493 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2494 // Takes care of updating the successors and removing the old terminator.
2495 // Also makes sure not to introduce new successors by assuming that edges to
2496 // non-successor TrueBBs and FalseBBs aren't reachable.
2497 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2498                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
2499                                        uint32_t TrueWeight,
2500                                        uint32_t FalseWeight){
2501   // Remove any superfluous successor edges from the CFG.
2502   // First, figure out which successors to preserve.
2503   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2504   // successor.
2505   BasicBlock *KeepEdge1 = TrueBB;
2506   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2507
2508   // Then remove the rest.
2509   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2510     BasicBlock *Succ = OldTerm->getSuccessor(I);
2511     // Make sure only to keep exactly one copy of each edge.
2512     if (Succ == KeepEdge1)
2513       KeepEdge1 = nullptr;
2514     else if (Succ == KeepEdge2)
2515       KeepEdge2 = nullptr;
2516     else
2517       Succ->removePredecessor(OldTerm->getParent());
2518   }
2519
2520   IRBuilder<> Builder(OldTerm);
2521   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2522
2523   // Insert an appropriate new terminator.
2524   if (!KeepEdge1 && !KeepEdge2) {
2525     if (TrueBB == FalseBB)
2526       // We were only looking for one successor, and it was present.
2527       // Create an unconditional branch to it.
2528       Builder.CreateBr(TrueBB);
2529     else {
2530       // We found both of the successors we were looking for.
2531       // Create a conditional branch sharing the condition of the select.
2532       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2533       if (TrueWeight != FalseWeight)
2534         NewBI->setMetadata(LLVMContext::MD_prof,
2535                            MDBuilder(OldTerm->getContext()).
2536                            createBranchWeights(TrueWeight, FalseWeight));
2537     }
2538   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2539     // Neither of the selected blocks were successors, so this
2540     // terminator must be unreachable.
2541     new UnreachableInst(OldTerm->getContext(), OldTerm);
2542   } else {
2543     // One of the selected values was a successor, but the other wasn't.
2544     // Insert an unconditional branch to the one that was found;
2545     // the edge to the one that wasn't must be unreachable.
2546     if (!KeepEdge1)
2547       // Only TrueBB was found.
2548       Builder.CreateBr(TrueBB);
2549     else
2550       // Only FalseBB was found.
2551       Builder.CreateBr(FalseBB);
2552   }
2553
2554   EraseTerminatorInstAndDCECond(OldTerm);
2555   return true;
2556 }
2557
2558 // SimplifySwitchOnSelect - Replaces
2559 //   (switch (select cond, X, Y)) on constant X, Y
2560 // with a branch - conditional if X and Y lead to distinct BBs,
2561 // unconditional otherwise.
2562 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2563   // Check for constant integer values in the select.
2564   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2565   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2566   if (!TrueVal || !FalseVal)
2567     return false;
2568
2569   // Find the relevant condition and destinations.
2570   Value *Condition = Select->getCondition();
2571   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2572   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2573
2574   // Get weight for TrueBB and FalseBB.
2575   uint32_t TrueWeight = 0, FalseWeight = 0;
2576   SmallVector<uint64_t, 8> Weights;
2577   bool HasWeights = HasBranchWeights(SI);
2578   if (HasWeights) {
2579     GetBranchWeights(SI, Weights);
2580     if (Weights.size() == 1 + SI->getNumCases()) {
2581       TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2582                                      getSuccessorIndex()];
2583       FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2584                                       getSuccessorIndex()];
2585     }
2586   }
2587
2588   // Perform the actual simplification.
2589   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2590                                     TrueWeight, FalseWeight);
2591 }
2592
2593 // SimplifyIndirectBrOnSelect - Replaces
2594 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
2595 //                             blockaddress(@fn, BlockB)))
2596 // with
2597 //   (br cond, BlockA, BlockB).
2598 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2599   // Check that both operands of the select are block addresses.
2600   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2601   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2602   if (!TBA || !FBA)
2603     return false;
2604
2605   // Extract the actual blocks.
2606   BasicBlock *TrueBB = TBA->getBasicBlock();
2607   BasicBlock *FalseBB = FBA->getBasicBlock();
2608
2609   // Perform the actual simplification.
2610   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2611                                     0, 0);
2612 }
2613
2614 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2615 /// instruction (a seteq/setne with a constant) as the only instruction in a
2616 /// block that ends with an uncond branch.  We are looking for a very specific
2617 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
2618 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2619 /// default value goes to an uncond block with a seteq in it, we get something
2620 /// like:
2621 ///
2622 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
2623 /// DEFAULT:
2624 ///   %tmp = icmp eq i8 %A, 92
2625 ///   br label %end
2626 /// end:
2627 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2628 ///
2629 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2630 /// the PHI, merging the third icmp into the switch.
2631 static bool TryToSimplifyUncondBranchWithICmpInIt(
2632     ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2633     const DataLayout *DL) {
2634   BasicBlock *BB = ICI->getParent();
2635
2636   // If the block has any PHIs in it or the icmp has multiple uses, it is too
2637   // complex.
2638   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2639
2640   Value *V = ICI->getOperand(0);
2641   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2642
2643   // The pattern we're looking for is where our only predecessor is a switch on
2644   // 'V' and this block is the default case for the switch.  In this case we can
2645   // fold the compared value into the switch to simplify things.
2646   BasicBlock *Pred = BB->getSinglePredecessor();
2647   if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2648
2649   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2650   if (SI->getCondition() != V)
2651     return false;
2652
2653   // If BB is reachable on a non-default case, then we simply know the value of
2654   // V in this block.  Substitute it and constant fold the icmp instruction
2655   // away.
2656   if (SI->getDefaultDest() != BB) {
2657     ConstantInt *VVal = SI->findCaseDest(BB);
2658     assert(VVal && "Should have a unique destination value");
2659     ICI->setOperand(0, VVal);
2660
2661     if (Value *V = SimplifyInstruction(ICI, DL)) {
2662       ICI->replaceAllUsesWith(V);
2663       ICI->eraseFromParent();
2664     }
2665     // BB is now empty, so it is likely to simplify away.
2666     return SimplifyCFG(BB, TTI, DL) | true;
2667   }
2668
2669   // Ok, the block is reachable from the default dest.  If the constant we're
2670   // comparing exists in one of the other edges, then we can constant fold ICI
2671   // and zap it.
2672   if (SI->findCaseValue(Cst) != SI->case_default()) {
2673     Value *V;
2674     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2675       V = ConstantInt::getFalse(BB->getContext());
2676     else
2677       V = ConstantInt::getTrue(BB->getContext());
2678
2679     ICI->replaceAllUsesWith(V);
2680     ICI->eraseFromParent();
2681     // BB is now empty, so it is likely to simplify away.
2682     return SimplifyCFG(BB, TTI, DL) | true;
2683   }
2684
2685   // The use of the icmp has to be in the 'end' block, by the only PHI node in
2686   // the block.
2687   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2688   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2689   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2690       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2691     return false;
2692
2693   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2694   // true in the PHI.
2695   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2696   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
2697
2698   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2699     std::swap(DefaultCst, NewCst);
2700
2701   // Replace ICI (which is used by the PHI for the default value) with true or
2702   // false depending on if it is EQ or NE.
2703   ICI->replaceAllUsesWith(DefaultCst);
2704   ICI->eraseFromParent();
2705
2706   // Okay, the switch goes to this block on a default value.  Add an edge from
2707   // the switch to the merge point on the compared value.
2708   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2709                                          BB->getParent(), BB);
2710   SmallVector<uint64_t, 8> Weights;
2711   bool HasWeights = HasBranchWeights(SI);
2712   if (HasWeights) {
2713     GetBranchWeights(SI, Weights);
2714     if (Weights.size() == 1 + SI->getNumCases()) {
2715       // Split weight for default case to case for "Cst".
2716       Weights[0] = (Weights[0]+1) >> 1;
2717       Weights.push_back(Weights[0]);
2718
2719       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2720       SI->setMetadata(LLVMContext::MD_prof,
2721                       MDBuilder(SI->getContext()).
2722                       createBranchWeights(MDWeights));
2723     }
2724   }
2725   SI->addCase(Cst, NewBB);
2726
2727   // NewBB branches to the phi block, add the uncond branch and the phi entry.
2728   Builder.SetInsertPoint(NewBB);
2729   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2730   Builder.CreateBr(SuccBlock);
2731   PHIUse->addIncoming(NewCst, NewBB);
2732   return true;
2733 }
2734
2735 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2736 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2737 /// fold it into a switch instruction if so.
2738 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2739                                       IRBuilder<> &Builder) {
2740   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2741   if (!Cond) return false;
2742
2743
2744   // Change br (X == 0 | X == 1), T, F into a switch instruction.
2745   // If this is a bunch of seteq's or'd together, or if it's a bunch of
2746   // 'setne's and'ed together, collect them.
2747   Value *CompVal = nullptr;
2748   std::vector<ConstantInt*> Values;
2749   bool TrueWhenEqual = true;
2750   Value *ExtraCase = nullptr;
2751   unsigned UsedICmps = 0;
2752
2753   if (Cond->getOpcode() == Instruction::Or) {
2754     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
2755                                      UsedICmps);
2756   } else if (Cond->getOpcode() == Instruction::And) {
2757     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
2758                                      UsedICmps);
2759     TrueWhenEqual = false;
2760   }
2761
2762   // If we didn't have a multiply compared value, fail.
2763   if (!CompVal) return false;
2764
2765   // Avoid turning single icmps into a switch.
2766   if (UsedICmps <= 1)
2767     return false;
2768
2769   // There might be duplicate constants in the list, which the switch
2770   // instruction can't handle, remove them now.
2771   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2772   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2773
2774   // If Extra was used, we require at least two switch values to do the
2775   // transformation.  A switch with one value is just an cond branch.
2776   if (ExtraCase && Values.size() < 2) return false;
2777
2778   // TODO: Preserve branch weight metadata, similarly to how
2779   // FoldValueComparisonIntoPredecessors preserves it.
2780
2781   // Figure out which block is which destination.
2782   BasicBlock *DefaultBB = BI->getSuccessor(1);
2783   BasicBlock *EdgeBB    = BI->getSuccessor(0);
2784   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2785
2786   BasicBlock *BB = BI->getParent();
2787
2788   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2789                << " cases into SWITCH.  BB is:\n" << *BB);
2790
2791   // If there are any extra values that couldn't be folded into the switch
2792   // then we evaluate them with an explicit branch first.  Split the block
2793   // right before the condbr to handle it.
2794   if (ExtraCase) {
2795     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2796     // Remove the uncond branch added to the old block.
2797     TerminatorInst *OldTI = BB->getTerminator();
2798     Builder.SetInsertPoint(OldTI);
2799
2800     if (TrueWhenEqual)
2801       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2802     else
2803       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2804
2805     OldTI->eraseFromParent();
2806
2807     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2808     // for the edge we just added.
2809     AddPredecessorToBlock(EdgeBB, BB, NewBB);
2810
2811     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
2812           << "\nEXTRABB = " << *BB);
2813     BB = NewBB;
2814   }
2815
2816   Builder.SetInsertPoint(BI);
2817   // Convert pointer to int before we switch.
2818   if (CompVal->getType()->isPointerTy()) {
2819     assert(DL && "Cannot switch on pointer without DataLayout");
2820     CompVal = Builder.CreatePtrToInt(CompVal,
2821                                      DL->getIntPtrType(CompVal->getType()),
2822                                      "magicptr");
2823   }
2824
2825   // Create the new switch instruction now.
2826   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2827
2828   // Add all of the 'cases' to the switch instruction.
2829   for (unsigned i = 0, e = Values.size(); i != e; ++i)
2830     New->addCase(Values[i], EdgeBB);
2831
2832   // We added edges from PI to the EdgeBB.  As such, if there were any
2833   // PHI nodes in EdgeBB, they need entries to be added corresponding to
2834   // the number of edges added.
2835   for (BasicBlock::iterator BBI = EdgeBB->begin();
2836        isa<PHINode>(BBI); ++BBI) {
2837     PHINode *PN = cast<PHINode>(BBI);
2838     Value *InVal = PN->getIncomingValueForBlock(BB);
2839     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2840       PN->addIncoming(InVal, BB);
2841   }
2842
2843   // Erase the old branch instruction.
2844   EraseTerminatorInstAndDCECond(BI);
2845
2846   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
2847   return true;
2848 }
2849
2850 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2851   // If this is a trivial landing pad that just continues unwinding the caught
2852   // exception then zap the landing pad, turning its invokes into calls.
2853   BasicBlock *BB = RI->getParent();
2854   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2855   if (RI->getValue() != LPInst)
2856     // Not a landing pad, or the resume is not unwinding the exception that
2857     // caused control to branch here.
2858     return false;
2859
2860   // Check that there are no other instructions except for debug intrinsics.
2861   BasicBlock::iterator I = LPInst, E = RI;
2862   while (++I != E)
2863     if (!isa<DbgInfoIntrinsic>(I))
2864       return false;
2865
2866   // Turn all invokes that unwind here into calls and delete the basic block.
2867   bool InvokeRequiresTableEntry = false;
2868   bool Changed = false;
2869   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2870     InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2871
2872     if (II->hasFnAttr(Attribute::UWTable)) {
2873       // Don't remove an `invoke' instruction if the ABI requires an entry into
2874       // the table.
2875       InvokeRequiresTableEntry = true;
2876       continue;
2877     }
2878
2879     SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2880
2881     // Insert a call instruction before the invoke.
2882     CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2883     Call->takeName(II);
2884     Call->setCallingConv(II->getCallingConv());
2885     Call->setAttributes(II->getAttributes());
2886     Call->setDebugLoc(II->getDebugLoc());
2887
2888     // Anything that used the value produced by the invoke instruction now uses
2889     // the value produced by the call instruction.  Note that we do this even
2890     // for void functions and calls with no uses so that the callgraph edge is
2891     // updated.
2892     II->replaceAllUsesWith(Call);
2893     BB->removePredecessor(II->getParent());
2894
2895     // Insert a branch to the normal destination right before the invoke.
2896     BranchInst::Create(II->getNormalDest(), II);
2897
2898     // Finally, delete the invoke instruction!
2899     II->eraseFromParent();
2900     Changed = true;
2901   }
2902
2903   if (!InvokeRequiresTableEntry)
2904     // The landingpad is now unreachable.  Zap it.
2905     BB->eraseFromParent();
2906
2907   return Changed;
2908 }
2909
2910 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2911   BasicBlock *BB = RI->getParent();
2912   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2913
2914   // Find predecessors that end with branches.
2915   SmallVector<BasicBlock*, 8> UncondBranchPreds;
2916   SmallVector<BranchInst*, 8> CondBranchPreds;
2917   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2918     BasicBlock *P = *PI;
2919     TerminatorInst *PTI = P->getTerminator();
2920     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2921       if (BI->isUnconditional())
2922         UncondBranchPreds.push_back(P);
2923       else
2924         CondBranchPreds.push_back(BI);
2925     }
2926   }
2927
2928   // If we found some, do the transformation!
2929   if (!UncondBranchPreds.empty() && DupRet) {
2930     while (!UncondBranchPreds.empty()) {
2931       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2932       DEBUG(dbgs() << "FOLDING: " << *BB
2933             << "INTO UNCOND BRANCH PRED: " << *Pred);
2934       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2935     }
2936
2937     // If we eliminated all predecessors of the block, delete the block now.
2938     if (pred_begin(BB) == pred_end(BB))
2939       // We know there are no successors, so just nuke the block.
2940       BB->eraseFromParent();
2941
2942     return true;
2943   }
2944
2945   // Check out all of the conditional branches going to this return
2946   // instruction.  If any of them just select between returns, change the
2947   // branch itself into a select/return pair.
2948   while (!CondBranchPreds.empty()) {
2949     BranchInst *BI = CondBranchPreds.pop_back_val();
2950
2951     // Check to see if the non-BB successor is also a return block.
2952     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2953         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2954         SimplifyCondBranchToTwoReturns(BI, Builder))
2955       return true;
2956   }
2957   return false;
2958 }
2959
2960 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2961   BasicBlock *BB = UI->getParent();
2962
2963   bool Changed = false;
2964
2965   // If there are any instructions immediately before the unreachable that can
2966   // be removed, do so.
2967   while (UI != BB->begin()) {
2968     BasicBlock::iterator BBI = UI;
2969     --BBI;
2970     // Do not delete instructions that can have side effects which might cause
2971     // the unreachable to not be reachable; specifically, calls and volatile
2972     // operations may have this effect.
2973     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2974
2975     if (BBI->mayHaveSideEffects()) {
2976       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2977         if (SI->isVolatile())
2978           break;
2979       } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2980         if (LI->isVolatile())
2981           break;
2982       } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2983         if (RMWI->isVolatile())
2984           break;
2985       } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2986         if (CXI->isVolatile())
2987           break;
2988       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2989                  !isa<LandingPadInst>(BBI)) {
2990         break;
2991       }
2992       // Note that deleting LandingPad's here is in fact okay, although it
2993       // involves a bit of subtle reasoning. If this inst is a LandingPad,
2994       // all the predecessors of this block will be the unwind edges of Invokes,
2995       // and we can therefore guarantee this block will be erased.
2996     }
2997
2998     // Delete this instruction (any uses are guaranteed to be dead)
2999     if (!BBI->use_empty())
3000       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3001     BBI->eraseFromParent();
3002     Changed = true;
3003   }
3004
3005   // If the unreachable instruction is the first in the block, take a gander
3006   // at all of the predecessors of this instruction, and simplify them.
3007   if (&BB->front() != UI) return Changed;
3008
3009   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3010   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3011     TerminatorInst *TI = Preds[i]->getTerminator();
3012     IRBuilder<> Builder(TI);
3013     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3014       if (BI->isUnconditional()) {
3015         if (BI->getSuccessor(0) == BB) {
3016           new UnreachableInst(TI->getContext(), TI);
3017           TI->eraseFromParent();
3018           Changed = true;
3019         }
3020       } else {
3021         if (BI->getSuccessor(0) == BB) {
3022           Builder.CreateBr(BI->getSuccessor(1));
3023           EraseTerminatorInstAndDCECond(BI);
3024         } else if (BI->getSuccessor(1) == BB) {
3025           Builder.CreateBr(BI->getSuccessor(0));
3026           EraseTerminatorInstAndDCECond(BI);
3027           Changed = true;
3028         }
3029       }
3030     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3031       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3032            i != e; ++i)
3033         if (i.getCaseSuccessor() == BB) {
3034           BB->removePredecessor(SI->getParent());
3035           SI->removeCase(i);
3036           --i; --e;
3037           Changed = true;
3038         }
3039       // If the default value is unreachable, figure out the most popular
3040       // destination and make it the default.
3041       if (SI->getDefaultDest() == BB) {
3042         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3043         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3044              i != e; ++i) {
3045           std::pair<unsigned, unsigned> &entry =
3046               Popularity[i.getCaseSuccessor()];
3047           if (entry.first == 0) {
3048             entry.first = 1;
3049             entry.second = i.getCaseIndex();
3050           } else {
3051             entry.first++;
3052           }
3053         }
3054
3055         // Find the most popular block.
3056         unsigned MaxPop = 0;
3057         unsigned MaxIndex = 0;
3058         BasicBlock *MaxBlock = nullptr;
3059         for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3060              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3061           if (I->second.first > MaxPop ||
3062               (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3063             MaxPop = I->second.first;
3064             MaxIndex = I->second.second;
3065             MaxBlock = I->first;
3066           }
3067         }
3068         if (MaxBlock) {
3069           // Make this the new default, allowing us to delete any explicit
3070           // edges to it.
3071           SI->setDefaultDest(MaxBlock);
3072           Changed = true;
3073
3074           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3075           // it.
3076           if (isa<PHINode>(MaxBlock->begin()))
3077             for (unsigned i = 0; i != MaxPop-1; ++i)
3078               MaxBlock->removePredecessor(SI->getParent());
3079
3080           for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3081                i != e; ++i)
3082             if (i.getCaseSuccessor() == MaxBlock) {
3083               SI->removeCase(i);
3084               --i; --e;
3085             }
3086         }
3087       }
3088     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3089       if (II->getUnwindDest() == BB) {
3090         // Convert the invoke to a call instruction.  This would be a good
3091         // place to note that the call does not throw though.
3092         BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3093         II->removeFromParent();   // Take out of symbol table
3094
3095         // Insert the call now...
3096         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3097         Builder.SetInsertPoint(BI);
3098         CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3099                                           Args, II->getName());
3100         CI->setCallingConv(II->getCallingConv());
3101         CI->setAttributes(II->getAttributes());
3102         // If the invoke produced a value, the call does now instead.
3103         II->replaceAllUsesWith(CI);
3104         delete II;
3105         Changed = true;
3106       }
3107     }
3108   }
3109
3110   // If this block is now dead, remove it.
3111   if (pred_begin(BB) == pred_end(BB) &&
3112       BB != &BB->getParent()->getEntryBlock()) {
3113     // We know there are no successors, so just nuke the block.
3114     BB->eraseFromParent();
3115     return true;
3116   }
3117
3118   return Changed;
3119 }
3120
3121 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3122 /// integer range comparison into a sub, an icmp and a branch.
3123 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3124   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3125
3126   // Make sure all cases point to the same destination and gather the values.
3127   SmallVector<ConstantInt *, 16> Cases;
3128   SwitchInst::CaseIt I = SI->case_begin();
3129   Cases.push_back(I.getCaseValue());
3130   SwitchInst::CaseIt PrevI = I++;
3131   for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3132     if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3133       return false;
3134     Cases.push_back(I.getCaseValue());
3135   }
3136   assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3137
3138   // Sort the case values, then check if they form a range we can transform.
3139   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3140   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3141     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3142       return false;
3143   }
3144
3145   Constant *Offset = ConstantExpr::getNeg(Cases.back());
3146   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3147
3148   Value *Sub = SI->getCondition();
3149   if (!Offset->isNullValue())
3150     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3151   Value *Cmp;
3152   // If NumCases overflowed, then all possible values jump to the successor.
3153   if (NumCases->isNullValue() && SI->getNumCases() != 0)
3154     Cmp = ConstantInt::getTrue(SI->getContext());
3155   else
3156     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3157   BranchInst *NewBI = Builder.CreateCondBr(
3158       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3159
3160   // Update weight for the newly-created conditional branch.
3161   SmallVector<uint64_t, 8> Weights;
3162   bool HasWeights = HasBranchWeights(SI);
3163   if (HasWeights) {
3164     GetBranchWeights(SI, Weights);
3165     if (Weights.size() == 1 + SI->getNumCases()) {
3166       // Combine all weights for the cases to be the true weight of NewBI.
3167       // We assume that the sum of all weights for a Terminator can fit into 32
3168       // bits.
3169       uint32_t NewTrueWeight = 0;
3170       for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3171         NewTrueWeight += (uint32_t)Weights[I];
3172       NewBI->setMetadata(LLVMContext::MD_prof,
3173                          MDBuilder(SI->getContext()).
3174                          createBranchWeights(NewTrueWeight,
3175                                              (uint32_t)Weights[0]));
3176     }
3177   }
3178
3179   // Prune obsolete incoming values off the successor's PHI nodes.
3180   for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3181        isa<PHINode>(BBI); ++BBI) {
3182     for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3183       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3184   }
3185   SI->eraseFromParent();
3186
3187   return true;
3188 }
3189
3190 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3191 /// and use it to remove dead cases.
3192 static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3193   Value *Cond = SI->getCondition();
3194   unsigned Bits = Cond->getType()->getIntegerBitWidth();
3195   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3196   computeKnownBits(Cond, KnownZero, KnownOne);
3197
3198   // Gather dead cases.
3199   SmallVector<ConstantInt*, 8> DeadCases;
3200   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3201     if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3202         (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3203       DeadCases.push_back(I.getCaseValue());
3204       DEBUG(dbgs() << "SimplifyCFG: switch case '"
3205                    << I.getCaseValue() << "' is dead.\n");
3206     }
3207   }
3208
3209   SmallVector<uint64_t, 8> Weights;
3210   bool HasWeight = HasBranchWeights(SI);
3211   if (HasWeight) {
3212     GetBranchWeights(SI, Weights);
3213     HasWeight = (Weights.size() == 1 + SI->getNumCases());
3214   }
3215
3216   // Remove dead cases from the switch.
3217   for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3218     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3219     assert(Case != SI->case_default() &&
3220            "Case was not found. Probably mistake in DeadCases forming.");
3221     if (HasWeight) {
3222       std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3223       Weights.pop_back();
3224     }
3225
3226     // Prune unused values from PHI nodes.
3227     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3228     SI->removeCase(Case);
3229   }
3230   if (HasWeight && Weights.size() >= 2) {
3231     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3232     SI->setMetadata(LLVMContext::MD_prof,
3233                     MDBuilder(SI->getParent()->getContext()).
3234                     createBranchWeights(MDWeights));
3235   }
3236
3237   return !DeadCases.empty();
3238 }
3239
3240 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3241 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3242 /// by an unconditional branch), look at the phi node for BB in the successor
3243 /// block and see if the incoming value is equal to CaseValue. If so, return
3244 /// the phi node, and set PhiIndex to BB's index in the phi node.
3245 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3246                                               BasicBlock *BB,
3247                                               int *PhiIndex) {
3248   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3249     return nullptr; // BB must be empty to be a candidate for simplification.
3250   if (!BB->getSinglePredecessor())
3251     return nullptr; // BB must be dominated by the switch.
3252
3253   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3254   if (!Branch || !Branch->isUnconditional())
3255     return nullptr; // Terminator must be unconditional branch.
3256
3257   BasicBlock *Succ = Branch->getSuccessor(0);
3258
3259   BasicBlock::iterator I = Succ->begin();
3260   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3261     int Idx = PHI->getBasicBlockIndex(BB);
3262     assert(Idx >= 0 && "PHI has no entry for predecessor?");
3263
3264     Value *InValue = PHI->getIncomingValue(Idx);
3265     if (InValue != CaseValue) continue;
3266
3267     *PhiIndex = Idx;
3268     return PHI;
3269   }
3270
3271   return nullptr;
3272 }
3273
3274 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3275 /// instruction to a phi node dominated by the switch, if that would mean that
3276 /// some of the destination blocks of the switch can be folded away.
3277 /// Returns true if a change is made.
3278 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3279   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3280   ForwardingNodesMap ForwardingNodes;
3281
3282   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3283     ConstantInt *CaseValue = I.getCaseValue();
3284     BasicBlock *CaseDest = I.getCaseSuccessor();
3285
3286     int PhiIndex;
3287     PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3288                                                  &PhiIndex);
3289     if (!PHI) continue;
3290
3291     ForwardingNodes[PHI].push_back(PhiIndex);
3292   }
3293
3294   bool Changed = false;
3295
3296   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3297        E = ForwardingNodes.end(); I != E; ++I) {
3298     PHINode *Phi = I->first;
3299     SmallVectorImpl<int> &Indexes = I->second;
3300
3301     if (Indexes.size() < 2) continue;
3302
3303     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3304       Phi->setIncomingValue(Indexes[I], SI->getCondition());
3305     Changed = true;
3306   }
3307
3308   return Changed;
3309 }
3310
3311 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3312 /// initializing an array of constants like C.
3313 static bool ValidLookupTableConstant(Constant *C) {
3314   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3315     return CE->isGEPWithNoNotionalOverIndexing();
3316   if (C->isThreadDependent())
3317     return false;
3318   if (C->isDLLImportDependent())
3319     return false;
3320
3321   return isa<ConstantFP>(C) ||
3322       isa<ConstantInt>(C) ||
3323       isa<ConstantPointerNull>(C) ||
3324       isa<GlobalValue>(C) ||
3325       isa<UndefValue>(C);
3326 }
3327
3328 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3329 /// its constant value in ConstantPool, returning 0 if it's not there.
3330 static Constant *LookupConstant(Value *V,
3331                          const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3332   if (Constant *C = dyn_cast<Constant>(V))
3333     return C;
3334   return ConstantPool.lookup(V);
3335 }
3336
3337 /// ConstantFold - Try to fold instruction I into a constant. This works for
3338 /// simple instructions such as binary operations where both operands are
3339 /// constant or can be replaced by constants from the ConstantPool. Returns the
3340 /// resulting constant on success, 0 otherwise.
3341 static Constant *
3342 ConstantFold(Instruction *I,
3343              const SmallDenseMap<Value *, Constant *> &ConstantPool,
3344              const DataLayout *DL) {
3345   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3346     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3347     if (!A)
3348       return nullptr;
3349     if (A->isAllOnesValue())
3350       return LookupConstant(Select->getTrueValue(), ConstantPool);
3351     if (A->isNullValue())
3352       return LookupConstant(Select->getFalseValue(), ConstantPool);
3353     return nullptr;
3354   }
3355
3356   SmallVector<Constant *, 4> COps;
3357   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3358     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3359       COps.push_back(A);
3360     else
3361       return nullptr;
3362   }
3363
3364   if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3365     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3366                                            COps[1], DL);
3367
3368   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3369 }
3370
3371 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3372 /// at the common destination basic block, *CommonDest, for one of the case
3373 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3374 /// case), of a switch instruction SI.
3375 static bool
3376 GetCaseResults(SwitchInst *SI,
3377                ConstantInt *CaseVal,
3378                BasicBlock *CaseDest,
3379                BasicBlock **CommonDest,
3380                SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3381                const DataLayout *DL) {
3382   // The block from which we enter the common destination.
3383   BasicBlock *Pred = SI->getParent();
3384
3385   // If CaseDest is empty except for some side-effect free instructions through
3386   // which we can constant-propagate the CaseVal, continue to its successor.
3387   SmallDenseMap<Value*, Constant*> ConstantPool;
3388   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3389   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3390        ++I) {
3391     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3392       // If the terminator is a simple branch, continue to the next block.
3393       if (T->getNumSuccessors() != 1)
3394         return false;
3395       Pred = CaseDest;
3396       CaseDest = T->getSuccessor(0);
3397     } else if (isa<DbgInfoIntrinsic>(I)) {
3398       // Skip debug intrinsic.
3399       continue;
3400     } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3401       // Instruction is side-effect free and constant.
3402       ConstantPool.insert(std::make_pair(I, C));
3403     } else {
3404       break;
3405     }
3406   }
3407
3408   // If we did not have a CommonDest before, use the current one.
3409   if (!*CommonDest)
3410     *CommonDest = CaseDest;
3411   // If the destination isn't the common one, abort.
3412   if (CaseDest != *CommonDest)
3413     return false;
3414
3415   // Get the values for this case from phi nodes in the destination block.
3416   BasicBlock::iterator I = (*CommonDest)->begin();
3417   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3418     int Idx = PHI->getBasicBlockIndex(Pred);
3419     if (Idx == -1)
3420       continue;
3421
3422     Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3423                                         ConstantPool);
3424     if (!ConstVal)
3425       return false;
3426
3427     // Note: If the constant comes from constant-propagating the case value
3428     // through the CaseDest basic block, it will be safe to remove the
3429     // instructions in that block. They cannot be used (except in the phi nodes
3430     // we visit) outside CaseDest, because that block does not dominate its
3431     // successor. If it did, we would not be in this phi node.
3432
3433     // Be conservative about which kinds of constants we support.
3434     if (!ValidLookupTableConstant(ConstVal))
3435       return false;
3436
3437     Res.push_back(std::make_pair(PHI, ConstVal));
3438   }
3439
3440   return Res.size() > 0;
3441 }
3442
3443 namespace {
3444   /// SwitchLookupTable - This class represents a lookup table that can be used
3445   /// to replace a switch.
3446   class SwitchLookupTable {
3447   public:
3448     /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3449     /// with the contents of Values, using DefaultValue to fill any holes in the
3450     /// table.
3451     SwitchLookupTable(Module &M,
3452                       uint64_t TableSize,
3453                       ConstantInt *Offset,
3454              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3455                       Constant *DefaultValue,
3456                       const DataLayout *DL);
3457
3458     /// BuildLookup - Build instructions with Builder to retrieve the value at
3459     /// the position given by Index in the lookup table.
3460     Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3461
3462     /// WouldFitInRegister - Return true if a table with TableSize elements of
3463     /// type ElementType would fit in a target-legal register.
3464     static bool WouldFitInRegister(const DataLayout *DL,
3465                                    uint64_t TableSize,
3466                                    const Type *ElementType);
3467
3468   private:
3469     // Depending on the contents of the table, it can be represented in
3470     // different ways.
3471     enum {
3472       // For tables where each element contains the same value, we just have to
3473       // store that single value and return it for each lookup.
3474       SingleValueKind,
3475
3476       // For small tables with integer elements, we can pack them into a bitmap
3477       // that fits into a target-legal register. Values are retrieved by
3478       // shift and mask operations.
3479       BitMapKind,
3480
3481       // The table is stored as an array of values. Values are retrieved by load
3482       // instructions from the table.
3483       ArrayKind
3484     } Kind;
3485
3486     // For SingleValueKind, this is the single value.
3487     Constant *SingleValue;
3488
3489     // For BitMapKind, this is the bitmap.
3490     ConstantInt *BitMap;
3491     IntegerType *BitMapElementTy;
3492
3493     // For ArrayKind, this is the array.
3494     GlobalVariable *Array;
3495   };
3496 }
3497
3498 SwitchLookupTable::SwitchLookupTable(Module &M,
3499                                      uint64_t TableSize,
3500                                      ConstantInt *Offset,
3501              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3502                                      Constant *DefaultValue,
3503                                      const DataLayout *DL)
3504     : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3505       Array(nullptr) {
3506   assert(Values.size() && "Can't build lookup table without values!");
3507   assert(TableSize >= Values.size() && "Can't fit values in table!");
3508
3509   // If all values in the table are equal, this is that value.
3510   SingleValue = Values.begin()->second;
3511
3512   Type *ValueType = Values.begin()->second->getType();
3513
3514   // Build up the table contents.
3515   SmallVector<Constant*, 64> TableContents(TableSize);
3516   for (size_t I = 0, E = Values.size(); I != E; ++I) {
3517     ConstantInt *CaseVal = Values[I].first;
3518     Constant *CaseRes = Values[I].second;
3519     assert(CaseRes->getType() == ValueType);
3520
3521     uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3522                    .getLimitedValue();
3523     TableContents[Idx] = CaseRes;
3524
3525     if (CaseRes != SingleValue)
3526       SingleValue = nullptr;
3527   }
3528
3529   // Fill in any holes in the table with the default result.
3530   if (Values.size() < TableSize) {
3531     assert(DefaultValue && "Need a default value to fill the lookup table holes.");
3532     assert(DefaultValue->getType() == ValueType);
3533     for (uint64_t I = 0; I < TableSize; ++I) {
3534       if (!TableContents[I])
3535         TableContents[I] = DefaultValue;
3536     }
3537
3538     if (DefaultValue != SingleValue)
3539       SingleValue = nullptr;
3540   }
3541
3542   // If each element in the table contains the same value, we only need to store
3543   // that single value.
3544   if (SingleValue) {
3545     Kind = SingleValueKind;
3546     return;
3547   }
3548
3549   // If the type is integer and the table fits in a register, build a bitmap.
3550   if (WouldFitInRegister(DL, TableSize, ValueType)) {
3551     IntegerType *IT = cast<IntegerType>(ValueType);
3552     APInt TableInt(TableSize * IT->getBitWidth(), 0);
3553     for (uint64_t I = TableSize; I > 0; --I) {
3554       TableInt <<= IT->getBitWidth();
3555       // Insert values into the bitmap. Undef values are set to zero.
3556       if (!isa<UndefValue>(TableContents[I - 1])) {
3557         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3558         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3559       }
3560     }
3561     BitMap = ConstantInt::get(M.getContext(), TableInt);
3562     BitMapElementTy = IT;
3563     Kind = BitMapKind;
3564     ++NumBitMaps;
3565     return;
3566   }
3567
3568   // Store the table in an array.
3569   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3570   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3571
3572   Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3573                              GlobalVariable::PrivateLinkage,
3574                              Initializer,
3575                              "switch.table");
3576   Array->setUnnamedAddr(true);
3577   Kind = ArrayKind;
3578 }
3579
3580 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3581   switch (Kind) {
3582     case SingleValueKind:
3583       return SingleValue;
3584     case BitMapKind: {
3585       // Type of the bitmap (e.g. i59).
3586       IntegerType *MapTy = BitMap->getType();
3587
3588       // Cast Index to the same type as the bitmap.
3589       // Note: The Index is <= the number of elements in the table, so
3590       // truncating it to the width of the bitmask is safe.
3591       Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3592
3593       // Multiply the shift amount by the element width.
3594       ShiftAmt = Builder.CreateMul(ShiftAmt,
3595                       ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3596                                    "switch.shiftamt");
3597
3598       // Shift down.
3599       Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3600                                               "switch.downshift");
3601       // Mask off.
3602       return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3603                                  "switch.masked");
3604     }
3605     case ArrayKind: {
3606       Value *GEPIndices[] = { Builder.getInt32(0), Index };
3607       Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3608                                              "switch.gep");
3609       return Builder.CreateLoad(GEP, "switch.load");
3610     }
3611   }
3612   llvm_unreachable("Unknown lookup table kind!");
3613 }
3614
3615 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3616                                            uint64_t TableSize,
3617                                            const Type *ElementType) {
3618   if (!DL)
3619     return false;
3620   const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3621   if (!IT)
3622     return false;
3623   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3624   // are <= 15, we could try to narrow the type.
3625
3626   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3627   if (TableSize >= UINT_MAX/IT->getBitWidth())
3628     return false;
3629   return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3630 }
3631
3632 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3633 /// for this switch, based on the number of cases, size of the table and the
3634 /// types of the results.
3635 static bool ShouldBuildLookupTable(SwitchInst *SI,
3636                                    uint64_t TableSize,
3637                                    const TargetTransformInfo &TTI,
3638                                    const DataLayout *DL,
3639                             const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3640   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3641     return false; // TableSize overflowed, or mul below might overflow.
3642
3643   bool AllTablesFitInRegister = true;
3644   bool HasIllegalType = false;
3645   for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3646        E = ResultTypes.end(); I != E; ++I) {
3647     Type *Ty = I->second;
3648
3649     // Saturate this flag to true.
3650     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3651
3652     // Saturate this flag to false.
3653     AllTablesFitInRegister = AllTablesFitInRegister &&
3654       SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3655
3656     // If both flags saturate, we're done. NOTE: This *only* works with
3657     // saturating flags, and all flags have to saturate first due to the
3658     // non-deterministic behavior of iterating over a dense map.
3659     if (HasIllegalType && !AllTablesFitInRegister)
3660       break;
3661   }
3662
3663   // If each table would fit in a register, we should build it anyway.
3664   if (AllTablesFitInRegister)
3665     return true;
3666
3667   // Don't build a table that doesn't fit in-register if it has illegal types.
3668   if (HasIllegalType)
3669     return false;
3670
3671   // The table density should be at least 40%. This is the same criterion as for
3672   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3673   // FIXME: Find the best cut-off.
3674   return SI->getNumCases() * 10 >= TableSize * 4;
3675 }
3676
3677 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3678 /// phi nodes in a common successor block with different constant values,
3679 /// replace the switch with lookup tables.
3680 static bool SwitchToLookupTable(SwitchInst *SI,
3681                                 IRBuilder<> &Builder,
3682                                 const TargetTransformInfo &TTI,
3683                                 const DataLayout* DL) {
3684   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3685
3686   // Only build lookup table when we have a target that supports it.
3687   if (!TTI.shouldBuildLookupTables())
3688     return false;
3689
3690   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3691   // split off a dense part and build a lookup table for that.
3692
3693   // FIXME: This creates arrays of GEPs to constant strings, which means each
3694   // GEP needs a runtime relocation in PIC code. We should just build one big
3695   // string and lookup indices into that.
3696
3697   // Ignore switches with less than three cases. Lookup tables will not make them
3698   // faster, so we don't analyze them.
3699   if (SI->getNumCases() < 3)
3700     return false;
3701
3702   // Figure out the corresponding result for each case value and phi node in the
3703   // common destination, as well as the the min and max case values.
3704   assert(SI->case_begin() != SI->case_end());
3705   SwitchInst::CaseIt CI = SI->case_begin();
3706   ConstantInt *MinCaseVal = CI.getCaseValue();
3707   ConstantInt *MaxCaseVal = CI.getCaseValue();
3708
3709   BasicBlock *CommonDest = nullptr;
3710   typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3711   SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3712   SmallDenseMap<PHINode*, Constant*> DefaultResults;
3713   SmallDenseMap<PHINode*, Type*> ResultTypes;
3714   SmallVector<PHINode*, 4> PHIs;
3715
3716   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3717     ConstantInt *CaseVal = CI.getCaseValue();
3718     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3719       MinCaseVal = CaseVal;
3720     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3721       MaxCaseVal = CaseVal;
3722
3723     // Resulting value at phi nodes for this case value.
3724     typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3725     ResultsTy Results;
3726     if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3727                         Results, DL))
3728       return false;
3729
3730     // Append the result from this case to the list for each phi.
3731     for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3732       if (!ResultLists.count(I->first))
3733         PHIs.push_back(I->first);
3734       ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3735     }
3736   }
3737
3738   // Keep track of the result types.
3739   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3740     PHINode *PHI = PHIs[I];
3741     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3742   }
3743
3744   uint64_t NumResults = ResultLists[PHIs[0]].size();
3745   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3746   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3747   bool TableHasHoles = (NumResults < TableSize);
3748
3749   // If the table has holes, we need a constant result for the default case
3750   // or a bitmask that fits in a register.
3751   SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3752   bool HasDefaultResults = false;
3753   if (TableHasHoles) {
3754     HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3755                                        &CommonDest, DefaultResultsList, DL);
3756   }
3757   bool NeedMask = (TableHasHoles && !HasDefaultResults);
3758   if (NeedMask) {
3759     // As an extra penalty for the validity test we require more cases.
3760     if (SI->getNumCases() < 4)  // FIXME: Find best threshold value (benchmark).
3761       return false;
3762     if (!(DL && DL->fitsInLegalInteger(TableSize)))
3763       return false;
3764   }
3765
3766   for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3767     PHINode *PHI = DefaultResultsList[I].first;
3768     Constant *Result = DefaultResultsList[I].second;
3769     DefaultResults[PHI] = Result;
3770   }
3771
3772   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
3773     return false;
3774
3775   // Create the BB that does the lookups.
3776   Module &Mod = *CommonDest->getParent()->getParent();
3777   BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3778                                             "switch.lookup",
3779                                             CommonDest->getParent(),
3780                                             CommonDest);
3781
3782   // Compute the table index value.
3783   Builder.SetInsertPoint(SI);
3784   Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3785                                         "switch.tableidx");
3786
3787   // Compute the maximum table size representable by the integer type we are
3788   // switching upon.
3789   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
3790   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
3791   assert(MaxTableSize >= TableSize &&
3792          "It is impossible for a switch to have more entries than the max "
3793          "representable value of its input integer type's size.");
3794
3795   // If we have a fully covered lookup table, unconditionally branch to the
3796   // lookup table BB. Otherwise, check if the condition value is within the case
3797   // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3798   // destination.
3799   const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3800   if (GeneratingCoveredLookupTable) {
3801     Builder.CreateBr(LookupBB);
3802     SI->getDefaultDest()->removePredecessor(SI->getParent());
3803   } else {
3804     Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3805                                          MinCaseVal->getType(), TableSize));
3806     Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3807   }
3808
3809   // Populate the BB that does the lookups.
3810   Builder.SetInsertPoint(LookupBB);
3811
3812   if (NeedMask) {
3813     // Before doing the lookup we do the hole check.
3814     // The LookupBB is therefore re-purposed to do the hole check
3815     // and we create a new LookupBB.
3816     BasicBlock *MaskBB = LookupBB;
3817     MaskBB->setName("switch.hole_check");
3818     LookupBB = BasicBlock::Create(Mod.getContext(),
3819                                   "switch.lookup",
3820                                   CommonDest->getParent(),
3821                                   CommonDest);
3822
3823     // Build bitmask; fill in a 1 bit for every case.
3824     APInt MaskInt(TableSize, 0);
3825     APInt One(TableSize, 1);
3826     const ResultListTy &ResultList = ResultLists[PHIs[0]];
3827     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3828       uint64_t Idx = (ResultList[I].first->getValue() -
3829                       MinCaseVal->getValue()).getLimitedValue();
3830       MaskInt |= One << Idx;
3831     }
3832     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3833
3834     // Get the TableIndex'th bit of the bitmask.
3835     // If this bit is 0 (meaning hole) jump to the default destination,
3836     // else continue with table lookup.
3837     IntegerType *MapTy = TableMask->getType();
3838     Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3839                                                  "switch.maskindex");
3840     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3841                                         "switch.shifted");
3842     Value *LoBit = Builder.CreateTrunc(Shifted,
3843                                        Type::getInt1Ty(Mod.getContext()),
3844                                        "switch.lobit");
3845     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3846
3847     Builder.SetInsertPoint(LookupBB);
3848     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3849   }
3850
3851   bool ReturnedEarly = false;
3852   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3853     PHINode *PHI = PHIs[I];
3854
3855     // If using a bitmask, use any value to fill the lookup table holes.
3856     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
3857     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3858                             DV, DL);
3859
3860     Value *Result = Table.BuildLookup(TableIndex, Builder);
3861
3862     // If the result is used to return immediately from the function, we want to
3863     // do that right here.
3864     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3865         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
3866       Builder.CreateRet(Result);
3867       ReturnedEarly = true;
3868       break;
3869     }
3870
3871     PHI->addIncoming(Result, LookupBB);
3872   }
3873
3874   if (!ReturnedEarly)
3875     Builder.CreateBr(CommonDest);
3876
3877   // Remove the switch.
3878   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3879     BasicBlock *Succ = SI->getSuccessor(i);
3880
3881     if (Succ == SI->getDefaultDest())
3882       continue;
3883     Succ->removePredecessor(SI->getParent());
3884   }
3885   SI->eraseFromParent();
3886
3887   ++NumLookupTables;
3888   if (NeedMask)
3889     ++NumLookupTablesHoles;
3890   return true;
3891 }
3892
3893 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3894   BasicBlock *BB = SI->getParent();
3895
3896   if (isValueEqualityComparison(SI)) {
3897     // If we only have one predecessor, and if it is a branch on this value,
3898     // see if that predecessor totally determines the outcome of this switch.
3899     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3900       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3901         return SimplifyCFG(BB, TTI, DL) | true;
3902
3903     Value *Cond = SI->getCondition();
3904     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3905       if (SimplifySwitchOnSelect(SI, Select))
3906         return SimplifyCFG(BB, TTI, DL) | true;
3907
3908     // If the block only contains the switch, see if we can fold the block
3909     // away into any preds.
3910     BasicBlock::iterator BBI = BB->begin();
3911     // Ignore dbg intrinsics.
3912     while (isa<DbgInfoIntrinsic>(BBI))
3913       ++BBI;
3914     if (SI == &*BBI)
3915       if (FoldValueComparisonIntoPredecessors(SI, Builder))
3916         return SimplifyCFG(BB, TTI, DL) | true;
3917   }
3918
3919   // Try to transform the switch into an icmp and a branch.
3920   if (TurnSwitchRangeIntoICmp(SI, Builder))
3921     return SimplifyCFG(BB, TTI, DL) | true;
3922
3923   // Remove unreachable cases.
3924   if (EliminateDeadSwitchCases(SI))
3925     return SimplifyCFG(BB, TTI, DL) | true;
3926
3927   if (ForwardSwitchConditionToPHI(SI))
3928     return SimplifyCFG(BB, TTI, DL) | true;
3929
3930   if (SwitchToLookupTable(SI, Builder, TTI, DL))
3931     return SimplifyCFG(BB, TTI, DL) | true;
3932
3933   return false;
3934 }
3935
3936 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3937   BasicBlock *BB = IBI->getParent();
3938   bool Changed = false;
3939
3940   // Eliminate redundant destinations.
3941   SmallPtrSet<Value *, 8> Succs;
3942   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3943     BasicBlock *Dest = IBI->getDestination(i);
3944     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3945       Dest->removePredecessor(BB);
3946       IBI->removeDestination(i);
3947       --i; --e;
3948       Changed = true;
3949     }
3950   }
3951
3952   if (IBI->getNumDestinations() == 0) {
3953     // If the indirectbr has no successors, change it to unreachable.
3954     new UnreachableInst(IBI->getContext(), IBI);
3955     EraseTerminatorInstAndDCECond(IBI);
3956     return true;
3957   }
3958
3959   if (IBI->getNumDestinations() == 1) {
3960     // If the indirectbr has one successor, change it to a direct branch.
3961     BranchInst::Create(IBI->getDestination(0), IBI);
3962     EraseTerminatorInstAndDCECond(IBI);
3963     return true;
3964   }
3965
3966   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3967     if (SimplifyIndirectBrOnSelect(IBI, SI))
3968       return SimplifyCFG(BB, TTI, DL) | true;
3969   }
3970   return Changed;
3971 }
3972
3973 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
3974   BasicBlock *BB = BI->getParent();
3975
3976   if (SinkCommon && SinkThenElseCodeToEnd(BI))
3977     return true;
3978
3979   // If the Terminator is the only non-phi instruction, simplify the block.
3980   BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
3981   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3982       TryToSimplifyUncondBranchFromEmptyBlock(BB))
3983     return true;
3984
3985   // If the only instruction in the block is a seteq/setne comparison
3986   // against a constant, try to simplify the block.
3987   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3988     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3989       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3990         ;
3991       if (I->isTerminator() &&
3992           TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL))
3993         return true;
3994     }
3995
3996   // If this basic block is ONLY a compare and a branch, and if a predecessor
3997   // branches to us and our successor, fold the comparison into the
3998   // predecessor and use logical operations to update the incoming value
3999   // for PHI nodes in common successor.
4000   if (FoldBranchToCommonDest(BI))
4001     return SimplifyCFG(BB, TTI, DL) | true;
4002   return false;
4003 }
4004
4005
4006 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4007   BasicBlock *BB = BI->getParent();
4008
4009   // Conditional branch
4010   if (isValueEqualityComparison(BI)) {
4011     // If we only have one predecessor, and if it is a branch on this value,
4012     // see if that predecessor totally determines the outcome of this
4013     // switch.
4014     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4015       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4016         return SimplifyCFG(BB, TTI, DL) | true;
4017
4018     // This block must be empty, except for the setcond inst, if it exists.
4019     // Ignore dbg intrinsics.
4020     BasicBlock::iterator I = BB->begin();
4021     // Ignore dbg intrinsics.
4022     while (isa<DbgInfoIntrinsic>(I))
4023       ++I;
4024     if (&*I == BI) {
4025       if (FoldValueComparisonIntoPredecessors(BI, Builder))
4026         return SimplifyCFG(BB, TTI, DL) | true;
4027     } else if (&*I == cast<Instruction>(BI->getCondition())){
4028       ++I;
4029       // Ignore dbg intrinsics.
4030       while (isa<DbgInfoIntrinsic>(I))
4031         ++I;
4032       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4033         return SimplifyCFG(BB, TTI, DL) | true;
4034     }
4035   }
4036
4037   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4038   if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4039     return true;
4040
4041   // If this basic block is ONLY a compare and a branch, and if a predecessor
4042   // branches to us and one of our successors, fold the comparison into the
4043   // predecessor and use logical operations to pick the right destination.
4044   if (FoldBranchToCommonDest(BI))
4045     return SimplifyCFG(BB, TTI, DL) | true;
4046
4047   // We have a conditional branch to two blocks that are only reachable
4048   // from BI.  We know that the condbr dominates the two blocks, so see if
4049   // there is any identical code in the "then" and "else" blocks.  If so, we
4050   // can hoist it up to the branching block.
4051   if (BI->getSuccessor(0)->getSinglePredecessor()) {
4052     if (BI->getSuccessor(1)->getSinglePredecessor()) {
4053       if (HoistThenElseCodeToIf(BI))
4054         return SimplifyCFG(BB, TTI, DL) | true;
4055     } else {
4056       // If Successor #1 has multiple preds, we may be able to conditionally
4057       // execute Successor #0 if it branches to successor #1.
4058       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4059       if (Succ0TI->getNumSuccessors() == 1 &&
4060           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4061         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
4062           return SimplifyCFG(BB, TTI, DL) | true;
4063     }
4064   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4065     // If Successor #0 has multiple preds, we may be able to conditionally
4066     // execute Successor #1 if it branches to successor #0.
4067     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4068     if (Succ1TI->getNumSuccessors() == 1 &&
4069         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4070       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
4071         return SimplifyCFG(BB, TTI, DL) | true;
4072   }
4073
4074   // If this is a branch on a phi node in the current block, thread control
4075   // through this block if any PHI node entries are constants.
4076   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4077     if (PN->getParent() == BI->getParent())
4078       if (FoldCondBranchOnPHI(BI, DL))
4079         return SimplifyCFG(BB, TTI, DL) | true;
4080
4081   // Scan predecessor blocks for conditional branches.
4082   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4083     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4084       if (PBI != BI && PBI->isConditional())
4085         if (SimplifyCondBranchToCondBranch(PBI, BI))
4086           return SimplifyCFG(BB, TTI, DL) | true;
4087
4088   return false;
4089 }
4090
4091 /// Check if passing a value to an instruction will cause undefined behavior.
4092 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4093   Constant *C = dyn_cast<Constant>(V);
4094   if (!C)
4095     return false;
4096
4097   if (I->use_empty())
4098     return false;
4099
4100   if (C->isNullValue()) {
4101     // Only look at the first use, avoid hurting compile time with long uselists
4102     User *Use = *I->user_begin();
4103
4104     // Now make sure that there are no instructions in between that can alter
4105     // control flow (eg. calls)
4106     for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4107       if (i == I->getParent()->end() || i->mayHaveSideEffects())
4108         return false;
4109
4110     // Look through GEPs. A load from a GEP derived from NULL is still undefined
4111     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4112       if (GEP->getPointerOperand() == I)
4113         return passingValueIsAlwaysUndefined(V, GEP);
4114
4115     // Look through bitcasts.
4116     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4117       return passingValueIsAlwaysUndefined(V, BC);
4118
4119     // Load from null is undefined.
4120     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4121       if (!LI->isVolatile())
4122         return LI->getPointerAddressSpace() == 0;
4123
4124     // Store to null is undefined.
4125     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4126       if (!SI->isVolatile())
4127         return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4128   }
4129   return false;
4130 }
4131
4132 /// If BB has an incoming value that will always trigger undefined behavior
4133 /// (eg. null pointer dereference), remove the branch leading here.
4134 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4135   for (BasicBlock::iterator i = BB->begin();
4136        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4137     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4138       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4139         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4140         IRBuilder<> Builder(T);
4141         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4142           BB->removePredecessor(PHI->getIncomingBlock(i));
4143           // Turn uncoditional branches into unreachables and remove the dead
4144           // destination from conditional branches.
4145           if (BI->isUnconditional())
4146             Builder.CreateUnreachable();
4147           else
4148             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4149                                                          BI->getSuccessor(0));
4150           BI->eraseFromParent();
4151           return true;
4152         }
4153         // TODO: SwitchInst.
4154       }
4155
4156   return false;
4157 }
4158
4159 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4160   bool Changed = false;
4161
4162   assert(BB && BB->getParent() && "Block not embedded in function!");
4163   assert(BB->getTerminator() && "Degenerate basic block encountered!");
4164
4165   // Remove basic blocks that have no predecessors (except the entry block)...
4166   // or that just have themself as a predecessor.  These are unreachable.
4167   if ((pred_begin(BB) == pred_end(BB) &&
4168        BB != &BB->getParent()->getEntryBlock()) ||
4169       BB->getSinglePredecessor() == BB) {
4170     DEBUG(dbgs() << "Removing BB: \n" << *BB);
4171     DeleteDeadBlock(BB);
4172     return true;
4173   }
4174
4175   // Check to see if we can constant propagate this terminator instruction
4176   // away...
4177   Changed |= ConstantFoldTerminator(BB, true);
4178
4179   // Check for and eliminate duplicate PHI nodes in this block.
4180   Changed |= EliminateDuplicatePHINodes(BB);
4181
4182   // Check for and remove branches that will always cause undefined behavior.
4183   Changed |= removeUndefIntroducingPredecessor(BB);
4184
4185   // Merge basic blocks into their predecessor if there is only one distinct
4186   // pred, and if there is only one distinct successor of the predecessor, and
4187   // if there are no PHI nodes.
4188   //
4189   if (MergeBlockIntoPredecessor(BB))
4190     return true;
4191
4192   IRBuilder<> Builder(BB);
4193
4194   // If there is a trivial two-entry PHI node in this basic block, and we can
4195   // eliminate it, do so now.
4196   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4197     if (PN->getNumIncomingValues() == 2)
4198       Changed |= FoldTwoEntryPHINode(PN, DL);
4199
4200   Builder.SetInsertPoint(BB->getTerminator());
4201   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4202     if (BI->isUnconditional()) {
4203       if (SimplifyUncondBranch(BI, Builder)) return true;
4204     } else {
4205       if (SimplifyCondBranch(BI, Builder)) return true;
4206     }
4207   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4208     if (SimplifyReturn(RI, Builder)) return true;
4209   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4210     if (SimplifyResume(RI, Builder)) return true;
4211   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4212     if (SimplifySwitch(SI, Builder)) return true;
4213   } else if (UnreachableInst *UI =
4214                dyn_cast<UnreachableInst>(BB->getTerminator())) {
4215     if (SimplifyUnreachable(UI)) return true;
4216   } else if (IndirectBrInst *IBI =
4217                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4218     if (SimplifyIndirectBr(IBI)) return true;
4219   }
4220
4221   return Changed;
4222 }
4223
4224 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
4225 /// example, it adjusts branches to branches to eliminate the extra hop, it
4226 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4227 /// of the CFG.  It returns true if a modification was made.
4228 ///
4229 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4230                        const DataLayout *DL) {
4231   return SimplifyCFGOpt(TTI, DL).run(BB);
4232 }