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