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