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