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