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