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