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