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