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