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