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