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