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