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