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   SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
1924 
1925   unsigned SpeculationCost = 0;
1926   Value *SpeculatedStoreValue = nullptr;
1927   StoreInst *SpeculatedStore = nullptr;
1928   for (BasicBlock::iterator BBI = ThenBB->begin(),
1929                             BBE = std::prev(ThenBB->end());
1930        BBI != BBE; ++BBI) {
1931     Instruction *I = &*BBI;
1932     // Skip debug info.
1933     if (isa<DbgInfoIntrinsic>(I)) {
1934       SpeculatedDbgIntrinsics.push_back(I);
1935       continue;
1936     }
1937 
1938     // Only speculatively execute a single instruction (not counting the
1939     // terminator) for now.
1940     ++SpeculationCost;
1941     if (SpeculationCost > 1)
1942       return false;
1943 
1944     // Don't hoist the instruction if it's unsafe or expensive.
1945     if (!isSafeToSpeculativelyExecute(I) &&
1946         !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1947                                   I, BB, ThenBB, EndBB))))
1948       return false;
1949     if (!SpeculatedStoreValue &&
1950         ComputeSpeculationCost(I, TTI) >
1951             PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
1952       return false;
1953 
1954     // Store the store speculation candidate.
1955     if (SpeculatedStoreValue)
1956       SpeculatedStore = cast<StoreInst>(I);
1957 
1958     // Do not hoist the instruction if any of its operands are defined but not
1959     // used in BB. The transformation will prevent the operand from
1960     // being sunk into the use block.
1961     for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
1962       Instruction *OpI = dyn_cast<Instruction>(*i);
1963       if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
1964         continue; // Not a candidate for sinking.
1965 
1966       ++SinkCandidateUseCounts[OpI];
1967     }
1968   }
1969 
1970   // Consider any sink candidates which are only used in CondBB as costs for
1971   // speculation. Note, while we iterate over a DenseMap here, we are summing
1972   // and so iteration order isn't significant.
1973   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1974            I = SinkCandidateUseCounts.begin(),
1975            E = SinkCandidateUseCounts.end();
1976        I != E; ++I)
1977     if (I->first->getNumUses() == I->second) {
1978       ++SpeculationCost;
1979       if (SpeculationCost > 1)
1980         return false;
1981     }
1982 
1983   // Check that the PHI nodes can be converted to selects.
1984   bool HaveRewritablePHIs = false;
1985   for (BasicBlock::iterator I = EndBB->begin();
1986        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1987     Value *OrigV = PN->getIncomingValueForBlock(BB);
1988     Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1989 
1990     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1991     // Skip PHIs which are trivial.
1992     if (ThenV == OrigV)
1993       continue;
1994 
1995     // Don't convert to selects if we could remove undefined behavior instead.
1996     if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1997         passingValueIsAlwaysUndefined(ThenV, PN))
1998       return false;
1999 
2000     HaveRewritablePHIs = true;
2001     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2002     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2003     if (!OrigCE && !ThenCE)
2004       continue; // Known safe and cheap.
2005 
2006     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2007         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
2008       return false;
2009     unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
2010     unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
2011     unsigned MaxCost =
2012         2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2013     if (OrigCost + ThenCost > MaxCost)
2014       return false;
2015 
2016     // Account for the cost of an unfolded ConstantExpr which could end up
2017     // getting expanded into Instructions.
2018     // FIXME: This doesn't account for how many operations are combined in the
2019     // constant expression.
2020     ++SpeculationCost;
2021     if (SpeculationCost > 1)
2022       return false;
2023   }
2024 
2025   // If there are no PHIs to process, bail early. This helps ensure idempotence
2026   // as well.
2027   if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
2028     return false;
2029 
2030   // If we get here, we can hoist the instruction and if-convert.
2031   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2032 
2033   // Insert a select of the value of the speculated store.
2034   if (SpeculatedStoreValue) {
2035     IRBuilder<NoFolder> Builder(BI);
2036     Value *TrueV = SpeculatedStore->getValueOperand();
2037     Value *FalseV = SpeculatedStoreValue;
2038     if (Invert)
2039       std::swap(TrueV, FalseV);
2040     Value *S = Builder.CreateSelect(
2041         BrCond, TrueV, FalseV, "spec.store.select", BI);
2042     SpeculatedStore->setOperand(0, S);
2043     SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2044                                          SpeculatedStore->getDebugLoc());
2045   }
2046 
2047   // Metadata can be dependent on the condition we are hoisting above.
2048   // Conservatively strip all metadata on the instruction.
2049   for (auto &I : *ThenBB)
2050     I.dropUnknownNonDebugMetadata();
2051 
2052   // Hoist the instructions.
2053   BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2054                            ThenBB->begin(), std::prev(ThenBB->end()));
2055 
2056   // Insert selects and rewrite the PHI operands.
2057   IRBuilder<NoFolder> Builder(BI);
2058   for (BasicBlock::iterator I = EndBB->begin();
2059        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2060     unsigned OrigI = PN->getBasicBlockIndex(BB);
2061     unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
2062     Value *OrigV = PN->getIncomingValue(OrigI);
2063     Value *ThenV = PN->getIncomingValue(ThenI);
2064 
2065     // Skip PHIs which are trivial.
2066     if (OrigV == ThenV)
2067       continue;
2068 
2069     // Create a select whose true value is the speculatively executed value and
2070     // false value is the preexisting value. Swap them if the branch
2071     // destinations were inverted.
2072     Value *TrueV = ThenV, *FalseV = OrigV;
2073     if (Invert)
2074       std::swap(TrueV, FalseV);
2075     Value *V = Builder.CreateSelect(
2076         BrCond, TrueV, FalseV, "spec.select", BI);
2077     PN->setIncomingValue(OrigI, V);
2078     PN->setIncomingValue(ThenI, V);
2079   }
2080 
2081   // Remove speculated dbg intrinsics.
2082   // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2083   // dbg value for the different flows and inserting it after the select.
2084   for (Instruction *I : SpeculatedDbgIntrinsics)
2085     I->eraseFromParent();
2086 
2087   ++NumSpeculations;
2088   return true;
2089 }
2090 
2091 /// Return true if we can thread a branch across this block.
2092 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2093   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
2094   unsigned Size = 0;
2095 
2096   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2097     if (isa<DbgInfoIntrinsic>(BBI))
2098       continue;
2099     if (Size > 10)
2100       return false; // Don't clone large BB's.
2101     ++Size;
2102 
2103     // We can only support instructions that do not define values that are
2104     // live outside of the current basic block.
2105     for (User *U : BBI->users()) {
2106       Instruction *UI = cast<Instruction>(U);
2107       if (UI->getParent() != BB || isa<PHINode>(UI))
2108         return false;
2109     }
2110 
2111     // Looks ok, continue checking.
2112   }
2113 
2114   return true;
2115 }
2116 
2117 /// If we have a conditional branch on a PHI node value that is defined in the
2118 /// same block as the branch and if any PHI entries are constants, thread edges
2119 /// corresponding to that entry to be branches to their ultimate destination.
2120 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
2121                                 AssumptionCache *AC) {
2122   BasicBlock *BB = BI->getParent();
2123   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
2124   // NOTE: we currently cannot transform this case if the PHI node is used
2125   // outside of the block.
2126   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2127     return false;
2128 
2129   // Degenerate case of a single entry PHI.
2130   if (PN->getNumIncomingValues() == 1) {
2131     FoldSingleEntryPHINodes(PN->getParent());
2132     return true;
2133   }
2134 
2135   // Now we know that this block has multiple preds and two succs.
2136   if (!BlockIsSimpleEnoughToThreadThrough(BB))
2137     return false;
2138 
2139   // Can't fold blocks that contain noduplicate or convergent calls.
2140   if (any_of(*BB, [](const Instruction &I) {
2141         const CallInst *CI = dyn_cast<CallInst>(&I);
2142         return CI && (CI->cannotDuplicate() || CI->isConvergent());
2143       }))
2144     return false;
2145 
2146   // Okay, this is a simple enough basic block.  See if any phi values are
2147   // constants.
2148   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2149     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
2150     if (!CB || !CB->getType()->isIntegerTy(1))
2151       continue;
2152 
2153     // Okay, we now know that all edges from PredBB should be revectored to
2154     // branch to RealDest.
2155     BasicBlock *PredBB = PN->getIncomingBlock(i);
2156     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
2157 
2158     if (RealDest == BB)
2159       continue; // Skip self loops.
2160     // Skip if the predecessor's terminator is an indirect branch.
2161     if (isa<IndirectBrInst>(PredBB->getTerminator()))
2162       continue;
2163 
2164     // The dest block might have PHI nodes, other predecessors and other
2165     // difficult cases.  Instead of being smart about this, just insert a new
2166     // block that jumps to the destination block, effectively splitting
2167     // the edge we are about to create.
2168     BasicBlock *EdgeBB =
2169         BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2170                            RealDest->getParent(), RealDest);
2171     BranchInst::Create(RealDest, EdgeBB);
2172 
2173     // Update PHI nodes.
2174     AddPredecessorToBlock(RealDest, EdgeBB, BB);
2175 
2176     // BB may have instructions that are being threaded over.  Clone these
2177     // instructions into EdgeBB.  We know that there will be no uses of the
2178     // cloned instructions outside of EdgeBB.
2179     BasicBlock::iterator InsertPt = EdgeBB->begin();
2180     DenseMap<Value *, Value *> TranslateMap; // Track translated values.
2181     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2182       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2183         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2184         continue;
2185       }
2186       // Clone the instruction.
2187       Instruction *N = BBI->clone();
2188       if (BBI->hasName())
2189         N->setName(BBI->getName() + ".c");
2190 
2191       // Update operands due to translation.
2192       for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2193         DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
2194         if (PI != TranslateMap.end())
2195           *i = PI->second;
2196       }
2197 
2198       // Check for trivial simplification.
2199       if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
2200         if (!BBI->use_empty())
2201           TranslateMap[&*BBI] = V;
2202         if (!N->mayHaveSideEffects()) {
2203           N->deleteValue(); // Instruction folded away, don't need actual inst
2204           N = nullptr;
2205         }
2206       } else {
2207         if (!BBI->use_empty())
2208           TranslateMap[&*BBI] = N;
2209       }
2210       // Insert the new instruction into its new home.
2211       if (N)
2212         EdgeBB->getInstList().insert(InsertPt, N);
2213 
2214       // Register the new instruction with the assumption cache if necessary.
2215       if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2216         if (II->getIntrinsicID() == Intrinsic::assume)
2217           AC->registerAssumption(II);
2218     }
2219 
2220     // Loop over all of the edges from PredBB to BB, changing them to branch
2221     // to EdgeBB instead.
2222     TerminatorInst *PredBBTI = PredBB->getTerminator();
2223     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2224       if (PredBBTI->getSuccessor(i) == BB) {
2225         BB->removePredecessor(PredBB);
2226         PredBBTI->setSuccessor(i, EdgeBB);
2227       }
2228 
2229     // Recurse, simplifying any other constants.
2230     return FoldCondBranchOnPHI(BI, DL, AC) | true;
2231   }
2232 
2233   return false;
2234 }
2235 
2236 /// Given a BB that starts with the specified two-entry PHI node,
2237 /// see if we can eliminate it.
2238 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2239                                 const DataLayout &DL) {
2240   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
2241   // statement", which has a very simple dominance structure.  Basically, we
2242   // are trying to find the condition that is being branched on, which
2243   // subsequently causes this merge to happen.  We really want control
2244   // dependence information for this check, but simplifycfg can't keep it up
2245   // to date, and this catches most of the cases we care about anyway.
2246   BasicBlock *BB = PN->getParent();
2247   BasicBlock *IfTrue, *IfFalse;
2248   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
2249   if (!IfCond ||
2250       // Don't bother if the branch will be constant folded trivially.
2251       isa<ConstantInt>(IfCond))
2252     return false;
2253 
2254   // Okay, we found that we can merge this two-entry phi node into a select.
2255   // Doing so would require us to fold *all* two entry phi nodes in this block.
2256   // At some point this becomes non-profitable (particularly if the target
2257   // doesn't support cmov's).  Only do this transformation if there are two or
2258   // fewer PHI nodes in this block.
2259   unsigned NumPhis = 0;
2260   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2261     if (NumPhis > 2)
2262       return false;
2263 
2264   // Loop over the PHI's seeing if we can promote them all to select
2265   // instructions.  While we are at it, keep track of the instructions
2266   // that need to be moved to the dominating block.
2267   SmallPtrSet<Instruction *, 4> AggressiveInsts;
2268   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2269            MaxCostVal1 = PHINodeFoldingThreshold;
2270   MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2271   MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
2272 
2273   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2274     PHINode *PN = cast<PHINode>(II++);
2275     if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
2276       PN->replaceAllUsesWith(V);
2277       PN->eraseFromParent();
2278       continue;
2279     }
2280 
2281     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
2282                              MaxCostVal0, TTI) ||
2283         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
2284                              MaxCostVal1, TTI))
2285       return false;
2286   }
2287 
2288   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
2289   // we ran out of PHIs then we simplified them all.
2290   PN = dyn_cast<PHINode>(BB->begin());
2291   if (!PN)
2292     return true;
2293 
2294   // Don't fold i1 branches on PHIs which contain binary operators.  These can
2295   // often be turned into switches and other things.
2296   if (PN->getType()->isIntegerTy(1) &&
2297       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2298        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2299        isa<BinaryOperator>(IfCond)))
2300     return false;
2301 
2302   // If all PHI nodes are promotable, check to make sure that all instructions
2303   // in the predecessor blocks can be promoted as well. If not, we won't be able
2304   // to get rid of the control flow, so it's not worth promoting to select
2305   // instructions.
2306   BasicBlock *DomBlock = nullptr;
2307   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2308   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2309   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
2310     IfBlock1 = nullptr;
2311   } else {
2312     DomBlock = *pred_begin(IfBlock1);
2313     for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2314          ++I)
2315       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2316         // This is not an aggressive instruction that we can promote.
2317         // Because of this, we won't be able to get rid of the control flow, so
2318         // the xform is not worth it.
2319         return false;
2320       }
2321   }
2322 
2323   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
2324     IfBlock2 = nullptr;
2325   } else {
2326     DomBlock = *pred_begin(IfBlock2);
2327     for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2328          ++I)
2329       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2330         // This is not an aggressive instruction that we can promote.
2331         // Because of this, we won't be able to get rid of the control flow, so
2332         // the xform is not worth it.
2333         return false;
2334       }
2335   }
2336 
2337   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
2338                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
2339 
2340   // If we can still promote the PHI nodes after this gauntlet of tests,
2341   // do all of the PHI's now.
2342   Instruction *InsertPt = DomBlock->getTerminator();
2343   IRBuilder<NoFolder> Builder(InsertPt);
2344 
2345   // Move all 'aggressive' instructions, which are defined in the
2346   // conditional parts of the if's up to the dominating block.
2347   if (IfBlock1) {
2348     for (auto &I : *IfBlock1)
2349       I.dropUnknownNonDebugMetadata();
2350     DomBlock->getInstList().splice(InsertPt->getIterator(),
2351                                    IfBlock1->getInstList(), IfBlock1->begin(),
2352                                    IfBlock1->getTerminator()->getIterator());
2353   }
2354   if (IfBlock2) {
2355     for (auto &I : *IfBlock2)
2356       I.dropUnknownNonDebugMetadata();
2357     DomBlock->getInstList().splice(InsertPt->getIterator(),
2358                                    IfBlock2->getInstList(), IfBlock2->begin(),
2359                                    IfBlock2->getTerminator()->getIterator());
2360   }
2361 
2362   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2363     // Change the PHI node into a select instruction.
2364     Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
2365     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
2366 
2367     Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2368     PN->replaceAllUsesWith(Sel);
2369     Sel->takeName(PN);
2370     PN->eraseFromParent();
2371   }
2372 
2373   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2374   // has been flattened.  Change DomBlock to jump directly to our new block to
2375   // avoid other simplifycfg's kicking in on the diamond.
2376   TerminatorInst *OldTI = DomBlock->getTerminator();
2377   Builder.SetInsertPoint(OldTI);
2378   Builder.CreateBr(BB);
2379   OldTI->eraseFromParent();
2380   return true;
2381 }
2382 
2383 /// If we found a conditional branch that goes to two returning blocks,
2384 /// try to merge them together into one return,
2385 /// introducing a select if the return values disagree.
2386 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
2387                                            IRBuilder<> &Builder) {
2388   assert(BI->isConditional() && "Must be a conditional branch");
2389   BasicBlock *TrueSucc = BI->getSuccessor(0);
2390   BasicBlock *FalseSucc = BI->getSuccessor(1);
2391   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2392   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
2393 
2394   // Check to ensure both blocks are empty (just a return) or optionally empty
2395   // with PHI nodes.  If there are other instructions, merging would cause extra
2396   // computation on one path or the other.
2397   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2398     return false;
2399   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
2400     return false;
2401 
2402   Builder.SetInsertPoint(BI);
2403   // Okay, we found a branch that is going to two return nodes.  If
2404   // there is no return value for this function, just change the
2405   // branch into a return.
2406   if (FalseRet->getNumOperands() == 0) {
2407     TrueSucc->removePredecessor(BI->getParent());
2408     FalseSucc->removePredecessor(BI->getParent());
2409     Builder.CreateRetVoid();
2410     EraseTerminatorInstAndDCECond(BI);
2411     return true;
2412   }
2413 
2414   // Otherwise, figure out what the true and false return values are
2415   // so we can insert a new select instruction.
2416   Value *TrueValue = TrueRet->getReturnValue();
2417   Value *FalseValue = FalseRet->getReturnValue();
2418 
2419   // Unwrap any PHI nodes in the return blocks.
2420   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2421     if (TVPN->getParent() == TrueSucc)
2422       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2423   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2424     if (FVPN->getParent() == FalseSucc)
2425       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
2426 
2427   // In order for this transformation to be safe, we must be able to
2428   // unconditionally execute both operands to the return.  This is
2429   // normally the case, but we could have a potentially-trapping
2430   // constant expression that prevents this transformation from being
2431   // safe.
2432   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2433     if (TCV->canTrap())
2434       return false;
2435   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2436     if (FCV->canTrap())
2437       return false;
2438 
2439   // Okay, we collected all the mapped values and checked them for sanity, and
2440   // defined to really do this transformation.  First, update the CFG.
2441   TrueSucc->removePredecessor(BI->getParent());
2442   FalseSucc->removePredecessor(BI->getParent());
2443 
2444   // Insert select instructions where needed.
2445   Value *BrCond = BI->getCondition();
2446   if (TrueValue) {
2447     // Insert a select if the results differ.
2448     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2449     } else if (isa<UndefValue>(TrueValue)) {
2450       TrueValue = FalseValue;
2451     } else {
2452       TrueValue =
2453           Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
2454     }
2455   }
2456 
2457   Value *RI =
2458       !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2459 
2460   (void)RI;
2461 
2462   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2463                << "\n  " << *BI << "NewRet = " << *RI
2464                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
2465 
2466   EraseTerminatorInstAndDCECond(BI);
2467 
2468   return true;
2469 }
2470 
2471 /// Return true if the given instruction is available
2472 /// in its predecessor block. If yes, the instruction will be removed.
2473 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2474   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2475     return false;
2476   for (Instruction &I : *PB) {
2477     Instruction *PBI = &I;
2478     // Check whether Inst and PBI generate the same value.
2479     if (Inst->isIdenticalTo(PBI)) {
2480       Inst->replaceAllUsesWith(PBI);
2481       Inst->eraseFromParent();
2482       return true;
2483     }
2484   }
2485   return false;
2486 }
2487 
2488 /// Return true if either PBI or BI has branch weight available, and store
2489 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2490 /// not have branch weight, use 1:1 as its weight.
2491 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2492                                    uint64_t &PredTrueWeight,
2493                                    uint64_t &PredFalseWeight,
2494                                    uint64_t &SuccTrueWeight,
2495                                    uint64_t &SuccFalseWeight) {
2496   bool PredHasWeights =
2497       PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2498   bool SuccHasWeights =
2499       BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2500   if (PredHasWeights || SuccHasWeights) {
2501     if (!PredHasWeights)
2502       PredTrueWeight = PredFalseWeight = 1;
2503     if (!SuccHasWeights)
2504       SuccTrueWeight = SuccFalseWeight = 1;
2505     return true;
2506   } else {
2507     return false;
2508   }
2509 }
2510 
2511 /// If this basic block is simple enough, and if a predecessor branches to us
2512 /// and one of our successors, fold the block into the predecessor and use
2513 /// logical operations to pick the right destination.
2514 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
2515   BasicBlock *BB = BI->getParent();
2516 
2517   Instruction *Cond = nullptr;
2518   if (BI->isConditional())
2519     Cond = dyn_cast<Instruction>(BI->getCondition());
2520   else {
2521     // For unconditional branch, check for a simple CFG pattern, where
2522     // BB has a single predecessor and BB's successor is also its predecessor's
2523     // successor. If such pattern exists, check for CSE between BB and its
2524     // predecessor.
2525     if (BasicBlock *PB = BB->getSinglePredecessor())
2526       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2527         if (PBI->isConditional() &&
2528             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2529              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2530           for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2531             Instruction *Curr = &*I++;
2532             if (isa<CmpInst>(Curr)) {
2533               Cond = Curr;
2534               break;
2535             }
2536             // Quit if we can't remove this instruction.
2537             if (!checkCSEInPredecessor(Curr, PB))
2538               return false;
2539           }
2540         }
2541 
2542     if (!Cond)
2543       return false;
2544   }
2545 
2546   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2547       Cond->getParent() != BB || !Cond->hasOneUse())
2548     return false;
2549 
2550   // Make sure the instruction after the condition is the cond branch.
2551   BasicBlock::iterator CondIt = ++Cond->getIterator();
2552 
2553   // Ignore dbg intrinsics.
2554   while (isa<DbgInfoIntrinsic>(CondIt))
2555     ++CondIt;
2556 
2557   if (&*CondIt != BI)
2558     return false;
2559 
2560   // Only allow this transformation if computing the condition doesn't involve
2561   // too many instructions and these involved instructions can be executed
2562   // unconditionally. We denote all involved instructions except the condition
2563   // as "bonus instructions", and only allow this transformation when the
2564   // number of the bonus instructions does not exceed a certain threshold.
2565   unsigned NumBonusInsts = 0;
2566   for (auto I = BB->begin(); Cond != &*I; ++I) {
2567     // Ignore dbg intrinsics.
2568     if (isa<DbgInfoIntrinsic>(I))
2569       continue;
2570     if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
2571       return false;
2572     // I has only one use and can be executed unconditionally.
2573     Instruction *User = dyn_cast<Instruction>(I->user_back());
2574     if (User == nullptr || User->getParent() != BB)
2575       return false;
2576     // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2577     // to use any other instruction, User must be an instruction between next(I)
2578     // and Cond.
2579     ++NumBonusInsts;
2580     // Early exits once we reach the limit.
2581     if (NumBonusInsts > BonusInstThreshold)
2582       return false;
2583   }
2584 
2585   // Cond is known to be a compare or binary operator.  Check to make sure that
2586   // neither operand is a potentially-trapping constant expression.
2587   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2588     if (CE->canTrap())
2589       return false;
2590   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2591     if (CE->canTrap())
2592       return false;
2593 
2594   // Finally, don't infinitely unroll conditional loops.
2595   BasicBlock *TrueDest = BI->getSuccessor(0);
2596   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2597   if (TrueDest == BB || FalseDest == BB)
2598     return false;
2599 
2600   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2601     BasicBlock *PredBlock = *PI;
2602     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2603 
2604     // Check that we have two conditional branches.  If there is a PHI node in
2605     // the common successor, verify that the same value flows in from both
2606     // blocks.
2607     SmallVector<PHINode *, 4> PHIs;
2608     if (!PBI || PBI->isUnconditional() ||
2609         (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
2610         (!BI->isConditional() &&
2611          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2612       continue;
2613 
2614     // Determine if the two branches share a common destination.
2615     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2616     bool InvertPredCond = false;
2617 
2618     if (BI->isConditional()) {
2619       if (PBI->getSuccessor(0) == TrueDest) {
2620         Opc = Instruction::Or;
2621       } else if (PBI->getSuccessor(1) == FalseDest) {
2622         Opc = Instruction::And;
2623       } else if (PBI->getSuccessor(0) == FalseDest) {
2624         Opc = Instruction::And;
2625         InvertPredCond = true;
2626       } else if (PBI->getSuccessor(1) == TrueDest) {
2627         Opc = Instruction::Or;
2628         InvertPredCond = true;
2629       } else {
2630         continue;
2631       }
2632     } else {
2633       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2634         continue;
2635     }
2636 
2637     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2638     IRBuilder<> Builder(PBI);
2639 
2640     // If we need to invert the condition in the pred block to match, do so now.
2641     if (InvertPredCond) {
2642       Value *NewCond = PBI->getCondition();
2643 
2644       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2645         CmpInst *CI = cast<CmpInst>(NewCond);
2646         CI->setPredicate(CI->getInversePredicate());
2647       } else {
2648         NewCond =
2649             Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
2650       }
2651 
2652       PBI->setCondition(NewCond);
2653       PBI->swapSuccessors();
2654     }
2655 
2656     // If we have bonus instructions, clone them into the predecessor block.
2657     // Note that there may be multiple predecessor blocks, so we cannot move
2658     // bonus instructions to a predecessor block.
2659     ValueToValueMapTy VMap; // maps original values to cloned values
2660     // We already make sure Cond is the last instruction before BI. Therefore,
2661     // all instructions before Cond other than DbgInfoIntrinsic are bonus
2662     // instructions.
2663     for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
2664       if (isa<DbgInfoIntrinsic>(BonusInst))
2665         continue;
2666       Instruction *NewBonusInst = BonusInst->clone();
2667       RemapInstruction(NewBonusInst, VMap,
2668                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2669       VMap[&*BonusInst] = NewBonusInst;
2670 
2671       // If we moved a load, we cannot any longer claim any knowledge about
2672       // its potential value. The previous information might have been valid
2673       // only given the branch precondition.
2674       // For an analogous reason, we must also drop all the metadata whose
2675       // semantics we don't understand.
2676       NewBonusInst->dropUnknownNonDebugMetadata();
2677 
2678       PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2679       NewBonusInst->takeName(&*BonusInst);
2680       BonusInst->setName(BonusInst->getName() + ".old");
2681     }
2682 
2683     // Clone Cond into the predecessor basic block, and or/and the
2684     // two conditions together.
2685     Instruction *New = Cond->clone();
2686     RemapInstruction(New, VMap,
2687                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2688     PredBlock->getInstList().insert(PBI->getIterator(), New);
2689     New->takeName(Cond);
2690     Cond->setName(New->getName() + ".old");
2691 
2692     if (BI->isConditional()) {
2693       Instruction *NewCond = cast<Instruction>(
2694           Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
2695       PBI->setCondition(NewCond);
2696 
2697       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2698       bool HasWeights =
2699           extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2700                                  SuccTrueWeight, SuccFalseWeight);
2701       SmallVector<uint64_t, 8> NewWeights;
2702 
2703       if (PBI->getSuccessor(0) == BB) {
2704         if (HasWeights) {
2705           // PBI: br i1 %x, BB, FalseDest
2706           // BI:  br i1 %y, TrueDest, FalseDest
2707           // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2708           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2709           // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2710           //               TrueWeight for PBI * FalseWeight for BI.
2711           // We assume that total weights of a BranchInst can fit into 32 bits.
2712           // Therefore, we will not have overflow using 64-bit arithmetic.
2713           NewWeights.push_back(PredFalseWeight *
2714                                    (SuccFalseWeight + SuccTrueWeight) +
2715                                PredTrueWeight * SuccFalseWeight);
2716         }
2717         AddPredecessorToBlock(TrueDest, PredBlock, BB);
2718         PBI->setSuccessor(0, TrueDest);
2719       }
2720       if (PBI->getSuccessor(1) == BB) {
2721         if (HasWeights) {
2722           // PBI: br i1 %x, TrueDest, BB
2723           // BI:  br i1 %y, TrueDest, FalseDest
2724           // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2725           //              FalseWeight for PBI * TrueWeight for BI.
2726           NewWeights.push_back(PredTrueWeight *
2727                                    (SuccFalseWeight + SuccTrueWeight) +
2728                                PredFalseWeight * SuccTrueWeight);
2729           // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2730           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2731         }
2732         AddPredecessorToBlock(FalseDest, PredBlock, BB);
2733         PBI->setSuccessor(1, FalseDest);
2734       }
2735       if (NewWeights.size() == 2) {
2736         // Halve the weights if any of them cannot fit in an uint32_t
2737         FitWeights(NewWeights);
2738 
2739         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2740                                            NewWeights.end());
2741         PBI->setMetadata(
2742             LLVMContext::MD_prof,
2743             MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
2744       } else
2745         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2746     } else {
2747       // Update PHI nodes in the common successors.
2748       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2749         ConstantInt *PBI_C = cast<ConstantInt>(
2750             PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2751         assert(PBI_C->getType()->isIntegerTy(1));
2752         Instruction *MergedCond = nullptr;
2753         if (PBI->getSuccessor(0) == TrueDest) {
2754           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2755           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2756           //       is false: !PBI_Cond and BI_Value
2757           Instruction *NotCond = cast<Instruction>(
2758               Builder.CreateNot(PBI->getCondition(), "not.cond"));
2759           MergedCond = cast<Instruction>(
2760               Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
2761           if (PBI_C->isOne())
2762             MergedCond = cast<Instruction>(Builder.CreateBinOp(
2763                 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
2764         } else {
2765           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2766           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2767           //       is false: PBI_Cond and BI_Value
2768           MergedCond = cast<Instruction>(Builder.CreateBinOp(
2769               Instruction::And, PBI->getCondition(), New, "and.cond"));
2770           if (PBI_C->isOne()) {
2771             Instruction *NotCond = cast<Instruction>(
2772                 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2773             MergedCond = cast<Instruction>(Builder.CreateBinOp(
2774                 Instruction::Or, NotCond, MergedCond, "or.cond"));
2775           }
2776         }
2777         // Update PHI Node.
2778         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2779                                   MergedCond);
2780       }
2781       // Change PBI from Conditional to Unconditional.
2782       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2783       EraseTerminatorInstAndDCECond(PBI);
2784       PBI = New_PBI;
2785     }
2786 
2787     // If BI was a loop latch, it may have had associated loop metadata.
2788     // We need to copy it to the new latch, that is, PBI.
2789     if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2790       PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2791 
2792     // TODO: If BB is reachable from all paths through PredBlock, then we
2793     // could replace PBI's branch probabilities with BI's.
2794 
2795     // Copy any debug value intrinsics into the end of PredBlock.
2796     for (Instruction &I : *BB)
2797       if (isa<DbgInfoIntrinsic>(I))
2798         I.clone()->insertBefore(PBI);
2799 
2800     return true;
2801   }
2802   return false;
2803 }
2804 
2805 // If there is only one store in BB1 and BB2, return it, otherwise return
2806 // nullptr.
2807 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2808   StoreInst *S = nullptr;
2809   for (auto *BB : {BB1, BB2}) {
2810     if (!BB)
2811       continue;
2812     for (auto &I : *BB)
2813       if (auto *SI = dyn_cast<StoreInst>(&I)) {
2814         if (S)
2815           // Multiple stores seen.
2816           return nullptr;
2817         else
2818           S = SI;
2819       }
2820   }
2821   return S;
2822 }
2823 
2824 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2825                                               Value *AlternativeV = nullptr) {
2826   // PHI is going to be a PHI node that allows the value V that is defined in
2827   // BB to be referenced in BB's only successor.
2828   //
2829   // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2830   // doesn't matter to us what the other operand is (it'll never get used). We
2831   // could just create a new PHI with an undef incoming value, but that could
2832   // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2833   // other PHI. So here we directly look for some PHI in BB's successor with V
2834   // as an incoming operand. If we find one, we use it, else we create a new
2835   // one.
2836   //
2837   // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2838   // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2839   // where OtherBB is the single other predecessor of BB's only successor.
2840   PHINode *PHI = nullptr;
2841   BasicBlock *Succ = BB->getSingleSuccessor();
2842 
2843   for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2844     if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2845       PHI = cast<PHINode>(I);
2846       if (!AlternativeV)
2847         break;
2848 
2849       assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2850       auto PredI = pred_begin(Succ);
2851       BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2852       if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2853         break;
2854       PHI = nullptr;
2855     }
2856   if (PHI)
2857     return PHI;
2858 
2859   // If V is not an instruction defined in BB, just return it.
2860   if (!AlternativeV &&
2861       (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2862     return V;
2863 
2864   PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
2865   PHI->addIncoming(V, BB);
2866   for (BasicBlock *PredBB : predecessors(Succ))
2867     if (PredBB != BB)
2868       PHI->addIncoming(
2869           AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
2870   return PHI;
2871 }
2872 
2873 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2874                                            BasicBlock *QTB, BasicBlock *QFB,
2875                                            BasicBlock *PostBB, Value *Address,
2876                                            bool InvertPCond, bool InvertQCond,
2877                                            const DataLayout &DL) {
2878   auto IsaBitcastOfPointerType = [](const Instruction &I) {
2879     return Operator::getOpcode(&I) == Instruction::BitCast &&
2880            I.getType()->isPointerTy();
2881   };
2882 
2883   // If we're not in aggressive mode, we only optimize if we have some
2884   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2885   auto IsWorthwhile = [&](BasicBlock *BB) {
2886     if (!BB)
2887       return true;
2888     // Heuristic: if the block can be if-converted/phi-folded and the
2889     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2890     // thread this store.
2891     unsigned N = 0;
2892     for (auto &I : *BB) {
2893       // Cheap instructions viable for folding.
2894       if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2895           isa<StoreInst>(I))
2896         ++N;
2897       // Free instructions.
2898       else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2899                IsaBitcastOfPointerType(I))
2900         continue;
2901       else
2902         return false;
2903     }
2904     // The store we want to merge is counted in N, so add 1 to make sure
2905     // we're counting the instructions that would be left.
2906     return N <= (PHINodeFoldingThreshold + 1);
2907   };
2908 
2909   if (!MergeCondStoresAggressively &&
2910       (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2911        !IsWorthwhile(QFB)))
2912     return false;
2913 
2914   // For every pointer, there must be exactly two stores, one coming from
2915   // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2916   // store (to any address) in PTB,PFB or QTB,QFB.
2917   // FIXME: We could relax this restriction with a bit more work and performance
2918   // testing.
2919   StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2920   StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2921   if (!PStore || !QStore)
2922     return false;
2923 
2924   // Now check the stores are compatible.
2925   if (!QStore->isUnordered() || !PStore->isUnordered())
2926     return false;
2927 
2928   // Check that sinking the store won't cause program behavior changes. Sinking
2929   // the store out of the Q blocks won't change any behavior as we're sinking
2930   // from a block to its unconditional successor. But we're moving a store from
2931   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2932   // So we need to check that there are no aliasing loads or stores in
2933   // QBI, QTB and QFB. We also need to check there are no conflicting memory
2934   // operations between PStore and the end of its parent block.
2935   //
2936   // The ideal way to do this is to query AliasAnalysis, but we don't
2937   // preserve AA currently so that is dangerous. Be super safe and just
2938   // check there are no other memory operations at all.
2939   for (auto &I : *QFB->getSinglePredecessor())
2940     if (I.mayReadOrWriteMemory())
2941       return false;
2942   for (auto &I : *QFB)
2943     if (&I != QStore && I.mayReadOrWriteMemory())
2944       return false;
2945   if (QTB)
2946     for (auto &I : *QTB)
2947       if (&I != QStore && I.mayReadOrWriteMemory())
2948         return false;
2949   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2950        I != E; ++I)
2951     if (&*I != PStore && I->mayReadOrWriteMemory())
2952       return false;
2953 
2954   // OK, we're going to sink the stores to PostBB. The store has to be
2955   // conditional though, so first create the predicate.
2956   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2957                      ->getCondition();
2958   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2959                      ->getCondition();
2960 
2961   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2962                                                 PStore->getParent());
2963   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2964                                                 QStore->getParent(), PPHI);
2965 
2966   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2967 
2968   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2969   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2970 
2971   if (InvertPCond)
2972     PPred = QB.CreateNot(PPred);
2973   if (InvertQCond)
2974     QPred = QB.CreateNot(QPred);
2975   Value *CombinedPred = QB.CreateOr(PPred, QPred);
2976 
2977   auto *T =
2978       SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
2979   QB.SetInsertPoint(T);
2980   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2981   AAMDNodes AAMD;
2982   PStore->getAAMetadata(AAMD, /*Merge=*/false);
2983   PStore->getAAMetadata(AAMD, /*Merge=*/true);
2984   SI->setAAMetadata(AAMD);
2985   unsigned PAlignment = PStore->getAlignment();
2986   unsigned QAlignment = QStore->getAlignment();
2987   unsigned TypeAlignment =
2988       DL.getABITypeAlignment(SI->getValueOperand()->getType());
2989   unsigned MinAlignment;
2990   unsigned MaxAlignment;
2991   std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
2992   // Choose the minimum alignment. If we could prove both stores execute, we
2993   // could use biggest one.  In this case, though, we only know that one of the
2994   // stores executes.  And we don't know it's safe to take the alignment from a
2995   // store that doesn't execute.
2996   if (MinAlignment != 0) {
2997     // Choose the minimum of all non-zero alignments.
2998     SI->setAlignment(MinAlignment);
2999   } else if (MaxAlignment != 0) {
3000     // Choose the minimal alignment between the non-zero alignment and the ABI
3001     // default alignment for the type of the stored value.
3002     SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
3003   } else {
3004     // If both alignments are zero, use ABI default alignment for the type of
3005     // the stored value.
3006     SI->setAlignment(TypeAlignment);
3007   }
3008 
3009   QStore->eraseFromParent();
3010   PStore->eraseFromParent();
3011 
3012   return true;
3013 }
3014 
3015 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3016                                    const DataLayout &DL) {
3017   // The intention here is to find diamonds or triangles (see below) where each
3018   // conditional block contains a store to the same address. Both of these
3019   // stores are conditional, so they can't be unconditionally sunk. But it may
3020   // be profitable to speculatively sink the stores into one merged store at the
3021   // end, and predicate the merged store on the union of the two conditions of
3022   // PBI and QBI.
3023   //
3024   // This can reduce the number of stores executed if both of the conditions are
3025   // true, and can allow the blocks to become small enough to be if-converted.
3026   // This optimization will also chain, so that ladders of test-and-set
3027   // sequences can be if-converted away.
3028   //
3029   // We only deal with simple diamonds or triangles:
3030   //
3031   //     PBI       or      PBI        or a combination of the two
3032   //    /   \               | \
3033   //   PTB  PFB             |  PFB
3034   //    \   /               | /
3035   //     QBI                QBI
3036   //    /  \                | \
3037   //   QTB  QFB             |  QFB
3038   //    \  /                | /
3039   //    PostBB            PostBB
3040   //
3041   // We model triangles as a type of diamond with a nullptr "true" block.
3042   // Triangles are canonicalized so that the fallthrough edge is represented by
3043   // a true condition, as in the diagram above.
3044   BasicBlock *PTB = PBI->getSuccessor(0);
3045   BasicBlock *PFB = PBI->getSuccessor(1);
3046   BasicBlock *QTB = QBI->getSuccessor(0);
3047   BasicBlock *QFB = QBI->getSuccessor(1);
3048   BasicBlock *PostBB = QFB->getSingleSuccessor();
3049 
3050   // Make sure we have a good guess for PostBB. If QTB's only successor is
3051   // QFB, then QFB is a better PostBB.
3052   if (QTB->getSingleSuccessor() == QFB)
3053     PostBB = QFB;
3054 
3055   // If we couldn't find a good PostBB, stop.
3056   if (!PostBB)
3057     return false;
3058 
3059   bool InvertPCond = false, InvertQCond = false;
3060   // Canonicalize fallthroughs to the true branches.
3061   if (PFB == QBI->getParent()) {
3062     std::swap(PFB, PTB);
3063     InvertPCond = true;
3064   }
3065   if (QFB == PostBB) {
3066     std::swap(QFB, QTB);
3067     InvertQCond = true;
3068   }
3069 
3070   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3071   // and QFB may not. Model fallthroughs as a nullptr block.
3072   if (PTB == QBI->getParent())
3073     PTB = nullptr;
3074   if (QTB == PostBB)
3075     QTB = nullptr;
3076 
3077   // Legality bailouts. We must have at least the non-fallthrough blocks and
3078   // the post-dominating block, and the non-fallthroughs must only have one
3079   // predecessor.
3080   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3081     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3082   };
3083   if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3084       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3085     return false;
3086   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3087       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3088     return false;
3089   if (!PostBB->hasNUses(2) || !QBI->getParent()->hasNUses(2))
3090     return false;
3091 
3092   // OK, this is a sequence of two diamonds or triangles.
3093   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3094   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3095   for (auto *BB : {PTB, PFB}) {
3096     if (!BB)
3097       continue;
3098     for (auto &I : *BB)
3099       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3100         PStoreAddresses.insert(SI->getPointerOperand());
3101   }
3102   for (auto *BB : {QTB, QFB}) {
3103     if (!BB)
3104       continue;
3105     for (auto &I : *BB)
3106       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3107         QStoreAddresses.insert(SI->getPointerOperand());
3108   }
3109 
3110   set_intersect(PStoreAddresses, QStoreAddresses);
3111   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3112   // clear what it contains.
3113   auto &CommonAddresses = PStoreAddresses;
3114 
3115   bool Changed = false;
3116   for (auto *Address : CommonAddresses)
3117     Changed |= mergeConditionalStoreToAddress(
3118         PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
3119   return Changed;
3120 }
3121 
3122 /// If we have a conditional branch as a predecessor of another block,
3123 /// this function tries to simplify it.  We know
3124 /// that PBI and BI are both conditional branches, and BI is in one of the
3125 /// successor blocks of PBI - PBI branches to BI.
3126 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3127                                            const DataLayout &DL) {
3128   assert(PBI->isConditional() && BI->isConditional());
3129   BasicBlock *BB = BI->getParent();
3130 
3131   // If this block ends with a branch instruction, and if there is a
3132   // predecessor that ends on a branch of the same condition, make
3133   // this conditional branch redundant.
3134   if (PBI->getCondition() == BI->getCondition() &&
3135       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3136     // Okay, the outcome of this conditional branch is statically
3137     // knowable.  If this block had a single pred, handle specially.
3138     if (BB->getSinglePredecessor()) {
3139       // Turn this into a branch on constant.
3140       bool CondIsTrue = PBI->getSuccessor(0) == BB;
3141       BI->setCondition(
3142           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3143       return true; // Nuke the branch on constant.
3144     }
3145 
3146     // Otherwise, if there are multiple predecessors, insert a PHI that merges
3147     // in the constant and simplify the block result.  Subsequent passes of
3148     // simplifycfg will thread the block.
3149     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3150       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3151       PHINode *NewPN = PHINode::Create(
3152           Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3153           BI->getCondition()->getName() + ".pr", &BB->front());
3154       // Okay, we're going to insert the PHI node.  Since PBI is not the only
3155       // predecessor, compute the PHI'd conditional value for all of the preds.
3156       // Any predecessor where the condition is not computable we keep symbolic.
3157       for (pred_iterator PI = PB; PI != PE; ++PI) {
3158         BasicBlock *P = *PI;
3159         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3160             PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3161             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3162           bool CondIsTrue = PBI->getSuccessor(0) == BB;
3163           NewPN->addIncoming(
3164               ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3165               P);
3166         } else {
3167           NewPN->addIncoming(BI->getCondition(), P);
3168         }
3169       }
3170 
3171       BI->setCondition(NewPN);
3172       return true;
3173     }
3174   }
3175 
3176   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3177     if (CE->canTrap())
3178       return false;
3179 
3180   // If both branches are conditional and both contain stores to the same
3181   // address, remove the stores from the conditionals and create a conditional
3182   // merged store at the end.
3183   if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
3184     return true;
3185 
3186   // If this is a conditional branch in an empty block, and if any
3187   // predecessors are a conditional branch to one of our destinations,
3188   // fold the conditions into logical ops and one cond br.
3189   BasicBlock::iterator BBI = BB->begin();
3190   // Ignore dbg intrinsics.
3191   while (isa<DbgInfoIntrinsic>(BBI))
3192     ++BBI;
3193   if (&*BBI != BI)
3194     return false;
3195 
3196   int PBIOp, BIOp;
3197   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3198     PBIOp = 0;
3199     BIOp = 0;
3200   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3201     PBIOp = 0;
3202     BIOp = 1;
3203   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3204     PBIOp = 1;
3205     BIOp = 0;
3206   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3207     PBIOp = 1;
3208     BIOp = 1;
3209   } else {
3210     return false;
3211   }
3212 
3213   // Check to make sure that the other destination of this branch
3214   // isn't BB itself.  If so, this is an infinite loop that will
3215   // keep getting unwound.
3216   if (PBI->getSuccessor(PBIOp) == BB)
3217     return false;
3218 
3219   // Do not perform this transformation if it would require
3220   // insertion of a large number of select instructions. For targets
3221   // without predication/cmovs, this is a big pessimization.
3222 
3223   // Also do not perform this transformation if any phi node in the common
3224   // destination block can trap when reached by BB or PBB (PR17073). In that
3225   // case, it would be unsafe to hoist the operation into a select instruction.
3226 
3227   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3228   unsigned NumPhis = 0;
3229   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3230        ++II, ++NumPhis) {
3231     if (NumPhis > 2) // Disable this xform.
3232       return false;
3233 
3234     PHINode *PN = cast<PHINode>(II);
3235     Value *BIV = PN->getIncomingValueForBlock(BB);
3236     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3237       if (CE->canTrap())
3238         return false;
3239 
3240     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3241     Value *PBIV = PN->getIncomingValue(PBBIdx);
3242     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3243       if (CE->canTrap())
3244         return false;
3245   }
3246 
3247   // Finally, if everything is ok, fold the branches to logical ops.
3248   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3249 
3250   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
3251                << "AND: " << *BI->getParent());
3252 
3253   // If OtherDest *is* BB, then BB is a basic block with a single conditional
3254   // branch in it, where one edge (OtherDest) goes back to itself but the other
3255   // exits.  We don't *know* that the program avoids the infinite loop
3256   // (even though that seems likely).  If we do this xform naively, we'll end up
3257   // recursively unpeeling the loop.  Since we know that (after the xform is
3258   // done) that the block *is* infinite if reached, we just make it an obviously
3259   // infinite loop with no cond branch.
3260   if (OtherDest == BB) {
3261     // Insert it at the end of the function, because it's either code,
3262     // or it won't matter if it's hot. :)
3263     BasicBlock *InfLoopBlock =
3264         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3265     BranchInst::Create(InfLoopBlock, InfLoopBlock);
3266     OtherDest = InfLoopBlock;
3267   }
3268 
3269   DEBUG(dbgs() << *PBI->getParent()->getParent());
3270 
3271   // BI may have other predecessors.  Because of this, we leave
3272   // it alone, but modify PBI.
3273 
3274   // Make sure we get to CommonDest on True&True directions.
3275   Value *PBICond = PBI->getCondition();
3276   IRBuilder<NoFolder> Builder(PBI);
3277   if (PBIOp)
3278     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3279 
3280   Value *BICond = BI->getCondition();
3281   if (BIOp)
3282     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3283 
3284   // Merge the conditions.
3285   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
3286 
3287   // Modify PBI to branch on the new condition to the new dests.
3288   PBI->setCondition(Cond);
3289   PBI->setSuccessor(0, CommonDest);
3290   PBI->setSuccessor(1, OtherDest);
3291 
3292   // Update branch weight for PBI.
3293   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3294   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3295   bool HasWeights =
3296       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3297                              SuccTrueWeight, SuccFalseWeight);
3298   if (HasWeights) {
3299     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3300     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3301     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3302     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3303     // The weight to CommonDest should be PredCommon * SuccTotal +
3304     //                                    PredOther * SuccCommon.
3305     // The weight to OtherDest should be PredOther * SuccOther.
3306     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3307                                   PredOther * SuccCommon,
3308                               PredOther * SuccOther};
3309     // Halve the weights if any of them cannot fit in an uint32_t
3310     FitWeights(NewWeights);
3311 
3312     PBI->setMetadata(LLVMContext::MD_prof,
3313                      MDBuilder(BI->getContext())
3314                          .createBranchWeights(NewWeights[0], NewWeights[1]));
3315   }
3316 
3317   // OtherDest may have phi nodes.  If so, add an entry from PBI's
3318   // block that are identical to the entries for BI's block.
3319   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3320 
3321   // We know that the CommonDest already had an edge from PBI to
3322   // it.  If it has PHIs though, the PHIs may have different
3323   // entries for BB and PBI's BB.  If so, insert a select to make
3324   // them agree.
3325   PHINode *PN;
3326   for (BasicBlock::iterator II = CommonDest->begin();
3327        (PN = dyn_cast<PHINode>(II)); ++II) {
3328     Value *BIV = PN->getIncomingValueForBlock(BB);
3329     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3330     Value *PBIV = PN->getIncomingValue(PBBIdx);
3331     if (BIV != PBIV) {
3332       // Insert a select in PBI to pick the right value.
3333       SelectInst *NV = cast<SelectInst>(
3334           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3335       PN->setIncomingValue(PBBIdx, NV);
3336       // Although the select has the same condition as PBI, the original branch
3337       // weights for PBI do not apply to the new select because the select's
3338       // 'logical' edges are incoming edges of the phi that is eliminated, not
3339       // the outgoing edges of PBI.
3340       if (HasWeights) {
3341         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3342         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3343         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3344         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3345         // The weight to PredCommonDest should be PredCommon * SuccTotal.
3346         // The weight to PredOtherDest should be PredOther * SuccCommon.
3347         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3348                                   PredOther * SuccCommon};
3349 
3350         FitWeights(NewWeights);
3351 
3352         NV->setMetadata(LLVMContext::MD_prof,
3353                         MDBuilder(BI->getContext())
3354                             .createBranchWeights(NewWeights[0], NewWeights[1]));
3355       }
3356     }
3357   }
3358 
3359   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3360   DEBUG(dbgs() << *PBI->getParent()->getParent());
3361 
3362   // This basic block is probably dead.  We know it has at least
3363   // one fewer predecessor.
3364   return true;
3365 }
3366 
3367 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3368 // true or to FalseBB if Cond is false.
3369 // Takes care of updating the successors and removing the old terminator.
3370 // Also makes sure not to introduce new successors by assuming that edges to
3371 // non-successor TrueBBs and FalseBBs aren't reachable.
3372 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
3373                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
3374                                        uint32_t TrueWeight,
3375                                        uint32_t FalseWeight) {
3376   // Remove any superfluous successor edges from the CFG.
3377   // First, figure out which successors to preserve.
3378   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3379   // successor.
3380   BasicBlock *KeepEdge1 = TrueBB;
3381   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3382 
3383   // Then remove the rest.
3384   for (BasicBlock *Succ : OldTerm->successors()) {
3385     // Make sure only to keep exactly one copy of each edge.
3386     if (Succ == KeepEdge1)
3387       KeepEdge1 = nullptr;
3388     else if (Succ == KeepEdge2)
3389       KeepEdge2 = nullptr;
3390     else
3391       Succ->removePredecessor(OldTerm->getParent(),
3392                               /*DontDeleteUselessPHIs=*/true);
3393   }
3394 
3395   IRBuilder<> Builder(OldTerm);
3396   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3397 
3398   // Insert an appropriate new terminator.
3399   if (!KeepEdge1 && !KeepEdge2) {
3400     if (TrueBB == FalseBB)
3401       // We were only looking for one successor, and it was present.
3402       // Create an unconditional branch to it.
3403       Builder.CreateBr(TrueBB);
3404     else {
3405       // We found both of the successors we were looking for.
3406       // Create a conditional branch sharing the condition of the select.
3407       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3408       if (TrueWeight != FalseWeight)
3409         NewBI->setMetadata(LLVMContext::MD_prof,
3410                            MDBuilder(OldTerm->getContext())
3411                                .createBranchWeights(TrueWeight, FalseWeight));
3412     }
3413   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3414     // Neither of the selected blocks were successors, so this
3415     // terminator must be unreachable.
3416     new UnreachableInst(OldTerm->getContext(), OldTerm);
3417   } else {
3418     // One of the selected values was a successor, but the other wasn't.
3419     // Insert an unconditional branch to the one that was found;
3420     // the edge to the one that wasn't must be unreachable.
3421     if (!KeepEdge1)
3422       // Only TrueBB was found.
3423       Builder.CreateBr(TrueBB);
3424     else
3425       // Only FalseBB was found.
3426       Builder.CreateBr(FalseBB);
3427   }
3428 
3429   EraseTerminatorInstAndDCECond(OldTerm);
3430   return true;
3431 }
3432 
3433 // Replaces
3434 //   (switch (select cond, X, Y)) on constant X, Y
3435 // with a branch - conditional if X and Y lead to distinct BBs,
3436 // unconditional otherwise.
3437 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3438   // Check for constant integer values in the select.
3439   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3440   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3441   if (!TrueVal || !FalseVal)
3442     return false;
3443 
3444   // Find the relevant condition and destinations.
3445   Value *Condition = Select->getCondition();
3446   BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3447   BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
3448 
3449   // Get weight for TrueBB and FalseBB.
3450   uint32_t TrueWeight = 0, FalseWeight = 0;
3451   SmallVector<uint64_t, 8> Weights;
3452   bool HasWeights = HasBranchWeights(SI);
3453   if (HasWeights) {
3454     GetBranchWeights(SI, Weights);
3455     if (Weights.size() == 1 + SI->getNumCases()) {
3456       TrueWeight =
3457           (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
3458       FalseWeight =
3459           (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
3460     }
3461   }
3462 
3463   // Perform the actual simplification.
3464   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3465                                     FalseWeight);
3466 }
3467 
3468 // Replaces
3469 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
3470 //                             blockaddress(@fn, BlockB)))
3471 // with
3472 //   (br cond, BlockA, BlockB).
3473 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3474   // Check that both operands of the select are block addresses.
3475   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3476   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3477   if (!TBA || !FBA)
3478     return false;
3479 
3480   // Extract the actual blocks.
3481   BasicBlock *TrueBB = TBA->getBasicBlock();
3482   BasicBlock *FalseBB = FBA->getBasicBlock();
3483 
3484   // Perform the actual simplification.
3485   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3486                                     0);
3487 }
3488 
3489 /// This is called when we find an icmp instruction
3490 /// (a seteq/setne with a constant) as the only instruction in a
3491 /// block that ends with an uncond branch.  We are looking for a very specific
3492 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
3493 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3494 /// default value goes to an uncond block with a seteq in it, we get something
3495 /// like:
3496 ///
3497 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
3498 /// DEFAULT:
3499 ///   %tmp = icmp eq i8 %A, 92
3500 ///   br label %end
3501 /// end:
3502 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3503 ///
3504 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3505 /// the PHI, merging the third icmp into the switch.
3506 static bool tryToSimplifyUncondBranchWithICmpInIt(
3507     ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3508     const TargetTransformInfo &TTI, const SimplifyCFGOptions &Options) {
3509   BasicBlock *BB = ICI->getParent();
3510 
3511   // If the block has any PHIs in it or the icmp has multiple uses, it is too
3512   // complex.
3513   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3514     return false;
3515 
3516   Value *V = ICI->getOperand(0);
3517   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3518 
3519   // The pattern we're looking for is where our only predecessor is a switch on
3520   // 'V' and this block is the default case for the switch.  In this case we can
3521   // fold the compared value into the switch to simplify things.
3522   BasicBlock *Pred = BB->getSinglePredecessor();
3523   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3524     return false;
3525 
3526   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3527   if (SI->getCondition() != V)
3528     return false;
3529 
3530   // If BB is reachable on a non-default case, then we simply know the value of
3531   // V in this block.  Substitute it and constant fold the icmp instruction
3532   // away.
3533   if (SI->getDefaultDest() != BB) {
3534     ConstantInt *VVal = SI->findCaseDest(BB);
3535     assert(VVal && "Should have a unique destination value");
3536     ICI->setOperand(0, VVal);
3537 
3538     if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
3539       ICI->replaceAllUsesWith(V);
3540       ICI->eraseFromParent();
3541     }
3542     // BB is now empty, so it is likely to simplify away.
3543     return simplifyCFG(BB, TTI, Options) | true;
3544   }
3545 
3546   // Ok, the block is reachable from the default dest.  If the constant we're
3547   // comparing exists in one of the other edges, then we can constant fold ICI
3548   // and zap it.
3549   if (SI->findCaseValue(Cst) != SI->case_default()) {
3550     Value *V;
3551     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3552       V = ConstantInt::getFalse(BB->getContext());
3553     else
3554       V = ConstantInt::getTrue(BB->getContext());
3555 
3556     ICI->replaceAllUsesWith(V);
3557     ICI->eraseFromParent();
3558     // BB is now empty, so it is likely to simplify away.
3559     return simplifyCFG(BB, TTI, Options) | true;
3560   }
3561 
3562   // The use of the icmp has to be in the 'end' block, by the only PHI node in
3563   // the block.
3564   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3565   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3566   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3567       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3568     return false;
3569 
3570   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3571   // true in the PHI.
3572   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3573   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3574 
3575   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3576     std::swap(DefaultCst, NewCst);
3577 
3578   // Replace ICI (which is used by the PHI for the default value) with true or
3579   // false depending on if it is EQ or NE.
3580   ICI->replaceAllUsesWith(DefaultCst);
3581   ICI->eraseFromParent();
3582 
3583   // Okay, the switch goes to this block on a default value.  Add an edge from
3584   // the switch to the merge point on the compared value.
3585   BasicBlock *NewBB =
3586       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
3587   SmallVector<uint64_t, 8> Weights;
3588   bool HasWeights = HasBranchWeights(SI);
3589   if (HasWeights) {
3590     GetBranchWeights(SI, Weights);
3591     if (Weights.size() == 1 + SI->getNumCases()) {
3592       // Split weight for default case to case for "Cst".
3593       Weights[0] = (Weights[0] + 1) >> 1;
3594       Weights.push_back(Weights[0]);
3595 
3596       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3597       SI->setMetadata(
3598           LLVMContext::MD_prof,
3599           MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
3600     }
3601   }
3602   SI->addCase(Cst, NewBB);
3603 
3604   // NewBB branches to the phi block, add the uncond branch and the phi entry.
3605   Builder.SetInsertPoint(NewBB);
3606   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3607   Builder.CreateBr(SuccBlock);
3608   PHIUse->addIncoming(NewCst, NewBB);
3609   return true;
3610 }
3611 
3612 /// The specified branch is a conditional branch.
3613 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3614 /// fold it into a switch instruction if so.
3615 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3616                                       const DataLayout &DL) {
3617   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3618   if (!Cond)
3619     return false;
3620 
3621   // Change br (X == 0 | X == 1), T, F into a switch instruction.
3622   // If this is a bunch of seteq's or'd together, or if it's a bunch of
3623   // 'setne's and'ed together, collect them.
3624 
3625   // Try to gather values from a chain of and/or to be turned into a switch
3626   ConstantComparesGatherer ConstantCompare(Cond, DL);
3627   // Unpack the result
3628   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
3629   Value *CompVal = ConstantCompare.CompValue;
3630   unsigned UsedICmps = ConstantCompare.UsedICmps;
3631   Value *ExtraCase = ConstantCompare.Extra;
3632 
3633   // If we didn't have a multiply compared value, fail.
3634   if (!CompVal)
3635     return false;
3636 
3637   // Avoid turning single icmps into a switch.
3638   if (UsedICmps <= 1)
3639     return false;
3640 
3641   bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3642 
3643   // There might be duplicate constants in the list, which the switch
3644   // instruction can't handle, remove them now.
3645   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3646   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3647 
3648   // If Extra was used, we require at least two switch values to do the
3649   // transformation.  A switch with one value is just a conditional branch.
3650   if (ExtraCase && Values.size() < 2)
3651     return false;
3652 
3653   // TODO: Preserve branch weight metadata, similarly to how
3654   // FoldValueComparisonIntoPredecessors preserves it.
3655 
3656   // Figure out which block is which destination.
3657   BasicBlock *DefaultBB = BI->getSuccessor(1);
3658   BasicBlock *EdgeBB = BI->getSuccessor(0);
3659   if (!TrueWhenEqual)
3660     std::swap(DefaultBB, EdgeBB);
3661 
3662   BasicBlock *BB = BI->getParent();
3663 
3664   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3665                << " cases into SWITCH.  BB is:\n"
3666                << *BB);
3667 
3668   // If there are any extra values that couldn't be folded into the switch
3669   // then we evaluate them with an explicit branch first.  Split the block
3670   // right before the condbr to handle it.
3671   if (ExtraCase) {
3672     BasicBlock *NewBB =
3673         BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
3674     // Remove the uncond branch added to the old block.
3675     TerminatorInst *OldTI = BB->getTerminator();
3676     Builder.SetInsertPoint(OldTI);
3677 
3678     if (TrueWhenEqual)
3679       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
3680     else
3681       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
3682 
3683     OldTI->eraseFromParent();
3684 
3685     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3686     // for the edge we just added.
3687     AddPredecessorToBlock(EdgeBB, BB, NewBB);
3688 
3689     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
3690                  << "\nEXTRABB = " << *BB);
3691     BB = NewBB;
3692   }
3693 
3694   Builder.SetInsertPoint(BI);
3695   // Convert pointer to int before we switch.
3696   if (CompVal->getType()->isPointerTy()) {
3697     CompVal = Builder.CreatePtrToInt(
3698         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
3699   }
3700 
3701   // Create the new switch instruction now.
3702   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
3703 
3704   // Add all of the 'cases' to the switch instruction.
3705   for (unsigned i = 0, e = Values.size(); i != e; ++i)
3706     New->addCase(Values[i], EdgeBB);
3707 
3708   // We added edges from PI to the EdgeBB.  As such, if there were any
3709   // PHI nodes in EdgeBB, they need entries to be added corresponding to
3710   // the number of edges added.
3711   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
3712     PHINode *PN = cast<PHINode>(BBI);
3713     Value *InVal = PN->getIncomingValueForBlock(BB);
3714     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
3715       PN->addIncoming(InVal, BB);
3716   }
3717 
3718   // Erase the old branch instruction.
3719   EraseTerminatorInstAndDCECond(BI);
3720 
3721   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
3722   return true;
3723 }
3724 
3725 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3726   if (isa<PHINode>(RI->getValue()))
3727     return SimplifyCommonResume(RI);
3728   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3729            RI->getValue() == RI->getParent()->getFirstNonPHI())
3730     // The resume must unwind the exception that caused control to branch here.
3731     return SimplifySingleResume(RI);
3732 
3733   return false;
3734 }
3735 
3736 // Simplify resume that is shared by several landing pads (phi of landing pad).
3737 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3738   BasicBlock *BB = RI->getParent();
3739 
3740   // Check that there are no other instructions except for debug intrinsics
3741   // between the phi of landing pads (RI->getValue()) and resume instruction.
3742   BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3743                        E = RI->getIterator();
3744   while (++I != E)
3745     if (!isa<DbgInfoIntrinsic>(I))
3746       return false;
3747 
3748   SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
3749   auto *PhiLPInst = cast<PHINode>(RI->getValue());
3750 
3751   // Check incoming blocks to see if any of them are trivial.
3752   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3753        Idx++) {
3754     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3755     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3756 
3757     // If the block has other successors, we can not delete it because
3758     // it has other dependents.
3759     if (IncomingBB->getUniqueSuccessor() != BB)
3760       continue;
3761 
3762     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3763     // Not the landing pad that caused the control to branch here.
3764     if (IncomingValue != LandingPad)
3765       continue;
3766 
3767     bool isTrivial = true;
3768 
3769     I = IncomingBB->getFirstNonPHI()->getIterator();
3770     E = IncomingBB->getTerminator()->getIterator();
3771     while (++I != E)
3772       if (!isa<DbgInfoIntrinsic>(I)) {
3773         isTrivial = false;
3774         break;
3775       }
3776 
3777     if (isTrivial)
3778       TrivialUnwindBlocks.insert(IncomingBB);
3779   }
3780 
3781   // If no trivial unwind blocks, don't do any simplifications.
3782   if (TrivialUnwindBlocks.empty())
3783     return false;
3784 
3785   // Turn all invokes that unwind here into calls.
3786   for (auto *TrivialBB : TrivialUnwindBlocks) {
3787     // Blocks that will be simplified should be removed from the phi node.
3788     // Note there could be multiple edges to the resume block, and we need
3789     // to remove them all.
3790     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3791       BB->removePredecessor(TrivialBB, true);
3792 
3793     for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3794          PI != PE;) {
3795       BasicBlock *Pred = *PI++;
3796       removeUnwindEdge(Pred);
3797     }
3798 
3799     // In each SimplifyCFG run, only the current processed block can be erased.
3800     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3801     // of erasing TrivialBB, we only remove the branch to the common resume
3802     // block so that we can later erase the resume block since it has no
3803     // predecessors.
3804     TrivialBB->getTerminator()->eraseFromParent();
3805     new UnreachableInst(RI->getContext(), TrivialBB);
3806   }
3807 
3808   // Delete the resume block if all its predecessors have been removed.
3809   if (pred_empty(BB))
3810     BB->eraseFromParent();
3811 
3812   return !TrivialUnwindBlocks.empty();
3813 }
3814 
3815 // Simplify resume that is only used by a single (non-phi) landing pad.
3816 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
3817   BasicBlock *BB = RI->getParent();
3818   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
3819   assert(RI->getValue() == LPInst &&
3820          "Resume must unwind the exception that caused control to here");
3821 
3822   // Check that there are no other instructions except for debug intrinsics.
3823   BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3824   while (++I != E)
3825     if (!isa<DbgInfoIntrinsic>(I))
3826       return false;
3827 
3828   // Turn all invokes that unwind here into calls and delete the basic block.
3829   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3830     BasicBlock *Pred = *PI++;
3831     removeUnwindEdge(Pred);
3832   }
3833 
3834   // The landingpad is now unreachable.  Zap it.
3835   BB->eraseFromParent();
3836   if (LoopHeaders)
3837     LoopHeaders->erase(BB);
3838   return true;
3839 }
3840 
3841 static bool removeEmptyCleanup(CleanupReturnInst *RI) {
3842   // If this is a trivial cleanup pad that executes no instructions, it can be
3843   // eliminated.  If the cleanup pad continues to the caller, any predecessor
3844   // that is an EH pad will be updated to continue to the caller and any
3845   // predecessor that terminates with an invoke instruction will have its invoke
3846   // instruction converted to a call instruction.  If the cleanup pad being
3847   // simplified does not continue to the caller, each predecessor will be
3848   // updated to continue to the unwind destination of the cleanup pad being
3849   // simplified.
3850   BasicBlock *BB = RI->getParent();
3851   CleanupPadInst *CPInst = RI->getCleanupPad();
3852   if (CPInst->getParent() != BB)
3853     // This isn't an empty cleanup.
3854     return false;
3855 
3856   // We cannot kill the pad if it has multiple uses.  This typically arises
3857   // from unreachable basic blocks.
3858   if (!CPInst->hasOneUse())
3859     return false;
3860 
3861   // Check that there are no other instructions except for benign intrinsics.
3862   BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
3863   while (++I != E) {
3864     auto *II = dyn_cast<IntrinsicInst>(I);
3865     if (!II)
3866       return false;
3867 
3868     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3869     switch (IntrinsicID) {
3870     case Intrinsic::dbg_declare:
3871     case Intrinsic::dbg_value:
3872     case Intrinsic::lifetime_end:
3873       break;
3874     default:
3875       return false;
3876     }
3877   }
3878 
3879   // If the cleanup return we are simplifying unwinds to the caller, this will
3880   // set UnwindDest to nullptr.
3881   BasicBlock *UnwindDest = RI->getUnwindDest();
3882   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
3883 
3884   // We're about to remove BB from the control flow.  Before we do, sink any
3885   // PHINodes into the unwind destination.  Doing this before changing the
3886   // control flow avoids some potentially slow checks, since we can currently
3887   // be certain that UnwindDest and BB have no common predecessors (since they
3888   // are both EH pads).
3889   if (UnwindDest) {
3890     // First, go through the PHI nodes in UnwindDest and update any nodes that
3891     // reference the block we are removing
3892     for (BasicBlock::iterator I = UnwindDest->begin(),
3893                               IE = DestEHPad->getIterator();
3894          I != IE; ++I) {
3895       PHINode *DestPN = cast<PHINode>(I);
3896 
3897       int Idx = DestPN->getBasicBlockIndex(BB);
3898       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
3899       assert(Idx != -1);
3900       // This PHI node has an incoming value that corresponds to a control
3901       // path through the cleanup pad we are removing.  If the incoming
3902       // value is in the cleanup pad, it must be a PHINode (because we
3903       // verified above that the block is otherwise empty).  Otherwise, the
3904       // value is either a constant or a value that dominates the cleanup
3905       // pad being removed.
3906       //
3907       // Because BB and UnwindDest are both EH pads, all of their
3908       // predecessors must unwind to these blocks, and since no instruction
3909       // can have multiple unwind destinations, there will be no overlap in
3910       // incoming blocks between SrcPN and DestPN.
3911       Value *SrcVal = DestPN->getIncomingValue(Idx);
3912       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3913 
3914       // Remove the entry for the block we are deleting.
3915       DestPN->removeIncomingValue(Idx, false);
3916 
3917       if (SrcPN && SrcPN->getParent() == BB) {
3918         // If the incoming value was a PHI node in the cleanup pad we are
3919         // removing, we need to merge that PHI node's incoming values into
3920         // DestPN.
3921         for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3922              SrcIdx != SrcE; ++SrcIdx) {
3923           DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3924                               SrcPN->getIncomingBlock(SrcIdx));
3925         }
3926       } else {
3927         // Otherwise, the incoming value came from above BB and
3928         // so we can just reuse it.  We must associate all of BB's
3929         // predecessors with this value.
3930         for (auto *pred : predecessors(BB)) {
3931           DestPN->addIncoming(SrcVal, pred);
3932         }
3933       }
3934     }
3935 
3936     // Sink any remaining PHI nodes directly into UnwindDest.
3937     Instruction *InsertPt = DestEHPad;
3938     for (BasicBlock::iterator I = BB->begin(),
3939                               IE = BB->getFirstNonPHI()->getIterator();
3940          I != IE;) {
3941       // The iterator must be incremented here because the instructions are
3942       // being moved to another block.
3943       PHINode *PN = cast<PHINode>(I++);
3944       if (PN->use_empty())
3945         // If the PHI node has no uses, just leave it.  It will be erased
3946         // when we erase BB below.
3947         continue;
3948 
3949       // Otherwise, sink this PHI node into UnwindDest.
3950       // Any predecessors to UnwindDest which are not already represented
3951       // must be back edges which inherit the value from the path through
3952       // BB.  In this case, the PHI value must reference itself.
3953       for (auto *pred : predecessors(UnwindDest))
3954         if (pred != BB)
3955           PN->addIncoming(PN, pred);
3956       PN->moveBefore(InsertPt);
3957     }
3958   }
3959 
3960   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3961     // The iterator must be updated here because we are removing this pred.
3962     BasicBlock *PredBB = *PI++;
3963     if (UnwindDest == nullptr) {
3964       removeUnwindEdge(PredBB);
3965     } else {
3966       TerminatorInst *TI = PredBB->getTerminator();
3967       TI->replaceUsesOfWith(BB, UnwindDest);
3968     }
3969   }
3970 
3971   // The cleanup pad is now unreachable.  Zap it.
3972   BB->eraseFromParent();
3973   return true;
3974 }
3975 
3976 // Try to merge two cleanuppads together.
3977 static bool mergeCleanupPad(CleanupReturnInst *RI) {
3978   // Skip any cleanuprets which unwind to caller, there is nothing to merge
3979   // with.
3980   BasicBlock *UnwindDest = RI->getUnwindDest();
3981   if (!UnwindDest)
3982     return false;
3983 
3984   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3985   // be safe to merge without code duplication.
3986   if (UnwindDest->getSinglePredecessor() != RI->getParent())
3987     return false;
3988 
3989   // Verify that our cleanuppad's unwind destination is another cleanuppad.
3990   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3991   if (!SuccessorCleanupPad)
3992     return false;
3993 
3994   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3995   // Replace any uses of the successor cleanupad with the predecessor pad
3996   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3997   // funclet bundle operands.
3998   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3999   // Remove the old cleanuppad.
4000   SuccessorCleanupPad->eraseFromParent();
4001   // Now, we simply replace the cleanupret with a branch to the unwind
4002   // destination.
4003   BranchInst::Create(UnwindDest, RI->getParent());
4004   RI->eraseFromParent();
4005 
4006   return true;
4007 }
4008 
4009 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
4010   // It is possible to transiantly have an undef cleanuppad operand because we
4011   // have deleted some, but not all, dead blocks.
4012   // Eventually, this block will be deleted.
4013   if (isa<UndefValue>(RI->getOperand(0)))
4014     return false;
4015 
4016   if (mergeCleanupPad(RI))
4017     return true;
4018 
4019   if (removeEmptyCleanup(RI))
4020     return true;
4021 
4022   return false;
4023 }
4024 
4025 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4026   BasicBlock *BB = RI->getParent();
4027   if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4028     return false;
4029 
4030   // Find predecessors that end with branches.
4031   SmallVector<BasicBlock *, 8> UncondBranchPreds;
4032   SmallVector<BranchInst *, 8> CondBranchPreds;
4033   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4034     BasicBlock *P = *PI;
4035     TerminatorInst *PTI = P->getTerminator();
4036     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4037       if (BI->isUnconditional())
4038         UncondBranchPreds.push_back(P);
4039       else
4040         CondBranchPreds.push_back(BI);
4041     }
4042   }
4043 
4044   // If we found some, do the transformation!
4045   if (!UncondBranchPreds.empty() && DupRet) {
4046     while (!UncondBranchPreds.empty()) {
4047       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4048       DEBUG(dbgs() << "FOLDING: " << *BB
4049                    << "INTO UNCOND BRANCH PRED: " << *Pred);
4050       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
4051     }
4052 
4053     // If we eliminated all predecessors of the block, delete the block now.
4054     if (pred_empty(BB)) {
4055       // We know there are no successors, so just nuke the block.
4056       BB->eraseFromParent();
4057       if (LoopHeaders)
4058         LoopHeaders->erase(BB);
4059     }
4060 
4061     return true;
4062   }
4063 
4064   // Check out all of the conditional branches going to this return
4065   // instruction.  If any of them just select between returns, change the
4066   // branch itself into a select/return pair.
4067   while (!CondBranchPreds.empty()) {
4068     BranchInst *BI = CondBranchPreds.pop_back_val();
4069 
4070     // Check to see if the non-BB successor is also a return block.
4071     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4072         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4073         SimplifyCondBranchToTwoReturns(BI, Builder))
4074       return true;
4075   }
4076   return false;
4077 }
4078 
4079 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4080   BasicBlock *BB = UI->getParent();
4081 
4082   bool Changed = false;
4083 
4084   // If there are any instructions immediately before the unreachable that can
4085   // be removed, do so.
4086   while (UI->getIterator() != BB->begin()) {
4087     BasicBlock::iterator BBI = UI->getIterator();
4088     --BBI;
4089     // Do not delete instructions that can have side effects which might cause
4090     // the unreachable to not be reachable; specifically, calls and volatile
4091     // operations may have this effect.
4092     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4093       break;
4094 
4095     if (BBI->mayHaveSideEffects()) {
4096       if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4097         if (SI->isVolatile())
4098           break;
4099       } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4100         if (LI->isVolatile())
4101           break;
4102       } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4103         if (RMWI->isVolatile())
4104           break;
4105       } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4106         if (CXI->isVolatile())
4107           break;
4108       } else if (isa<CatchPadInst>(BBI)) {
4109         // A catchpad may invoke exception object constructors and such, which
4110         // in some languages can be arbitrary code, so be conservative by
4111         // default.
4112         // For CoreCLR, it just involves a type test, so can be removed.
4113         if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4114             EHPersonality::CoreCLR)
4115           break;
4116       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4117                  !isa<LandingPadInst>(BBI)) {
4118         break;
4119       }
4120       // Note that deleting LandingPad's here is in fact okay, although it
4121       // involves a bit of subtle reasoning. If this inst is a LandingPad,
4122       // all the predecessors of this block will be the unwind edges of Invokes,
4123       // and we can therefore guarantee this block will be erased.
4124     }
4125 
4126     // Delete this instruction (any uses are guaranteed to be dead)
4127     if (!BBI->use_empty())
4128       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4129     BBI->eraseFromParent();
4130     Changed = true;
4131   }
4132 
4133   // If the unreachable instruction is the first in the block, take a gander
4134   // at all of the predecessors of this instruction, and simplify them.
4135   if (&BB->front() != UI)
4136     return Changed;
4137 
4138   SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4139   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4140     TerminatorInst *TI = Preds[i]->getTerminator();
4141     IRBuilder<> Builder(TI);
4142     if (auto *BI = dyn_cast<BranchInst>(TI)) {
4143       if (BI->isUnconditional()) {
4144         if (BI->getSuccessor(0) == BB) {
4145           new UnreachableInst(TI->getContext(), TI);
4146           TI->eraseFromParent();
4147           Changed = true;
4148         }
4149       } else {
4150         if (BI->getSuccessor(0) == BB) {
4151           Builder.CreateBr(BI->getSuccessor(1));
4152           EraseTerminatorInstAndDCECond(BI);
4153         } else if (BI->getSuccessor(1) == BB) {
4154           Builder.CreateBr(BI->getSuccessor(0));
4155           EraseTerminatorInstAndDCECond(BI);
4156           Changed = true;
4157         }
4158       }
4159     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4160       for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
4161         if (i->getCaseSuccessor() != BB) {
4162           ++i;
4163           continue;
4164         }
4165         BB->removePredecessor(SI->getParent());
4166         i = SI->removeCase(i);
4167         e = SI->case_end();
4168         Changed = true;
4169       }
4170     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4171       if (II->getUnwindDest() == BB) {
4172         removeUnwindEdge(TI->getParent());
4173         Changed = true;
4174       }
4175     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4176       if (CSI->getUnwindDest() == BB) {
4177         removeUnwindEdge(TI->getParent());
4178         Changed = true;
4179         continue;
4180       }
4181 
4182       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4183                                              E = CSI->handler_end();
4184            I != E; ++I) {
4185         if (*I == BB) {
4186           CSI->removeHandler(I);
4187           --I;
4188           --E;
4189           Changed = true;
4190         }
4191       }
4192       if (CSI->getNumHandlers() == 0) {
4193         BasicBlock *CatchSwitchBB = CSI->getParent();
4194         if (CSI->hasUnwindDest()) {
4195           // Redirect preds to the unwind dest
4196           CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4197         } else {
4198           // Rewrite all preds to unwind to caller (or from invoke to call).
4199           SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4200           for (BasicBlock *EHPred : EHPreds)
4201             removeUnwindEdge(EHPred);
4202         }
4203         // The catchswitch is no longer reachable.
4204         new UnreachableInst(CSI->getContext(), CSI);
4205         CSI->eraseFromParent();
4206         Changed = true;
4207       }
4208     } else if (isa<CleanupReturnInst>(TI)) {
4209       new UnreachableInst(TI->getContext(), TI);
4210       TI->eraseFromParent();
4211       Changed = true;
4212     }
4213   }
4214 
4215   // If this block is now dead, remove it.
4216   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4217     // We know there are no successors, so just nuke the block.
4218     BB->eraseFromParent();
4219     if (LoopHeaders)
4220       LoopHeaders->erase(BB);
4221     return true;
4222   }
4223 
4224   return Changed;
4225 }
4226 
4227 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4228   assert(Cases.size() >= 1);
4229 
4230   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4231   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4232     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4233       return false;
4234   }
4235   return true;
4236 }
4237 
4238 /// Turn a switch with two reachable destinations into an integer range
4239 /// comparison and branch.
4240 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
4241   assert(SI->getNumCases() > 1 && "Degenerate switch?");
4242 
4243   bool HasDefault =
4244       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4245 
4246   // Partition the cases into two sets with different destinations.
4247   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4248   BasicBlock *DestB = nullptr;
4249   SmallVector<ConstantInt *, 16> CasesA;
4250   SmallVector<ConstantInt *, 16> CasesB;
4251 
4252   for (auto Case : SI->cases()) {
4253     BasicBlock *Dest = Case.getCaseSuccessor();
4254     if (!DestA)
4255       DestA = Dest;
4256     if (Dest == DestA) {
4257       CasesA.push_back(Case.getCaseValue());
4258       continue;
4259     }
4260     if (!DestB)
4261       DestB = Dest;
4262     if (Dest == DestB) {
4263       CasesB.push_back(Case.getCaseValue());
4264       continue;
4265     }
4266     return false; // More than two destinations.
4267   }
4268 
4269   assert(DestA && DestB &&
4270          "Single-destination switch should have been folded.");
4271   assert(DestA != DestB);
4272   assert(DestB != SI->getDefaultDest());
4273   assert(!CasesB.empty() && "There must be non-default cases.");
4274   assert(!CasesA.empty() || HasDefault);
4275 
4276   // Figure out if one of the sets of cases form a contiguous range.
4277   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4278   BasicBlock *ContiguousDest = nullptr;
4279   BasicBlock *OtherDest = nullptr;
4280   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4281     ContiguousCases = &CasesA;
4282     ContiguousDest = DestA;
4283     OtherDest = DestB;
4284   } else if (CasesAreContiguous(CasesB)) {
4285     ContiguousCases = &CasesB;
4286     ContiguousDest = DestB;
4287     OtherDest = DestA;
4288   } else
4289     return false;
4290 
4291   // Start building the compare and branch.
4292 
4293   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4294   Constant *NumCases =
4295       ConstantInt::get(Offset->getType(), ContiguousCases->size());
4296 
4297   Value *Sub = SI->getCondition();
4298   if (!Offset->isNullValue())
4299     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4300 
4301   Value *Cmp;
4302   // If NumCases overflowed, then all possible values jump to the successor.
4303   if (NumCases->isNullValue() && !ContiguousCases->empty())
4304     Cmp = ConstantInt::getTrue(SI->getContext());
4305   else
4306     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4307   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4308 
4309   // Update weight for the newly-created conditional branch.
4310   if (HasBranchWeights(SI)) {
4311     SmallVector<uint64_t, 8> Weights;
4312     GetBranchWeights(SI, Weights);
4313     if (Weights.size() == 1 + SI->getNumCases()) {
4314       uint64_t TrueWeight = 0;
4315       uint64_t FalseWeight = 0;
4316       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4317         if (SI->getSuccessor(I) == ContiguousDest)
4318           TrueWeight += Weights[I];
4319         else
4320           FalseWeight += Weights[I];
4321       }
4322       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4323         TrueWeight /= 2;
4324         FalseWeight /= 2;
4325       }
4326       NewBI->setMetadata(LLVMContext::MD_prof,
4327                          MDBuilder(SI->getContext())
4328                              .createBranchWeights((uint32_t)TrueWeight,
4329                                                   (uint32_t)FalseWeight));
4330     }
4331   }
4332 
4333   // Prune obsolete incoming values off the successors' PHI nodes.
4334   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4335     unsigned PreviousEdges = ContiguousCases->size();
4336     if (ContiguousDest == SI->getDefaultDest())
4337       ++PreviousEdges;
4338     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4339       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4340   }
4341   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4342     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4343     if (OtherDest == SI->getDefaultDest())
4344       ++PreviousEdges;
4345     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4346       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4347   }
4348 
4349   // Drop the switch.
4350   SI->eraseFromParent();
4351 
4352   return true;
4353 }
4354 
4355 /// Compute masked bits for the condition of a switch
4356 /// and use it to remove dead cases.
4357 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4358                                      const DataLayout &DL) {
4359   Value *Cond = SI->getCondition();
4360   unsigned Bits = Cond->getType()->getIntegerBitWidth();
4361   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
4362 
4363   // We can also eliminate cases by determining that their values are outside of
4364   // the limited range of the condition based on how many significant (non-sign)
4365   // bits are in the condition value.
4366   unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4367   unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4368 
4369   // Gather dead cases.
4370   SmallVector<ConstantInt *, 8> DeadCases;
4371   for (auto &Case : SI->cases()) {
4372     const APInt &CaseVal = Case.getCaseValue()->getValue();
4373     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
4374         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4375       DeadCases.push_back(Case.getCaseValue());
4376       DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
4377     }
4378   }
4379 
4380   // If we can prove that the cases must cover all possible values, the
4381   // default destination becomes dead and we can remove it.  If we know some
4382   // of the bits in the value, we can use that to more precisely compute the
4383   // number of possible unique case values.
4384   bool HasDefault =
4385       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4386   const unsigned NumUnknownBits =
4387       Bits - (Known.Zero | Known.One).countPopulation();
4388   assert(NumUnknownBits <= Bits);
4389   if (HasDefault && DeadCases.empty() &&
4390       NumUnknownBits < 64 /* avoid overflow */ &&
4391       SI->getNumCases() == (1ULL << NumUnknownBits)) {
4392     DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4393     BasicBlock *NewDefault =
4394         SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
4395     SI->setDefaultDest(&*NewDefault);
4396     SplitBlock(&*NewDefault, &NewDefault->front());
4397     auto *OldTI = NewDefault->getTerminator();
4398     new UnreachableInst(SI->getContext(), OldTI);
4399     EraseTerminatorInstAndDCECond(OldTI);
4400     return true;
4401   }
4402 
4403   SmallVector<uint64_t, 8> Weights;
4404   bool HasWeight = HasBranchWeights(SI);
4405   if (HasWeight) {
4406     GetBranchWeights(SI, Weights);
4407     HasWeight = (Weights.size() == 1 + SI->getNumCases());
4408   }
4409 
4410   // Remove dead cases from the switch.
4411   for (ConstantInt *DeadCase : DeadCases) {
4412     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4413     assert(CaseI != SI->case_default() &&
4414            "Case was not found. Probably mistake in DeadCases forming.");
4415     if (HasWeight) {
4416       std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
4417       Weights.pop_back();
4418     }
4419 
4420     // Prune unused values from PHI nodes.
4421     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4422     SI->removeCase(CaseI);
4423   }
4424   if (HasWeight && Weights.size() >= 2) {
4425     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4426     SI->setMetadata(LLVMContext::MD_prof,
4427                     MDBuilder(SI->getParent()->getContext())
4428                         .createBranchWeights(MDWeights));
4429   }
4430 
4431   return !DeadCases.empty();
4432 }
4433 
4434 /// If BB would be eligible for simplification by
4435 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4436 /// by an unconditional branch), look at the phi node for BB in the successor
4437 /// block and see if the incoming value is equal to CaseValue. If so, return
4438 /// the phi node, and set PhiIndex to BB's index in the phi node.
4439 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4440                                               BasicBlock *BB, int *PhiIndex) {
4441   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4442     return nullptr; // BB must be empty to be a candidate for simplification.
4443   if (!BB->getSinglePredecessor())
4444     return nullptr; // BB must be dominated by the switch.
4445 
4446   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4447   if (!Branch || !Branch->isUnconditional())
4448     return nullptr; // Terminator must be unconditional branch.
4449 
4450   BasicBlock *Succ = Branch->getSuccessor(0);
4451 
4452   BasicBlock::iterator I = Succ->begin();
4453   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4454     int Idx = PHI->getBasicBlockIndex(BB);
4455     assert(Idx >= 0 && "PHI has no entry for predecessor?");
4456 
4457     Value *InValue = PHI->getIncomingValue(Idx);
4458     if (InValue != CaseValue)
4459       continue;
4460 
4461     *PhiIndex = Idx;
4462     return PHI;
4463   }
4464 
4465   return nullptr;
4466 }
4467 
4468 /// Try to forward the condition of a switch instruction to a phi node
4469 /// dominated by the switch, if that would mean that some of the destination
4470 /// blocks of the switch can be folded away. Return true if a change is made.
4471 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4472   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4473 
4474   ForwardingNodesMap ForwardingNodes;
4475   BasicBlock *SwitchBlock = SI->getParent();
4476   bool Changed = false;
4477   for (auto &Case : SI->cases()) {
4478     ConstantInt *CaseValue = Case.getCaseValue();
4479     BasicBlock *CaseDest = Case.getCaseSuccessor();
4480 
4481     // Replace phi operands in successor blocks that are using the constant case
4482     // value rather than the switch condition variable:
4483     //   switchbb:
4484     //   switch i32 %x, label %default [
4485     //     i32 17, label %succ
4486     //   ...
4487     //   succ:
4488     //     %r = phi i32 ... [ 17, %switchbb ] ...
4489     // -->
4490     //     %r = phi i32 ... [ %x, %switchbb ] ...
4491 
4492     for (Instruction &InstInCaseDest : *CaseDest) {
4493       auto *Phi = dyn_cast<PHINode>(&InstInCaseDest);
4494       if (!Phi) break;
4495 
4496       // This only works if there is exactly 1 incoming edge from the switch to
4497       // a phi. If there is >1, that means multiple cases of the switch map to 1
4498       // value in the phi, and that phi value is not the switch condition. Thus,
4499       // this transform would not make sense (the phi would be invalid because
4500       // a phi can't have different incoming values from the same block).
4501       int SwitchBBIdx = Phi->getBasicBlockIndex(SwitchBlock);
4502       if (Phi->getIncomingValue(SwitchBBIdx) == CaseValue &&
4503           count(Phi->blocks(), SwitchBlock) == 1) {
4504         Phi->setIncomingValue(SwitchBBIdx, SI->getCondition());
4505         Changed = true;
4506       }
4507     }
4508 
4509     // Collect phi nodes that are indirectly using this switch's case constants.
4510     int PhiIdx;
4511     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4512       ForwardingNodes[Phi].push_back(PhiIdx);
4513   }
4514 
4515   for (auto &ForwardingNode : ForwardingNodes) {
4516     PHINode *Phi = ForwardingNode.first;
4517     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
4518     if (Indexes.size() < 2)
4519       continue;
4520 
4521     for (int Index : Indexes)
4522       Phi->setIncomingValue(Index, SI->getCondition());
4523     Changed = true;
4524   }
4525 
4526   return Changed;
4527 }
4528 
4529 /// Return true if the backend will be able to handle
4530 /// initializing an array of constants like C.
4531 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4532   if (C->isThreadDependent())
4533     return false;
4534   if (C->isDLLImportDependent())
4535     return false;
4536 
4537   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4538       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4539       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4540     return false;
4541 
4542   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
4543     if (!CE->isGEPWithNoNotionalOverIndexing())
4544       return false;
4545     if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4546       return false;
4547   }
4548 
4549   if (!TTI.shouldBuildLookupTablesForConstant(C))
4550     return false;
4551 
4552   return true;
4553 }
4554 
4555 /// If V is a Constant, return it. Otherwise, try to look up
4556 /// its constant value in ConstantPool, returning 0 if it's not there.
4557 static Constant *
4558 LookupConstant(Value *V,
4559                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4560   if (Constant *C = dyn_cast<Constant>(V))
4561     return C;
4562   return ConstantPool.lookup(V);
4563 }
4564 
4565 /// Try to fold instruction I into a constant. This works for
4566 /// simple instructions such as binary operations where both operands are
4567 /// constant or can be replaced by constants from the ConstantPool. Returns the
4568 /// resulting constant on success, 0 otherwise.
4569 static Constant *
4570 ConstantFold(Instruction *I, const DataLayout &DL,
4571              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4572   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
4573     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4574     if (!A)
4575       return nullptr;
4576     if (A->isAllOnesValue())
4577       return LookupConstant(Select->getTrueValue(), ConstantPool);
4578     if (A->isNullValue())
4579       return LookupConstant(Select->getFalseValue(), ConstantPool);
4580     return nullptr;
4581   }
4582 
4583   SmallVector<Constant *, 4> COps;
4584   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4585     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4586       COps.push_back(A);
4587     else
4588       return nullptr;
4589   }
4590 
4591   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4592     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4593                                            COps[1], DL);
4594   }
4595 
4596   return ConstantFoldInstOperands(I, COps, DL);
4597 }
4598 
4599 /// Try to determine the resulting constant values in phi nodes
4600 /// at the common destination basic block, *CommonDest, for one of the case
4601 /// destionations CaseDest corresponding to value CaseVal (0 for the default
4602 /// case), of a switch instruction SI.
4603 static bool
4604 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4605                BasicBlock **CommonDest,
4606                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4607                const DataLayout &DL, const TargetTransformInfo &TTI) {
4608   // The block from which we enter the common destination.
4609   BasicBlock *Pred = SI->getParent();
4610 
4611   // If CaseDest is empty except for some side-effect free instructions through
4612   // which we can constant-propagate the CaseVal, continue to its successor.
4613   SmallDenseMap<Value *, Constant *> ConstantPool;
4614   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4615   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4616        ++I) {
4617     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4618       // If the terminator is a simple branch, continue to the next block.
4619       if (T->getNumSuccessors() != 1 || T->isExceptional())
4620         return false;
4621       Pred = CaseDest;
4622       CaseDest = T->getSuccessor(0);
4623     } else if (isa<DbgInfoIntrinsic>(I)) {
4624       // Skip debug intrinsic.
4625       continue;
4626     } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
4627       // Instruction is side-effect free and constant.
4628 
4629       // If the instruction has uses outside this block or a phi node slot for
4630       // the block, it is not safe to bypass the instruction since it would then
4631       // no longer dominate all its uses.
4632       for (auto &Use : I->uses()) {
4633         User *User = Use.getUser();
4634         if (Instruction *I = dyn_cast<Instruction>(User))
4635           if (I->getParent() == CaseDest)
4636             continue;
4637         if (PHINode *Phi = dyn_cast<PHINode>(User))
4638           if (Phi->getIncomingBlock(Use) == CaseDest)
4639             continue;
4640         return false;
4641       }
4642 
4643       ConstantPool.insert(std::make_pair(&*I, C));
4644     } else {
4645       break;
4646     }
4647   }
4648 
4649   // If we did not have a CommonDest before, use the current one.
4650   if (!*CommonDest)
4651     *CommonDest = CaseDest;
4652   // If the destination isn't the common one, abort.
4653   if (CaseDest != *CommonDest)
4654     return false;
4655 
4656   // Get the values for this case from phi nodes in the destination block.
4657   BasicBlock::iterator I = (*CommonDest)->begin();
4658   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4659     int Idx = PHI->getBasicBlockIndex(Pred);
4660     if (Idx == -1)
4661       continue;
4662 
4663     Constant *ConstVal =
4664         LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
4665     if (!ConstVal)
4666       return false;
4667 
4668     // Be conservative about which kinds of constants we support.
4669     if (!ValidLookupTableConstant(ConstVal, TTI))
4670       return false;
4671 
4672     Res.push_back(std::make_pair(PHI, ConstVal));
4673   }
4674 
4675   return Res.size() > 0;
4676 }
4677 
4678 // Helper function used to add CaseVal to the list of cases that generate
4679 // Result.
4680 static void MapCaseToResult(ConstantInt *CaseVal,
4681                             SwitchCaseResultVectorTy &UniqueResults,
4682                             Constant *Result) {
4683   for (auto &I : UniqueResults) {
4684     if (I.first == Result) {
4685       I.second.push_back(CaseVal);
4686       return;
4687     }
4688   }
4689   UniqueResults.push_back(
4690       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
4691 }
4692 
4693 // Helper function that initializes a map containing
4694 // results for the PHI node of the common destination block for a switch
4695 // instruction. Returns false if multiple PHI nodes have been found or if
4696 // there is not a common destination block for the switch.
4697 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4698                                   BasicBlock *&CommonDest,
4699                                   SwitchCaseResultVectorTy &UniqueResults,
4700                                   Constant *&DefaultResult,
4701                                   const DataLayout &DL,
4702                                   const TargetTransformInfo &TTI) {
4703   for (auto &I : SI->cases()) {
4704     ConstantInt *CaseVal = I.getCaseValue();
4705 
4706     // Resulting value at phi nodes for this case value.
4707     SwitchCaseResultsTy Results;
4708     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4709                         DL, TTI))
4710       return false;
4711 
4712     // Only one value per case is permitted
4713     if (Results.size() > 1)
4714       return false;
4715     MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4716 
4717     // Check the PHI consistency.
4718     if (!PHI)
4719       PHI = Results[0].first;
4720     else if (PHI != Results[0].first)
4721       return false;
4722   }
4723   // Find the default result value.
4724   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4725   BasicBlock *DefaultDest = SI->getDefaultDest();
4726   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4727                  DL, TTI);
4728   // If the default value is not found abort unless the default destination
4729   // is unreachable.
4730   DefaultResult =
4731       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4732   if ((!DefaultResult &&
4733        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4734     return false;
4735 
4736   return true;
4737 }
4738 
4739 // Helper function that checks if it is possible to transform a switch with only
4740 // two cases (or two cases + default) that produces a result into a select.
4741 // Example:
4742 // switch (a) {
4743 //   case 10:                %0 = icmp eq i32 %a, 10
4744 //     return 10;            %1 = select i1 %0, i32 10, i32 4
4745 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
4746 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
4747 //   default:
4748 //     return 4;
4749 // }
4750 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4751                                    Constant *DefaultResult, Value *Condition,
4752                                    IRBuilder<> &Builder) {
4753   assert(ResultVector.size() == 2 &&
4754          "We should have exactly two unique results at this point");
4755   // If we are selecting between only two cases transform into a simple
4756   // select or a two-way select if default is possible.
4757   if (ResultVector[0].second.size() == 1 &&
4758       ResultVector[1].second.size() == 1) {
4759     ConstantInt *const FirstCase = ResultVector[0].second[0];
4760     ConstantInt *const SecondCase = ResultVector[1].second[0];
4761 
4762     bool DefaultCanTrigger = DefaultResult;
4763     Value *SelectValue = ResultVector[1].first;
4764     if (DefaultCanTrigger) {
4765       Value *const ValueCompare =
4766           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4767       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4768                                          DefaultResult, "switch.select");
4769     }
4770     Value *const ValueCompare =
4771         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4772     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4773                                 SelectValue, "switch.select");
4774   }
4775 
4776   return nullptr;
4777 }
4778 
4779 // Helper function to cleanup a switch instruction that has been converted into
4780 // a select, fixing up PHI nodes and basic blocks.
4781 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4782                                               Value *SelectValue,
4783                                               IRBuilder<> &Builder) {
4784   BasicBlock *SelectBB = SI->getParent();
4785   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4786     PHI->removeIncomingValue(SelectBB);
4787   PHI->addIncoming(SelectValue, SelectBB);
4788 
4789   Builder.CreateBr(PHI->getParent());
4790 
4791   // Remove the switch.
4792   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4793     BasicBlock *Succ = SI->getSuccessor(i);
4794 
4795     if (Succ == PHI->getParent())
4796       continue;
4797     Succ->removePredecessor(SelectBB);
4798   }
4799   SI->eraseFromParent();
4800 }
4801 
4802 /// If the switch is only used to initialize one or more
4803 /// phi nodes in a common successor block with only two different
4804 /// constant values, replace the switch with select.
4805 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4806                            const DataLayout &DL,
4807                            const TargetTransformInfo &TTI) {
4808   Value *const Cond = SI->getCondition();
4809   PHINode *PHI = nullptr;
4810   BasicBlock *CommonDest = nullptr;
4811   Constant *DefaultResult;
4812   SwitchCaseResultVectorTy UniqueResults;
4813   // Collect all the cases that will deliver the same value from the switch.
4814   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4815                              DL, TTI))
4816     return false;
4817   // Selects choose between maximum two values.
4818   if (UniqueResults.size() != 2)
4819     return false;
4820   assert(PHI != nullptr && "PHI for value select not found");
4821 
4822   Builder.SetInsertPoint(SI);
4823   Value *SelectValue =
4824       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
4825   if (SelectValue) {
4826     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4827     return true;
4828   }
4829   // The switch couldn't be converted into a select.
4830   return false;
4831 }
4832 
4833 namespace {
4834 
4835 /// This class represents a lookup table that can be used to replace a switch.
4836 class SwitchLookupTable {
4837 public:
4838   /// Create a lookup table to use as a switch replacement with the contents
4839   /// of Values, using DefaultValue to fill any holes in the table.
4840   SwitchLookupTable(
4841       Module &M, uint64_t TableSize, ConstantInt *Offset,
4842       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4843       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
4844 
4845   /// Build instructions with Builder to retrieve the value at
4846   /// the position given by Index in the lookup table.
4847   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4848 
4849   /// Return true if a table with TableSize elements of
4850   /// type ElementType would fit in a target-legal register.
4851   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4852                                  Type *ElementType);
4853 
4854 private:
4855   // Depending on the contents of the table, it can be represented in
4856   // different ways.
4857   enum {
4858     // For tables where each element contains the same value, we just have to
4859     // store that single value and return it for each lookup.
4860     SingleValueKind,
4861 
4862     // For tables where there is a linear relationship between table index
4863     // and values. We calculate the result with a simple multiplication
4864     // and addition instead of a table lookup.
4865     LinearMapKind,
4866 
4867     // For small tables with integer elements, we can pack them into a bitmap
4868     // that fits into a target-legal register. Values are retrieved by
4869     // shift and mask operations.
4870     BitMapKind,
4871 
4872     // The table is stored as an array of values. Values are retrieved by load
4873     // instructions from the table.
4874     ArrayKind
4875   } Kind;
4876 
4877   // For SingleValueKind, this is the single value.
4878   Constant *SingleValue = nullptr;
4879 
4880   // For BitMapKind, this is the bitmap.
4881   ConstantInt *BitMap = nullptr;
4882   IntegerType *BitMapElementTy = nullptr;
4883 
4884   // For LinearMapKind, these are the constants used to derive the value.
4885   ConstantInt *LinearOffset = nullptr;
4886   ConstantInt *LinearMultiplier = nullptr;
4887 
4888   // For ArrayKind, this is the array.
4889   GlobalVariable *Array = nullptr;
4890 };
4891 
4892 } // end anonymous namespace
4893 
4894 SwitchLookupTable::SwitchLookupTable(
4895     Module &M, uint64_t TableSize, ConstantInt *Offset,
4896     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4897     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
4898   assert(Values.size() && "Can't build lookup table without values!");
4899   assert(TableSize >= Values.size() && "Can't fit values in table!");
4900 
4901   // If all values in the table are equal, this is that value.
4902   SingleValue = Values.begin()->second;
4903 
4904   Type *ValueType = Values.begin()->second->getType();
4905 
4906   // Build up the table contents.
4907   SmallVector<Constant *, 64> TableContents(TableSize);
4908   for (size_t I = 0, E = Values.size(); I != E; ++I) {
4909     ConstantInt *CaseVal = Values[I].first;
4910     Constant *CaseRes = Values[I].second;
4911     assert(CaseRes->getType() == ValueType);
4912 
4913     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
4914     TableContents[Idx] = CaseRes;
4915 
4916     if (CaseRes != SingleValue)
4917       SingleValue = nullptr;
4918   }
4919 
4920   // Fill in any holes in the table with the default result.
4921   if (Values.size() < TableSize) {
4922     assert(DefaultValue &&
4923            "Need a default value to fill the lookup table holes.");
4924     assert(DefaultValue->getType() == ValueType);
4925     for (uint64_t I = 0; I < TableSize; ++I) {
4926       if (!TableContents[I])
4927         TableContents[I] = DefaultValue;
4928     }
4929 
4930     if (DefaultValue != SingleValue)
4931       SingleValue = nullptr;
4932   }
4933 
4934   // If each element in the table contains the same value, we only need to store
4935   // that single value.
4936   if (SingleValue) {
4937     Kind = SingleValueKind;
4938     return;
4939   }
4940 
4941   // Check if we can derive the value with a linear transformation from the
4942   // table index.
4943   if (isa<IntegerType>(ValueType)) {
4944     bool LinearMappingPossible = true;
4945     APInt PrevVal;
4946     APInt DistToPrev;
4947     assert(TableSize >= 2 && "Should be a SingleValue table.");
4948     // Check if there is the same distance between two consecutive values.
4949     for (uint64_t I = 0; I < TableSize; ++I) {
4950       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4951       if (!ConstVal) {
4952         // This is an undef. We could deal with it, but undefs in lookup tables
4953         // are very seldom. It's probably not worth the additional complexity.
4954         LinearMappingPossible = false;
4955         break;
4956       }
4957       const APInt &Val = ConstVal->getValue();
4958       if (I != 0) {
4959         APInt Dist = Val - PrevVal;
4960         if (I == 1) {
4961           DistToPrev = Dist;
4962         } else if (Dist != DistToPrev) {
4963           LinearMappingPossible = false;
4964           break;
4965         }
4966       }
4967       PrevVal = Val;
4968     }
4969     if (LinearMappingPossible) {
4970       LinearOffset = cast<ConstantInt>(TableContents[0]);
4971       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4972       Kind = LinearMapKind;
4973       ++NumLinearMaps;
4974       return;
4975     }
4976   }
4977 
4978   // If the type is integer and the table fits in a register, build a bitmap.
4979   if (WouldFitInRegister(DL, TableSize, ValueType)) {
4980     IntegerType *IT = cast<IntegerType>(ValueType);
4981     APInt TableInt(TableSize * IT->getBitWidth(), 0);
4982     for (uint64_t I = TableSize; I > 0; --I) {
4983       TableInt <<= IT->getBitWidth();
4984       // Insert values into the bitmap. Undef values are set to zero.
4985       if (!isa<UndefValue>(TableContents[I - 1])) {
4986         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4987         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4988       }
4989     }
4990     BitMap = ConstantInt::get(M.getContext(), TableInt);
4991     BitMapElementTy = IT;
4992     Kind = BitMapKind;
4993     ++NumBitMaps;
4994     return;
4995   }
4996 
4997   // Store the table in an array.
4998   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4999   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5000 
5001   Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
5002                              GlobalVariable::PrivateLinkage, Initializer,
5003                              "switch.table." + FuncName);
5004   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5005   Kind = ArrayKind;
5006 }
5007 
5008 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5009   switch (Kind) {
5010   case SingleValueKind:
5011     return SingleValue;
5012   case LinearMapKind: {
5013     // Derive the result value from the input value.
5014     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5015                                           false, "switch.idx.cast");
5016     if (!LinearMultiplier->isOne())
5017       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5018     if (!LinearOffset->isZero())
5019       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5020     return Result;
5021   }
5022   case BitMapKind: {
5023     // Type of the bitmap (e.g. i59).
5024     IntegerType *MapTy = BitMap->getType();
5025 
5026     // Cast Index to the same type as the bitmap.
5027     // Note: The Index is <= the number of elements in the table, so
5028     // truncating it to the width of the bitmask is safe.
5029     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5030 
5031     // Multiply the shift amount by the element width.
5032     ShiftAmt = Builder.CreateMul(
5033         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5034         "switch.shiftamt");
5035 
5036     // Shift down.
5037     Value *DownShifted =
5038         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5039     // Mask off.
5040     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5041   }
5042   case ArrayKind: {
5043     // Make sure the table index will not overflow when treated as signed.
5044     IntegerType *IT = cast<IntegerType>(Index->getType());
5045     uint64_t TableSize =
5046         Array->getInitializer()->getType()->getArrayNumElements();
5047     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5048       Index = Builder.CreateZExt(
5049           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5050           "switch.tableidx.zext");
5051 
5052     Value *GEPIndices[] = {Builder.getInt32(0), Index};
5053     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5054                                            GEPIndices, "switch.gep");
5055     return Builder.CreateLoad(GEP, "switch.load");
5056   }
5057   }
5058   llvm_unreachable("Unknown lookup table kind!");
5059 }
5060 
5061 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5062                                            uint64_t TableSize,
5063                                            Type *ElementType) {
5064   auto *IT = dyn_cast<IntegerType>(ElementType);
5065   if (!IT)
5066     return false;
5067   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5068   // are <= 15, we could try to narrow the type.
5069 
5070   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5071   if (TableSize >= UINT_MAX / IT->getBitWidth())
5072     return false;
5073   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5074 }
5075 
5076 /// Determine whether a lookup table should be built for this switch, based on
5077 /// the number of cases, size of the table, and the types of the results.
5078 static bool
5079 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5080                        const TargetTransformInfo &TTI, const DataLayout &DL,
5081                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5082   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5083     return false; // TableSize overflowed, or mul below might overflow.
5084 
5085   bool AllTablesFitInRegister = true;
5086   bool HasIllegalType = false;
5087   for (const auto &I : ResultTypes) {
5088     Type *Ty = I.second;
5089 
5090     // Saturate this flag to true.
5091     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5092 
5093     // Saturate this flag to false.
5094     AllTablesFitInRegister =
5095         AllTablesFitInRegister &&
5096         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5097 
5098     // If both flags saturate, we're done. NOTE: This *only* works with
5099     // saturating flags, and all flags have to saturate first due to the
5100     // non-deterministic behavior of iterating over a dense map.
5101     if (HasIllegalType && !AllTablesFitInRegister)
5102       break;
5103   }
5104 
5105   // If each table would fit in a register, we should build it anyway.
5106   if (AllTablesFitInRegister)
5107     return true;
5108 
5109   // Don't build a table that doesn't fit in-register if it has illegal types.
5110   if (HasIllegalType)
5111     return false;
5112 
5113   // The table density should be at least 40%. This is the same criterion as for
5114   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5115   // FIXME: Find the best cut-off.
5116   return SI->getNumCases() * 10 >= TableSize * 4;
5117 }
5118 
5119 /// Try to reuse the switch table index compare. Following pattern:
5120 /// \code
5121 ///     if (idx < tablesize)
5122 ///        r = table[idx]; // table does not contain default_value
5123 ///     else
5124 ///        r = default_value;
5125 ///     if (r != default_value)
5126 ///        ...
5127 /// \endcode
5128 /// Is optimized to:
5129 /// \code
5130 ///     cond = idx < tablesize;
5131 ///     if (cond)
5132 ///        r = table[idx];
5133 ///     else
5134 ///        r = default_value;
5135 ///     if (cond)
5136 ///        ...
5137 /// \endcode
5138 /// Jump threading will then eliminate the second if(cond).
5139 static void reuseTableCompare(
5140     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5141     Constant *DefaultValue,
5142     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5143   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5144   if (!CmpInst)
5145     return;
5146 
5147   // We require that the compare is in the same block as the phi so that jump
5148   // threading can do its work afterwards.
5149   if (CmpInst->getParent() != PhiBlock)
5150     return;
5151 
5152   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5153   if (!CmpOp1)
5154     return;
5155 
5156   Value *RangeCmp = RangeCheckBranch->getCondition();
5157   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5158   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5159 
5160   // Check if the compare with the default value is constant true or false.
5161   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5162                                                  DefaultValue, CmpOp1, true);
5163   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5164     return;
5165 
5166   // Check if the compare with the case values is distinct from the default
5167   // compare result.
5168   for (auto ValuePair : Values) {
5169     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5170                                                 ValuePair.second, CmpOp1, true);
5171     if (!CaseConst || CaseConst == DefaultConst)
5172       return;
5173     assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5174            "Expect true or false as compare result.");
5175   }
5176 
5177   // Check if the branch instruction dominates the phi node. It's a simple
5178   // dominance check, but sufficient for our needs.
5179   // Although this check is invariant in the calling loops, it's better to do it
5180   // at this late stage. Practically we do it at most once for a switch.
5181   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5182   for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5183     BasicBlock *Pred = *PI;
5184     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5185       return;
5186   }
5187 
5188   if (DefaultConst == FalseConst) {
5189     // The compare yields the same result. We can replace it.
5190     CmpInst->replaceAllUsesWith(RangeCmp);
5191     ++NumTableCmpReuses;
5192   } else {
5193     // The compare yields the same result, just inverted. We can replace it.
5194     Value *InvertedTableCmp = BinaryOperator::CreateXor(
5195         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5196         RangeCheckBranch);
5197     CmpInst->replaceAllUsesWith(InvertedTableCmp);
5198     ++NumTableCmpReuses;
5199   }
5200 }
5201 
5202 /// If the switch is only used to initialize one or more phi nodes in a common
5203 /// successor block with different constant values, replace the switch with
5204 /// lookup tables.
5205 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5206                                 const DataLayout &DL,
5207                                 const TargetTransformInfo &TTI) {
5208   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5209 
5210   Function *Fn = SI->getParent()->getParent();
5211   // Only build lookup table when we have a target that supports it or the
5212   // attribute is not set.
5213   if (!TTI.shouldBuildLookupTables() ||
5214       (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
5215     return false;
5216 
5217   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5218   // split off a dense part and build a lookup table for that.
5219 
5220   // FIXME: This creates arrays of GEPs to constant strings, which means each
5221   // GEP needs a runtime relocation in PIC code. We should just build one big
5222   // string and lookup indices into that.
5223 
5224   // Ignore switches with less than three cases. Lookup tables will not make
5225   // them faster, so we don't analyze them.
5226   if (SI->getNumCases() < 3)
5227     return false;
5228 
5229   // Figure out the corresponding result for each case value and phi node in the
5230   // common destination, as well as the min and max case values.
5231   assert(SI->case_begin() != SI->case_end());
5232   SwitchInst::CaseIt CI = SI->case_begin();
5233   ConstantInt *MinCaseVal = CI->getCaseValue();
5234   ConstantInt *MaxCaseVal = CI->getCaseValue();
5235 
5236   BasicBlock *CommonDest = nullptr;
5237 
5238   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5239   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5240 
5241   SmallDenseMap<PHINode *, Constant *> DefaultResults;
5242   SmallDenseMap<PHINode *, Type *> ResultTypes;
5243   SmallVector<PHINode *, 4> PHIs;
5244 
5245   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5246     ConstantInt *CaseVal = CI->getCaseValue();
5247     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5248       MinCaseVal = CaseVal;
5249     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5250       MaxCaseVal = CaseVal;
5251 
5252     // Resulting value at phi nodes for this case value.
5253     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5254     ResultsTy Results;
5255     if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5256                         Results, DL, TTI))
5257       return false;
5258 
5259     // Append the result from this case to the list for each phi.
5260     for (const auto &I : Results) {
5261       PHINode *PHI = I.first;
5262       Constant *Value = I.second;
5263       if (!ResultLists.count(PHI))
5264         PHIs.push_back(PHI);
5265       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5266     }
5267   }
5268 
5269   // Keep track of the result types.
5270   for (PHINode *PHI : PHIs) {
5271     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5272   }
5273 
5274   uint64_t NumResults = ResultLists[PHIs[0]].size();
5275   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5276   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5277   bool TableHasHoles = (NumResults < TableSize);
5278 
5279   // If the table has holes, we need a constant result for the default case
5280   // or a bitmask that fits in a register.
5281   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5282   bool HasDefaultResults =
5283       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5284                      DefaultResultsList, DL, TTI);
5285 
5286   bool NeedMask = (TableHasHoles && !HasDefaultResults);
5287   if (NeedMask) {
5288     // As an extra penalty for the validity test we require more cases.
5289     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5290       return false;
5291     if (!DL.fitsInLegalInteger(TableSize))
5292       return false;
5293   }
5294 
5295   for (const auto &I : DefaultResultsList) {
5296     PHINode *PHI = I.first;
5297     Constant *Result = I.second;
5298     DefaultResults[PHI] = Result;
5299   }
5300 
5301   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5302     return false;
5303 
5304   // Create the BB that does the lookups.
5305   Module &Mod = *CommonDest->getParent()->getParent();
5306   BasicBlock *LookupBB = BasicBlock::Create(
5307       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5308 
5309   // Compute the table index value.
5310   Builder.SetInsertPoint(SI);
5311   Value *TableIndex;
5312   if (MinCaseVal->isNullValue())
5313     TableIndex = SI->getCondition();
5314   else
5315     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5316                                    "switch.tableidx");
5317 
5318   // Compute the maximum table size representable by the integer type we are
5319   // switching upon.
5320   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5321   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5322   assert(MaxTableSize >= TableSize &&
5323          "It is impossible for a switch to have more entries than the max "
5324          "representable value of its input integer type's size.");
5325 
5326   // If the default destination is unreachable, or if the lookup table covers
5327   // all values of the conditional variable, branch directly to the lookup table
5328   // BB. Otherwise, check that the condition is within the case range.
5329   const bool DefaultIsReachable =
5330       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5331   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5332   BranchInst *RangeCheckBranch = nullptr;
5333 
5334   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5335     Builder.CreateBr(LookupBB);
5336     // Note: We call removeProdecessor later since we need to be able to get the
5337     // PHI value for the default case in case we're using a bit mask.
5338   } else {
5339     Value *Cmp = Builder.CreateICmpULT(
5340         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5341     RangeCheckBranch =
5342         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5343   }
5344 
5345   // Populate the BB that does the lookups.
5346   Builder.SetInsertPoint(LookupBB);
5347 
5348   if (NeedMask) {
5349     // Before doing the lookup, we do the hole check. The LookupBB is therefore
5350     // re-purposed to do the hole check, and we create a new LookupBB.
5351     BasicBlock *MaskBB = LookupBB;
5352     MaskBB->setName("switch.hole_check");
5353     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5354                                   CommonDest->getParent(), CommonDest);
5355 
5356     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
5357     // unnecessary illegal types.
5358     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5359     APInt MaskInt(TableSizePowOf2, 0);
5360     APInt One(TableSizePowOf2, 1);
5361     // Build bitmask; fill in a 1 bit for every case.
5362     const ResultListTy &ResultList = ResultLists[PHIs[0]];
5363     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5364       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5365                          .getLimitedValue();
5366       MaskInt |= One << Idx;
5367     }
5368     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5369 
5370     // Get the TableIndex'th bit of the bitmask.
5371     // If this bit is 0 (meaning hole) jump to the default destination,
5372     // else continue with table lookup.
5373     IntegerType *MapTy = TableMask->getType();
5374     Value *MaskIndex =
5375         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5376     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5377     Value *LoBit = Builder.CreateTrunc(
5378         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5379     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5380 
5381     Builder.SetInsertPoint(LookupBB);
5382     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5383   }
5384 
5385   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5386     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
5387     // do not delete PHINodes here.
5388     SI->getDefaultDest()->removePredecessor(SI->getParent(),
5389                                             /*DontDeleteUselessPHIs=*/true);
5390   }
5391 
5392   bool ReturnedEarly = false;
5393   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5394     PHINode *PHI = PHIs[I];
5395     const ResultListTy &ResultList = ResultLists[PHI];
5396 
5397     // If using a bitmask, use any value to fill the lookup table holes.
5398     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5399     StringRef FuncName = Fn->getName();
5400     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5401                             FuncName);
5402 
5403     Value *Result = Table.BuildLookup(TableIndex, Builder);
5404 
5405     // If the result is used to return immediately from the function, we want to
5406     // do that right here.
5407     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5408         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5409       Builder.CreateRet(Result);
5410       ReturnedEarly = true;
5411       break;
5412     }
5413 
5414     // Do a small peephole optimization: re-use the switch table compare if
5415     // possible.
5416     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5417       BasicBlock *PhiBlock = PHI->getParent();
5418       // Search for compare instructions which use the phi.
5419       for (auto *User : PHI->users()) {
5420         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5421       }
5422     }
5423 
5424     PHI->addIncoming(Result, LookupBB);
5425   }
5426 
5427   if (!ReturnedEarly)
5428     Builder.CreateBr(CommonDest);
5429 
5430   // Remove the switch.
5431   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5432     BasicBlock *Succ = SI->getSuccessor(i);
5433 
5434     if (Succ == SI->getDefaultDest())
5435       continue;
5436     Succ->removePredecessor(SI->getParent());
5437   }
5438   SI->eraseFromParent();
5439 
5440   ++NumLookupTables;
5441   if (NeedMask)
5442     ++NumLookupTablesHoles;
5443   return true;
5444 }
5445 
5446 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5447   // See also SelectionDAGBuilder::isDense(), which this function was based on.
5448   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5449   uint64_t Range = Diff + 1;
5450   uint64_t NumCases = Values.size();
5451   // 40% is the default density for building a jump table in optsize/minsize mode.
5452   uint64_t MinDensity = 40;
5453 
5454   return NumCases * 100 >= Range * MinDensity;
5455 }
5456 
5457 /// Try to transform a switch that has "holes" in it to a contiguous sequence
5458 /// of cases.
5459 ///
5460 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5461 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5462 ///
5463 /// This converts a sparse switch into a dense switch which allows better
5464 /// lowering and could also allow transforming into a lookup table.
5465 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5466                               const DataLayout &DL,
5467                               const TargetTransformInfo &TTI) {
5468   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5469   if (CondTy->getIntegerBitWidth() > 64 ||
5470       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5471     return false;
5472   // Only bother with this optimization if there are more than 3 switch cases;
5473   // SDAG will only bother creating jump tables for 4 or more cases.
5474   if (SI->getNumCases() < 4)
5475     return false;
5476 
5477   // This transform is agnostic to the signedness of the input or case values. We
5478   // can treat the case values as signed or unsigned. We can optimize more common
5479   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5480   // as signed.
5481   SmallVector<int64_t,4> Values;
5482   for (auto &C : SI->cases())
5483     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5484   std::sort(Values.begin(), Values.end());
5485 
5486   // If the switch is already dense, there's nothing useful to do here.
5487   if (isSwitchDense(Values))
5488     return false;
5489 
5490   // First, transform the values such that they start at zero and ascend.
5491   int64_t Base = Values[0];
5492   for (auto &V : Values)
5493     V -= (uint64_t)(Base);
5494 
5495   // Now we have signed numbers that have been shifted so that, given enough
5496   // precision, there are no negative values. Since the rest of the transform
5497   // is bitwise only, we switch now to an unsigned representation.
5498   uint64_t GCD = 0;
5499   for (auto &V : Values)
5500     GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
5501 
5502   // This transform can be done speculatively because it is so cheap - it results
5503   // in a single rotate operation being inserted. This can only happen if the
5504   // factor extracted is a power of 2.
5505   // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5506   // inverse of GCD and then perform this transform.
5507   // FIXME: It's possible that optimizing a switch on powers of two might also
5508   // be beneficial - flag values are often powers of two and we could use a CLZ
5509   // as the key function.
5510   if (GCD <= 1 || !isPowerOf2_64(GCD))
5511     // No common divisor found or too expensive to compute key function.
5512     return false;
5513 
5514   unsigned Shift = Log2_64(GCD);
5515   for (auto &V : Values)
5516     V = (int64_t)((uint64_t)V >> Shift);
5517 
5518   if (!isSwitchDense(Values))
5519     // Transform didn't create a dense switch.
5520     return false;
5521 
5522   // The obvious transform is to shift the switch condition right and emit a
5523   // check that the condition actually cleanly divided by GCD, i.e.
5524   //   C & (1 << Shift - 1) == 0
5525   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5526   //
5527   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5528   // shift and puts the shifted-off bits in the uppermost bits. If any of these
5529   // are nonzero then the switch condition will be very large and will hit the
5530   // default case.
5531 
5532   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5533   Builder.SetInsertPoint(SI);
5534   auto *ShiftC = ConstantInt::get(Ty, Shift);
5535   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
5536   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5537   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5538   auto *Rot = Builder.CreateOr(LShr, Shl);
5539   SI->replaceUsesOfWith(SI->getCondition(), Rot);
5540 
5541   for (auto Case : SI->cases()) {
5542     auto *Orig = Case.getCaseValue();
5543     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
5544     Case.setValue(
5545         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5546   }
5547   return true;
5548 }
5549 
5550 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
5551   BasicBlock *BB = SI->getParent();
5552 
5553   if (isValueEqualityComparison(SI)) {
5554     // If we only have one predecessor, and if it is a branch on this value,
5555     // see if that predecessor totally determines the outcome of this switch.
5556     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5557       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5558         return simplifyCFG(BB, TTI, Options) | true;
5559 
5560     Value *Cond = SI->getCondition();
5561     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5562       if (SimplifySwitchOnSelect(SI, Select))
5563         return simplifyCFG(BB, TTI, Options) | true;
5564 
5565     // If the block only contains the switch, see if we can fold the block
5566     // away into any preds.
5567     BasicBlock::iterator BBI = BB->begin();
5568     // Ignore dbg intrinsics.
5569     while (isa<DbgInfoIntrinsic>(BBI))
5570       ++BBI;
5571     if (SI == &*BBI)
5572       if (FoldValueComparisonIntoPredecessors(SI, Builder))
5573         return simplifyCFG(BB, TTI, Options) | true;
5574   }
5575 
5576   // Try to transform the switch into an icmp and a branch.
5577   if (TurnSwitchRangeIntoICmp(SI, Builder))
5578     return simplifyCFG(BB, TTI, Options) | true;
5579 
5580   // Remove unreachable cases.
5581   if (eliminateDeadSwitchCases(SI, Options.AC, DL))
5582     return simplifyCFG(BB, TTI, Options) | true;
5583 
5584   if (switchToSelect(SI, Builder, DL, TTI))
5585     return simplifyCFG(BB, TTI, Options) | true;
5586 
5587   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
5588     return simplifyCFG(BB, TTI, Options) | true;
5589 
5590   // The conversion from switch to lookup tables results in difficult-to-analyze
5591   // code and makes pruning branches much harder. This is a problem if the
5592   // switch expression itself can still be restricted as a result of inlining or
5593   // CVP. Therefore, only apply this transformation during late stages of the
5594   // optimisation pipeline.
5595   if (Options.ConvertSwitchToLookupTable &&
5596       SwitchToLookupTable(SI, Builder, DL, TTI))
5597     return simplifyCFG(BB, TTI, Options) | true;
5598 
5599   if (ReduceSwitchRange(SI, Builder, DL, TTI))
5600     return simplifyCFG(BB, TTI, Options) | true;
5601 
5602   return false;
5603 }
5604 
5605 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5606   BasicBlock *BB = IBI->getParent();
5607   bool Changed = false;
5608 
5609   // Eliminate redundant destinations.
5610   SmallPtrSet<Value *, 8> Succs;
5611   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5612     BasicBlock *Dest = IBI->getDestination(i);
5613     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
5614       Dest->removePredecessor(BB);
5615       IBI->removeDestination(i);
5616       --i;
5617       --e;
5618       Changed = true;
5619     }
5620   }
5621 
5622   if (IBI->getNumDestinations() == 0) {
5623     // If the indirectbr has no successors, change it to unreachable.
5624     new UnreachableInst(IBI->getContext(), IBI);
5625     EraseTerminatorInstAndDCECond(IBI);
5626     return true;
5627   }
5628 
5629   if (IBI->getNumDestinations() == 1) {
5630     // If the indirectbr has one successor, change it to a direct branch.
5631     BranchInst::Create(IBI->getDestination(0), IBI);
5632     EraseTerminatorInstAndDCECond(IBI);
5633     return true;
5634   }
5635 
5636   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5637     if (SimplifyIndirectBrOnSelect(IBI, SI))
5638       return simplifyCFG(BB, TTI, Options) | true;
5639   }
5640   return Changed;
5641 }
5642 
5643 /// Given an block with only a single landing pad and a unconditional branch
5644 /// try to find another basic block which this one can be merged with.  This
5645 /// handles cases where we have multiple invokes with unique landing pads, but
5646 /// a shared handler.
5647 ///
5648 /// We specifically choose to not worry about merging non-empty blocks
5649 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
5650 /// practice, the optimizer produces empty landing pad blocks quite frequently
5651 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
5652 /// sinking in this file)
5653 ///
5654 /// This is primarily a code size optimization.  We need to avoid performing
5655 /// any transform which might inhibit optimization (such as our ability to
5656 /// specialize a particular handler via tail commoning).  We do this by not
5657 /// merging any blocks which require us to introduce a phi.  Since the same
5658 /// values are flowing through both blocks, we don't loose any ability to
5659 /// specialize.  If anything, we make such specialization more likely.
5660 ///
5661 /// TODO - This transformation could remove entries from a phi in the target
5662 /// block when the inputs in the phi are the same for the two blocks being
5663 /// merged.  In some cases, this could result in removal of the PHI entirely.
5664 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5665                                  BasicBlock *BB) {
5666   auto Succ = BB->getUniqueSuccessor();
5667   assert(Succ);
5668   // If there's a phi in the successor block, we'd likely have to introduce
5669   // a phi into the merged landing pad block.
5670   if (isa<PHINode>(*Succ->begin()))
5671     return false;
5672 
5673   for (BasicBlock *OtherPred : predecessors(Succ)) {
5674     if (BB == OtherPred)
5675       continue;
5676     BasicBlock::iterator I = OtherPred->begin();
5677     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5678     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5679       continue;
5680     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5681       ;
5682     BranchInst *BI2 = dyn_cast<BranchInst>(I);
5683     if (!BI2 || !BI2->isIdenticalTo(BI))
5684       continue;
5685 
5686     // We've found an identical block.  Update our predecessors to take that
5687     // path instead and make ourselves dead.
5688     SmallSet<BasicBlock *, 16> Preds;
5689     Preds.insert(pred_begin(BB), pred_end(BB));
5690     for (BasicBlock *Pred : Preds) {
5691       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5692       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5693              "unexpected successor");
5694       II->setUnwindDest(OtherPred);
5695     }
5696 
5697     // The debug info in OtherPred doesn't cover the merged control flow that
5698     // used to go through BB.  We need to delete it or update it.
5699     for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5700       Instruction &Inst = *I;
5701       I++;
5702       if (isa<DbgInfoIntrinsic>(Inst))
5703         Inst.eraseFromParent();
5704     }
5705 
5706     SmallSet<BasicBlock *, 16> Succs;
5707     Succs.insert(succ_begin(BB), succ_end(BB));
5708     for (BasicBlock *Succ : Succs) {
5709       Succ->removePredecessor(BB);
5710     }
5711 
5712     IRBuilder<> Builder(BI);
5713     Builder.CreateUnreachable();
5714     BI->eraseFromParent();
5715     return true;
5716   }
5717   return false;
5718 }
5719 
5720 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5721                                           IRBuilder<> &Builder) {
5722   BasicBlock *BB = BI->getParent();
5723   BasicBlock *Succ = BI->getSuccessor(0);
5724 
5725   if (SinkCommon && SinkThenElseCodeToEnd(BI))
5726     return true;
5727 
5728   // If the Terminator is the only non-phi instruction, simplify the block.
5729   // If LoopHeader is provided, check if the block or its successor is a loop
5730   // header. (This is for early invocations before loop simplify and
5731   // vectorization to keep canonical loop forms for nested loops. These blocks
5732   // can be eliminated when the pass is invoked later in the back-end.)
5733   bool NeedCanonicalLoop =
5734       Options.NeedCanonicalLoop &&
5735       (LoopHeaders && (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5736   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5737   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5738       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
5739     return true;
5740 
5741   // If the only instruction in the block is a seteq/setne comparison against a
5742   // constant, try to simplify the block.
5743   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5744     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5745       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5746         ;
5747       if (I->isTerminator() &&
5748           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, Options))
5749         return true;
5750     }
5751 
5752   // See if we can merge an empty landing pad block with another which is
5753   // equivalent.
5754   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5755     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5756       ;
5757     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
5758       return true;
5759   }
5760 
5761   // If this basic block is ONLY a compare and a branch, and if a predecessor
5762   // branches to us and our successor, fold the comparison into the
5763   // predecessor and use logical operations to update the incoming value
5764   // for PHI nodes in common successor.
5765   if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
5766     return simplifyCFG(BB, TTI, Options) | true;
5767   return false;
5768 }
5769 
5770 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5771   BasicBlock *PredPred = nullptr;
5772   for (auto *P : predecessors(BB)) {
5773     BasicBlock *PPred = P->getSinglePredecessor();
5774     if (!PPred || (PredPred && PredPred != PPred))
5775       return nullptr;
5776     PredPred = PPred;
5777   }
5778   return PredPred;
5779 }
5780 
5781 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5782   BasicBlock *BB = BI->getParent();
5783 
5784   // Conditional branch
5785   if (isValueEqualityComparison(BI)) {
5786     // If we only have one predecessor, and if it is a branch on this value,
5787     // see if that predecessor totally determines the outcome of this
5788     // switch.
5789     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5790       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5791         return simplifyCFG(BB, TTI, Options) | true;
5792 
5793     // This block must be empty, except for the setcond inst, if it exists.
5794     // Ignore dbg intrinsics.
5795     BasicBlock::iterator I = BB->begin();
5796     // Ignore dbg intrinsics.
5797     while (isa<DbgInfoIntrinsic>(I))
5798       ++I;
5799     if (&*I == BI) {
5800       if (FoldValueComparisonIntoPredecessors(BI, Builder))
5801         return simplifyCFG(BB, TTI, Options) | true;
5802     } else if (&*I == cast<Instruction>(BI->getCondition())) {
5803       ++I;
5804       // Ignore dbg intrinsics.
5805       while (isa<DbgInfoIntrinsic>(I))
5806         ++I;
5807       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5808         return simplifyCFG(BB, TTI, Options) | true;
5809     }
5810   }
5811 
5812   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5813   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5814     return true;
5815 
5816   // If this basic block has a single dominating predecessor block and the
5817   // dominating block's condition implies BI's condition, we know the direction
5818   // of the BI branch.
5819   if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5820     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5821     if (PBI && PBI->isConditional() &&
5822         PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
5823       assert(PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB);
5824       bool CondIsTrue = PBI->getSuccessor(0) == BB;
5825       Optional<bool> Implication = isImpliedCondition(
5826           PBI->getCondition(), BI->getCondition(), DL, CondIsTrue);
5827       if (Implication) {
5828         // Turn this into a branch on constant.
5829         auto *OldCond = BI->getCondition();
5830         ConstantInt *CI = *Implication
5831                               ? ConstantInt::getTrue(BB->getContext())
5832                               : ConstantInt::getFalse(BB->getContext());
5833         BI->setCondition(CI);
5834         RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5835         return simplifyCFG(BB, TTI, Options) | true;
5836       }
5837     }
5838   }
5839 
5840   // If this basic block is ONLY a compare and a branch, and if a predecessor
5841   // branches to us and one of our successors, fold the comparison into the
5842   // predecessor and use logical operations to pick the right destination.
5843   if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
5844     return simplifyCFG(BB, TTI, Options) | true;
5845 
5846   // We have a conditional branch to two blocks that are only reachable
5847   // from BI.  We know that the condbr dominates the two blocks, so see if
5848   // there is any identical code in the "then" and "else" blocks.  If so, we
5849   // can hoist it up to the branching block.
5850   if (BI->getSuccessor(0)->getSinglePredecessor()) {
5851     if (BI->getSuccessor(1)->getSinglePredecessor()) {
5852       if (HoistThenElseCodeToIf(BI, TTI))
5853         return simplifyCFG(BB, TTI, Options) | true;
5854     } else {
5855       // If Successor #1 has multiple preds, we may be able to conditionally
5856       // execute Successor #0 if it branches to Successor #1.
5857       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5858       if (Succ0TI->getNumSuccessors() == 1 &&
5859           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5860         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5861           return simplifyCFG(BB, TTI, Options) | true;
5862     }
5863   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
5864     // If Successor #0 has multiple preds, we may be able to conditionally
5865     // execute Successor #1 if it branches to Successor #0.
5866     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5867     if (Succ1TI->getNumSuccessors() == 1 &&
5868         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
5869       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5870         return simplifyCFG(BB, TTI, Options) | true;
5871   }
5872 
5873   // If this is a branch on a phi node in the current block, thread control
5874   // through this block if any PHI node entries are constants.
5875   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5876     if (PN->getParent() == BI->getParent())
5877       if (FoldCondBranchOnPHI(BI, DL, Options.AC))
5878         return simplifyCFG(BB, TTI, Options) | true;
5879 
5880   // Scan predecessor blocks for conditional branches.
5881   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5882     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5883       if (PBI != BI && PBI->isConditional())
5884         if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
5885           return simplifyCFG(BB, TTI, Options) | true;
5886 
5887   // Look for diamond patterns.
5888   if (MergeCondStores)
5889     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5890       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5891         if (PBI != BI && PBI->isConditional())
5892           if (mergeConditionalStores(PBI, BI, DL))
5893             return simplifyCFG(BB, TTI, Options) | true;
5894 
5895   return false;
5896 }
5897 
5898 /// Check if passing a value to an instruction will cause undefined behavior.
5899 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5900   Constant *C = dyn_cast<Constant>(V);
5901   if (!C)
5902     return false;
5903 
5904   if (I->use_empty())
5905     return false;
5906 
5907   if (C->isNullValue() || isa<UndefValue>(C)) {
5908     // Only look at the first use, avoid hurting compile time with long uselists
5909     User *Use = *I->user_begin();
5910 
5911     // Now make sure that there are no instructions in between that can alter
5912     // control flow (eg. calls)
5913     for (BasicBlock::iterator
5914              i = ++BasicBlock::iterator(I),
5915              UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5916          i != UI; ++i)
5917       if (i == I->getParent()->end() || i->mayHaveSideEffects())
5918         return false;
5919 
5920     // Look through GEPs. A load from a GEP derived from NULL is still undefined
5921     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5922       if (GEP->getPointerOperand() == I)
5923         return passingValueIsAlwaysUndefined(V, GEP);
5924 
5925     // Look through bitcasts.
5926     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5927       return passingValueIsAlwaysUndefined(V, BC);
5928 
5929     // Load from null is undefined.
5930     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
5931       if (!LI->isVolatile())
5932         return LI->getPointerAddressSpace() == 0;
5933 
5934     // Store to null is undefined.
5935     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
5936       if (!SI->isVolatile())
5937         return SI->getPointerAddressSpace() == 0 &&
5938                SI->getPointerOperand() == I;
5939 
5940     // A call to null is undefined.
5941     if (auto CS = CallSite(Use))
5942       return CS.getCalledValue() == I;
5943   }
5944   return false;
5945 }
5946 
5947 /// If BB has an incoming value that will always trigger undefined behavior
5948 /// (eg. null pointer dereference), remove the branch leading here.
5949 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5950   for (BasicBlock::iterator i = BB->begin();
5951        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5952     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5953       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5954         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5955         IRBuilder<> Builder(T);
5956         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5957           BB->removePredecessor(PHI->getIncomingBlock(i));
5958           // Turn uncoditional branches into unreachables and remove the dead
5959           // destination from conditional branches.
5960           if (BI->isUnconditional())
5961             Builder.CreateUnreachable();
5962           else
5963             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5964                                                        : BI->getSuccessor(0));
5965           BI->eraseFromParent();
5966           return true;
5967         }
5968         // TODO: SwitchInst.
5969       }
5970 
5971   return false;
5972 }
5973 
5974 bool SimplifyCFGOpt::run(BasicBlock *BB) {
5975   bool Changed = false;
5976 
5977   assert(BB && BB->getParent() && "Block not embedded in function!");
5978   assert(BB->getTerminator() && "Degenerate basic block encountered!");
5979 
5980   // Remove basic blocks that have no predecessors (except the entry block)...
5981   // or that just have themself as a predecessor.  These are unreachable.
5982   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
5983       BB->getSinglePredecessor() == BB) {
5984     DEBUG(dbgs() << "Removing BB: \n" << *BB);
5985     DeleteDeadBlock(BB);
5986     return true;
5987   }
5988 
5989   // Check to see if we can constant propagate this terminator instruction
5990   // away...
5991   Changed |= ConstantFoldTerminator(BB, true);
5992 
5993   // Check for and eliminate duplicate PHI nodes in this block.
5994   Changed |= EliminateDuplicatePHINodes(BB);
5995 
5996   // Check for and remove branches that will always cause undefined behavior.
5997   Changed |= removeUndefIntroducingPredecessor(BB);
5998 
5999   // Merge basic blocks into their predecessor if there is only one distinct
6000   // pred, and if there is only one distinct successor of the predecessor, and
6001   // if there are no PHI nodes.
6002   if (MergeBlockIntoPredecessor(BB))
6003     return true;
6004 
6005   IRBuilder<> Builder(BB);
6006 
6007   // If there is a trivial two-entry PHI node in this basic block, and we can
6008   // eliminate it, do so now.
6009   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
6010     if (PN->getNumIncomingValues() == 2)
6011       Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
6012 
6013   Builder.SetInsertPoint(BB->getTerminator());
6014   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
6015     if (BI->isUnconditional()) {
6016       if (SimplifyUncondBranch(BI, Builder))
6017         return true;
6018     } else {
6019       if (SimplifyCondBranch(BI, Builder))
6020         return true;
6021     }
6022   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
6023     if (SimplifyReturn(RI, Builder))
6024       return true;
6025   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
6026     if (SimplifyResume(RI, Builder))
6027       return true;
6028   } else if (CleanupReturnInst *RI =
6029                  dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
6030     if (SimplifyCleanupReturn(RI))
6031       return true;
6032   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
6033     if (SimplifySwitch(SI, Builder))
6034       return true;
6035   } else if (UnreachableInst *UI =
6036                  dyn_cast<UnreachableInst>(BB->getTerminator())) {
6037     if (SimplifyUnreachable(UI))
6038       return true;
6039   } else if (IndirectBrInst *IBI =
6040                  dyn_cast<IndirectBrInst>(BB->getTerminator())) {
6041     if (SimplifyIndirectBr(IBI))
6042       return true;
6043   }
6044 
6045   return Changed;
6046 }
6047 
6048 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6049                        const SimplifyCFGOptions &Options,
6050                        SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
6051   return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
6052                         Options)
6053       .run(BB);
6054 }
6055