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