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