Make use of @llvm.assume in ValueTracking (computeKnownBits, etc.)
[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     // Ensure that any values used in the bonus instruction are also used
2100     // by the terminator of the predecessor.  This means that those values
2101     // must already have been resolved, so we won't be inhibiting the
2102     // out-of-order core by speculating them earlier. We also allow
2103     // instructions that are used by the terminator's condition because it
2104     // exposes more merging opportunities.
2105     bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() &&
2106                          BonusInst->user_back() == Cond);
2107
2108     if (BonusInst && !UsedByBranch) {
2109       // Collect the values used by the bonus inst
2110       SmallPtrSet<Value*, 4> UsedValues;
2111       for (Instruction::op_iterator OI = BonusInst->op_begin(),
2112            OE = BonusInst->op_end(); OI != OE; ++OI) {
2113         Value *V = *OI;
2114         if (!isa<Constant>(V) && !isa<Argument>(V))
2115           UsedValues.insert(V);
2116       }
2117
2118       SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2119       Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
2120
2121       // Walk up to four levels back up the use-def chain of the predecessor's
2122       // terminator to see if all those values were used.  The choice of four
2123       // levels is arbitrary, to provide a compile-time-cost bound.
2124       while (!Worklist.empty()) {
2125         std::pair<Value*, unsigned> Pair = Worklist.back();
2126         Worklist.pop_back();
2127
2128         if (Pair.second >= 4) continue;
2129         UsedValues.erase(Pair.first);
2130         if (UsedValues.empty()) break;
2131
2132         if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
2133           for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2134                OI != OE; ++OI)
2135             Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
2136         }
2137       }
2138
2139       if (!UsedValues.empty()) return false;
2140     }
2141
2142     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2143     IRBuilder<> Builder(PBI);
2144
2145     // If we need to invert the condition in the pred block to match, do so now.
2146     if (InvertPredCond) {
2147       Value *NewCond = PBI->getCondition();
2148
2149       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2150         CmpInst *CI = cast<CmpInst>(NewCond);
2151         CI->setPredicate(CI->getInversePredicate());
2152       } else {
2153         NewCond = Builder.CreateNot(NewCond,
2154                                     PBI->getCondition()->getName()+".not");
2155       }
2156
2157       PBI->setCondition(NewCond);
2158       PBI->swapSuccessors();
2159     }
2160
2161     // If we have a bonus inst, clone it into the predecessor block.
2162     Instruction *NewBonus = nullptr;
2163     if (BonusInst) {
2164       NewBonus = BonusInst->clone();
2165
2166       // If we moved a load, we cannot any longer claim any knowledge about
2167       // its potential value. The previous information might have been valid
2168       // only given the branch precondition.
2169       // For an analogous reason, we must also drop all the metadata whose
2170       // semantics we don't understand.
2171       NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
2172
2173       PredBlock->getInstList().insert(PBI, NewBonus);
2174       NewBonus->takeName(BonusInst);
2175       BonusInst->setName(BonusInst->getName()+".old");
2176     }
2177
2178     // Clone Cond into the predecessor basic block, and or/and the
2179     // two conditions together.
2180     Instruction *New = Cond->clone();
2181     if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
2182     PredBlock->getInstList().insert(PBI, New);
2183     New->takeName(Cond);
2184     Cond->setName(New->getName()+".old");
2185
2186     if (BI->isConditional()) {
2187       Instruction *NewCond =
2188         cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2189                                             New, "or.cond"));
2190       PBI->setCondition(NewCond);
2191
2192       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2193       bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2194                                                   PredFalseWeight);
2195       bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2196                                                   SuccFalseWeight);
2197       SmallVector<uint64_t, 8> NewWeights;
2198
2199       if (PBI->getSuccessor(0) == BB) {
2200         if (PredHasWeights && SuccHasWeights) {
2201           // PBI: br i1 %x, BB, FalseDest
2202           // BI:  br i1 %y, TrueDest, FalseDest
2203           //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2204           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2205           //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2206           //               TrueWeight for PBI * FalseWeight for BI.
2207           // We assume that total weights of a BranchInst can fit into 32 bits.
2208           // Therefore, we will not have overflow using 64-bit arithmetic.
2209           NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2210                SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2211         }
2212         AddPredecessorToBlock(TrueDest, PredBlock, BB);
2213         PBI->setSuccessor(0, TrueDest);
2214       }
2215       if (PBI->getSuccessor(1) == BB) {
2216         if (PredHasWeights && SuccHasWeights) {
2217           // PBI: br i1 %x, TrueDest, BB
2218           // BI:  br i1 %y, TrueDest, FalseDest
2219           //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2220           //              FalseWeight for PBI * TrueWeight for BI.
2221           NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2222               SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2223           //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2224           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2225         }
2226         AddPredecessorToBlock(FalseDest, PredBlock, BB);
2227         PBI->setSuccessor(1, FalseDest);
2228       }
2229       if (NewWeights.size() == 2) {
2230         // Halve the weights if any of them cannot fit in an uint32_t
2231         FitWeights(NewWeights);
2232
2233         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2234         PBI->setMetadata(LLVMContext::MD_prof,
2235                          MDBuilder(BI->getContext()).
2236                          createBranchWeights(MDWeights));
2237       } else
2238         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2239     } else {
2240       // Update PHI nodes in the common successors.
2241       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2242         ConstantInt *PBI_C = cast<ConstantInt>(
2243           PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2244         assert(PBI_C->getType()->isIntegerTy(1));
2245         Instruction *MergedCond = nullptr;
2246         if (PBI->getSuccessor(0) == TrueDest) {
2247           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2248           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2249           //       is false: !PBI_Cond and BI_Value
2250           Instruction *NotCond =
2251             cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2252                                 "not.cond"));
2253           MergedCond =
2254             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2255                                 NotCond, New,
2256                                 "and.cond"));
2257           if (PBI_C->isOne())
2258             MergedCond =
2259               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2260                                   PBI->getCondition(), MergedCond,
2261                                   "or.cond"));
2262         } else {
2263           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2264           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2265           //       is false: PBI_Cond and BI_Value
2266           MergedCond =
2267             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2268                                 PBI->getCondition(), New,
2269                                 "and.cond"));
2270           if (PBI_C->isOne()) {
2271             Instruction *NotCond =
2272               cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2273                                   "not.cond"));
2274             MergedCond =
2275               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2276                                   NotCond, MergedCond,
2277                                   "or.cond"));
2278           }
2279         }
2280         // Update PHI Node.
2281         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2282                                   MergedCond);
2283       }
2284       // Change PBI from Conditional to Unconditional.
2285       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2286       EraseTerminatorInstAndDCECond(PBI);
2287       PBI = New_PBI;
2288     }
2289
2290     // TODO: If BB is reachable from all paths through PredBlock, then we
2291     // could replace PBI's branch probabilities with BI's.
2292
2293     // Copy any debug value intrinsics into the end of PredBlock.
2294     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2295       if (isa<DbgInfoIntrinsic>(*I))
2296         I->clone()->insertBefore(PBI);
2297
2298     return true;
2299   }
2300   return false;
2301 }
2302
2303 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2304 /// predecessor of another block, this function tries to simplify it.  We know
2305 /// that PBI and BI are both conditional branches, and BI is in one of the
2306 /// successor blocks of PBI - PBI branches to BI.
2307 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2308   assert(PBI->isConditional() && BI->isConditional());
2309   BasicBlock *BB = BI->getParent();
2310
2311   // If this block ends with a branch instruction, and if there is a
2312   // predecessor that ends on a branch of the same condition, make
2313   // this conditional branch redundant.
2314   if (PBI->getCondition() == BI->getCondition() &&
2315       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2316     // Okay, the outcome of this conditional branch is statically
2317     // knowable.  If this block had a single pred, handle specially.
2318     if (BB->getSinglePredecessor()) {
2319       // Turn this into a branch on constant.
2320       bool CondIsTrue = PBI->getSuccessor(0) == BB;
2321       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2322                                         CondIsTrue));
2323       return true;  // Nuke the branch on constant.
2324     }
2325
2326     // Otherwise, if there are multiple predecessors, insert a PHI that merges
2327     // in the constant and simplify the block result.  Subsequent passes of
2328     // simplifycfg will thread the block.
2329     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2330       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2331       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2332                                        std::distance(PB, PE),
2333                                        BI->getCondition()->getName() + ".pr",
2334                                        BB->begin());
2335       // Okay, we're going to insert the PHI node.  Since PBI is not the only
2336       // predecessor, compute the PHI'd conditional value for all of the preds.
2337       // Any predecessor where the condition is not computable we keep symbolic.
2338       for (pred_iterator PI = PB; PI != PE; ++PI) {
2339         BasicBlock *P = *PI;
2340         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2341             PBI != BI && PBI->isConditional() &&
2342             PBI->getCondition() == BI->getCondition() &&
2343             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2344           bool CondIsTrue = PBI->getSuccessor(0) == BB;
2345           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2346                                               CondIsTrue), P);
2347         } else {
2348           NewPN->addIncoming(BI->getCondition(), P);
2349         }
2350       }
2351
2352       BI->setCondition(NewPN);
2353       return true;
2354     }
2355   }
2356
2357   // If this is a conditional branch in an empty block, and if any
2358   // predecessors are a conditional branch to one of our destinations,
2359   // fold the conditions into logical ops and one cond br.
2360   BasicBlock::iterator BBI = BB->begin();
2361   // Ignore dbg intrinsics.
2362   while (isa<DbgInfoIntrinsic>(BBI))
2363     ++BBI;
2364   if (&*BBI != BI)
2365     return false;
2366
2367
2368   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2369     if (CE->canTrap())
2370       return false;
2371
2372   int PBIOp, BIOp;
2373   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2374     PBIOp = BIOp = 0;
2375   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2376     PBIOp = 0, BIOp = 1;
2377   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2378     PBIOp = 1, BIOp = 0;
2379   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2380     PBIOp = BIOp = 1;
2381   else
2382     return false;
2383
2384   // Check to make sure that the other destination of this branch
2385   // isn't BB itself.  If so, this is an infinite loop that will
2386   // keep getting unwound.
2387   if (PBI->getSuccessor(PBIOp) == BB)
2388     return false;
2389
2390   // Do not perform this transformation if it would require
2391   // insertion of a large number of select instructions. For targets
2392   // without predication/cmovs, this is a big pessimization.
2393
2394   // Also do not perform this transformation if any phi node in the common
2395   // destination block can trap when reached by BB or PBB (PR17073). In that
2396   // case, it would be unsafe to hoist the operation into a select instruction.
2397
2398   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2399   unsigned NumPhis = 0;
2400   for (BasicBlock::iterator II = CommonDest->begin();
2401        isa<PHINode>(II); ++II, ++NumPhis) {
2402     if (NumPhis > 2) // Disable this xform.
2403       return false;
2404
2405     PHINode *PN = cast<PHINode>(II);
2406     Value *BIV = PN->getIncomingValueForBlock(BB);
2407     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2408       if (CE->canTrap())
2409         return false;
2410
2411     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2412     Value *PBIV = PN->getIncomingValue(PBBIdx);
2413     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2414       if (CE->canTrap())
2415         return false;
2416   }
2417
2418   // Finally, if everything is ok, fold the branches to logical ops.
2419   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2420
2421   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2422                << "AND: " << *BI->getParent());
2423
2424
2425   // If OtherDest *is* BB, then BB is a basic block with a single conditional
2426   // branch in it, where one edge (OtherDest) goes back to itself but the other
2427   // exits.  We don't *know* that the program avoids the infinite loop
2428   // (even though that seems likely).  If we do this xform naively, we'll end up
2429   // recursively unpeeling the loop.  Since we know that (after the xform is
2430   // done) that the block *is* infinite if reached, we just make it an obviously
2431   // infinite loop with no cond branch.
2432   if (OtherDest == BB) {
2433     // Insert it at the end of the function, because it's either code,
2434     // or it won't matter if it's hot. :)
2435     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2436                                                   "infloop", BB->getParent());
2437     BranchInst::Create(InfLoopBlock, InfLoopBlock);
2438     OtherDest = InfLoopBlock;
2439   }
2440
2441   DEBUG(dbgs() << *PBI->getParent()->getParent());
2442
2443   // BI may have other predecessors.  Because of this, we leave
2444   // it alone, but modify PBI.
2445
2446   // Make sure we get to CommonDest on True&True directions.
2447   Value *PBICond = PBI->getCondition();
2448   IRBuilder<true, NoFolder> Builder(PBI);
2449   if (PBIOp)
2450     PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2451
2452   Value *BICond = BI->getCondition();
2453   if (BIOp)
2454     BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2455
2456   // Merge the conditions.
2457   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2458
2459   // Modify PBI to branch on the new condition to the new dests.
2460   PBI->setCondition(Cond);
2461   PBI->setSuccessor(0, CommonDest);
2462   PBI->setSuccessor(1, OtherDest);
2463
2464   // Update branch weight for PBI.
2465   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2466   bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2467                                               PredFalseWeight);
2468   bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2469                                               SuccFalseWeight);
2470   if (PredHasWeights && SuccHasWeights) {
2471     uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2472     uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2473     uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2474     uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2475     // The weight to CommonDest should be PredCommon * SuccTotal +
2476     //                                    PredOther * SuccCommon.
2477     // The weight to OtherDest should be PredOther * SuccOther.
2478     SmallVector<uint64_t, 2> NewWeights;
2479     NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2480                          PredOther * SuccCommon);
2481     NewWeights.push_back(PredOther * SuccOther);
2482     // Halve the weights if any of them cannot fit in an uint32_t
2483     FitWeights(NewWeights);
2484
2485     SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2486     PBI->setMetadata(LLVMContext::MD_prof,
2487                      MDBuilder(BI->getContext()).
2488                      createBranchWeights(MDWeights));
2489   }
2490
2491   // OtherDest may have phi nodes.  If so, add an entry from PBI's
2492   // block that are identical to the entries for BI's block.
2493   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2494
2495   // We know that the CommonDest already had an edge from PBI to
2496   // it.  If it has PHIs though, the PHIs may have different
2497   // entries for BB and PBI's BB.  If so, insert a select to make
2498   // them agree.
2499   PHINode *PN;
2500   for (BasicBlock::iterator II = CommonDest->begin();
2501        (PN = dyn_cast<PHINode>(II)); ++II) {
2502     Value *BIV = PN->getIncomingValueForBlock(BB);
2503     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2504     Value *PBIV = PN->getIncomingValue(PBBIdx);
2505     if (BIV != PBIV) {
2506       // Insert a select in PBI to pick the right value.
2507       Value *NV = cast<SelectInst>
2508         (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2509       PN->setIncomingValue(PBBIdx, NV);
2510     }
2511   }
2512
2513   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2514   DEBUG(dbgs() << *PBI->getParent()->getParent());
2515
2516   // This basic block is probably dead.  We know it has at least
2517   // one fewer predecessor.
2518   return true;
2519 }
2520
2521 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2522 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2523 // Takes care of updating the successors and removing the old terminator.
2524 // Also makes sure not to introduce new successors by assuming that edges to
2525 // non-successor TrueBBs and FalseBBs aren't reachable.
2526 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2527                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
2528                                        uint32_t TrueWeight,
2529                                        uint32_t FalseWeight){
2530   // Remove any superfluous successor edges from the CFG.
2531   // First, figure out which successors to preserve.
2532   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2533   // successor.
2534   BasicBlock *KeepEdge1 = TrueBB;
2535   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2536
2537   // Then remove the rest.
2538   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2539     BasicBlock *Succ = OldTerm->getSuccessor(I);
2540     // Make sure only to keep exactly one copy of each edge.
2541     if (Succ == KeepEdge1)
2542       KeepEdge1 = nullptr;
2543     else if (Succ == KeepEdge2)
2544       KeepEdge2 = nullptr;
2545     else
2546       Succ->removePredecessor(OldTerm->getParent());
2547   }
2548
2549   IRBuilder<> Builder(OldTerm);
2550   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2551
2552   // Insert an appropriate new terminator.
2553   if (!KeepEdge1 && !KeepEdge2) {
2554     if (TrueBB == FalseBB)
2555       // We were only looking for one successor, and it was present.
2556       // Create an unconditional branch to it.
2557       Builder.CreateBr(TrueBB);
2558     else {
2559       // We found both of the successors we were looking for.
2560       // Create a conditional branch sharing the condition of the select.
2561       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2562       if (TrueWeight != FalseWeight)
2563         NewBI->setMetadata(LLVMContext::MD_prof,
2564                            MDBuilder(OldTerm->getContext()).
2565                            createBranchWeights(TrueWeight, FalseWeight));
2566     }
2567   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2568     // Neither of the selected blocks were successors, so this
2569     // terminator must be unreachable.
2570     new UnreachableInst(OldTerm->getContext(), OldTerm);
2571   } else {
2572     // One of the selected values was a successor, but the other wasn't.
2573     // Insert an unconditional branch to the one that was found;
2574     // the edge to the one that wasn't must be unreachable.
2575     if (!KeepEdge1)
2576       // Only TrueBB was found.
2577       Builder.CreateBr(TrueBB);
2578     else
2579       // Only FalseBB was found.
2580       Builder.CreateBr(FalseBB);
2581   }
2582
2583   EraseTerminatorInstAndDCECond(OldTerm);
2584   return true;
2585 }
2586
2587 // SimplifySwitchOnSelect - Replaces
2588 //   (switch (select cond, X, Y)) on constant X, Y
2589 // with a branch - conditional if X and Y lead to distinct BBs,
2590 // unconditional otherwise.
2591 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2592   // Check for constant integer values in the select.
2593   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2594   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2595   if (!TrueVal || !FalseVal)
2596     return false;
2597
2598   // Find the relevant condition and destinations.
2599   Value *Condition = Select->getCondition();
2600   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2601   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2602
2603   // Get weight for TrueBB and FalseBB.
2604   uint32_t TrueWeight = 0, FalseWeight = 0;
2605   SmallVector<uint64_t, 8> Weights;
2606   bool HasWeights = HasBranchWeights(SI);
2607   if (HasWeights) {
2608     GetBranchWeights(SI, Weights);
2609     if (Weights.size() == 1 + SI->getNumCases()) {
2610       TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2611                                      getSuccessorIndex()];
2612       FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2613                                       getSuccessorIndex()];
2614     }
2615   }
2616
2617   // Perform the actual simplification.
2618   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2619                                     TrueWeight, FalseWeight);
2620 }
2621
2622 // SimplifyIndirectBrOnSelect - Replaces
2623 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
2624 //                             blockaddress(@fn, BlockB)))
2625 // with
2626 //   (br cond, BlockA, BlockB).
2627 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2628   // Check that both operands of the select are block addresses.
2629   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2630   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2631   if (!TBA || !FBA)
2632     return false;
2633
2634   // Extract the actual blocks.
2635   BasicBlock *TrueBB = TBA->getBasicBlock();
2636   BasicBlock *FalseBB = FBA->getBasicBlock();
2637
2638   // Perform the actual simplification.
2639   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2640                                     0, 0);
2641 }
2642
2643 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2644 /// instruction (a seteq/setne with a constant) as the only instruction in a
2645 /// block that ends with an uncond branch.  We are looking for a very specific
2646 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
2647 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2648 /// default value goes to an uncond block with a seteq in it, we get something
2649 /// like:
2650 ///
2651 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
2652 /// DEFAULT:
2653 ///   %tmp = icmp eq i8 %A, 92
2654 ///   br label %end
2655 /// end:
2656 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2657 ///
2658 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2659 /// the PHI, merging the third icmp into the switch.
2660 static bool TryToSimplifyUncondBranchWithICmpInIt(
2661     ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2662     const DataLayout *DL, AssumptionTracker *AT) {
2663   BasicBlock *BB = ICI->getParent();
2664
2665   // If the block has any PHIs in it or the icmp has multiple uses, it is too
2666   // complex.
2667   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2668
2669   Value *V = ICI->getOperand(0);
2670   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2671
2672   // The pattern we're looking for is where our only predecessor is a switch on
2673   // 'V' and this block is the default case for the switch.  In this case we can
2674   // fold the compared value into the switch to simplify things.
2675   BasicBlock *Pred = BB->getSinglePredecessor();
2676   if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2677
2678   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2679   if (SI->getCondition() != V)
2680     return false;
2681
2682   // If BB is reachable on a non-default case, then we simply know the value of
2683   // V in this block.  Substitute it and constant fold the icmp instruction
2684   // away.
2685   if (SI->getDefaultDest() != BB) {
2686     ConstantInt *VVal = SI->findCaseDest(BB);
2687     assert(VVal && "Should have a unique destination value");
2688     ICI->setOperand(0, VVal);
2689
2690     if (Value *V = SimplifyInstruction(ICI, DL)) {
2691       ICI->replaceAllUsesWith(V);
2692       ICI->eraseFromParent();
2693     }
2694     // BB is now empty, so it is likely to simplify away.
2695     return SimplifyCFG(BB, TTI, DL, AT) | true;
2696   }
2697
2698   // Ok, the block is reachable from the default dest.  If the constant we're
2699   // comparing exists in one of the other edges, then we can constant fold ICI
2700   // and zap it.
2701   if (SI->findCaseValue(Cst) != SI->case_default()) {
2702     Value *V;
2703     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2704       V = ConstantInt::getFalse(BB->getContext());
2705     else
2706       V = ConstantInt::getTrue(BB->getContext());
2707
2708     ICI->replaceAllUsesWith(V);
2709     ICI->eraseFromParent();
2710     // BB is now empty, so it is likely to simplify away.
2711     return SimplifyCFG(BB, TTI, DL, AT) | true;
2712   }
2713
2714   // The use of the icmp has to be in the 'end' block, by the only PHI node in
2715   // the block.
2716   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2717   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2718   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2719       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2720     return false;
2721
2722   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2723   // true in the PHI.
2724   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2725   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
2726
2727   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2728     std::swap(DefaultCst, NewCst);
2729
2730   // Replace ICI (which is used by the PHI for the default value) with true or
2731   // false depending on if it is EQ or NE.
2732   ICI->replaceAllUsesWith(DefaultCst);
2733   ICI->eraseFromParent();
2734
2735   // Okay, the switch goes to this block on a default value.  Add an edge from
2736   // the switch to the merge point on the compared value.
2737   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2738                                          BB->getParent(), BB);
2739   SmallVector<uint64_t, 8> Weights;
2740   bool HasWeights = HasBranchWeights(SI);
2741   if (HasWeights) {
2742     GetBranchWeights(SI, Weights);
2743     if (Weights.size() == 1 + SI->getNumCases()) {
2744       // Split weight for default case to case for "Cst".
2745       Weights[0] = (Weights[0]+1) >> 1;
2746       Weights.push_back(Weights[0]);
2747
2748       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2749       SI->setMetadata(LLVMContext::MD_prof,
2750                       MDBuilder(SI->getContext()).
2751                       createBranchWeights(MDWeights));
2752     }
2753   }
2754   SI->addCase(Cst, NewBB);
2755
2756   // NewBB branches to the phi block, add the uncond branch and the phi entry.
2757   Builder.SetInsertPoint(NewBB);
2758   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2759   Builder.CreateBr(SuccBlock);
2760   PHIUse->addIncoming(NewCst, NewBB);
2761   return true;
2762 }
2763
2764 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2765 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2766 /// fold it into a switch instruction if so.
2767 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2768                                       IRBuilder<> &Builder) {
2769   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2770   if (!Cond) return false;
2771
2772
2773   // Change br (X == 0 | X == 1), T, F into a switch instruction.
2774   // If this is a bunch of seteq's or'd together, or if it's a bunch of
2775   // 'setne's and'ed together, collect them.
2776   Value *CompVal = nullptr;
2777   std::vector<ConstantInt*> Values;
2778   bool TrueWhenEqual = true;
2779   Value *ExtraCase = nullptr;
2780   unsigned UsedICmps = 0;
2781
2782   if (Cond->getOpcode() == Instruction::Or) {
2783     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
2784                                      UsedICmps);
2785   } else if (Cond->getOpcode() == Instruction::And) {
2786     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
2787                                      UsedICmps);
2788     TrueWhenEqual = false;
2789   }
2790
2791   // If we didn't have a multiply compared value, fail.
2792   if (!CompVal) return false;
2793
2794   // Avoid turning single icmps into a switch.
2795   if (UsedICmps <= 1)
2796     return false;
2797
2798   // There might be duplicate constants in the list, which the switch
2799   // instruction can't handle, remove them now.
2800   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2801   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2802
2803   // If Extra was used, we require at least two switch values to do the
2804   // transformation.  A switch with one value is just an cond branch.
2805   if (ExtraCase && Values.size() < 2) return false;
2806
2807   // TODO: Preserve branch weight metadata, similarly to how
2808   // FoldValueComparisonIntoPredecessors preserves it.
2809
2810   // Figure out which block is which destination.
2811   BasicBlock *DefaultBB = BI->getSuccessor(1);
2812   BasicBlock *EdgeBB    = BI->getSuccessor(0);
2813   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2814
2815   BasicBlock *BB = BI->getParent();
2816
2817   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2818                << " cases into SWITCH.  BB is:\n" << *BB);
2819
2820   // If there are any extra values that couldn't be folded into the switch
2821   // then we evaluate them with an explicit branch first.  Split the block
2822   // right before the condbr to handle it.
2823   if (ExtraCase) {
2824     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2825     // Remove the uncond branch added to the old block.
2826     TerminatorInst *OldTI = BB->getTerminator();
2827     Builder.SetInsertPoint(OldTI);
2828
2829     if (TrueWhenEqual)
2830       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2831     else
2832       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2833
2834     OldTI->eraseFromParent();
2835
2836     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2837     // for the edge we just added.
2838     AddPredecessorToBlock(EdgeBB, BB, NewBB);
2839
2840     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
2841           << "\nEXTRABB = " << *BB);
2842     BB = NewBB;
2843   }
2844
2845   Builder.SetInsertPoint(BI);
2846   // Convert pointer to int before we switch.
2847   if (CompVal->getType()->isPointerTy()) {
2848     assert(DL && "Cannot switch on pointer without DataLayout");
2849     CompVal = Builder.CreatePtrToInt(CompVal,
2850                                      DL->getIntPtrType(CompVal->getType()),
2851                                      "magicptr");
2852   }
2853
2854   // Create the new switch instruction now.
2855   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2856
2857   // Add all of the 'cases' to the switch instruction.
2858   for (unsigned i = 0, e = Values.size(); i != e; ++i)
2859     New->addCase(Values[i], EdgeBB);
2860
2861   // We added edges from PI to the EdgeBB.  As such, if there were any
2862   // PHI nodes in EdgeBB, they need entries to be added corresponding to
2863   // the number of edges added.
2864   for (BasicBlock::iterator BBI = EdgeBB->begin();
2865        isa<PHINode>(BBI); ++BBI) {
2866     PHINode *PN = cast<PHINode>(BBI);
2867     Value *InVal = PN->getIncomingValueForBlock(BB);
2868     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2869       PN->addIncoming(InVal, BB);
2870   }
2871
2872   // Erase the old branch instruction.
2873   EraseTerminatorInstAndDCECond(BI);
2874
2875   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
2876   return true;
2877 }
2878
2879 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2880   // If this is a trivial landing pad that just continues unwinding the caught
2881   // exception then zap the landing pad, turning its invokes into calls.
2882   BasicBlock *BB = RI->getParent();
2883   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2884   if (RI->getValue() != LPInst)
2885     // Not a landing pad, or the resume is not unwinding the exception that
2886     // caused control to branch here.
2887     return false;
2888
2889   // Check that there are no other instructions except for debug intrinsics.
2890   BasicBlock::iterator I = LPInst, E = RI;
2891   while (++I != E)
2892     if (!isa<DbgInfoIntrinsic>(I))
2893       return false;
2894
2895   // Turn all invokes that unwind here into calls and delete the basic block.
2896   bool InvokeRequiresTableEntry = false;
2897   bool Changed = false;
2898   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2899     InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2900
2901     if (II->hasFnAttr(Attribute::UWTable)) {
2902       // Don't remove an `invoke' instruction if the ABI requires an entry into
2903       // the table.
2904       InvokeRequiresTableEntry = true;
2905       continue;
2906     }
2907
2908     SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2909
2910     // Insert a call instruction before the invoke.
2911     CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2912     Call->takeName(II);
2913     Call->setCallingConv(II->getCallingConv());
2914     Call->setAttributes(II->getAttributes());
2915     Call->setDebugLoc(II->getDebugLoc());
2916
2917     // Anything that used the value produced by the invoke instruction now uses
2918     // the value produced by the call instruction.  Note that we do this even
2919     // for void functions and calls with no uses so that the callgraph edge is
2920     // updated.
2921     II->replaceAllUsesWith(Call);
2922     BB->removePredecessor(II->getParent());
2923
2924     // Insert a branch to the normal destination right before the invoke.
2925     BranchInst::Create(II->getNormalDest(), II);
2926
2927     // Finally, delete the invoke instruction!
2928     II->eraseFromParent();
2929     Changed = true;
2930   }
2931
2932   if (!InvokeRequiresTableEntry)
2933     // The landingpad is now unreachable.  Zap it.
2934     BB->eraseFromParent();
2935
2936   return Changed;
2937 }
2938
2939 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2940   BasicBlock *BB = RI->getParent();
2941   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2942
2943   // Find predecessors that end with branches.
2944   SmallVector<BasicBlock*, 8> UncondBranchPreds;
2945   SmallVector<BranchInst*, 8> CondBranchPreds;
2946   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2947     BasicBlock *P = *PI;
2948     TerminatorInst *PTI = P->getTerminator();
2949     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2950       if (BI->isUnconditional())
2951         UncondBranchPreds.push_back(P);
2952       else
2953         CondBranchPreds.push_back(BI);
2954     }
2955   }
2956
2957   // If we found some, do the transformation!
2958   if (!UncondBranchPreds.empty() && DupRet) {
2959     while (!UncondBranchPreds.empty()) {
2960       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2961       DEBUG(dbgs() << "FOLDING: " << *BB
2962             << "INTO UNCOND BRANCH PRED: " << *Pred);
2963       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2964     }
2965
2966     // If we eliminated all predecessors of the block, delete the block now.
2967     if (pred_begin(BB) == pred_end(BB))
2968       // We know there are no successors, so just nuke the block.
2969       BB->eraseFromParent();
2970
2971     return true;
2972   }
2973
2974   // Check out all of the conditional branches going to this return
2975   // instruction.  If any of them just select between returns, change the
2976   // branch itself into a select/return pair.
2977   while (!CondBranchPreds.empty()) {
2978     BranchInst *BI = CondBranchPreds.pop_back_val();
2979
2980     // Check to see if the non-BB successor is also a return block.
2981     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2982         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2983         SimplifyCondBranchToTwoReturns(BI, Builder))
2984       return true;
2985   }
2986   return false;
2987 }
2988
2989 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2990   BasicBlock *BB = UI->getParent();
2991
2992   bool Changed = false;
2993
2994   // If there are any instructions immediately before the unreachable that can
2995   // be removed, do so.
2996   while (UI != BB->begin()) {
2997     BasicBlock::iterator BBI = UI;
2998     --BBI;
2999     // Do not delete instructions that can have side effects which might cause
3000     // the unreachable to not be reachable; specifically, calls and volatile
3001     // operations may have this effect.
3002     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3003
3004     if (BBI->mayHaveSideEffects()) {
3005       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3006         if (SI->isVolatile())
3007           break;
3008       } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3009         if (LI->isVolatile())
3010           break;
3011       } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3012         if (RMWI->isVolatile())
3013           break;
3014       } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3015         if (CXI->isVolatile())
3016           break;
3017       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3018                  !isa<LandingPadInst>(BBI)) {
3019         break;
3020       }
3021       // Note that deleting LandingPad's here is in fact okay, although it
3022       // involves a bit of subtle reasoning. If this inst is a LandingPad,
3023       // all the predecessors of this block will be the unwind edges of Invokes,
3024       // and we can therefore guarantee this block will be erased.
3025     }
3026
3027     // Delete this instruction (any uses are guaranteed to be dead)
3028     if (!BBI->use_empty())
3029       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3030     BBI->eraseFromParent();
3031     Changed = true;
3032   }
3033
3034   // If the unreachable instruction is the first in the block, take a gander
3035   // at all of the predecessors of this instruction, and simplify them.
3036   if (&BB->front() != UI) return Changed;
3037
3038   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3039   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3040     TerminatorInst *TI = Preds[i]->getTerminator();
3041     IRBuilder<> Builder(TI);
3042     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3043       if (BI->isUnconditional()) {
3044         if (BI->getSuccessor(0) == BB) {
3045           new UnreachableInst(TI->getContext(), TI);
3046           TI->eraseFromParent();
3047           Changed = true;
3048         }
3049       } else {
3050         if (BI->getSuccessor(0) == BB) {
3051           Builder.CreateBr(BI->getSuccessor(1));
3052           EraseTerminatorInstAndDCECond(BI);
3053         } else if (BI->getSuccessor(1) == BB) {
3054           Builder.CreateBr(BI->getSuccessor(0));
3055           EraseTerminatorInstAndDCECond(BI);
3056           Changed = true;
3057         }
3058       }
3059     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3060       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3061            i != e; ++i)
3062         if (i.getCaseSuccessor() == BB) {
3063           BB->removePredecessor(SI->getParent());
3064           SI->removeCase(i);
3065           --i; --e;
3066           Changed = true;
3067         }
3068       // If the default value is unreachable, figure out the most popular
3069       // destination and make it the default.
3070       if (SI->getDefaultDest() == BB) {
3071         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3072         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3073              i != e; ++i) {
3074           std::pair<unsigned, unsigned> &entry =
3075               Popularity[i.getCaseSuccessor()];
3076           if (entry.first == 0) {
3077             entry.first = 1;
3078             entry.second = i.getCaseIndex();
3079           } else {
3080             entry.first++;
3081           }
3082         }
3083
3084         // Find the most popular block.
3085         unsigned MaxPop = 0;
3086         unsigned MaxIndex = 0;
3087         BasicBlock *MaxBlock = nullptr;
3088         for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3089              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3090           if (I->second.first > MaxPop ||
3091               (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3092             MaxPop = I->second.first;
3093             MaxIndex = I->second.second;
3094             MaxBlock = I->first;
3095           }
3096         }
3097         if (MaxBlock) {
3098           // Make this the new default, allowing us to delete any explicit
3099           // edges to it.
3100           SI->setDefaultDest(MaxBlock);
3101           Changed = true;
3102
3103           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3104           // it.
3105           if (isa<PHINode>(MaxBlock->begin()))
3106             for (unsigned i = 0; i != MaxPop-1; ++i)
3107               MaxBlock->removePredecessor(SI->getParent());
3108
3109           for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3110                i != e; ++i)
3111             if (i.getCaseSuccessor() == MaxBlock) {
3112               SI->removeCase(i);
3113               --i; --e;
3114             }
3115         }
3116       }
3117     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3118       if (II->getUnwindDest() == BB) {
3119         // Convert the invoke to a call instruction.  This would be a good
3120         // place to note that the call does not throw though.
3121         BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3122         II->removeFromParent();   // Take out of symbol table
3123
3124         // Insert the call now...
3125         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3126         Builder.SetInsertPoint(BI);
3127         CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3128                                           Args, II->getName());
3129         CI->setCallingConv(II->getCallingConv());
3130         CI->setAttributes(II->getAttributes());
3131         // If the invoke produced a value, the call does now instead.
3132         II->replaceAllUsesWith(CI);
3133         delete II;
3134         Changed = true;
3135       }
3136     }
3137   }
3138
3139   // If this block is now dead, remove it.
3140   if (pred_begin(BB) == pred_end(BB) &&
3141       BB != &BB->getParent()->getEntryBlock()) {
3142     // We know there are no successors, so just nuke the block.
3143     BB->eraseFromParent();
3144     return true;
3145   }
3146
3147   return Changed;
3148 }
3149
3150 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3151 /// integer range comparison into a sub, an icmp and a branch.
3152 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3153   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3154
3155   // Make sure all cases point to the same destination and gather the values.
3156   SmallVector<ConstantInt *, 16> Cases;
3157   SwitchInst::CaseIt I = SI->case_begin();
3158   Cases.push_back(I.getCaseValue());
3159   SwitchInst::CaseIt PrevI = I++;
3160   for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3161     if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3162       return false;
3163     Cases.push_back(I.getCaseValue());
3164   }
3165   assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3166
3167   // Sort the case values, then check if they form a range we can transform.
3168   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3169   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3170     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3171       return false;
3172   }
3173
3174   Constant *Offset = ConstantExpr::getNeg(Cases.back());
3175   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3176
3177   Value *Sub = SI->getCondition();
3178   if (!Offset->isNullValue())
3179     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3180   Value *Cmp;
3181   // If NumCases overflowed, then all possible values jump to the successor.
3182   if (NumCases->isNullValue() && SI->getNumCases() != 0)
3183     Cmp = ConstantInt::getTrue(SI->getContext());
3184   else
3185     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3186   BranchInst *NewBI = Builder.CreateCondBr(
3187       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3188
3189   // Update weight for the newly-created conditional branch.
3190   SmallVector<uint64_t, 8> Weights;
3191   bool HasWeights = HasBranchWeights(SI);
3192   if (HasWeights) {
3193     GetBranchWeights(SI, Weights);
3194     if (Weights.size() == 1 + SI->getNumCases()) {
3195       // Combine all weights for the cases to be the true weight of NewBI.
3196       // We assume that the sum of all weights for a Terminator can fit into 32
3197       // bits.
3198       uint32_t NewTrueWeight = 0;
3199       for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3200         NewTrueWeight += (uint32_t)Weights[I];
3201       NewBI->setMetadata(LLVMContext::MD_prof,
3202                          MDBuilder(SI->getContext()).
3203                          createBranchWeights(NewTrueWeight,
3204                                              (uint32_t)Weights[0]));
3205     }
3206   }
3207
3208   // Prune obsolete incoming values off the successor's PHI nodes.
3209   for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3210        isa<PHINode>(BBI); ++BBI) {
3211     for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3212       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3213   }
3214   SI->eraseFromParent();
3215
3216   return true;
3217 }
3218
3219 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3220 /// and use it to remove dead cases.
3221 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3222                                      AssumptionTracker *AT) {
3223   Value *Cond = SI->getCondition();
3224   unsigned Bits = Cond->getType()->getIntegerBitWidth();
3225   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3226   computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3227
3228   // Gather dead cases.
3229   SmallVector<ConstantInt*, 8> DeadCases;
3230   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3231     if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3232         (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3233       DeadCases.push_back(I.getCaseValue());
3234       DEBUG(dbgs() << "SimplifyCFG: switch case '"
3235                    << I.getCaseValue() << "' is dead.\n");
3236     }
3237   }
3238
3239   SmallVector<uint64_t, 8> Weights;
3240   bool HasWeight = HasBranchWeights(SI);
3241   if (HasWeight) {
3242     GetBranchWeights(SI, Weights);
3243     HasWeight = (Weights.size() == 1 + SI->getNumCases());
3244   }
3245
3246   // Remove dead cases from the switch.
3247   for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3248     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3249     assert(Case != SI->case_default() &&
3250            "Case was not found. Probably mistake in DeadCases forming.");
3251     if (HasWeight) {
3252       std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3253       Weights.pop_back();
3254     }
3255
3256     // Prune unused values from PHI nodes.
3257     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3258     SI->removeCase(Case);
3259   }
3260   if (HasWeight && Weights.size() >= 2) {
3261     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3262     SI->setMetadata(LLVMContext::MD_prof,
3263                     MDBuilder(SI->getParent()->getContext()).
3264                     createBranchWeights(MDWeights));
3265   }
3266
3267   return !DeadCases.empty();
3268 }
3269
3270 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3271 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3272 /// by an unconditional branch), look at the phi node for BB in the successor
3273 /// block and see if the incoming value is equal to CaseValue. If so, return
3274 /// the phi node, and set PhiIndex to BB's index in the phi node.
3275 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3276                                               BasicBlock *BB,
3277                                               int *PhiIndex) {
3278   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3279     return nullptr; // BB must be empty to be a candidate for simplification.
3280   if (!BB->getSinglePredecessor())
3281     return nullptr; // BB must be dominated by the switch.
3282
3283   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3284   if (!Branch || !Branch->isUnconditional())
3285     return nullptr; // Terminator must be unconditional branch.
3286
3287   BasicBlock *Succ = Branch->getSuccessor(0);
3288
3289   BasicBlock::iterator I = Succ->begin();
3290   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3291     int Idx = PHI->getBasicBlockIndex(BB);
3292     assert(Idx >= 0 && "PHI has no entry for predecessor?");
3293
3294     Value *InValue = PHI->getIncomingValue(Idx);
3295     if (InValue != CaseValue) continue;
3296
3297     *PhiIndex = Idx;
3298     return PHI;
3299   }
3300
3301   return nullptr;
3302 }
3303
3304 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3305 /// instruction to a phi node dominated by the switch, if that would mean that
3306 /// some of the destination blocks of the switch can be folded away.
3307 /// Returns true if a change is made.
3308 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3309   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3310   ForwardingNodesMap ForwardingNodes;
3311
3312   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3313     ConstantInt *CaseValue = I.getCaseValue();
3314     BasicBlock *CaseDest = I.getCaseSuccessor();
3315
3316     int PhiIndex;
3317     PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3318                                                  &PhiIndex);
3319     if (!PHI) continue;
3320
3321     ForwardingNodes[PHI].push_back(PhiIndex);
3322   }
3323
3324   bool Changed = false;
3325
3326   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3327        E = ForwardingNodes.end(); I != E; ++I) {
3328     PHINode *Phi = I->first;
3329     SmallVectorImpl<int> &Indexes = I->second;
3330
3331     if (Indexes.size() < 2) continue;
3332
3333     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3334       Phi->setIncomingValue(Indexes[I], SI->getCondition());
3335     Changed = true;
3336   }
3337
3338   return Changed;
3339 }
3340
3341 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3342 /// initializing an array of constants like C.
3343 static bool ValidLookupTableConstant(Constant *C) {
3344   if (C->isThreadDependent())
3345     return false;
3346   if (C->isDLLImportDependent())
3347     return false;
3348
3349   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3350     return CE->isGEPWithNoNotionalOverIndexing();
3351
3352   return isa<ConstantFP>(C) ||
3353       isa<ConstantInt>(C) ||
3354       isa<ConstantPointerNull>(C) ||
3355       isa<GlobalValue>(C) ||
3356       isa<UndefValue>(C);
3357 }
3358
3359 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3360 /// its constant value in ConstantPool, returning 0 if it's not there.
3361 static Constant *LookupConstant(Value *V,
3362                          const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3363   if (Constant *C = dyn_cast<Constant>(V))
3364     return C;
3365   return ConstantPool.lookup(V);
3366 }
3367
3368 /// ConstantFold - Try to fold instruction I into a constant. This works for
3369 /// simple instructions such as binary operations where both operands are
3370 /// constant or can be replaced by constants from the ConstantPool. Returns the
3371 /// resulting constant on success, 0 otherwise.
3372 static Constant *
3373 ConstantFold(Instruction *I,
3374              const SmallDenseMap<Value *, Constant *> &ConstantPool,
3375              const DataLayout *DL) {
3376   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3377     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3378     if (!A)
3379       return nullptr;
3380     if (A->isAllOnesValue())
3381       return LookupConstant(Select->getTrueValue(), ConstantPool);
3382     if (A->isNullValue())
3383       return LookupConstant(Select->getFalseValue(), ConstantPool);
3384     return nullptr;
3385   }
3386
3387   SmallVector<Constant *, 4> COps;
3388   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3389     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3390       COps.push_back(A);
3391     else
3392       return nullptr;
3393   }
3394
3395   if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3396     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3397                                            COps[1], DL);
3398
3399   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3400 }
3401
3402 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3403 /// at the common destination basic block, *CommonDest, for one of the case
3404 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3405 /// case), of a switch instruction SI.
3406 static bool
3407 GetCaseResults(SwitchInst *SI,
3408                ConstantInt *CaseVal,
3409                BasicBlock *CaseDest,
3410                BasicBlock **CommonDest,
3411                SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3412                const DataLayout *DL) {
3413   // The block from which we enter the common destination.
3414   BasicBlock *Pred = SI->getParent();
3415
3416   // If CaseDest is empty except for some side-effect free instructions through
3417   // which we can constant-propagate the CaseVal, continue to its successor.
3418   SmallDenseMap<Value*, Constant*> ConstantPool;
3419   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3420   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3421        ++I) {
3422     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3423       // If the terminator is a simple branch, continue to the next block.
3424       if (T->getNumSuccessors() != 1)
3425         return false;
3426       Pred = CaseDest;
3427       CaseDest = T->getSuccessor(0);
3428     } else if (isa<DbgInfoIntrinsic>(I)) {
3429       // Skip debug intrinsic.
3430       continue;
3431     } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3432       // Instruction is side-effect free and constant.
3433       ConstantPool.insert(std::make_pair(I, C));
3434     } else {
3435       break;
3436     }
3437   }
3438
3439   // If we did not have a CommonDest before, use the current one.
3440   if (!*CommonDest)
3441     *CommonDest = CaseDest;
3442   // If the destination isn't the common one, abort.
3443   if (CaseDest != *CommonDest)
3444     return false;
3445
3446   // Get the values for this case from phi nodes in the destination block.
3447   BasicBlock::iterator I = (*CommonDest)->begin();
3448   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3449     int Idx = PHI->getBasicBlockIndex(Pred);
3450     if (Idx == -1)
3451       continue;
3452
3453     Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3454                                         ConstantPool);
3455     if (!ConstVal)
3456       return false;
3457
3458     // Note: If the constant comes from constant-propagating the case value
3459     // through the CaseDest basic block, it will be safe to remove the
3460     // instructions in that block. They cannot be used (except in the phi nodes
3461     // we visit) outside CaseDest, because that block does not dominate its
3462     // successor. If it did, we would not be in this phi node.
3463
3464     // Be conservative about which kinds of constants we support.
3465     if (!ValidLookupTableConstant(ConstVal))
3466       return false;
3467
3468     Res.push_back(std::make_pair(PHI, ConstVal));
3469   }
3470
3471   return Res.size() > 0;
3472 }
3473
3474 namespace {
3475   /// SwitchLookupTable - This class represents a lookup table that can be used
3476   /// to replace a switch.
3477   class SwitchLookupTable {
3478   public:
3479     /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3480     /// with the contents of Values, using DefaultValue to fill any holes in the
3481     /// table.
3482     SwitchLookupTable(Module &M,
3483                       uint64_t TableSize,
3484                       ConstantInt *Offset,
3485              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3486                       Constant *DefaultValue,
3487                       const DataLayout *DL);
3488
3489     /// BuildLookup - Build instructions with Builder to retrieve the value at
3490     /// the position given by Index in the lookup table.
3491     Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3492
3493     /// WouldFitInRegister - Return true if a table with TableSize elements of
3494     /// type ElementType would fit in a target-legal register.
3495     static bool WouldFitInRegister(const DataLayout *DL,
3496                                    uint64_t TableSize,
3497                                    const Type *ElementType);
3498
3499   private:
3500     // Depending on the contents of the table, it can be represented in
3501     // different ways.
3502     enum {
3503       // For tables where each element contains the same value, we just have to
3504       // store that single value and return it for each lookup.
3505       SingleValueKind,
3506
3507       // For small tables with integer elements, we can pack them into a bitmap
3508       // that fits into a target-legal register. Values are retrieved by
3509       // shift and mask operations.
3510       BitMapKind,
3511
3512       // The table is stored as an array of values. Values are retrieved by load
3513       // instructions from the table.
3514       ArrayKind
3515     } Kind;
3516
3517     // For SingleValueKind, this is the single value.
3518     Constant *SingleValue;
3519
3520     // For BitMapKind, this is the bitmap.
3521     ConstantInt *BitMap;
3522     IntegerType *BitMapElementTy;
3523
3524     // For ArrayKind, this is the array.
3525     GlobalVariable *Array;
3526   };
3527 }
3528
3529 SwitchLookupTable::SwitchLookupTable(Module &M,
3530                                      uint64_t TableSize,
3531                                      ConstantInt *Offset,
3532              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3533                                      Constant *DefaultValue,
3534                                      const DataLayout *DL)
3535     : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3536       Array(nullptr) {
3537   assert(Values.size() && "Can't build lookup table without values!");
3538   assert(TableSize >= Values.size() && "Can't fit values in table!");
3539
3540   // If all values in the table are equal, this is that value.
3541   SingleValue = Values.begin()->second;
3542
3543   Type *ValueType = Values.begin()->second->getType();
3544
3545   // Build up the table contents.
3546   SmallVector<Constant*, 64> TableContents(TableSize);
3547   for (size_t I = 0, E = Values.size(); I != E; ++I) {
3548     ConstantInt *CaseVal = Values[I].first;
3549     Constant *CaseRes = Values[I].second;
3550     assert(CaseRes->getType() == ValueType);
3551
3552     uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3553                    .getLimitedValue();
3554     TableContents[Idx] = CaseRes;
3555
3556     if (CaseRes != SingleValue)
3557       SingleValue = nullptr;
3558   }
3559
3560   // Fill in any holes in the table with the default result.
3561   if (Values.size() < TableSize) {
3562     assert(DefaultValue &&
3563            "Need a default value to fill the lookup table holes.");
3564     assert(DefaultValue->getType() == ValueType);
3565     for (uint64_t I = 0; I < TableSize; ++I) {
3566       if (!TableContents[I])
3567         TableContents[I] = DefaultValue;
3568     }
3569
3570     if (DefaultValue != SingleValue)
3571       SingleValue = nullptr;
3572   }
3573
3574   // If each element in the table contains the same value, we only need to store
3575   // that single value.
3576   if (SingleValue) {
3577     Kind = SingleValueKind;
3578     return;
3579   }
3580
3581   // If the type is integer and the table fits in a register, build a bitmap.
3582   if (WouldFitInRegister(DL, TableSize, ValueType)) {
3583     IntegerType *IT = cast<IntegerType>(ValueType);
3584     APInt TableInt(TableSize * IT->getBitWidth(), 0);
3585     for (uint64_t I = TableSize; I > 0; --I) {
3586       TableInt <<= IT->getBitWidth();
3587       // Insert values into the bitmap. Undef values are set to zero.
3588       if (!isa<UndefValue>(TableContents[I - 1])) {
3589         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3590         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3591       }
3592     }
3593     BitMap = ConstantInt::get(M.getContext(), TableInt);
3594     BitMapElementTy = IT;
3595     Kind = BitMapKind;
3596     ++NumBitMaps;
3597     return;
3598   }
3599
3600   // Store the table in an array.
3601   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3602   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3603
3604   Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3605                              GlobalVariable::PrivateLinkage,
3606                              Initializer,
3607                              "switch.table");
3608   Array->setUnnamedAddr(true);
3609   Kind = ArrayKind;
3610 }
3611
3612 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3613   switch (Kind) {
3614     case SingleValueKind:
3615       return SingleValue;
3616     case BitMapKind: {
3617       // Type of the bitmap (e.g. i59).
3618       IntegerType *MapTy = BitMap->getType();
3619
3620       // Cast Index to the same type as the bitmap.
3621       // Note: The Index is <= the number of elements in the table, so
3622       // truncating it to the width of the bitmask is safe.
3623       Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3624
3625       // Multiply the shift amount by the element width.
3626       ShiftAmt = Builder.CreateMul(ShiftAmt,
3627                       ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3628                                    "switch.shiftamt");
3629
3630       // Shift down.
3631       Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3632                                               "switch.downshift");
3633       // Mask off.
3634       return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3635                                  "switch.masked");
3636     }
3637     case ArrayKind: {
3638       // Make sure the table index will not overflow when treated as signed.
3639       IntegerType *IT = cast<IntegerType>(Index->getType());
3640       uint64_t TableSize = Array->getInitializer()->getType()
3641                                 ->getArrayNumElements();
3642       if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3643         Index = Builder.CreateZExt(Index,
3644                                    IntegerType::get(IT->getContext(),
3645                                                     IT->getBitWidth() + 1),
3646                                    "switch.tableidx.zext");
3647
3648       Value *GEPIndices[] = { Builder.getInt32(0), Index };
3649       Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3650                                              "switch.gep");
3651       return Builder.CreateLoad(GEP, "switch.load");
3652     }
3653   }
3654   llvm_unreachable("Unknown lookup table kind!");
3655 }
3656
3657 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3658                                            uint64_t TableSize,
3659                                            const Type *ElementType) {
3660   if (!DL)
3661     return false;
3662   const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3663   if (!IT)
3664     return false;
3665   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3666   // are <= 15, we could try to narrow the type.
3667
3668   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3669   if (TableSize >= UINT_MAX/IT->getBitWidth())
3670     return false;
3671   return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3672 }
3673
3674 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3675 /// for this switch, based on the number of cases, size of the table and the
3676 /// types of the results.
3677 static bool ShouldBuildLookupTable(SwitchInst *SI,
3678                                    uint64_t TableSize,
3679                                    const TargetTransformInfo &TTI,
3680                                    const DataLayout *DL,
3681                             const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3682   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3683     return false; // TableSize overflowed, or mul below might overflow.
3684
3685   bool AllTablesFitInRegister = true;
3686   bool HasIllegalType = false;
3687   for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3688        E = ResultTypes.end(); I != E; ++I) {
3689     Type *Ty = I->second;
3690
3691     // Saturate this flag to true.
3692     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3693
3694     // Saturate this flag to false.
3695     AllTablesFitInRegister = AllTablesFitInRegister &&
3696       SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3697
3698     // If both flags saturate, we're done. NOTE: This *only* works with
3699     // saturating flags, and all flags have to saturate first due to the
3700     // non-deterministic behavior of iterating over a dense map.
3701     if (HasIllegalType && !AllTablesFitInRegister)
3702       break;
3703   }
3704
3705   // If each table would fit in a register, we should build it anyway.
3706   if (AllTablesFitInRegister)
3707     return true;
3708
3709   // Don't build a table that doesn't fit in-register if it has illegal types.
3710   if (HasIllegalType)
3711     return false;
3712
3713   // The table density should be at least 40%. This is the same criterion as for
3714   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3715   // FIXME: Find the best cut-off.
3716   return SI->getNumCases() * 10 >= TableSize * 4;
3717 }
3718
3719 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3720 /// phi nodes in a common successor block with different constant values,
3721 /// replace the switch with lookup tables.
3722 static bool SwitchToLookupTable(SwitchInst *SI,
3723                                 IRBuilder<> &Builder,
3724                                 const TargetTransformInfo &TTI,
3725                                 const DataLayout* DL) {
3726   assert(SI->getNumCases() > 1 && "Degenerate switch?");
3727
3728   // Only build lookup table when we have a target that supports it.
3729   if (!TTI.shouldBuildLookupTables())
3730     return false;
3731
3732   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3733   // split off a dense part and build a lookup table for that.
3734
3735   // FIXME: This creates arrays of GEPs to constant strings, which means each
3736   // GEP needs a runtime relocation in PIC code. We should just build one big
3737   // string and lookup indices into that.
3738
3739   // Ignore switches with less than three cases. Lookup tables will not make them
3740   // faster, so we don't analyze them.
3741   if (SI->getNumCases() < 3)
3742     return false;
3743
3744   // Figure out the corresponding result for each case value and phi node in the
3745   // common destination, as well as the the min and max case values.
3746   assert(SI->case_begin() != SI->case_end());
3747   SwitchInst::CaseIt CI = SI->case_begin();
3748   ConstantInt *MinCaseVal = CI.getCaseValue();
3749   ConstantInt *MaxCaseVal = CI.getCaseValue();
3750
3751   BasicBlock *CommonDest = nullptr;
3752   typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3753   SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3754   SmallDenseMap<PHINode*, Constant*> DefaultResults;
3755   SmallDenseMap<PHINode*, Type*> ResultTypes;
3756   SmallVector<PHINode*, 4> PHIs;
3757
3758   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3759     ConstantInt *CaseVal = CI.getCaseValue();
3760     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3761       MinCaseVal = CaseVal;
3762     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3763       MaxCaseVal = CaseVal;
3764
3765     // Resulting value at phi nodes for this case value.
3766     typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3767     ResultsTy Results;
3768     if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3769                         Results, DL))
3770       return false;
3771
3772     // Append the result from this case to the list for each phi.
3773     for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3774       if (!ResultLists.count(I->first))
3775         PHIs.push_back(I->first);
3776       ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3777     }
3778   }
3779
3780   // Keep track of the result types.
3781   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3782     PHINode *PHI = PHIs[I];
3783     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3784   }
3785
3786   uint64_t NumResults = ResultLists[PHIs[0]].size();
3787   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3788   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3789   bool TableHasHoles = (NumResults < TableSize);
3790
3791   // If the table has holes, we need a constant result for the default case
3792   // or a bitmask that fits in a register.
3793   SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3794   bool HasDefaultResults = false;
3795   if (TableHasHoles) {
3796     HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3797                                        &CommonDest, DefaultResultsList, DL);
3798   }
3799   bool NeedMask = (TableHasHoles && !HasDefaultResults);
3800   if (NeedMask) {
3801     // As an extra penalty for the validity test we require more cases.
3802     if (SI->getNumCases() < 4)  // FIXME: Find best threshold value (benchmark).
3803       return false;
3804     if (!(DL && DL->fitsInLegalInteger(TableSize)))
3805       return false;
3806   }
3807
3808   for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3809     PHINode *PHI = DefaultResultsList[I].first;
3810     Constant *Result = DefaultResultsList[I].second;
3811     DefaultResults[PHI] = Result;
3812   }
3813
3814   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
3815     return false;
3816
3817   // Create the BB that does the lookups.
3818   Module &Mod = *CommonDest->getParent()->getParent();
3819   BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3820                                             "switch.lookup",
3821                                             CommonDest->getParent(),
3822                                             CommonDest);
3823
3824   // Compute the table index value.
3825   Builder.SetInsertPoint(SI);
3826   Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3827                                         "switch.tableidx");
3828
3829   // Compute the maximum table size representable by the integer type we are
3830   // switching upon.
3831   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
3832   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
3833   assert(MaxTableSize >= TableSize &&
3834          "It is impossible for a switch to have more entries than the max "
3835          "representable value of its input integer type's size.");
3836
3837   // If we have a fully covered lookup table, unconditionally branch to the
3838   // lookup table BB. Otherwise, check if the condition value is within the case
3839   // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3840   // destination.
3841   const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3842   if (GeneratingCoveredLookupTable) {
3843     Builder.CreateBr(LookupBB);
3844     // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
3845     // do not delete PHINodes here.
3846     SI->getDefaultDest()->removePredecessor(SI->getParent(),
3847                                             true/*DontDeleteUselessPHIs*/);
3848   } else {
3849     Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3850                                        MinCaseVal->getType(), TableSize));
3851     Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3852   }
3853
3854   // Populate the BB that does the lookups.
3855   Builder.SetInsertPoint(LookupBB);
3856
3857   if (NeedMask) {
3858     // Before doing the lookup we do the hole check.
3859     // The LookupBB is therefore re-purposed to do the hole check
3860     // and we create a new LookupBB.
3861     BasicBlock *MaskBB = LookupBB;
3862     MaskBB->setName("switch.hole_check");
3863     LookupBB = BasicBlock::Create(Mod.getContext(),
3864                                   "switch.lookup",
3865                                   CommonDest->getParent(),
3866                                   CommonDest);
3867
3868     // Build bitmask; fill in a 1 bit for every case.
3869     APInt MaskInt(TableSize, 0);
3870     APInt One(TableSize, 1);
3871     const ResultListTy &ResultList = ResultLists[PHIs[0]];
3872     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3873       uint64_t Idx = (ResultList[I].first->getValue() -
3874                       MinCaseVal->getValue()).getLimitedValue();
3875       MaskInt |= One << Idx;
3876     }
3877     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3878
3879     // Get the TableIndex'th bit of the bitmask.
3880     // If this bit is 0 (meaning hole) jump to the default destination,
3881     // else continue with table lookup.
3882     IntegerType *MapTy = TableMask->getType();
3883     Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3884                                                  "switch.maskindex");
3885     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3886                                         "switch.shifted");
3887     Value *LoBit = Builder.CreateTrunc(Shifted,
3888                                        Type::getInt1Ty(Mod.getContext()),
3889                                        "switch.lobit");
3890     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3891
3892     Builder.SetInsertPoint(LookupBB);
3893     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3894   }
3895
3896   bool ReturnedEarly = false;
3897   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3898     PHINode *PHI = PHIs[I];
3899
3900     // If using a bitmask, use any value to fill the lookup table holes.
3901     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
3902     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3903                             DV, DL);
3904
3905     Value *Result = Table.BuildLookup(TableIndex, Builder);
3906
3907     // If the result is used to return immediately from the function, we want to
3908     // do that right here.
3909     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3910         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
3911       Builder.CreateRet(Result);
3912       ReturnedEarly = true;
3913       break;
3914     }
3915
3916     PHI->addIncoming(Result, LookupBB);
3917   }
3918
3919   if (!ReturnedEarly)
3920     Builder.CreateBr(CommonDest);
3921
3922   // Remove the switch.
3923   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3924     BasicBlock *Succ = SI->getSuccessor(i);
3925
3926     if (Succ == SI->getDefaultDest())
3927       continue;
3928     Succ->removePredecessor(SI->getParent());
3929   }
3930   SI->eraseFromParent();
3931
3932   ++NumLookupTables;
3933   if (NeedMask)
3934     ++NumLookupTablesHoles;
3935   return true;
3936 }
3937
3938 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3939   BasicBlock *BB = SI->getParent();
3940
3941   if (isValueEqualityComparison(SI)) {
3942     // If we only have one predecessor, and if it is a branch on this value,
3943     // see if that predecessor totally determines the outcome of this switch.
3944     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3945       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3946         return SimplifyCFG(BB, TTI, DL, AT) | true;
3947
3948     Value *Cond = SI->getCondition();
3949     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3950       if (SimplifySwitchOnSelect(SI, Select))
3951         return SimplifyCFG(BB, TTI, DL, AT) | true;
3952
3953     // If the block only contains the switch, see if we can fold the block
3954     // away into any preds.
3955     BasicBlock::iterator BBI = BB->begin();
3956     // Ignore dbg intrinsics.
3957     while (isa<DbgInfoIntrinsic>(BBI))
3958       ++BBI;
3959     if (SI == &*BBI)
3960       if (FoldValueComparisonIntoPredecessors(SI, Builder))
3961         return SimplifyCFG(BB, TTI, DL, AT) | true;
3962   }
3963
3964   // Try to transform the switch into an icmp and a branch.
3965   if (TurnSwitchRangeIntoICmp(SI, Builder))
3966     return SimplifyCFG(BB, TTI, DL, AT) | true;
3967
3968   // Remove unreachable cases.
3969   if (EliminateDeadSwitchCases(SI, DL, AT))
3970     return SimplifyCFG(BB, TTI, DL, AT) | true;
3971
3972   if (ForwardSwitchConditionToPHI(SI))
3973     return SimplifyCFG(BB, TTI, DL, AT) | true;
3974
3975   if (SwitchToLookupTable(SI, Builder, TTI, DL))
3976     return SimplifyCFG(BB, TTI, DL, AT) | true;
3977
3978   return false;
3979 }
3980
3981 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3982   BasicBlock *BB = IBI->getParent();
3983   bool Changed = false;
3984
3985   // Eliminate redundant destinations.
3986   SmallPtrSet<Value *, 8> Succs;
3987   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3988     BasicBlock *Dest = IBI->getDestination(i);
3989     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3990       Dest->removePredecessor(BB);
3991       IBI->removeDestination(i);
3992       --i; --e;
3993       Changed = true;
3994     }
3995   }
3996
3997   if (IBI->getNumDestinations() == 0) {
3998     // If the indirectbr has no successors, change it to unreachable.
3999     new UnreachableInst(IBI->getContext(), IBI);
4000     EraseTerminatorInstAndDCECond(IBI);
4001     return true;
4002   }
4003
4004   if (IBI->getNumDestinations() == 1) {
4005     // If the indirectbr has one successor, change it to a direct branch.
4006     BranchInst::Create(IBI->getDestination(0), IBI);
4007     EraseTerminatorInstAndDCECond(IBI);
4008     return true;
4009   }
4010
4011   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4012     if (SimplifyIndirectBrOnSelect(IBI, SI))
4013       return SimplifyCFG(BB, TTI, DL, AT) | true;
4014   }
4015   return Changed;
4016 }
4017
4018 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4019   BasicBlock *BB = BI->getParent();
4020
4021   if (SinkCommon && SinkThenElseCodeToEnd(BI))
4022     return true;
4023
4024   // If the Terminator is the only non-phi instruction, simplify the block.
4025   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4026   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4027       TryToSimplifyUncondBranchFromEmptyBlock(BB))
4028     return true;
4029
4030   // If the only instruction in the block is a seteq/setne comparison
4031   // against a constant, try to simplify the block.
4032   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4033     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4034       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4035         ;
4036       if (I->isTerminator() &&
4037           TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL, AT))
4038         return true;
4039     }
4040
4041   // If this basic block is ONLY a compare and a branch, and if a predecessor
4042   // branches to us and our successor, fold the comparison into the
4043   // predecessor and use logical operations to update the incoming value
4044   // for PHI nodes in common successor.
4045   if (FoldBranchToCommonDest(BI, DL))
4046     return SimplifyCFG(BB, TTI, DL, AT) | true;
4047   return false;
4048 }
4049
4050
4051 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4052   BasicBlock *BB = BI->getParent();
4053
4054   // Conditional branch
4055   if (isValueEqualityComparison(BI)) {
4056     // If we only have one predecessor, and if it is a branch on this value,
4057     // see if that predecessor totally determines the outcome of this
4058     // switch.
4059     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4060       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4061         return SimplifyCFG(BB, TTI, DL, AT) | true;
4062
4063     // This block must be empty, except for the setcond inst, if it exists.
4064     // Ignore dbg intrinsics.
4065     BasicBlock::iterator I = BB->begin();
4066     // Ignore dbg intrinsics.
4067     while (isa<DbgInfoIntrinsic>(I))
4068       ++I;
4069     if (&*I == BI) {
4070       if (FoldValueComparisonIntoPredecessors(BI, Builder))
4071         return SimplifyCFG(BB, TTI, DL, AT) | true;
4072     } else if (&*I == cast<Instruction>(BI->getCondition())){
4073       ++I;
4074       // Ignore dbg intrinsics.
4075       while (isa<DbgInfoIntrinsic>(I))
4076         ++I;
4077       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4078         return SimplifyCFG(BB, TTI, DL, AT) | true;
4079     }
4080   }
4081
4082   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4083   if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4084     return true;
4085
4086   // If this basic block is ONLY a compare and a branch, and if a predecessor
4087   // branches to us and one of our successors, fold the comparison into the
4088   // predecessor and use logical operations to pick the right destination.
4089   if (FoldBranchToCommonDest(BI, DL))
4090     return SimplifyCFG(BB, TTI, DL, AT) | true;
4091
4092   // We have a conditional branch to two blocks that are only reachable
4093   // from BI.  We know that the condbr dominates the two blocks, so see if
4094   // there is any identical code in the "then" and "else" blocks.  If so, we
4095   // can hoist it up to the branching block.
4096   if (BI->getSuccessor(0)->getSinglePredecessor()) {
4097     if (BI->getSuccessor(1)->getSinglePredecessor()) {
4098       if (HoistThenElseCodeToIf(BI, DL))
4099         return SimplifyCFG(BB, TTI, DL, AT) | true;
4100     } else {
4101       // If Successor #1 has multiple preds, we may be able to conditionally
4102       // execute Successor #0 if it branches to Successor #1.
4103       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4104       if (Succ0TI->getNumSuccessors() == 1 &&
4105           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4106         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4107           return SimplifyCFG(BB, TTI, DL, AT) | true;
4108     }
4109   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4110     // If Successor #0 has multiple preds, we may be able to conditionally
4111     // execute Successor #1 if it branches to Successor #0.
4112     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4113     if (Succ1TI->getNumSuccessors() == 1 &&
4114         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4115       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4116         return SimplifyCFG(BB, TTI, DL, AT) | true;
4117   }
4118
4119   // If this is a branch on a phi node in the current block, thread control
4120   // through this block if any PHI node entries are constants.
4121   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4122     if (PN->getParent() == BI->getParent())
4123       if (FoldCondBranchOnPHI(BI, DL))
4124         return SimplifyCFG(BB, TTI, DL, AT) | true;
4125
4126   // Scan predecessor blocks for conditional branches.
4127   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4128     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4129       if (PBI != BI && PBI->isConditional())
4130         if (SimplifyCondBranchToCondBranch(PBI, BI))
4131           return SimplifyCFG(BB, TTI, DL, AT) | true;
4132
4133   return false;
4134 }
4135
4136 /// Check if passing a value to an instruction will cause undefined behavior.
4137 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4138   Constant *C = dyn_cast<Constant>(V);
4139   if (!C)
4140     return false;
4141
4142   if (I->use_empty())
4143     return false;
4144
4145   if (C->isNullValue()) {
4146     // Only look at the first use, avoid hurting compile time with long uselists
4147     User *Use = *I->user_begin();
4148
4149     // Now make sure that there are no instructions in between that can alter
4150     // control flow (eg. calls)
4151     for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4152       if (i == I->getParent()->end() || i->mayHaveSideEffects())
4153         return false;
4154
4155     // Look through GEPs. A load from a GEP derived from NULL is still undefined
4156     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4157       if (GEP->getPointerOperand() == I)
4158         return passingValueIsAlwaysUndefined(V, GEP);
4159
4160     // Look through bitcasts.
4161     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4162       return passingValueIsAlwaysUndefined(V, BC);
4163
4164     // Load from null is undefined.
4165     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4166       if (!LI->isVolatile())
4167         return LI->getPointerAddressSpace() == 0;
4168
4169     // Store to null is undefined.
4170     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4171       if (!SI->isVolatile())
4172         return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4173   }
4174   return false;
4175 }
4176
4177 /// If BB has an incoming value that will always trigger undefined behavior
4178 /// (eg. null pointer dereference), remove the branch leading here.
4179 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4180   for (BasicBlock::iterator i = BB->begin();
4181        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4182     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4183       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4184         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4185         IRBuilder<> Builder(T);
4186         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4187           BB->removePredecessor(PHI->getIncomingBlock(i));
4188           // Turn uncoditional branches into unreachables and remove the dead
4189           // destination from conditional branches.
4190           if (BI->isUnconditional())
4191             Builder.CreateUnreachable();
4192           else
4193             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4194                                                          BI->getSuccessor(0));
4195           BI->eraseFromParent();
4196           return true;
4197         }
4198         // TODO: SwitchInst.
4199       }
4200
4201   return false;
4202 }
4203
4204 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4205   bool Changed = false;
4206
4207   assert(BB && BB->getParent() && "Block not embedded in function!");
4208   assert(BB->getTerminator() && "Degenerate basic block encountered!");
4209
4210   // Remove basic blocks that have no predecessors (except the entry block)...
4211   // or that just have themself as a predecessor.  These are unreachable.
4212   if ((pred_begin(BB) == pred_end(BB) &&
4213        BB != &BB->getParent()->getEntryBlock()) ||
4214       BB->getSinglePredecessor() == BB) {
4215     DEBUG(dbgs() << "Removing BB: \n" << *BB);
4216     DeleteDeadBlock(BB);
4217     return true;
4218   }
4219
4220   // Check to see if we can constant propagate this terminator instruction
4221   // away...
4222   Changed |= ConstantFoldTerminator(BB, true);
4223
4224   // Check for and eliminate duplicate PHI nodes in this block.
4225   Changed |= EliminateDuplicatePHINodes(BB);
4226
4227   // Check for and remove branches that will always cause undefined behavior.
4228   Changed |= removeUndefIntroducingPredecessor(BB);
4229
4230   // Merge basic blocks into their predecessor if there is only one distinct
4231   // pred, and if there is only one distinct successor of the predecessor, and
4232   // if there are no PHI nodes.
4233   //
4234   if (MergeBlockIntoPredecessor(BB))
4235     return true;
4236
4237   IRBuilder<> Builder(BB);
4238
4239   // If there is a trivial two-entry PHI node in this basic block, and we can
4240   // eliminate it, do so now.
4241   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4242     if (PN->getNumIncomingValues() == 2)
4243       Changed |= FoldTwoEntryPHINode(PN, DL);
4244
4245   Builder.SetInsertPoint(BB->getTerminator());
4246   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4247     if (BI->isUnconditional()) {
4248       if (SimplifyUncondBranch(BI, Builder)) return true;
4249     } else {
4250       if (SimplifyCondBranch(BI, Builder)) return true;
4251     }
4252   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4253     if (SimplifyReturn(RI, Builder)) return true;
4254   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4255     if (SimplifyResume(RI, Builder)) return true;
4256   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4257     if (SimplifySwitch(SI, Builder)) return true;
4258   } else if (UnreachableInst *UI =
4259                dyn_cast<UnreachableInst>(BB->getTerminator())) {
4260     if (SimplifyUnreachable(UI)) return true;
4261   } else if (IndirectBrInst *IBI =
4262                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4263     if (SimplifyIndirectBr(IBI)) return true;
4264   }
4265
4266   return Changed;
4267 }
4268
4269 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
4270 /// example, it adjusts branches to branches to eliminate the extra hop, it
4271 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4272 /// of the CFG.  It returns true if a modification was made.
4273 ///
4274 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4275                        const DataLayout *DL, AssumptionTracker *AT) {
4276   return SimplifyCFGOpt(TTI, DL, AT).run(BB);
4277 }