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