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 /// If this basic block is simple enough, and if a predecessor branches to us
2714 /// and one of our successors, fold the block into the predecessor and use
2715 /// logical operations to pick the right destination.
2716 bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU,
2717                                   const TargetTransformInfo *TTI,
2718                                   unsigned BonusInstThreshold) {
2719   BasicBlock *BB = BI->getParent();
2720 
2721   const unsigned PredCount = pred_size(BB);
2722 
2723   bool Changed = false;
2724 
2725   auto _ = make_scope_exit([&]() {
2726     if (Changed)
2727       ++NumFoldBranchToCommonDest;
2728   });
2729 
2730   TargetTransformInfo::TargetCostKind CostKind =
2731     BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
2732                                   : TargetTransformInfo::TCK_SizeAndLatency;
2733 
2734   Instruction *Cond = nullptr;
2735   if (BI->isConditional())
2736     Cond = dyn_cast<Instruction>(BI->getCondition());
2737   else {
2738     // For unconditional branch, check for a simple CFG pattern, where
2739     // BB has a single predecessor and BB's successor is also its predecessor's
2740     // successor. If such pattern exists, check for CSE between BB and its
2741     // predecessor.
2742     if (BasicBlock *PB = BB->getSinglePredecessor())
2743       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2744         if (PBI->isConditional() &&
2745             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2746              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2747           for (auto I = BB->instructionsWithoutDebug().begin(),
2748                     E = BB->instructionsWithoutDebug().end();
2749                I != E;) {
2750             Instruction *Curr = &*I++;
2751             if (isa<CmpInst>(Curr)) {
2752               Cond = Curr;
2753               break;
2754             }
2755             // Quit if we can't remove this instruction.
2756             if (!tryCSEWithPredecessor(Curr, PB))
2757               return Changed;
2758             Changed = true;
2759           }
2760         }
2761 
2762     if (!Cond)
2763       return Changed;
2764   }
2765 
2766   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2767       Cond->getParent() != BB || !Cond->hasOneUse())
2768     return Changed;
2769 
2770   // Only allow this transformation if computing the condition doesn't involve
2771   // too many instructions and these involved instructions can be executed
2772   // unconditionally. We denote all involved instructions except the condition
2773   // as "bonus instructions", and only allow this transformation when the
2774   // number of the bonus instructions we'll need to create when cloning into
2775   // each predecessor does not exceed a certain threshold.
2776   unsigned NumBonusInsts = 0;
2777   for (Instruction &I : *BB) {
2778     // Don't check the branch condition comparison itself.
2779     if (&I == Cond)
2780       continue;
2781     // Ignore dbg intrinsics, and the terminator.
2782     if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
2783       continue;
2784     // I must be safe to execute unconditionally.
2785     if (!isSafeToSpeculativelyExecute(&I))
2786       return Changed;
2787 
2788     // Account for the cost of duplicating this instruction into each
2789     // predecessor.
2790     NumBonusInsts += PredCount;
2791     // Early exits once we reach the limit.
2792     if (NumBonusInsts > BonusInstThreshold)
2793       return Changed;
2794   }
2795 
2796   // Also, for now, all liveout uses of bonus instructions must be in PHI nodes
2797   // in successor blocks as incoming values from the bonus instructions's block,
2798   // otherwise we'll fail to update them.
2799   // FIXME: We could lift this restriction, but we need to form PHI nodes and
2800   // rewrite offending uses, but we can't do that without having a domtree.
2801   if (any_of(*BB, [BB](Instruction &I) {
2802         return any_of(I.uses(), [BB](Use &U) {
2803           auto *User = cast<Instruction>(U.getUser());
2804           if (User->getParent() == BB)
2805             return false; // Not an external use.
2806           auto *PN = dyn_cast<PHINode>(User);
2807           return !PN || PN->getIncomingBlock(U) != BB;
2808         });
2809       }))
2810     return Changed;
2811 
2812   // Cond is known to be a compare or binary operator.  Check to make sure that
2813   // neither operand is a potentially-trapping constant expression.
2814   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2815     if (CE->canTrap())
2816       return Changed;
2817   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2818     if (CE->canTrap())
2819       return Changed;
2820 
2821   // Finally, don't infinitely unroll conditional loops.
2822   BasicBlock *TrueDest = BI->getSuccessor(0);
2823   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2824   if (TrueDest == BB || FalseDest == BB)
2825     return Changed;
2826 
2827   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2828     BasicBlock *PredBlock = *PI;
2829     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2830 
2831     // Check that we have two conditional branches.  If there is a PHI node in
2832     // the common successor, verify that the same value flows in from both
2833     // blocks.
2834     SmallVector<PHINode *, 4> PHIs;
2835     if (!PBI || PBI->isUnconditional() ||
2836         (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
2837         (!BI->isConditional() &&
2838          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2839       continue;
2840 
2841     // Determine if the two branches share a common destination.
2842     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2843     bool InvertPredCond = false;
2844 
2845     if (BI->isConditional()) {
2846       if (PBI->getSuccessor(0) == TrueDest) {
2847         Opc = Instruction::Or;
2848       } else if (PBI->getSuccessor(1) == FalseDest) {
2849         Opc = Instruction::And;
2850       } else if (PBI->getSuccessor(0) == FalseDest) {
2851         Opc = Instruction::And;
2852         InvertPredCond = true;
2853       } else if (PBI->getSuccessor(1) == TrueDest) {
2854         Opc = Instruction::Or;
2855         InvertPredCond = true;
2856       } else {
2857         continue;
2858       }
2859     } else {
2860       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2861         continue;
2862     }
2863 
2864     // Check the cost of inserting the necessary logic before performing the
2865     // transformation.
2866     if (TTI && Opc != Instruction::BinaryOpsEnd) {
2867       Type *Ty = BI->getCondition()->getType();
2868       unsigned Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
2869       if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
2870           !isa<CmpInst>(PBI->getCondition())))
2871         Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
2872 
2873       if (Cost > BranchFoldThreshold)
2874         continue;
2875     }
2876 
2877     LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2878     Changed = true;
2879 
2880     IRBuilder<> Builder(PBI);
2881 
2882     // If we need to invert the condition in the pred block to match, do so now.
2883     if (InvertPredCond) {
2884       Value *NewCond = PBI->getCondition();
2885 
2886       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2887         CmpInst *CI = cast<CmpInst>(NewCond);
2888         CI->setPredicate(CI->getInversePredicate());
2889       } else {
2890         NewCond =
2891             Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
2892       }
2893 
2894       PBI->setCondition(NewCond);
2895       PBI->swapSuccessors();
2896     }
2897 
2898     BasicBlock *UniqueSucc =
2899         BI->isConditional()
2900             ? (PBI->getSuccessor(0) == BB ? TrueDest : FalseDest)
2901             : TrueDest;
2902 
2903     // Before cloning instructions, notify the successor basic block that it
2904     // is about to have a new predecessor. This will update PHI nodes,
2905     // which will allow us to update live-out uses of bonus instructions.
2906     if (BI->isConditional())
2907       AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
2908 
2909     // If we have bonus instructions, clone them into the predecessor block.
2910     // Note that there may be multiple predecessor blocks, so we cannot move
2911     // bonus instructions to a predecessor block.
2912     ValueToValueMapTy VMap; // maps original values to cloned values
2913     Instruction *CondInPred;
2914     for (Instruction &BonusInst : *BB) {
2915       if (isa<DbgInfoIntrinsic>(BonusInst) || isa<BranchInst>(BonusInst))
2916         continue;
2917 
2918       Instruction *NewBonusInst = BonusInst.clone();
2919 
2920       if (&BonusInst == Cond)
2921         CondInPred = NewBonusInst;
2922 
2923       // When we fold the bonus instructions we want to make sure we
2924       // reset their debug locations in order to avoid stepping on dead
2925       // code caused by folding dead branches.
2926       NewBonusInst->setDebugLoc(DebugLoc());
2927 
2928       RemapInstruction(NewBonusInst, VMap,
2929                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2930       VMap[&BonusInst] = NewBonusInst;
2931 
2932       // If we moved a load, we cannot any longer claim any knowledge about
2933       // its potential value. The previous information might have been valid
2934       // only given the branch precondition.
2935       // For an analogous reason, we must also drop all the metadata whose
2936       // semantics we don't understand.
2937       NewBonusInst->dropUnknownNonDebugMetadata();
2938 
2939       PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2940       NewBonusInst->takeName(&BonusInst);
2941       BonusInst.setName(BonusInst.getName() + ".old");
2942       BonusInst.replaceUsesWithIf(
2943           NewBonusInst, [BB, BI, UniqueSucc, PredBlock](Use &U) {
2944             auto *User = cast<Instruction>(U.getUser());
2945             // Ignore non-external uses of bonus instructions.
2946             if (User->getParent() == BB) {
2947               assert(!isa<PHINode>(User) &&
2948                      "Non-external users are never PHI instructions.");
2949               return false;
2950             }
2951             (void)BI;
2952             assert(isa<PHINode>(User) && "All external users must be PHI's.");
2953             auto *PN = cast<PHINode>(User);
2954             assert(is_contained(successors(BB), User->getParent()) &&
2955                    "All external users must be in successors of BB.");
2956             assert((PN->getIncomingBlock(U) == BB ||
2957                     PN->getIncomingBlock(U) == PredBlock) &&
2958                    "The incoming block for that incoming value external use "
2959                    "must be either the original block with bonus instructions, "
2960                    "or the new predecessor block.");
2961             // UniqueSucc is the block for which we change it's predecessors,
2962             // so it is the only block in which we'll need to update PHI nodes.
2963             if (User->getParent() != UniqueSucc)
2964               return false;
2965             // Update the incoming value for the new predecessor.
2966             return PN->getIncomingBlock(U) ==
2967                    (BI->isConditional() ? PredBlock : BB);
2968           });
2969     }
2970 
2971     // Now that the Cond was cloned into the predecessor basic block,
2972     // or/and the two conditions together.
2973     if (BI->isConditional()) {
2974       Instruction *NewCond = cast<Instruction>(
2975           Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
2976       PBI->setCondition(NewCond);
2977 
2978       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2979       bool HasWeights =
2980           extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2981                                  SuccTrueWeight, SuccFalseWeight);
2982       SmallVector<uint64_t, 8> NewWeights;
2983 
2984       if (PBI->getSuccessor(0) == BB) {
2985         if (HasWeights) {
2986           // PBI: br i1 %x, BB, FalseDest
2987           // BI:  br i1 %y, UniqueSucc, FalseDest
2988           // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2989           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2990           // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2991           //               TrueWeight for PBI * FalseWeight for BI.
2992           // We assume that total weights of a BranchInst can fit into 32 bits.
2993           // Therefore, we will not have overflow using 64-bit arithmetic.
2994           NewWeights.push_back(PredFalseWeight *
2995                                    (SuccFalseWeight + SuccTrueWeight) +
2996                                PredTrueWeight * SuccFalseWeight);
2997         }
2998         PBI->setSuccessor(0, UniqueSucc);
2999       }
3000       if (PBI->getSuccessor(1) == BB) {
3001         if (HasWeights) {
3002           // PBI: br i1 %x, TrueDest, BB
3003           // BI:  br i1 %y, TrueDest, UniqueSucc
3004           // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3005           //              FalseWeight for PBI * TrueWeight for BI.
3006           NewWeights.push_back(PredTrueWeight *
3007                                    (SuccFalseWeight + SuccTrueWeight) +
3008                                PredFalseWeight * SuccTrueWeight);
3009           // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3010           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3011         }
3012         PBI->setSuccessor(1, UniqueSucc);
3013       }
3014       if (NewWeights.size() == 2) {
3015         // Halve the weights if any of them cannot fit in an uint32_t
3016         FitWeights(NewWeights);
3017 
3018         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
3019                                            NewWeights.end());
3020         setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3021       } else
3022         PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3023     } else {
3024       // Update PHI nodes in the common successors.
3025       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
3026         ConstantInt *PBI_C = cast<ConstantInt>(
3027             PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
3028         assert(PBI_C->getType()->isIntegerTy(1));
3029         Instruction *MergedCond = nullptr;
3030         if (PBI->getSuccessor(0) == UniqueSucc) {
3031           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
3032           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
3033           //       is false: !PBI_Cond and BI_Value
3034           Instruction *NotCond = cast<Instruction>(
3035               Builder.CreateNot(PBI->getCondition(), "not.cond"));
3036           MergedCond = cast<Instruction>(
3037                Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
3038                                    "and.cond"));
3039           if (PBI_C->isOne())
3040             MergedCond = cast<Instruction>(Builder.CreateBinOp(
3041                 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
3042         } else {
3043           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
3044           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
3045           //       is false: PBI_Cond and BI_Value
3046           MergedCond = cast<Instruction>(Builder.CreateBinOp(
3047               Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
3048           if (PBI_C->isOne()) {
3049             Instruction *NotCond = cast<Instruction>(
3050                 Builder.CreateNot(PBI->getCondition(), "not.cond"));
3051             MergedCond = cast<Instruction>(Builder.CreateBinOp(
3052                 Instruction::Or, NotCond, MergedCond, "or.cond"));
3053           }
3054         }
3055         // Update PHI Node.
3056 	PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond);
3057       }
3058 
3059       // PBI is changed to branch to UniqueSucc below. Remove itself from
3060       // potential phis from all other successors.
3061       if (MSSAU)
3062         MSSAU->changeCondBranchToUnconditionalTo(PBI, UniqueSucc);
3063 
3064       // Change PBI from Conditional to Unconditional.
3065       BranchInst *New_PBI = BranchInst::Create(UniqueSucc, PBI);
3066       EraseTerminatorAndDCECond(PBI, MSSAU);
3067       PBI = New_PBI;
3068     }
3069 
3070     // If BI was a loop latch, it may have had associated loop metadata.
3071     // We need to copy it to the new latch, that is, PBI.
3072     if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3073       PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3074 
3075     // TODO: If BB is reachable from all paths through PredBlock, then we
3076     // could replace PBI's branch probabilities with BI's.
3077 
3078     // Copy any debug value intrinsics into the end of PredBlock.
3079     for (Instruction &I : *BB) {
3080       if (isa<DbgInfoIntrinsic>(I)) {
3081         Instruction *NewI = I.clone();
3082         RemapInstruction(NewI, VMap,
3083                          RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
3084         NewI->insertBefore(PBI);
3085       }
3086     }
3087 
3088     return Changed;
3089   }
3090   return Changed;
3091 }
3092 
3093 // If there is only one store in BB1 and BB2, return it, otherwise return
3094 // nullptr.
3095 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
3096   StoreInst *S = nullptr;
3097   for (auto *BB : {BB1, BB2}) {
3098     if (!BB)
3099       continue;
3100     for (auto &I : *BB)
3101       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3102         if (S)
3103           // Multiple stores seen.
3104           return nullptr;
3105         else
3106           S = SI;
3107       }
3108   }
3109   return S;
3110 }
3111 
3112 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
3113                                               Value *AlternativeV = nullptr) {
3114   // PHI is going to be a PHI node that allows the value V that is defined in
3115   // BB to be referenced in BB's only successor.
3116   //
3117   // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3118   // doesn't matter to us what the other operand is (it'll never get used). We
3119   // could just create a new PHI with an undef incoming value, but that could
3120   // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3121   // other PHI. So here we directly look for some PHI in BB's successor with V
3122   // as an incoming operand. If we find one, we use it, else we create a new
3123   // one.
3124   //
3125   // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3126   // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3127   // where OtherBB is the single other predecessor of BB's only successor.
3128   PHINode *PHI = nullptr;
3129   BasicBlock *Succ = BB->getSingleSuccessor();
3130 
3131   for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3132     if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3133       PHI = cast<PHINode>(I);
3134       if (!AlternativeV)
3135         break;
3136 
3137       assert(Succ->hasNPredecessors(2));
3138       auto PredI = pred_begin(Succ);
3139       BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3140       if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3141         break;
3142       PHI = nullptr;
3143     }
3144   if (PHI)
3145     return PHI;
3146 
3147   // If V is not an instruction defined in BB, just return it.
3148   if (!AlternativeV &&
3149       (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3150     return V;
3151 
3152   PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3153   PHI->addIncoming(V, BB);
3154   for (BasicBlock *PredBB : predecessors(Succ))
3155     if (PredBB != BB)
3156       PHI->addIncoming(
3157           AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3158   return PHI;
3159 }
3160 
3161 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
3162                                            BasicBlock *QTB, BasicBlock *QFB,
3163                                            BasicBlock *PostBB, Value *Address,
3164                                            bool InvertPCond, bool InvertQCond,
3165                                            const DataLayout &DL,
3166                                            const TargetTransformInfo &TTI) {
3167   // For every pointer, there must be exactly two stores, one coming from
3168   // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3169   // store (to any address) in PTB,PFB or QTB,QFB.
3170   // FIXME: We could relax this restriction with a bit more work and performance
3171   // testing.
3172   StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3173   StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3174   if (!PStore || !QStore)
3175     return false;
3176 
3177   // Now check the stores are compatible.
3178   if (!QStore->isUnordered() || !PStore->isUnordered())
3179     return false;
3180 
3181   // Check that sinking the store won't cause program behavior changes. Sinking
3182   // the store out of the Q blocks won't change any behavior as we're sinking
3183   // from a block to its unconditional successor. But we're moving a store from
3184   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3185   // So we need to check that there are no aliasing loads or stores in
3186   // QBI, QTB and QFB. We also need to check there are no conflicting memory
3187   // operations between PStore and the end of its parent block.
3188   //
3189   // The ideal way to do this is to query AliasAnalysis, but we don't
3190   // preserve AA currently so that is dangerous. Be super safe and just
3191   // check there are no other memory operations at all.
3192   for (auto &I : *QFB->getSinglePredecessor())
3193     if (I.mayReadOrWriteMemory())
3194       return false;
3195   for (auto &I : *QFB)
3196     if (&I != QStore && I.mayReadOrWriteMemory())
3197       return false;
3198   if (QTB)
3199     for (auto &I : *QTB)
3200       if (&I != QStore && I.mayReadOrWriteMemory())
3201         return false;
3202   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3203        I != E; ++I)
3204     if (&*I != PStore && I->mayReadOrWriteMemory())
3205       return false;
3206 
3207   // If we're not in aggressive mode, we only optimize if we have some
3208   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3209   auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3210     if (!BB)
3211       return true;
3212     // Heuristic: if the block can be if-converted/phi-folded and the
3213     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3214     // thread this store.
3215     int BudgetRemaining =
3216         PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3217     for (auto &I : BB->instructionsWithoutDebug()) {
3218       // Consider terminator instruction to be free.
3219       if (I.isTerminator())
3220         continue;
3221       // If this is one the stores that we want to speculate out of this BB,
3222       // then don't count it's cost, consider it to be free.
3223       if (auto *S = dyn_cast<StoreInst>(&I))
3224         if (llvm::find(FreeStores, S))
3225           continue;
3226       // Else, we have a white-list of instructions that we are ak speculating.
3227       if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3228         return false; // Not in white-list - not worthwhile folding.
3229       // And finally, if this is a non-free instruction that we are okay
3230       // speculating, ensure that we consider the speculation budget.
3231       BudgetRemaining -= TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3232       if (BudgetRemaining < 0)
3233         return false; // Eagerly refuse to fold as soon as we're out of budget.
3234     }
3235     assert(BudgetRemaining >= 0 &&
3236            "When we run out of budget we will eagerly return from within the "
3237            "per-instruction loop.");
3238     return true;
3239   };
3240 
3241   const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3242   if (!MergeCondStoresAggressively &&
3243       (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3244        !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3245     return false;
3246 
3247   // If PostBB has more than two predecessors, we need to split it so we can
3248   // sink the store.
3249   if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3250     // We know that QFB's only successor is PostBB. And QFB has a single
3251     // predecessor. If QTB exists, then its only successor is also PostBB.
3252     // If QTB does not exist, then QFB's only predecessor has a conditional
3253     // branch to QFB and PostBB.
3254     BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3255     BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
3256                                                "condstore.split");
3257     if (!NewBB)
3258       return false;
3259     PostBB = NewBB;
3260   }
3261 
3262   // OK, we're going to sink the stores to PostBB. The store has to be
3263   // conditional though, so first create the predicate.
3264   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3265                      ->getCondition();
3266   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3267                      ->getCondition();
3268 
3269   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3270                                                 PStore->getParent());
3271   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3272                                                 QStore->getParent(), PPHI);
3273 
3274   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3275 
3276   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3277   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3278 
3279   if (InvertPCond)
3280     PPred = QB.CreateNot(PPred);
3281   if (InvertQCond)
3282     QPred = QB.CreateNot(QPred);
3283   Value *CombinedPred = QB.CreateOr(PPred, QPred);
3284 
3285   auto *T =
3286       SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
3287   QB.SetInsertPoint(T);
3288   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3289   AAMDNodes AAMD;
3290   PStore->getAAMetadata(AAMD, /*Merge=*/false);
3291   PStore->getAAMetadata(AAMD, /*Merge=*/true);
3292   SI->setAAMetadata(AAMD);
3293   // Choose the minimum alignment. If we could prove both stores execute, we
3294   // could use biggest one.  In this case, though, we only know that one of the
3295   // stores executes.  And we don't know it's safe to take the alignment from a
3296   // store that doesn't execute.
3297   SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3298 
3299   QStore->eraseFromParent();
3300   PStore->eraseFromParent();
3301 
3302   return true;
3303 }
3304 
3305 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3306                                    const DataLayout &DL,
3307                                    const TargetTransformInfo &TTI) {
3308   // The intention here is to find diamonds or triangles (see below) where each
3309   // conditional block contains a store to the same address. Both of these
3310   // stores are conditional, so they can't be unconditionally sunk. But it may
3311   // be profitable to speculatively sink the stores into one merged store at the
3312   // end, and predicate the merged store on the union of the two conditions of
3313   // PBI and QBI.
3314   //
3315   // This can reduce the number of stores executed if both of the conditions are
3316   // true, and can allow the blocks to become small enough to be if-converted.
3317   // This optimization will also chain, so that ladders of test-and-set
3318   // sequences can be if-converted away.
3319   //
3320   // We only deal with simple diamonds or triangles:
3321   //
3322   //     PBI       or      PBI        or a combination of the two
3323   //    /   \               | \
3324   //   PTB  PFB             |  PFB
3325   //    \   /               | /
3326   //     QBI                QBI
3327   //    /  \                | \
3328   //   QTB  QFB             |  QFB
3329   //    \  /                | /
3330   //    PostBB            PostBB
3331   //
3332   // We model triangles as a type of diamond with a nullptr "true" block.
3333   // Triangles are canonicalized so that the fallthrough edge is represented by
3334   // a true condition, as in the diagram above.
3335   BasicBlock *PTB = PBI->getSuccessor(0);
3336   BasicBlock *PFB = PBI->getSuccessor(1);
3337   BasicBlock *QTB = QBI->getSuccessor(0);
3338   BasicBlock *QFB = QBI->getSuccessor(1);
3339   BasicBlock *PostBB = QFB->getSingleSuccessor();
3340 
3341   // Make sure we have a good guess for PostBB. If QTB's only successor is
3342   // QFB, then QFB is a better PostBB.
3343   if (QTB->getSingleSuccessor() == QFB)
3344     PostBB = QFB;
3345 
3346   // If we couldn't find a good PostBB, stop.
3347   if (!PostBB)
3348     return false;
3349 
3350   bool InvertPCond = false, InvertQCond = false;
3351   // Canonicalize fallthroughs to the true branches.
3352   if (PFB == QBI->getParent()) {
3353     std::swap(PFB, PTB);
3354     InvertPCond = true;
3355   }
3356   if (QFB == PostBB) {
3357     std::swap(QFB, QTB);
3358     InvertQCond = true;
3359   }
3360 
3361   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3362   // and QFB may not. Model fallthroughs as a nullptr block.
3363   if (PTB == QBI->getParent())
3364     PTB = nullptr;
3365   if (QTB == PostBB)
3366     QTB = nullptr;
3367 
3368   // Legality bailouts. We must have at least the non-fallthrough blocks and
3369   // the post-dominating block, and the non-fallthroughs must only have one
3370   // predecessor.
3371   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3372     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3373   };
3374   if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3375       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3376     return false;
3377   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3378       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3379     return false;
3380   if (!QBI->getParent()->hasNUses(2))
3381     return false;
3382 
3383   // OK, this is a sequence of two diamonds or triangles.
3384   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3385   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3386   for (auto *BB : {PTB, PFB}) {
3387     if (!BB)
3388       continue;
3389     for (auto &I : *BB)
3390       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3391         PStoreAddresses.insert(SI->getPointerOperand());
3392   }
3393   for (auto *BB : {QTB, QFB}) {
3394     if (!BB)
3395       continue;
3396     for (auto &I : *BB)
3397       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3398         QStoreAddresses.insert(SI->getPointerOperand());
3399   }
3400 
3401   set_intersect(PStoreAddresses, QStoreAddresses);
3402   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3403   // clear what it contains.
3404   auto &CommonAddresses = PStoreAddresses;
3405 
3406   bool Changed = false;
3407   for (auto *Address : CommonAddresses)
3408     Changed |= mergeConditionalStoreToAddress(
3409         PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL, TTI);
3410   return Changed;
3411 }
3412 
3413 
3414 /// If the previous block ended with a widenable branch, determine if reusing
3415 /// the target block is profitable and legal.  This will have the effect of
3416 /// "widening" PBI, but doesn't require us to reason about hosting safety.
3417 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
3418   // TODO: This can be generalized in two important ways:
3419   // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3420   //    values from the PBI edge.
3421   // 2) We can sink side effecting instructions into BI's fallthrough
3422   //    successor provided they doesn't contribute to computation of
3423   //    BI's condition.
3424   Value *CondWB, *WC;
3425   BasicBlock *IfTrueBB, *IfFalseBB;
3426   if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3427       IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3428     return false;
3429   if (!IfFalseBB->phis().empty())
3430     return false; // TODO
3431   // Use lambda to lazily compute expensive condition after cheap ones.
3432   auto NoSideEffects = [](BasicBlock &BB) {
3433     return !llvm::any_of(BB, [](const Instruction &I) {
3434         return I.mayWriteToMemory() || I.mayHaveSideEffects();
3435       });
3436   };
3437   if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
3438       BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
3439       NoSideEffects(*BI->getParent())) {
3440     BI->getSuccessor(1)->removePredecessor(BI->getParent());
3441     BI->setSuccessor(1, IfFalseBB);
3442     return true;
3443   }
3444   if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
3445       BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
3446       NoSideEffects(*BI->getParent())) {
3447     BI->getSuccessor(0)->removePredecessor(BI->getParent());
3448     BI->setSuccessor(0, IfFalseBB);
3449     return true;
3450   }
3451   return false;
3452 }
3453 
3454 /// If we have a conditional branch as a predecessor of another block,
3455 /// this function tries to simplify it.  We know
3456 /// that PBI and BI are both conditional branches, and BI is in one of the
3457 /// successor blocks of PBI - PBI branches to BI.
3458 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3459                                            const DataLayout &DL,
3460                                            const TargetTransformInfo &TTI) {
3461   assert(PBI->isConditional() && BI->isConditional());
3462   BasicBlock *BB = BI->getParent();
3463 
3464   // If this block ends with a branch instruction, and if there is a
3465   // predecessor that ends on a branch of the same condition, make
3466   // this conditional branch redundant.
3467   if (PBI->getCondition() == BI->getCondition() &&
3468       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3469     // Okay, the outcome of this conditional branch is statically
3470     // knowable.  If this block had a single pred, handle specially.
3471     if (BB->getSinglePredecessor()) {
3472       // Turn this into a branch on constant.
3473       bool CondIsTrue = PBI->getSuccessor(0) == BB;
3474       BI->setCondition(
3475           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3476       return true; // Nuke the branch on constant.
3477     }
3478 
3479     // Otherwise, if there are multiple predecessors, insert a PHI that merges
3480     // in the constant and simplify the block result.  Subsequent passes of
3481     // simplifycfg will thread the block.
3482     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3483       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3484       PHINode *NewPN = PHINode::Create(
3485           Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3486           BI->getCondition()->getName() + ".pr", &BB->front());
3487       // Okay, we're going to insert the PHI node.  Since PBI is not the only
3488       // predecessor, compute the PHI'd conditional value for all of the preds.
3489       // Any predecessor where the condition is not computable we keep symbolic.
3490       for (pred_iterator PI = PB; PI != PE; ++PI) {
3491         BasicBlock *P = *PI;
3492         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3493             PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3494             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3495           bool CondIsTrue = PBI->getSuccessor(0) == BB;
3496           NewPN->addIncoming(
3497               ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3498               P);
3499         } else {
3500           NewPN->addIncoming(BI->getCondition(), P);
3501         }
3502       }
3503 
3504       BI->setCondition(NewPN);
3505       return true;
3506     }
3507   }
3508 
3509   // If the previous block ended with a widenable branch, determine if reusing
3510   // the target block is profitable and legal.  This will have the effect of
3511   // "widening" PBI, but doesn't require us to reason about hosting safety.
3512   if (tryWidenCondBranchToCondBranch(PBI, BI))
3513     return true;
3514 
3515   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3516     if (CE->canTrap())
3517       return false;
3518 
3519   // If both branches are conditional and both contain stores to the same
3520   // address, remove the stores from the conditionals and create a conditional
3521   // merged store at the end.
3522   if (MergeCondStores && mergeConditionalStores(PBI, BI, DL, TTI))
3523     return true;
3524 
3525   // If this is a conditional branch in an empty block, and if any
3526   // predecessors are a conditional branch to one of our destinations,
3527   // fold the conditions into logical ops and one cond br.
3528 
3529   // Ignore dbg intrinsics.
3530   if (&*BB->instructionsWithoutDebug().begin() != BI)
3531     return false;
3532 
3533   int PBIOp, BIOp;
3534   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3535     PBIOp = 0;
3536     BIOp = 0;
3537   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3538     PBIOp = 0;
3539     BIOp = 1;
3540   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3541     PBIOp = 1;
3542     BIOp = 0;
3543   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3544     PBIOp = 1;
3545     BIOp = 1;
3546   } else {
3547     return false;
3548   }
3549 
3550   // Check to make sure that the other destination of this branch
3551   // isn't BB itself.  If so, this is an infinite loop that will
3552   // keep getting unwound.
3553   if (PBI->getSuccessor(PBIOp) == BB)
3554     return false;
3555 
3556   // Do not perform this transformation if it would require
3557   // insertion of a large number of select instructions. For targets
3558   // without predication/cmovs, this is a big pessimization.
3559 
3560   // Also do not perform this transformation if any phi node in the common
3561   // destination block can trap when reached by BB or PBB (PR17073). In that
3562   // case, it would be unsafe to hoist the operation into a select instruction.
3563 
3564   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3565   unsigned NumPhis = 0;
3566   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3567        ++II, ++NumPhis) {
3568     if (NumPhis > 2) // Disable this xform.
3569       return false;
3570 
3571     PHINode *PN = cast<PHINode>(II);
3572     Value *BIV = PN->getIncomingValueForBlock(BB);
3573     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3574       if (CE->canTrap())
3575         return false;
3576 
3577     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3578     Value *PBIV = PN->getIncomingValue(PBBIdx);
3579     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3580       if (CE->canTrap())
3581         return false;
3582   }
3583 
3584   // Finally, if everything is ok, fold the branches to logical ops.
3585   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3586 
3587   LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
3588                     << "AND: " << *BI->getParent());
3589 
3590   // If OtherDest *is* BB, then BB is a basic block with a single conditional
3591   // branch in it, where one edge (OtherDest) goes back to itself but the other
3592   // exits.  We don't *know* that the program avoids the infinite loop
3593   // (even though that seems likely).  If we do this xform naively, we'll end up
3594   // recursively unpeeling the loop.  Since we know that (after the xform is
3595   // done) that the block *is* infinite if reached, we just make it an obviously
3596   // infinite loop with no cond branch.
3597   if (OtherDest == BB) {
3598     // Insert it at the end of the function, because it's either code,
3599     // or it won't matter if it's hot. :)
3600     BasicBlock *InfLoopBlock =
3601         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3602     BranchInst::Create(InfLoopBlock, InfLoopBlock);
3603     OtherDest = InfLoopBlock;
3604   }
3605 
3606   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3607 
3608   // BI may have other predecessors.  Because of this, we leave
3609   // it alone, but modify PBI.
3610 
3611   // Make sure we get to CommonDest on True&True directions.
3612   Value *PBICond = PBI->getCondition();
3613   IRBuilder<NoFolder> Builder(PBI);
3614   if (PBIOp)
3615     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3616 
3617   Value *BICond = BI->getCondition();
3618   if (BIOp)
3619     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3620 
3621   // Merge the conditions.
3622   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
3623 
3624   // Modify PBI to branch on the new condition to the new dests.
3625   PBI->setCondition(Cond);
3626   PBI->setSuccessor(0, CommonDest);
3627   PBI->setSuccessor(1, OtherDest);
3628 
3629   // Update branch weight for PBI.
3630   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3631   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3632   bool HasWeights =
3633       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3634                              SuccTrueWeight, SuccFalseWeight);
3635   if (HasWeights) {
3636     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3637     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3638     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3639     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3640     // The weight to CommonDest should be PredCommon * SuccTotal +
3641     //                                    PredOther * SuccCommon.
3642     // The weight to OtherDest should be PredOther * SuccOther.
3643     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3644                                   PredOther * SuccCommon,
3645                               PredOther * SuccOther};
3646     // Halve the weights if any of them cannot fit in an uint32_t
3647     FitWeights(NewWeights);
3648 
3649     setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
3650   }
3651 
3652   // OtherDest may have phi nodes.  If so, add an entry from PBI's
3653   // block that are identical to the entries for BI's block.
3654   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3655 
3656   // We know that the CommonDest already had an edge from PBI to
3657   // it.  If it has PHIs though, the PHIs may have different
3658   // entries for BB and PBI's BB.  If so, insert a select to make
3659   // them agree.
3660   for (PHINode &PN : CommonDest->phis()) {
3661     Value *BIV = PN.getIncomingValueForBlock(BB);
3662     unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
3663     Value *PBIV = PN.getIncomingValue(PBBIdx);
3664     if (BIV != PBIV) {
3665       // Insert a select in PBI to pick the right value.
3666       SelectInst *NV = cast<SelectInst>(
3667           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3668       PN.setIncomingValue(PBBIdx, NV);
3669       // Although the select has the same condition as PBI, the original branch
3670       // weights for PBI do not apply to the new select because the select's
3671       // 'logical' edges are incoming edges of the phi that is eliminated, not
3672       // the outgoing edges of PBI.
3673       if (HasWeights) {
3674         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3675         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3676         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3677         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3678         // The weight to PredCommonDest should be PredCommon * SuccTotal.
3679         // The weight to PredOtherDest should be PredOther * SuccCommon.
3680         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3681                                   PredOther * SuccCommon};
3682 
3683         FitWeights(NewWeights);
3684 
3685         setBranchWeights(NV, NewWeights[0], NewWeights[1]);
3686       }
3687     }
3688   }
3689 
3690   LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3691   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3692 
3693   // This basic block is probably dead.  We know it has at least
3694   // one fewer predecessor.
3695   return true;
3696 }
3697 
3698 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3699 // true or to FalseBB if Cond is false.
3700 // Takes care of updating the successors and removing the old terminator.
3701 // Also makes sure not to introduce new successors by assuming that edges to
3702 // non-successor TrueBBs and FalseBBs aren't reachable.
3703 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
3704                                                 Value *Cond, BasicBlock *TrueBB,
3705                                                 BasicBlock *FalseBB,
3706                                                 uint32_t TrueWeight,
3707                                                 uint32_t FalseWeight) {
3708   // Remove any superfluous successor edges from the CFG.
3709   // First, figure out which successors to preserve.
3710   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3711   // successor.
3712   BasicBlock *KeepEdge1 = TrueBB;
3713   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3714 
3715   // Then remove the rest.
3716   for (BasicBlock *Succ : successors(OldTerm)) {
3717     // Make sure only to keep exactly one copy of each edge.
3718     if (Succ == KeepEdge1)
3719       KeepEdge1 = nullptr;
3720     else if (Succ == KeepEdge2)
3721       KeepEdge2 = nullptr;
3722     else
3723       Succ->removePredecessor(OldTerm->getParent(),
3724                               /*KeepOneInputPHIs=*/true);
3725   }
3726 
3727   IRBuilder<> Builder(OldTerm);
3728   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3729 
3730   // Insert an appropriate new terminator.
3731   if (!KeepEdge1 && !KeepEdge2) {
3732     if (TrueBB == FalseBB)
3733       // We were only looking for one successor, and it was present.
3734       // Create an unconditional branch to it.
3735       Builder.CreateBr(TrueBB);
3736     else {
3737       // We found both of the successors we were looking for.
3738       // Create a conditional branch sharing the condition of the select.
3739       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3740       if (TrueWeight != FalseWeight)
3741         setBranchWeights(NewBI, TrueWeight, FalseWeight);
3742     }
3743   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3744     // Neither of the selected blocks were successors, so this
3745     // terminator must be unreachable.
3746     new UnreachableInst(OldTerm->getContext(), OldTerm);
3747   } else {
3748     // One of the selected values was a successor, but the other wasn't.
3749     // Insert an unconditional branch to the one that was found;
3750     // the edge to the one that wasn't must be unreachable.
3751     if (!KeepEdge1)
3752       // Only TrueBB was found.
3753       Builder.CreateBr(TrueBB);
3754     else
3755       // Only FalseBB was found.
3756       Builder.CreateBr(FalseBB);
3757   }
3758 
3759   EraseTerminatorAndDCECond(OldTerm);
3760   return true;
3761 }
3762 
3763 // Replaces
3764 //   (switch (select cond, X, Y)) on constant X, Y
3765 // with a branch - conditional if X and Y lead to distinct BBs,
3766 // unconditional otherwise.
3767 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
3768                                             SelectInst *Select) {
3769   // Check for constant integer values in the select.
3770   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3771   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3772   if (!TrueVal || !FalseVal)
3773     return false;
3774 
3775   // Find the relevant condition and destinations.
3776   Value *Condition = Select->getCondition();
3777   BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3778   BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
3779 
3780   // Get weight for TrueBB and FalseBB.
3781   uint32_t TrueWeight = 0, FalseWeight = 0;
3782   SmallVector<uint64_t, 8> Weights;
3783   bool HasWeights = HasBranchWeights(SI);
3784   if (HasWeights) {
3785     GetBranchWeights(SI, Weights);
3786     if (Weights.size() == 1 + SI->getNumCases()) {
3787       TrueWeight =
3788           (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
3789       FalseWeight =
3790           (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
3791     }
3792   }
3793 
3794   // Perform the actual simplification.
3795   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3796                                     FalseWeight);
3797 }
3798 
3799 // Replaces
3800 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
3801 //                             blockaddress(@fn, BlockB)))
3802 // with
3803 //   (br cond, BlockA, BlockB).
3804 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
3805                                                 SelectInst *SI) {
3806   // Check that both operands of the select are block addresses.
3807   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3808   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3809   if (!TBA || !FBA)
3810     return false;
3811 
3812   // Extract the actual blocks.
3813   BasicBlock *TrueBB = TBA->getBasicBlock();
3814   BasicBlock *FalseBB = FBA->getBasicBlock();
3815 
3816   // Perform the actual simplification.
3817   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3818                                     0);
3819 }
3820 
3821 /// This is called when we find an icmp instruction
3822 /// (a seteq/setne with a constant) as the only instruction in a
3823 /// block that ends with an uncond branch.  We are looking for a very specific
3824 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
3825 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3826 /// default value goes to an uncond block with a seteq in it, we get something
3827 /// like:
3828 ///
3829 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
3830 /// DEFAULT:
3831 ///   %tmp = icmp eq i8 %A, 92
3832 ///   br label %end
3833 /// end:
3834 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3835 ///
3836 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3837 /// the PHI, merging the third icmp into the switch.
3838 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
3839     ICmpInst *ICI, IRBuilder<> &Builder) {
3840   BasicBlock *BB = ICI->getParent();
3841 
3842   // If the block has any PHIs in it or the icmp has multiple uses, it is too
3843   // complex.
3844   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3845     return false;
3846 
3847   Value *V = ICI->getOperand(0);
3848   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3849 
3850   // The pattern we're looking for is where our only predecessor is a switch on
3851   // 'V' and this block is the default case for the switch.  In this case we can
3852   // fold the compared value into the switch to simplify things.
3853   BasicBlock *Pred = BB->getSinglePredecessor();
3854   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3855     return false;
3856 
3857   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3858   if (SI->getCondition() != V)
3859     return false;
3860 
3861   // If BB is reachable on a non-default case, then we simply know the value of
3862   // V in this block.  Substitute it and constant fold the icmp instruction
3863   // away.
3864   if (SI->getDefaultDest() != BB) {
3865     ConstantInt *VVal = SI->findCaseDest(BB);
3866     assert(VVal && "Should have a unique destination value");
3867     ICI->setOperand(0, VVal);
3868 
3869     if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
3870       ICI->replaceAllUsesWith(V);
3871       ICI->eraseFromParent();
3872     }
3873     // BB is now empty, so it is likely to simplify away.
3874     return requestResimplify();
3875   }
3876 
3877   // Ok, the block is reachable from the default dest.  If the constant we're
3878   // comparing exists in one of the other edges, then we can constant fold ICI
3879   // and zap it.
3880   if (SI->findCaseValue(Cst) != SI->case_default()) {
3881     Value *V;
3882     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3883       V = ConstantInt::getFalse(BB->getContext());
3884     else
3885       V = ConstantInt::getTrue(BB->getContext());
3886 
3887     ICI->replaceAllUsesWith(V);
3888     ICI->eraseFromParent();
3889     // BB is now empty, so it is likely to simplify away.
3890     return requestResimplify();
3891   }
3892 
3893   // The use of the icmp has to be in the 'end' block, by the only PHI node in
3894   // the block.
3895   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3896   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3897   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3898       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3899     return false;
3900 
3901   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3902   // true in the PHI.
3903   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3904   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3905 
3906   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3907     std::swap(DefaultCst, NewCst);
3908 
3909   // Replace ICI (which is used by the PHI for the default value) with true or
3910   // false depending on if it is EQ or NE.
3911   ICI->replaceAllUsesWith(DefaultCst);
3912   ICI->eraseFromParent();
3913 
3914   // Okay, the switch goes to this block on a default value.  Add an edge from
3915   // the switch to the merge point on the compared value.
3916   BasicBlock *NewBB =
3917       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
3918   {
3919     SwitchInstProfUpdateWrapper SIW(*SI);
3920     auto W0 = SIW.getSuccessorWeight(0);
3921     SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
3922     if (W0) {
3923       NewW = ((uint64_t(*W0) + 1) >> 1);
3924       SIW.setSuccessorWeight(0, *NewW);
3925     }
3926     SIW.addCase(Cst, NewBB, NewW);
3927   }
3928 
3929   // NewBB branches to the phi block, add the uncond branch and the phi entry.
3930   Builder.SetInsertPoint(NewBB);
3931   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3932   Builder.CreateBr(SuccBlock);
3933   PHIUse->addIncoming(NewCst, NewBB);
3934   return true;
3935 }
3936 
3937 /// The specified branch is a conditional branch.
3938 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3939 /// fold it into a switch instruction if so.
3940 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
3941                                                IRBuilder<> &Builder,
3942                                                const DataLayout &DL) {
3943   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3944   if (!Cond)
3945     return false;
3946 
3947   // Change br (X == 0 | X == 1), T, F into a switch instruction.
3948   // If this is a bunch of seteq's or'd together, or if it's a bunch of
3949   // 'setne's and'ed together, collect them.
3950 
3951   // Try to gather values from a chain of and/or to be turned into a switch
3952   ConstantComparesGatherer ConstantCompare(Cond, DL);
3953   // Unpack the result
3954   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
3955   Value *CompVal = ConstantCompare.CompValue;
3956   unsigned UsedICmps = ConstantCompare.UsedICmps;
3957   Value *ExtraCase = ConstantCompare.Extra;
3958 
3959   // If we didn't have a multiply compared value, fail.
3960   if (!CompVal)
3961     return false;
3962 
3963   // Avoid turning single icmps into a switch.
3964   if (UsedICmps <= 1)
3965     return false;
3966 
3967   bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3968 
3969   // There might be duplicate constants in the list, which the switch
3970   // instruction can't handle, remove them now.
3971   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3972   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3973 
3974   // If Extra was used, we require at least two switch values to do the
3975   // transformation.  A switch with one value is just a conditional branch.
3976   if (ExtraCase && Values.size() < 2)
3977     return false;
3978 
3979   // TODO: Preserve branch weight metadata, similarly to how
3980   // FoldValueComparisonIntoPredecessors preserves it.
3981 
3982   // Figure out which block is which destination.
3983   BasicBlock *DefaultBB = BI->getSuccessor(1);
3984   BasicBlock *EdgeBB = BI->getSuccessor(0);
3985   if (!TrueWhenEqual)
3986     std::swap(DefaultBB, EdgeBB);
3987 
3988   BasicBlock *BB = BI->getParent();
3989 
3990   // MSAN does not like undefs as branch condition which can be introduced
3991   // with "explicit branch".
3992   if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
3993     return false;
3994 
3995   LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3996                     << " cases into SWITCH.  BB is:\n"
3997                     << *BB);
3998 
3999   // If there are any extra values that couldn't be folded into the switch
4000   // then we evaluate them with an explicit branch first. Split the block
4001   // right before the condbr to handle it.
4002   if (ExtraCase) {
4003     BasicBlock *NewBB =
4004         BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
4005     // Remove the uncond branch added to the old block.
4006     Instruction *OldTI = BB->getTerminator();
4007     Builder.SetInsertPoint(OldTI);
4008 
4009     if (TrueWhenEqual)
4010       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4011     else
4012       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4013 
4014     OldTI->eraseFromParent();
4015 
4016     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4017     // for the edge we just added.
4018     AddPredecessorToBlock(EdgeBB, BB, NewBB);
4019 
4020     LLVM_DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
4021                       << "\nEXTRABB = " << *BB);
4022     BB = NewBB;
4023   }
4024 
4025   Builder.SetInsertPoint(BI);
4026   // Convert pointer to int before we switch.
4027   if (CompVal->getType()->isPointerTy()) {
4028     CompVal = Builder.CreatePtrToInt(
4029         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4030   }
4031 
4032   // Create the new switch instruction now.
4033   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4034 
4035   // Add all of the 'cases' to the switch instruction.
4036   for (unsigned i = 0, e = Values.size(); i != e; ++i)
4037     New->addCase(Values[i], EdgeBB);
4038 
4039   // We added edges from PI to the EdgeBB.  As such, if there were any
4040   // PHI nodes in EdgeBB, they need entries to be added corresponding to
4041   // the number of edges added.
4042   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4043     PHINode *PN = cast<PHINode>(BBI);
4044     Value *InVal = PN->getIncomingValueForBlock(BB);
4045     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4046       PN->addIncoming(InVal, BB);
4047   }
4048 
4049   // Erase the old branch instruction.
4050   EraseTerminatorAndDCECond(BI);
4051 
4052   LLVM_DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
4053   return true;
4054 }
4055 
4056 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4057   if (isa<PHINode>(RI->getValue()))
4058     return simplifyCommonResume(RI);
4059   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4060            RI->getValue() == RI->getParent()->getFirstNonPHI())
4061     // The resume must unwind the exception that caused control to branch here.
4062     return simplifySingleResume(RI);
4063 
4064   return false;
4065 }
4066 
4067 // Check if cleanup block is empty
4068 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4069   for (Instruction &I : R) {
4070     auto *II = dyn_cast<IntrinsicInst>(&I);
4071     if (!II)
4072       return false;
4073 
4074     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4075     switch (IntrinsicID) {
4076     case Intrinsic::dbg_declare:
4077     case Intrinsic::dbg_value:
4078     case Intrinsic::dbg_label:
4079     case Intrinsic::lifetime_end:
4080       break;
4081     default:
4082       return false;
4083     }
4084   }
4085   return true;
4086 }
4087 
4088 // Simplify resume that is shared by several landing pads (phi of landing pad).
4089 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4090   BasicBlock *BB = RI->getParent();
4091 
4092   // Check that there are no other instructions except for debug and lifetime
4093   // intrinsics between the phi's and resume instruction.
4094   if (!isCleanupBlockEmpty(
4095           make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4096     return false;
4097 
4098   SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4099   auto *PhiLPInst = cast<PHINode>(RI->getValue());
4100 
4101   // Check incoming blocks to see if any of them are trivial.
4102   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4103        Idx++) {
4104     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4105     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4106 
4107     // If the block has other successors, we can not delete it because
4108     // it has other dependents.
4109     if (IncomingBB->getUniqueSuccessor() != BB)
4110       continue;
4111 
4112     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4113     // Not the landing pad that caused the control to branch here.
4114     if (IncomingValue != LandingPad)
4115       continue;
4116 
4117     if (isCleanupBlockEmpty(
4118             make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4119       TrivialUnwindBlocks.insert(IncomingBB);
4120   }
4121 
4122   // If no trivial unwind blocks, don't do any simplifications.
4123   if (TrivialUnwindBlocks.empty())
4124     return false;
4125 
4126   // Turn all invokes that unwind here into calls.
4127   for (auto *TrivialBB : TrivialUnwindBlocks) {
4128     // Blocks that will be simplified should be removed from the phi node.
4129     // Note there could be multiple edges to the resume block, and we need
4130     // to remove them all.
4131     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4132       BB->removePredecessor(TrivialBB, true);
4133 
4134     for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
4135          PI != PE;) {
4136       BasicBlock *Pred = *PI++;
4137       removeUnwindEdge(Pred);
4138       ++NumInvokes;
4139     }
4140 
4141     // In each SimplifyCFG run, only the current processed block can be erased.
4142     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4143     // of erasing TrivialBB, we only remove the branch to the common resume
4144     // block so that we can later erase the resume block since it has no
4145     // predecessors.
4146     TrivialBB->getTerminator()->eraseFromParent();
4147     new UnreachableInst(RI->getContext(), TrivialBB);
4148   }
4149 
4150   // Delete the resume block if all its predecessors have been removed.
4151   if (pred_empty(BB))
4152     BB->eraseFromParent();
4153 
4154   return !TrivialUnwindBlocks.empty();
4155 }
4156 
4157 // Simplify resume that is only used by a single (non-phi) landing pad.
4158 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4159   BasicBlock *BB = RI->getParent();
4160   auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4161   assert(RI->getValue() == LPInst &&
4162          "Resume must unwind the exception that caused control to here");
4163 
4164   // Check that there are no other instructions except for debug intrinsics.
4165   if (!isCleanupBlockEmpty(
4166           make_range<Instruction *>(LPInst->getNextNode(), RI)))
4167     return false;
4168 
4169   // Turn all invokes that unwind here into calls and delete the basic block.
4170   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
4171     BasicBlock *Pred = *PI++;
4172     removeUnwindEdge(Pred);
4173     ++NumInvokes;
4174   }
4175 
4176   // The landingpad is now unreachable.  Zap it.
4177   if (LoopHeaders)
4178     LoopHeaders->erase(BB);
4179   BB->eraseFromParent();
4180   return true;
4181 }
4182 
4183 static bool removeEmptyCleanup(CleanupReturnInst *RI) {
4184   // If this is a trivial cleanup pad that executes no instructions, it can be
4185   // eliminated.  If the cleanup pad continues to the caller, any predecessor
4186   // that is an EH pad will be updated to continue to the caller and any
4187   // predecessor that terminates with an invoke instruction will have its invoke
4188   // instruction converted to a call instruction.  If the cleanup pad being
4189   // simplified does not continue to the caller, each predecessor will be
4190   // updated to continue to the unwind destination of the cleanup pad being
4191   // simplified.
4192   BasicBlock *BB = RI->getParent();
4193   CleanupPadInst *CPInst = RI->getCleanupPad();
4194   if (CPInst->getParent() != BB)
4195     // This isn't an empty cleanup.
4196     return false;
4197 
4198   // We cannot kill the pad if it has multiple uses.  This typically arises
4199   // from unreachable basic blocks.
4200   if (!CPInst->hasOneUse())
4201     return false;
4202 
4203   // Check that there are no other instructions except for benign intrinsics.
4204   if (!isCleanupBlockEmpty(
4205           make_range<Instruction *>(CPInst->getNextNode(), RI)))
4206     return false;
4207 
4208   // If the cleanup return we are simplifying unwinds to the caller, this will
4209   // set UnwindDest to nullptr.
4210   BasicBlock *UnwindDest = RI->getUnwindDest();
4211   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4212 
4213   // We're about to remove BB from the control flow.  Before we do, sink any
4214   // PHINodes into the unwind destination.  Doing this before changing the
4215   // control flow avoids some potentially slow checks, since we can currently
4216   // be certain that UnwindDest and BB have no common predecessors (since they
4217   // are both EH pads).
4218   if (UnwindDest) {
4219     // First, go through the PHI nodes in UnwindDest and update any nodes that
4220     // reference the block we are removing
4221     for (BasicBlock::iterator I = UnwindDest->begin(),
4222                               IE = DestEHPad->getIterator();
4223          I != IE; ++I) {
4224       PHINode *DestPN = cast<PHINode>(I);
4225 
4226       int Idx = DestPN->getBasicBlockIndex(BB);
4227       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4228       assert(Idx != -1);
4229       // This PHI node has an incoming value that corresponds to a control
4230       // path through the cleanup pad we are removing.  If the incoming
4231       // value is in the cleanup pad, it must be a PHINode (because we
4232       // verified above that the block is otherwise empty).  Otherwise, the
4233       // value is either a constant or a value that dominates the cleanup
4234       // pad being removed.
4235       //
4236       // Because BB and UnwindDest are both EH pads, all of their
4237       // predecessors must unwind to these blocks, and since no instruction
4238       // can have multiple unwind destinations, there will be no overlap in
4239       // incoming blocks between SrcPN and DestPN.
4240       Value *SrcVal = DestPN->getIncomingValue(Idx);
4241       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4242 
4243       // Remove the entry for the block we are deleting.
4244       DestPN->removeIncomingValue(Idx, false);
4245 
4246       if (SrcPN && SrcPN->getParent() == BB) {
4247         // If the incoming value was a PHI node in the cleanup pad we are
4248         // removing, we need to merge that PHI node's incoming values into
4249         // DestPN.
4250         for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
4251              SrcIdx != SrcE; ++SrcIdx) {
4252           DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
4253                               SrcPN->getIncomingBlock(SrcIdx));
4254         }
4255       } else {
4256         // Otherwise, the incoming value came from above BB and
4257         // so we can just reuse it.  We must associate all of BB's
4258         // predecessors with this value.
4259         for (auto *pred : predecessors(BB)) {
4260           DestPN->addIncoming(SrcVal, pred);
4261         }
4262       }
4263     }
4264 
4265     // Sink any remaining PHI nodes directly into UnwindDest.
4266     Instruction *InsertPt = DestEHPad;
4267     for (BasicBlock::iterator I = BB->begin(),
4268                               IE = BB->getFirstNonPHI()->getIterator();
4269          I != IE;) {
4270       // The iterator must be incremented here because the instructions are
4271       // being moved to another block.
4272       PHINode *PN = cast<PHINode>(I++);
4273       if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB))
4274         // If the PHI node has no uses or all of its uses are in this basic
4275         // block (meaning they are debug or lifetime intrinsics), just leave
4276         // it.  It will be erased when we erase BB below.
4277         continue;
4278 
4279       // Otherwise, sink this PHI node into UnwindDest.
4280       // Any predecessors to UnwindDest which are not already represented
4281       // must be back edges which inherit the value from the path through
4282       // BB.  In this case, the PHI value must reference itself.
4283       for (auto *pred : predecessors(UnwindDest))
4284         if (pred != BB)
4285           PN->addIncoming(PN, pred);
4286       PN->moveBefore(InsertPt);
4287     }
4288   }
4289 
4290   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
4291     // The iterator must be updated here because we are removing this pred.
4292     BasicBlock *PredBB = *PI++;
4293     if (UnwindDest == nullptr) {
4294       removeUnwindEdge(PredBB);
4295       ++NumInvokes;
4296     } else {
4297       Instruction *TI = PredBB->getTerminator();
4298       TI->replaceUsesOfWith(BB, UnwindDest);
4299     }
4300   }
4301 
4302   // The cleanup pad is now unreachable.  Zap it.
4303   BB->eraseFromParent();
4304   return true;
4305 }
4306 
4307 // Try to merge two cleanuppads together.
4308 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4309   // Skip any cleanuprets which unwind to caller, there is nothing to merge
4310   // with.
4311   BasicBlock *UnwindDest = RI->getUnwindDest();
4312   if (!UnwindDest)
4313     return false;
4314 
4315   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4316   // be safe to merge without code duplication.
4317   if (UnwindDest->getSinglePredecessor() != RI->getParent())
4318     return false;
4319 
4320   // Verify that our cleanuppad's unwind destination is another cleanuppad.
4321   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4322   if (!SuccessorCleanupPad)
4323     return false;
4324 
4325   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4326   // Replace any uses of the successor cleanupad with the predecessor pad
4327   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4328   // funclet bundle operands.
4329   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4330   // Remove the old cleanuppad.
4331   SuccessorCleanupPad->eraseFromParent();
4332   // Now, we simply replace the cleanupret with a branch to the unwind
4333   // destination.
4334   BranchInst::Create(UnwindDest, RI->getParent());
4335   RI->eraseFromParent();
4336 
4337   return true;
4338 }
4339 
4340 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4341   // It is possible to transiantly have an undef cleanuppad operand because we
4342   // have deleted some, but not all, dead blocks.
4343   // Eventually, this block will be deleted.
4344   if (isa<UndefValue>(RI->getOperand(0)))
4345     return false;
4346 
4347   if (mergeCleanupPad(RI))
4348     return true;
4349 
4350   if (removeEmptyCleanup(RI))
4351     return true;
4352 
4353   return false;
4354 }
4355 
4356 bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4357   BasicBlock *BB = RI->getParent();
4358   if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4359     return false;
4360 
4361   // Find predecessors that end with branches.
4362   SmallVector<BasicBlock *, 8> UncondBranchPreds;
4363   SmallVector<BranchInst *, 8> CondBranchPreds;
4364   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4365     BasicBlock *P = *PI;
4366     Instruction *PTI = P->getTerminator();
4367     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4368       if (BI->isUnconditional())
4369         UncondBranchPreds.push_back(P);
4370       else
4371         CondBranchPreds.push_back(BI);
4372     }
4373   }
4374 
4375   // If we found some, do the transformation!
4376   if (!UncondBranchPreds.empty() && DupRet) {
4377     while (!UncondBranchPreds.empty()) {
4378       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4379       LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
4380                         << "INTO UNCOND BRANCH PRED: " << *Pred);
4381       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
4382     }
4383 
4384     // If we eliminated all predecessors of the block, delete the block now.
4385     if (pred_empty(BB)) {
4386       // We know there are no successors, so just nuke the block.
4387       if (LoopHeaders)
4388         LoopHeaders->erase(BB);
4389       BB->eraseFromParent();
4390     }
4391 
4392     return true;
4393   }
4394 
4395   // Check out all of the conditional branches going to this return
4396   // instruction.  If any of them just select between returns, change the
4397   // branch itself into a select/return pair.
4398   while (!CondBranchPreds.empty()) {
4399     BranchInst *BI = CondBranchPreds.pop_back_val();
4400 
4401     // Check to see if the non-BB successor is also a return block.
4402     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4403         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4404         SimplifyCondBranchToTwoReturns(BI, Builder))
4405       return true;
4406   }
4407   return false;
4408 }
4409 
4410 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4411   BasicBlock *BB = UI->getParent();
4412 
4413   bool Changed = false;
4414 
4415   // If there are any instructions immediately before the unreachable that can
4416   // be removed, do so.
4417   while (UI->getIterator() != BB->begin()) {
4418     BasicBlock::iterator BBI = UI->getIterator();
4419     --BBI;
4420     // Do not delete instructions that can have side effects which might cause
4421     // the unreachable to not be reachable; specifically, calls and volatile
4422     // operations may have this effect.
4423     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4424       break;
4425 
4426     if (BBI->mayHaveSideEffects()) {
4427       if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4428         if (SI->isVolatile())
4429           break;
4430       } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4431         if (LI->isVolatile())
4432           break;
4433       } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4434         if (RMWI->isVolatile())
4435           break;
4436       } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4437         if (CXI->isVolatile())
4438           break;
4439       } else if (isa<CatchPadInst>(BBI)) {
4440         // A catchpad may invoke exception object constructors and such, which
4441         // in some languages can be arbitrary code, so be conservative by
4442         // default.
4443         // For CoreCLR, it just involves a type test, so can be removed.
4444         if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4445             EHPersonality::CoreCLR)
4446           break;
4447       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4448                  !isa<LandingPadInst>(BBI)) {
4449         break;
4450       }
4451       // Note that deleting LandingPad's here is in fact okay, although it
4452       // involves a bit of subtle reasoning. If this inst is a LandingPad,
4453       // all the predecessors of this block will be the unwind edges of Invokes,
4454       // and we can therefore guarantee this block will be erased.
4455     }
4456 
4457     // Delete this instruction (any uses are guaranteed to be dead)
4458     if (!BBI->use_empty())
4459       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4460     BBI->eraseFromParent();
4461     Changed = true;
4462   }
4463 
4464   // If the unreachable instruction is the first in the block, take a gander
4465   // at all of the predecessors of this instruction, and simplify them.
4466   if (&BB->front() != UI)
4467     return Changed;
4468 
4469   SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4470   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4471     Instruction *TI = Preds[i]->getTerminator();
4472     IRBuilder<> Builder(TI);
4473     if (auto *BI = dyn_cast<BranchInst>(TI)) {
4474       if (BI->isUnconditional()) {
4475         assert(BI->getSuccessor(0) == BB && "Incorrect CFG");
4476         new UnreachableInst(TI->getContext(), TI);
4477         TI->eraseFromParent();
4478         Changed = true;
4479       } else {
4480         Value* Cond = BI->getCondition();
4481         if (BI->getSuccessor(0) == BB) {
4482           Builder.CreateAssumption(Builder.CreateNot(Cond));
4483           Builder.CreateBr(BI->getSuccessor(1));
4484         } else {
4485           assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
4486           Builder.CreateAssumption(Cond);
4487           Builder.CreateBr(BI->getSuccessor(0));
4488         }
4489         EraseTerminatorAndDCECond(BI);
4490         Changed = true;
4491       }
4492     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4493       SwitchInstProfUpdateWrapper SU(*SI);
4494       for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
4495         if (i->getCaseSuccessor() != BB) {
4496           ++i;
4497           continue;
4498         }
4499         BB->removePredecessor(SU->getParent());
4500         i = SU.removeCase(i);
4501         e = SU->case_end();
4502         Changed = true;
4503       }
4504     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4505       if (II->getUnwindDest() == BB) {
4506         removeUnwindEdge(TI->getParent());
4507         Changed = true;
4508       }
4509     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4510       if (CSI->getUnwindDest() == BB) {
4511         removeUnwindEdge(TI->getParent());
4512         Changed = true;
4513         continue;
4514       }
4515 
4516       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4517                                              E = CSI->handler_end();
4518            I != E; ++I) {
4519         if (*I == BB) {
4520           CSI->removeHandler(I);
4521           --I;
4522           --E;
4523           Changed = true;
4524         }
4525       }
4526       if (CSI->getNumHandlers() == 0) {
4527         BasicBlock *CatchSwitchBB = CSI->getParent();
4528         if (CSI->hasUnwindDest()) {
4529           // Redirect preds to the unwind dest
4530           CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4531         } else {
4532           // Rewrite all preds to unwind to caller (or from invoke to call).
4533           SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4534           for (BasicBlock *EHPred : EHPreds)
4535             removeUnwindEdge(EHPred);
4536         }
4537         // The catchswitch is no longer reachable.
4538         new UnreachableInst(CSI->getContext(), CSI);
4539         CSI->eraseFromParent();
4540         Changed = true;
4541       }
4542     } else if (isa<CleanupReturnInst>(TI)) {
4543       new UnreachableInst(TI->getContext(), TI);
4544       TI->eraseFromParent();
4545       Changed = true;
4546     }
4547   }
4548 
4549   // If this block is now dead, remove it.
4550   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4551     // We know there are no successors, so just nuke the block.
4552     if (LoopHeaders)
4553       LoopHeaders->erase(BB);
4554     BB->eraseFromParent();
4555     return true;
4556   }
4557 
4558   return Changed;
4559 }
4560 
4561 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4562   assert(Cases.size() >= 1);
4563 
4564   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4565   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4566     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4567       return false;
4568   }
4569   return true;
4570 }
4571 
4572 static void createUnreachableSwitchDefault(SwitchInst *Switch) {
4573   LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4574   BasicBlock *NewDefaultBlock =
4575      SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), "");
4576   Switch->setDefaultDest(&*NewDefaultBlock);
4577   SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front());
4578   auto *NewTerminator = NewDefaultBlock->getTerminator();
4579   new UnreachableInst(Switch->getContext(), NewTerminator);
4580   EraseTerminatorAndDCECond(NewTerminator);
4581 }
4582 
4583 /// Turn a switch with two reachable destinations into an integer range
4584 /// comparison and branch.
4585 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
4586                                              IRBuilder<> &Builder) {
4587   assert(SI->getNumCases() > 1 && "Degenerate switch?");
4588 
4589   bool HasDefault =
4590       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4591 
4592   // Partition the cases into two sets with different destinations.
4593   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4594   BasicBlock *DestB = nullptr;
4595   SmallVector<ConstantInt *, 16> CasesA;
4596   SmallVector<ConstantInt *, 16> CasesB;
4597 
4598   for (auto Case : SI->cases()) {
4599     BasicBlock *Dest = Case.getCaseSuccessor();
4600     if (!DestA)
4601       DestA = Dest;
4602     if (Dest == DestA) {
4603       CasesA.push_back(Case.getCaseValue());
4604       continue;
4605     }
4606     if (!DestB)
4607       DestB = Dest;
4608     if (Dest == DestB) {
4609       CasesB.push_back(Case.getCaseValue());
4610       continue;
4611     }
4612     return false; // More than two destinations.
4613   }
4614 
4615   assert(DestA && DestB &&
4616          "Single-destination switch should have been folded.");
4617   assert(DestA != DestB);
4618   assert(DestB != SI->getDefaultDest());
4619   assert(!CasesB.empty() && "There must be non-default cases.");
4620   assert(!CasesA.empty() || HasDefault);
4621 
4622   // Figure out if one of the sets of cases form a contiguous range.
4623   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4624   BasicBlock *ContiguousDest = nullptr;
4625   BasicBlock *OtherDest = nullptr;
4626   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4627     ContiguousCases = &CasesA;
4628     ContiguousDest = DestA;
4629     OtherDest = DestB;
4630   } else if (CasesAreContiguous(CasesB)) {
4631     ContiguousCases = &CasesB;
4632     ContiguousDest = DestB;
4633     OtherDest = DestA;
4634   } else
4635     return false;
4636 
4637   // Start building the compare and branch.
4638 
4639   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4640   Constant *NumCases =
4641       ConstantInt::get(Offset->getType(), ContiguousCases->size());
4642 
4643   Value *Sub = SI->getCondition();
4644   if (!Offset->isNullValue())
4645     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4646 
4647   Value *Cmp;
4648   // If NumCases overflowed, then all possible values jump to the successor.
4649   if (NumCases->isNullValue() && !ContiguousCases->empty())
4650     Cmp = ConstantInt::getTrue(SI->getContext());
4651   else
4652     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4653   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4654 
4655   // Update weight for the newly-created conditional branch.
4656   if (HasBranchWeights(SI)) {
4657     SmallVector<uint64_t, 8> Weights;
4658     GetBranchWeights(SI, Weights);
4659     if (Weights.size() == 1 + SI->getNumCases()) {
4660       uint64_t TrueWeight = 0;
4661       uint64_t FalseWeight = 0;
4662       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4663         if (SI->getSuccessor(I) == ContiguousDest)
4664           TrueWeight += Weights[I];
4665         else
4666           FalseWeight += Weights[I];
4667       }
4668       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4669         TrueWeight /= 2;
4670         FalseWeight /= 2;
4671       }
4672       setBranchWeights(NewBI, TrueWeight, FalseWeight);
4673     }
4674   }
4675 
4676   // Prune obsolete incoming values off the successors' PHI nodes.
4677   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4678     unsigned PreviousEdges = ContiguousCases->size();
4679     if (ContiguousDest == SI->getDefaultDest())
4680       ++PreviousEdges;
4681     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4682       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4683   }
4684   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4685     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4686     if (OtherDest == SI->getDefaultDest())
4687       ++PreviousEdges;
4688     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4689       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4690   }
4691 
4692   // Clean up the default block - it may have phis or other instructions before
4693   // the unreachable terminator.
4694   if (!HasDefault)
4695     createUnreachableSwitchDefault(SI);
4696 
4697   // Drop the switch.
4698   SI->eraseFromParent();
4699 
4700   return true;
4701 }
4702 
4703 /// Compute masked bits for the condition of a switch
4704 /// and use it to remove dead cases.
4705 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4706                                      const DataLayout &DL) {
4707   Value *Cond = SI->getCondition();
4708   unsigned Bits = Cond->getType()->getIntegerBitWidth();
4709   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
4710 
4711   // We can also eliminate cases by determining that their values are outside of
4712   // the limited range of the condition based on how many significant (non-sign)
4713   // bits are in the condition value.
4714   unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4715   unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4716 
4717   // Gather dead cases.
4718   SmallVector<ConstantInt *, 8> DeadCases;
4719   for (auto &Case : SI->cases()) {
4720     const APInt &CaseVal = Case.getCaseValue()->getValue();
4721     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
4722         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4723       DeadCases.push_back(Case.getCaseValue());
4724       LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
4725                         << " is dead.\n");
4726     }
4727   }
4728 
4729   // If we can prove that the cases must cover all possible values, the
4730   // default destination becomes dead and we can remove it.  If we know some
4731   // of the bits in the value, we can use that to more precisely compute the
4732   // number of possible unique case values.
4733   bool HasDefault =
4734       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4735   const unsigned NumUnknownBits =
4736       Bits - (Known.Zero | Known.One).countPopulation();
4737   assert(NumUnknownBits <= Bits);
4738   if (HasDefault && DeadCases.empty() &&
4739       NumUnknownBits < 64 /* avoid overflow */ &&
4740       SI->getNumCases() == (1ULL << NumUnknownBits)) {
4741     createUnreachableSwitchDefault(SI);
4742     return true;
4743   }
4744 
4745   if (DeadCases.empty())
4746     return false;
4747 
4748   SwitchInstProfUpdateWrapper SIW(*SI);
4749   for (ConstantInt *DeadCase : DeadCases) {
4750     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4751     assert(CaseI != SI->case_default() &&
4752            "Case was not found. Probably mistake in DeadCases forming.");
4753     // Prune unused values from PHI nodes.
4754     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4755     SIW.removeCase(CaseI);
4756   }
4757 
4758   return true;
4759 }
4760 
4761 /// If BB would be eligible for simplification by
4762 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4763 /// by an unconditional branch), look at the phi node for BB in the successor
4764 /// block and see if the incoming value is equal to CaseValue. If so, return
4765 /// the phi node, and set PhiIndex to BB's index in the phi node.
4766 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4767                                               BasicBlock *BB, int *PhiIndex) {
4768   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4769     return nullptr; // BB must be empty to be a candidate for simplification.
4770   if (!BB->getSinglePredecessor())
4771     return nullptr; // BB must be dominated by the switch.
4772 
4773   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4774   if (!Branch || !Branch->isUnconditional())
4775     return nullptr; // Terminator must be unconditional branch.
4776 
4777   BasicBlock *Succ = Branch->getSuccessor(0);
4778 
4779   for (PHINode &PHI : Succ->phis()) {
4780     int Idx = PHI.getBasicBlockIndex(BB);
4781     assert(Idx >= 0 && "PHI has no entry for predecessor?");
4782 
4783     Value *InValue = PHI.getIncomingValue(Idx);
4784     if (InValue != CaseValue)
4785       continue;
4786 
4787     *PhiIndex = Idx;
4788     return &PHI;
4789   }
4790 
4791   return nullptr;
4792 }
4793 
4794 /// Try to forward the condition of a switch instruction to a phi node
4795 /// dominated by the switch, if that would mean that some of the destination
4796 /// blocks of the switch can be folded away. Return true if a change is made.
4797 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4798   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4799 
4800   ForwardingNodesMap ForwardingNodes;
4801   BasicBlock *SwitchBlock = SI->getParent();
4802   bool Changed = false;
4803   for (auto &Case : SI->cases()) {
4804     ConstantInt *CaseValue = Case.getCaseValue();
4805     BasicBlock *CaseDest = Case.getCaseSuccessor();
4806 
4807     // Replace phi operands in successor blocks that are using the constant case
4808     // value rather than the switch condition variable:
4809     //   switchbb:
4810     //   switch i32 %x, label %default [
4811     //     i32 17, label %succ
4812     //   ...
4813     //   succ:
4814     //     %r = phi i32 ... [ 17, %switchbb ] ...
4815     // -->
4816     //     %r = phi i32 ... [ %x, %switchbb ] ...
4817 
4818     for (PHINode &Phi : CaseDest->phis()) {
4819       // This only works if there is exactly 1 incoming edge from the switch to
4820       // a phi. If there is >1, that means multiple cases of the switch map to 1
4821       // value in the phi, and that phi value is not the switch condition. Thus,
4822       // this transform would not make sense (the phi would be invalid because
4823       // a phi can't have different incoming values from the same block).
4824       int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4825       if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4826           count(Phi.blocks(), SwitchBlock) == 1) {
4827         Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
4828         Changed = true;
4829       }
4830     }
4831 
4832     // Collect phi nodes that are indirectly using this switch's case constants.
4833     int PhiIdx;
4834     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4835       ForwardingNodes[Phi].push_back(PhiIdx);
4836   }
4837 
4838   for (auto &ForwardingNode : ForwardingNodes) {
4839     PHINode *Phi = ForwardingNode.first;
4840     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
4841     if (Indexes.size() < 2)
4842       continue;
4843 
4844     for (int Index : Indexes)
4845       Phi->setIncomingValue(Index, SI->getCondition());
4846     Changed = true;
4847   }
4848 
4849   return Changed;
4850 }
4851 
4852 /// Return true if the backend will be able to handle
4853 /// initializing an array of constants like C.
4854 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4855   if (C->isThreadDependent())
4856     return false;
4857   if (C->isDLLImportDependent())
4858     return false;
4859 
4860   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4861       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4862       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4863     return false;
4864 
4865   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
4866     if (!CE->isGEPWithNoNotionalOverIndexing())
4867       return false;
4868     if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4869       return false;
4870   }
4871 
4872   if (!TTI.shouldBuildLookupTablesForConstant(C))
4873     return false;
4874 
4875   return true;
4876 }
4877 
4878 /// If V is a Constant, return it. Otherwise, try to look up
4879 /// its constant value in ConstantPool, returning 0 if it's not there.
4880 static Constant *
4881 LookupConstant(Value *V,
4882                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4883   if (Constant *C = dyn_cast<Constant>(V))
4884     return C;
4885   return ConstantPool.lookup(V);
4886 }
4887 
4888 /// Try to fold instruction I into a constant. This works for
4889 /// simple instructions such as binary operations where both operands are
4890 /// constant or can be replaced by constants from the ConstantPool. Returns the
4891 /// resulting constant on success, 0 otherwise.
4892 static Constant *
4893 ConstantFold(Instruction *I, const DataLayout &DL,
4894              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4895   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
4896     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4897     if (!A)
4898       return nullptr;
4899     if (A->isAllOnesValue())
4900       return LookupConstant(Select->getTrueValue(), ConstantPool);
4901     if (A->isNullValue())
4902       return LookupConstant(Select->getFalseValue(), ConstantPool);
4903     return nullptr;
4904   }
4905 
4906   SmallVector<Constant *, 4> COps;
4907   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4908     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4909       COps.push_back(A);
4910     else
4911       return nullptr;
4912   }
4913 
4914   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4915     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4916                                            COps[1], DL);
4917   }
4918 
4919   return ConstantFoldInstOperands(I, COps, DL);
4920 }
4921 
4922 /// Try to determine the resulting constant values in phi nodes
4923 /// at the common destination basic block, *CommonDest, for one of the case
4924 /// destionations CaseDest corresponding to value CaseVal (0 for the default
4925 /// case), of a switch instruction SI.
4926 static bool
4927 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4928                BasicBlock **CommonDest,
4929                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4930                const DataLayout &DL, const TargetTransformInfo &TTI) {
4931   // The block from which we enter the common destination.
4932   BasicBlock *Pred = SI->getParent();
4933 
4934   // If CaseDest is empty except for some side-effect free instructions through
4935   // which we can constant-propagate the CaseVal, continue to its successor.
4936   SmallDenseMap<Value *, Constant *> ConstantPool;
4937   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4938   for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
4939     if (I.isTerminator()) {
4940       // If the terminator is a simple branch, continue to the next block.
4941       if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
4942         return false;
4943       Pred = CaseDest;
4944       CaseDest = I.getSuccessor(0);
4945     } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
4946       // Instruction is side-effect free and constant.
4947 
4948       // If the instruction has uses outside this block or a phi node slot for
4949       // the block, it is not safe to bypass the instruction since it would then
4950       // no longer dominate all its uses.
4951       for (auto &Use : I.uses()) {
4952         User *User = Use.getUser();
4953         if (Instruction *I = dyn_cast<Instruction>(User))
4954           if (I->getParent() == CaseDest)
4955             continue;
4956         if (PHINode *Phi = dyn_cast<PHINode>(User))
4957           if (Phi->getIncomingBlock(Use) == CaseDest)
4958             continue;
4959         return false;
4960       }
4961 
4962       ConstantPool.insert(std::make_pair(&I, C));
4963     } else {
4964       break;
4965     }
4966   }
4967 
4968   // If we did not have a CommonDest before, use the current one.
4969   if (!*CommonDest)
4970     *CommonDest = CaseDest;
4971   // If the destination isn't the common one, abort.
4972   if (CaseDest != *CommonDest)
4973     return false;
4974 
4975   // Get the values for this case from phi nodes in the destination block.
4976   for (PHINode &PHI : (*CommonDest)->phis()) {
4977     int Idx = PHI.getBasicBlockIndex(Pred);
4978     if (Idx == -1)
4979       continue;
4980 
4981     Constant *ConstVal =
4982         LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
4983     if (!ConstVal)
4984       return false;
4985 
4986     // Be conservative about which kinds of constants we support.
4987     if (!ValidLookupTableConstant(ConstVal, TTI))
4988       return false;
4989 
4990     Res.push_back(std::make_pair(&PHI, ConstVal));
4991   }
4992 
4993   return Res.size() > 0;
4994 }
4995 
4996 // Helper function used to add CaseVal to the list of cases that generate
4997 // Result. Returns the updated number of cases that generate this result.
4998 static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
4999                                  SwitchCaseResultVectorTy &UniqueResults,
5000                                  Constant *Result) {
5001   for (auto &I : UniqueResults) {
5002     if (I.first == Result) {
5003       I.second.push_back(CaseVal);
5004       return I.second.size();
5005     }
5006   }
5007   UniqueResults.push_back(
5008       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5009   return 1;
5010 }
5011 
5012 // Helper function that initializes a map containing
5013 // results for the PHI node of the common destination block for a switch
5014 // instruction. Returns false if multiple PHI nodes have been found or if
5015 // there is not a common destination block for the switch.
5016 static bool
5017 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
5018                       SwitchCaseResultVectorTy &UniqueResults,
5019                       Constant *&DefaultResult, const DataLayout &DL,
5020                       const TargetTransformInfo &TTI,
5021                       uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
5022   for (auto &I : SI->cases()) {
5023     ConstantInt *CaseVal = I.getCaseValue();
5024 
5025     // Resulting value at phi nodes for this case value.
5026     SwitchCaseResultsTy Results;
5027     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5028                         DL, TTI))
5029       return false;
5030 
5031     // Only one value per case is permitted.
5032     if (Results.size() > 1)
5033       return false;
5034 
5035     // Add the case->result mapping to UniqueResults.
5036     const uintptr_t NumCasesForResult =
5037         MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5038 
5039     // Early out if there are too many cases for this result.
5040     if (NumCasesForResult > MaxCasesPerResult)
5041       return false;
5042 
5043     // Early out if there are too many unique results.
5044     if (UniqueResults.size() > MaxUniqueResults)
5045       return false;
5046 
5047     // Check the PHI consistency.
5048     if (!PHI)
5049       PHI = Results[0].first;
5050     else if (PHI != Results[0].first)
5051       return false;
5052   }
5053   // Find the default result value.
5054   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5055   BasicBlock *DefaultDest = SI->getDefaultDest();
5056   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5057                  DL, TTI);
5058   // If the default value is not found abort unless the default destination
5059   // is unreachable.
5060   DefaultResult =
5061       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5062   if ((!DefaultResult &&
5063        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5064     return false;
5065 
5066   return true;
5067 }
5068 
5069 // Helper function that checks if it is possible to transform a switch with only
5070 // two cases (or two cases + default) that produces a result into a select.
5071 // Example:
5072 // switch (a) {
5073 //   case 10:                %0 = icmp eq i32 %a, 10
5074 //     return 10;            %1 = select i1 %0, i32 10, i32 4
5075 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
5076 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
5077 //   default:
5078 //     return 4;
5079 // }
5080 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
5081                                    Constant *DefaultResult, Value *Condition,
5082                                    IRBuilder<> &Builder) {
5083   assert(ResultVector.size() == 2 &&
5084          "We should have exactly two unique results at this point");
5085   // If we are selecting between only two cases transform into a simple
5086   // select or a two-way select if default is possible.
5087   if (ResultVector[0].second.size() == 1 &&
5088       ResultVector[1].second.size() == 1) {
5089     ConstantInt *const FirstCase = ResultVector[0].second[0];
5090     ConstantInt *const SecondCase = ResultVector[1].second[0];
5091 
5092     bool DefaultCanTrigger = DefaultResult;
5093     Value *SelectValue = ResultVector[1].first;
5094     if (DefaultCanTrigger) {
5095       Value *const ValueCompare =
5096           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5097       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5098                                          DefaultResult, "switch.select");
5099     }
5100     Value *const ValueCompare =
5101         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5102     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5103                                 SelectValue, "switch.select");
5104   }
5105 
5106   return nullptr;
5107 }
5108 
5109 // Helper function to cleanup a switch instruction that has been converted into
5110 // a select, fixing up PHI nodes and basic blocks.
5111 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
5112                                               Value *SelectValue,
5113                                               IRBuilder<> &Builder) {
5114   BasicBlock *SelectBB = SI->getParent();
5115   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5116     PHI->removeIncomingValue(SelectBB);
5117   PHI->addIncoming(SelectValue, SelectBB);
5118 
5119   Builder.CreateBr(PHI->getParent());
5120 
5121   // Remove the switch.
5122   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5123     BasicBlock *Succ = SI->getSuccessor(i);
5124 
5125     if (Succ == PHI->getParent())
5126       continue;
5127     Succ->removePredecessor(SelectBB);
5128   }
5129   SI->eraseFromParent();
5130 }
5131 
5132 /// If the switch is only used to initialize one or more
5133 /// phi nodes in a common successor block with only two different
5134 /// constant values, replace the switch with select.
5135 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5136                            const DataLayout &DL,
5137                            const TargetTransformInfo &TTI) {
5138   Value *const Cond = SI->getCondition();
5139   PHINode *PHI = nullptr;
5140   BasicBlock *CommonDest = nullptr;
5141   Constant *DefaultResult;
5142   SwitchCaseResultVectorTy UniqueResults;
5143   // Collect all the cases that will deliver the same value from the switch.
5144   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5145                              DL, TTI, 2, 1))
5146     return false;
5147   // Selects choose between maximum two values.
5148   if (UniqueResults.size() != 2)
5149     return false;
5150   assert(PHI != nullptr && "PHI for value select not found");
5151 
5152   Builder.SetInsertPoint(SI);
5153   Value *SelectValue =
5154       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
5155   if (SelectValue) {
5156     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
5157     return true;
5158   }
5159   // The switch couldn't be converted into a select.
5160   return false;
5161 }
5162 
5163 namespace {
5164 
5165 /// This class represents a lookup table that can be used to replace a switch.
5166 class SwitchLookupTable {
5167 public:
5168   /// Create a lookup table to use as a switch replacement with the contents
5169   /// of Values, using DefaultValue to fill any holes in the table.
5170   SwitchLookupTable(
5171       Module &M, uint64_t TableSize, ConstantInt *Offset,
5172       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5173       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5174 
5175   /// Build instructions with Builder to retrieve the value at
5176   /// the position given by Index in the lookup table.
5177   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5178 
5179   /// Return true if a table with TableSize elements of
5180   /// type ElementType would fit in a target-legal register.
5181   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5182                                  Type *ElementType);
5183 
5184 private:
5185   // Depending on the contents of the table, it can be represented in
5186   // different ways.
5187   enum {
5188     // For tables where each element contains the same value, we just have to
5189     // store that single value and return it for each lookup.
5190     SingleValueKind,
5191 
5192     // For tables where there is a linear relationship between table index
5193     // and values. We calculate the result with a simple multiplication
5194     // and addition instead of a table lookup.
5195     LinearMapKind,
5196 
5197     // For small tables with integer elements, we can pack them into a bitmap
5198     // that fits into a target-legal register. Values are retrieved by
5199     // shift and mask operations.
5200     BitMapKind,
5201 
5202     // The table is stored as an array of values. Values are retrieved by load
5203     // instructions from the table.
5204     ArrayKind
5205   } Kind;
5206 
5207   // For SingleValueKind, this is the single value.
5208   Constant *SingleValue = nullptr;
5209 
5210   // For BitMapKind, this is the bitmap.
5211   ConstantInt *BitMap = nullptr;
5212   IntegerType *BitMapElementTy = nullptr;
5213 
5214   // For LinearMapKind, these are the constants used to derive the value.
5215   ConstantInt *LinearOffset = nullptr;
5216   ConstantInt *LinearMultiplier = nullptr;
5217 
5218   // For ArrayKind, this is the array.
5219   GlobalVariable *Array = nullptr;
5220 };
5221 
5222 } // end anonymous namespace
5223 
5224 SwitchLookupTable::SwitchLookupTable(
5225     Module &M, uint64_t TableSize, ConstantInt *Offset,
5226     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5227     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5228   assert(Values.size() && "Can't build lookup table without values!");
5229   assert(TableSize >= Values.size() && "Can't fit values in table!");
5230 
5231   // If all values in the table are equal, this is that value.
5232   SingleValue = Values.begin()->second;
5233 
5234   Type *ValueType = Values.begin()->second->getType();
5235 
5236   // Build up the table contents.
5237   SmallVector<Constant *, 64> TableContents(TableSize);
5238   for (size_t I = 0, E = Values.size(); I != E; ++I) {
5239     ConstantInt *CaseVal = Values[I].first;
5240     Constant *CaseRes = Values[I].second;
5241     assert(CaseRes->getType() == ValueType);
5242 
5243     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5244     TableContents[Idx] = CaseRes;
5245 
5246     if (CaseRes != SingleValue)
5247       SingleValue = nullptr;
5248   }
5249 
5250   // Fill in any holes in the table with the default result.
5251   if (Values.size() < TableSize) {
5252     assert(DefaultValue &&
5253            "Need a default value to fill the lookup table holes.");
5254     assert(DefaultValue->getType() == ValueType);
5255     for (uint64_t I = 0; I < TableSize; ++I) {
5256       if (!TableContents[I])
5257         TableContents[I] = DefaultValue;
5258     }
5259 
5260     if (DefaultValue != SingleValue)
5261       SingleValue = nullptr;
5262   }
5263 
5264   // If each element in the table contains the same value, we only need to store
5265   // that single value.
5266   if (SingleValue) {
5267     Kind = SingleValueKind;
5268     return;
5269   }
5270 
5271   // Check if we can derive the value with a linear transformation from the
5272   // table index.
5273   if (isa<IntegerType>(ValueType)) {
5274     bool LinearMappingPossible = true;
5275     APInt PrevVal;
5276     APInt DistToPrev;
5277     assert(TableSize >= 2 && "Should be a SingleValue table.");
5278     // Check if there is the same distance between two consecutive values.
5279     for (uint64_t I = 0; I < TableSize; ++I) {
5280       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5281       if (!ConstVal) {
5282         // This is an undef. We could deal with it, but undefs in lookup tables
5283         // are very seldom. It's probably not worth the additional complexity.
5284         LinearMappingPossible = false;
5285         break;
5286       }
5287       const APInt &Val = ConstVal->getValue();
5288       if (I != 0) {
5289         APInt Dist = Val - PrevVal;
5290         if (I == 1) {
5291           DistToPrev = Dist;
5292         } else if (Dist != DistToPrev) {
5293           LinearMappingPossible = false;
5294           break;
5295         }
5296       }
5297       PrevVal = Val;
5298     }
5299     if (LinearMappingPossible) {
5300       LinearOffset = cast<ConstantInt>(TableContents[0]);
5301       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5302       Kind = LinearMapKind;
5303       ++NumLinearMaps;
5304       return;
5305     }
5306   }
5307 
5308   // If the type is integer and the table fits in a register, build a bitmap.
5309   if (WouldFitInRegister(DL, TableSize, ValueType)) {
5310     IntegerType *IT = cast<IntegerType>(ValueType);
5311     APInt TableInt(TableSize * IT->getBitWidth(), 0);
5312     for (uint64_t I = TableSize; I > 0; --I) {
5313       TableInt <<= IT->getBitWidth();
5314       // Insert values into the bitmap. Undef values are set to zero.
5315       if (!isa<UndefValue>(TableContents[I - 1])) {
5316         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5317         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5318       }
5319     }
5320     BitMap = ConstantInt::get(M.getContext(), TableInt);
5321     BitMapElementTy = IT;
5322     Kind = BitMapKind;
5323     ++NumBitMaps;
5324     return;
5325   }
5326 
5327   // Store the table in an array.
5328   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5329   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5330 
5331   Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5332                              GlobalVariable::PrivateLinkage, Initializer,
5333                              "switch.table." + FuncName);
5334   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5335   // Set the alignment to that of an array items. We will be only loading one
5336   // value out of it.
5337   Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5338   Kind = ArrayKind;
5339 }
5340 
5341 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5342   switch (Kind) {
5343   case SingleValueKind:
5344     return SingleValue;
5345   case LinearMapKind: {
5346     // Derive the result value from the input value.
5347     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5348                                           false, "switch.idx.cast");
5349     if (!LinearMultiplier->isOne())
5350       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5351     if (!LinearOffset->isZero())
5352       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5353     return Result;
5354   }
5355   case BitMapKind: {
5356     // Type of the bitmap (e.g. i59).
5357     IntegerType *MapTy = BitMap->getType();
5358 
5359     // Cast Index to the same type as the bitmap.
5360     // Note: The Index is <= the number of elements in the table, so
5361     // truncating it to the width of the bitmask is safe.
5362     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5363 
5364     // Multiply the shift amount by the element width.
5365     ShiftAmt = Builder.CreateMul(
5366         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5367         "switch.shiftamt");
5368 
5369     // Shift down.
5370     Value *DownShifted =
5371         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5372     // Mask off.
5373     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5374   }
5375   case ArrayKind: {
5376     // Make sure the table index will not overflow when treated as signed.
5377     IntegerType *IT = cast<IntegerType>(Index->getType());
5378     uint64_t TableSize =
5379         Array->getInitializer()->getType()->getArrayNumElements();
5380     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5381       Index = Builder.CreateZExt(
5382           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5383           "switch.tableidx.zext");
5384 
5385     Value *GEPIndices[] = {Builder.getInt32(0), Index};
5386     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5387                                            GEPIndices, "switch.gep");
5388     return Builder.CreateLoad(
5389         cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
5390         "switch.load");
5391   }
5392   }
5393   llvm_unreachable("Unknown lookup table kind!");
5394 }
5395 
5396 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5397                                            uint64_t TableSize,
5398                                            Type *ElementType) {
5399   auto *IT = dyn_cast<IntegerType>(ElementType);
5400   if (!IT)
5401     return false;
5402   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5403   // are <= 15, we could try to narrow the type.
5404 
5405   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5406   if (TableSize >= UINT_MAX / IT->getBitWidth())
5407     return false;
5408   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5409 }
5410 
5411 /// Determine whether a lookup table should be built for this switch, based on
5412 /// the number of cases, size of the table, and the types of the results.
5413 static bool
5414 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5415                        const TargetTransformInfo &TTI, const DataLayout &DL,
5416                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5417   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5418     return false; // TableSize overflowed, or mul below might overflow.
5419 
5420   bool AllTablesFitInRegister = true;
5421   bool HasIllegalType = false;
5422   for (const auto &I : ResultTypes) {
5423     Type *Ty = I.second;
5424 
5425     // Saturate this flag to true.
5426     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5427 
5428     // Saturate this flag to false.
5429     AllTablesFitInRegister =
5430         AllTablesFitInRegister &&
5431         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5432 
5433     // If both flags saturate, we're done. NOTE: This *only* works with
5434     // saturating flags, and all flags have to saturate first due to the
5435     // non-deterministic behavior of iterating over a dense map.
5436     if (HasIllegalType && !AllTablesFitInRegister)
5437       break;
5438   }
5439 
5440   // If each table would fit in a register, we should build it anyway.
5441   if (AllTablesFitInRegister)
5442     return true;
5443 
5444   // Don't build a table that doesn't fit in-register if it has illegal types.
5445   if (HasIllegalType)
5446     return false;
5447 
5448   // The table density should be at least 40%. This is the same criterion as for
5449   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5450   // FIXME: Find the best cut-off.
5451   return SI->getNumCases() * 10 >= TableSize * 4;
5452 }
5453 
5454 /// Try to reuse the switch table index compare. Following pattern:
5455 /// \code
5456 ///     if (idx < tablesize)
5457 ///        r = table[idx]; // table does not contain default_value
5458 ///     else
5459 ///        r = default_value;
5460 ///     if (r != default_value)
5461 ///        ...
5462 /// \endcode
5463 /// Is optimized to:
5464 /// \code
5465 ///     cond = idx < tablesize;
5466 ///     if (cond)
5467 ///        r = table[idx];
5468 ///     else
5469 ///        r = default_value;
5470 ///     if (cond)
5471 ///        ...
5472 /// \endcode
5473 /// Jump threading will then eliminate the second if(cond).
5474 static void reuseTableCompare(
5475     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5476     Constant *DefaultValue,
5477     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5478   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5479   if (!CmpInst)
5480     return;
5481 
5482   // We require that the compare is in the same block as the phi so that jump
5483   // threading can do its work afterwards.
5484   if (CmpInst->getParent() != PhiBlock)
5485     return;
5486 
5487   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5488   if (!CmpOp1)
5489     return;
5490 
5491   Value *RangeCmp = RangeCheckBranch->getCondition();
5492   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5493   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5494 
5495   // Check if the compare with the default value is constant true or false.
5496   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5497                                                  DefaultValue, CmpOp1, true);
5498   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5499     return;
5500 
5501   // Check if the compare with the case values is distinct from the default
5502   // compare result.
5503   for (auto ValuePair : Values) {
5504     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5505                                                 ValuePair.second, CmpOp1, true);
5506     if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5507       return;
5508     assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5509            "Expect true or false as compare result.");
5510   }
5511 
5512   // Check if the branch instruction dominates the phi node. It's a simple
5513   // dominance check, but sufficient for our needs.
5514   // Although this check is invariant in the calling loops, it's better to do it
5515   // at this late stage. Practically we do it at most once for a switch.
5516   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5517   for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5518     BasicBlock *Pred = *PI;
5519     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5520       return;
5521   }
5522 
5523   if (DefaultConst == FalseConst) {
5524     // The compare yields the same result. We can replace it.
5525     CmpInst->replaceAllUsesWith(RangeCmp);
5526     ++NumTableCmpReuses;
5527   } else {
5528     // The compare yields the same result, just inverted. We can replace it.
5529     Value *InvertedTableCmp = BinaryOperator::CreateXor(
5530         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5531         RangeCheckBranch);
5532     CmpInst->replaceAllUsesWith(InvertedTableCmp);
5533     ++NumTableCmpReuses;
5534   }
5535 }
5536 
5537 /// If the switch is only used to initialize one or more phi nodes in a common
5538 /// successor block with different constant values, replace the switch with
5539 /// lookup tables.
5540 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5541                                 const DataLayout &DL,
5542                                 const TargetTransformInfo &TTI) {
5543   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5544 
5545   Function *Fn = SI->getParent()->getParent();
5546   // Only build lookup table when we have a target that supports it or the
5547   // attribute is not set.
5548   if (!TTI.shouldBuildLookupTables() ||
5549       (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
5550     return false;
5551 
5552   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5553   // split off a dense part and build a lookup table for that.
5554 
5555   // FIXME: This creates arrays of GEPs to constant strings, which means each
5556   // GEP needs a runtime relocation in PIC code. We should just build one big
5557   // string and lookup indices into that.
5558 
5559   // Ignore switches with less than three cases. Lookup tables will not make
5560   // them faster, so we don't analyze them.
5561   if (SI->getNumCases() < 3)
5562     return false;
5563 
5564   // Figure out the corresponding result for each case value and phi node in the
5565   // common destination, as well as the min and max case values.
5566   assert(!SI->cases().empty());
5567   SwitchInst::CaseIt CI = SI->case_begin();
5568   ConstantInt *MinCaseVal = CI->getCaseValue();
5569   ConstantInt *MaxCaseVal = CI->getCaseValue();
5570 
5571   BasicBlock *CommonDest = nullptr;
5572 
5573   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5574   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5575 
5576   SmallDenseMap<PHINode *, Constant *> DefaultResults;
5577   SmallDenseMap<PHINode *, Type *> ResultTypes;
5578   SmallVector<PHINode *, 4> PHIs;
5579 
5580   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5581     ConstantInt *CaseVal = CI->getCaseValue();
5582     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5583       MinCaseVal = CaseVal;
5584     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5585       MaxCaseVal = CaseVal;
5586 
5587     // Resulting value at phi nodes for this case value.
5588     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5589     ResultsTy Results;
5590     if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5591                         Results, DL, TTI))
5592       return false;
5593 
5594     // Append the result from this case to the list for each phi.
5595     for (const auto &I : Results) {
5596       PHINode *PHI = I.first;
5597       Constant *Value = I.second;
5598       if (!ResultLists.count(PHI))
5599         PHIs.push_back(PHI);
5600       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5601     }
5602   }
5603 
5604   // Keep track of the result types.
5605   for (PHINode *PHI : PHIs) {
5606     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5607   }
5608 
5609   uint64_t NumResults = ResultLists[PHIs[0]].size();
5610   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5611   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5612   bool TableHasHoles = (NumResults < TableSize);
5613 
5614   // If the table has holes, we need a constant result for the default case
5615   // or a bitmask that fits in a register.
5616   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5617   bool HasDefaultResults =
5618       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5619                      DefaultResultsList, DL, TTI);
5620 
5621   bool NeedMask = (TableHasHoles && !HasDefaultResults);
5622   if (NeedMask) {
5623     // As an extra penalty for the validity test we require more cases.
5624     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5625       return false;
5626     if (!DL.fitsInLegalInteger(TableSize))
5627       return false;
5628   }
5629 
5630   for (const auto &I : DefaultResultsList) {
5631     PHINode *PHI = I.first;
5632     Constant *Result = I.second;
5633     DefaultResults[PHI] = Result;
5634   }
5635 
5636   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5637     return false;
5638 
5639   // Create the BB that does the lookups.
5640   Module &Mod = *CommonDest->getParent()->getParent();
5641   BasicBlock *LookupBB = BasicBlock::Create(
5642       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5643 
5644   // Compute the table index value.
5645   Builder.SetInsertPoint(SI);
5646   Value *TableIndex;
5647   if (MinCaseVal->isNullValue())
5648     TableIndex = SI->getCondition();
5649   else
5650     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5651                                    "switch.tableidx");
5652 
5653   // Compute the maximum table size representable by the integer type we are
5654   // switching upon.
5655   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5656   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5657   assert(MaxTableSize >= TableSize &&
5658          "It is impossible for a switch to have more entries than the max "
5659          "representable value of its input integer type's size.");
5660 
5661   // If the default destination is unreachable, or if the lookup table covers
5662   // all values of the conditional variable, branch directly to the lookup table
5663   // BB. Otherwise, check that the condition is within the case range.
5664   const bool DefaultIsReachable =
5665       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5666   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5667   BranchInst *RangeCheckBranch = nullptr;
5668 
5669   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5670     Builder.CreateBr(LookupBB);
5671     // Note: We call removeProdecessor later since we need to be able to get the
5672     // PHI value for the default case in case we're using a bit mask.
5673   } else {
5674     Value *Cmp = Builder.CreateICmpULT(
5675         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5676     RangeCheckBranch =
5677         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5678   }
5679 
5680   // Populate the BB that does the lookups.
5681   Builder.SetInsertPoint(LookupBB);
5682 
5683   if (NeedMask) {
5684     // Before doing the lookup, we do the hole check. The LookupBB is therefore
5685     // re-purposed to do the hole check, and we create a new LookupBB.
5686     BasicBlock *MaskBB = LookupBB;
5687     MaskBB->setName("switch.hole_check");
5688     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5689                                   CommonDest->getParent(), CommonDest);
5690 
5691     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
5692     // unnecessary illegal types.
5693     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5694     APInt MaskInt(TableSizePowOf2, 0);
5695     APInt One(TableSizePowOf2, 1);
5696     // Build bitmask; fill in a 1 bit for every case.
5697     const ResultListTy &ResultList = ResultLists[PHIs[0]];
5698     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5699       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5700                          .getLimitedValue();
5701       MaskInt |= One << Idx;
5702     }
5703     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5704 
5705     // Get the TableIndex'th bit of the bitmask.
5706     // If this bit is 0 (meaning hole) jump to the default destination,
5707     // else continue with table lookup.
5708     IntegerType *MapTy = TableMask->getType();
5709     Value *MaskIndex =
5710         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5711     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5712     Value *LoBit = Builder.CreateTrunc(
5713         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5714     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5715 
5716     Builder.SetInsertPoint(LookupBB);
5717     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5718   }
5719 
5720   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5721     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
5722     // do not delete PHINodes here.
5723     SI->getDefaultDest()->removePredecessor(SI->getParent(),
5724                                             /*KeepOneInputPHIs=*/true);
5725   }
5726 
5727   bool ReturnedEarly = false;
5728   for (PHINode *PHI : PHIs) {
5729     const ResultListTy &ResultList = ResultLists[PHI];
5730 
5731     // If using a bitmask, use any value to fill the lookup table holes.
5732     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5733     StringRef FuncName = Fn->getName();
5734     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5735                             FuncName);
5736 
5737     Value *Result = Table.BuildLookup(TableIndex, Builder);
5738 
5739     // If the result is used to return immediately from the function, we want to
5740     // do that right here.
5741     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5742         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5743       Builder.CreateRet(Result);
5744       ReturnedEarly = true;
5745       break;
5746     }
5747 
5748     // Do a small peephole optimization: re-use the switch table compare if
5749     // possible.
5750     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5751       BasicBlock *PhiBlock = PHI->getParent();
5752       // Search for compare instructions which use the phi.
5753       for (auto *User : PHI->users()) {
5754         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5755       }
5756     }
5757 
5758     PHI->addIncoming(Result, LookupBB);
5759   }
5760 
5761   if (!ReturnedEarly)
5762     Builder.CreateBr(CommonDest);
5763 
5764   // Remove the switch.
5765   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5766     BasicBlock *Succ = SI->getSuccessor(i);
5767 
5768     if (Succ == SI->getDefaultDest())
5769       continue;
5770     Succ->removePredecessor(SI->getParent());
5771   }
5772   SI->eraseFromParent();
5773 
5774   ++NumLookupTables;
5775   if (NeedMask)
5776     ++NumLookupTablesHoles;
5777   return true;
5778 }
5779 
5780 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5781   // See also SelectionDAGBuilder::isDense(), which this function was based on.
5782   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5783   uint64_t Range = Diff + 1;
5784   uint64_t NumCases = Values.size();
5785   // 40% is the default density for building a jump table in optsize/minsize mode.
5786   uint64_t MinDensity = 40;
5787 
5788   return NumCases * 100 >= Range * MinDensity;
5789 }
5790 
5791 /// Try to transform a switch that has "holes" in it to a contiguous sequence
5792 /// of cases.
5793 ///
5794 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5795 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5796 ///
5797 /// This converts a sparse switch into a dense switch which allows better
5798 /// lowering and could also allow transforming into a lookup table.
5799 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5800                               const DataLayout &DL,
5801                               const TargetTransformInfo &TTI) {
5802   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5803   if (CondTy->getIntegerBitWidth() > 64 ||
5804       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5805     return false;
5806   // Only bother with this optimization if there are more than 3 switch cases;
5807   // SDAG will only bother creating jump tables for 4 or more cases.
5808   if (SI->getNumCases() < 4)
5809     return false;
5810 
5811   // This transform is agnostic to the signedness of the input or case values. We
5812   // can treat the case values as signed or unsigned. We can optimize more common
5813   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5814   // as signed.
5815   SmallVector<int64_t,4> Values;
5816   for (auto &C : SI->cases())
5817     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5818   llvm::sort(Values);
5819 
5820   // If the switch is already dense, there's nothing useful to do here.
5821   if (isSwitchDense(Values))
5822     return false;
5823 
5824   // First, transform the values such that they start at zero and ascend.
5825   int64_t Base = Values[0];
5826   for (auto &V : Values)
5827     V -= (uint64_t)(Base);
5828 
5829   // Now we have signed numbers that have been shifted so that, given enough
5830   // precision, there are no negative values. Since the rest of the transform
5831   // is bitwise only, we switch now to an unsigned representation.
5832 
5833   // This transform can be done speculatively because it is so cheap - it
5834   // results in a single rotate operation being inserted.
5835   // FIXME: It's possible that optimizing a switch on powers of two might also
5836   // be beneficial - flag values are often powers of two and we could use a CLZ
5837   // as the key function.
5838 
5839   // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
5840   // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
5841   // less than 64.
5842   unsigned Shift = 64;
5843   for (auto &V : Values)
5844     Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
5845   assert(Shift < 64);
5846   if (Shift > 0)
5847     for (auto &V : Values)
5848       V = (int64_t)((uint64_t)V >> Shift);
5849 
5850   if (!isSwitchDense(Values))
5851     // Transform didn't create a dense switch.
5852     return false;
5853 
5854   // The obvious transform is to shift the switch condition right and emit a
5855   // check that the condition actually cleanly divided by GCD, i.e.
5856   //   C & (1 << Shift - 1) == 0
5857   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5858   //
5859   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5860   // shift and puts the shifted-off bits in the uppermost bits. If any of these
5861   // are nonzero then the switch condition will be very large and will hit the
5862   // default case.
5863 
5864   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5865   Builder.SetInsertPoint(SI);
5866   auto *ShiftC = ConstantInt::get(Ty, Shift);
5867   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
5868   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5869   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5870   auto *Rot = Builder.CreateOr(LShr, Shl);
5871   SI->replaceUsesOfWith(SI->getCondition(), Rot);
5872 
5873   for (auto Case : SI->cases()) {
5874     auto *Orig = Case.getCaseValue();
5875     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
5876     Case.setValue(
5877         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5878   }
5879   return true;
5880 }
5881 
5882 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
5883   BasicBlock *BB = SI->getParent();
5884 
5885   if (isValueEqualityComparison(SI)) {
5886     // If we only have one predecessor, and if it is a branch on this value,
5887     // see if that predecessor totally determines the outcome of this switch.
5888     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5889       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5890         return requestResimplify();
5891 
5892     Value *Cond = SI->getCondition();
5893     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5894       if (SimplifySwitchOnSelect(SI, Select))
5895         return requestResimplify();
5896 
5897     // If the block only contains the switch, see if we can fold the block
5898     // away into any preds.
5899     if (SI == &*BB->instructionsWithoutDebug().begin())
5900       if (FoldValueComparisonIntoPredecessors(SI, Builder))
5901         return requestResimplify();
5902   }
5903 
5904   // Try to transform the switch into an icmp and a branch.
5905   if (TurnSwitchRangeIntoICmp(SI, Builder))
5906     return requestResimplify();
5907 
5908   // Remove unreachable cases.
5909   if (eliminateDeadSwitchCases(SI, Options.AC, DL))
5910     return requestResimplify();
5911 
5912   if (switchToSelect(SI, Builder, DL, TTI))
5913     return requestResimplify();
5914 
5915   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
5916     return requestResimplify();
5917 
5918   // The conversion from switch to lookup tables results in difficult-to-analyze
5919   // code and makes pruning branches much harder. This is a problem if the
5920   // switch expression itself can still be restricted as a result of inlining or
5921   // CVP. Therefore, only apply this transformation during late stages of the
5922   // optimisation pipeline.
5923   if (Options.ConvertSwitchToLookupTable &&
5924       SwitchToLookupTable(SI, Builder, DL, TTI))
5925     return requestResimplify();
5926 
5927   if (ReduceSwitchRange(SI, Builder, DL, TTI))
5928     return requestResimplify();
5929 
5930   return false;
5931 }
5932 
5933 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
5934   BasicBlock *BB = IBI->getParent();
5935   bool Changed = false;
5936 
5937   // Eliminate redundant destinations.
5938   SmallPtrSet<Value *, 8> Succs;
5939   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5940     BasicBlock *Dest = IBI->getDestination(i);
5941     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
5942       Dest->removePredecessor(BB);
5943       IBI->removeDestination(i);
5944       --i;
5945       --e;
5946       Changed = true;
5947     }
5948   }
5949 
5950   if (IBI->getNumDestinations() == 0) {
5951     // If the indirectbr has no successors, change it to unreachable.
5952     new UnreachableInst(IBI->getContext(), IBI);
5953     EraseTerminatorAndDCECond(IBI);
5954     return true;
5955   }
5956 
5957   if (IBI->getNumDestinations() == 1) {
5958     // If the indirectbr has one successor, change it to a direct branch.
5959     BranchInst::Create(IBI->getDestination(0), IBI);
5960     EraseTerminatorAndDCECond(IBI);
5961     return true;
5962   }
5963 
5964   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5965     if (SimplifyIndirectBrOnSelect(IBI, SI))
5966       return requestResimplify();
5967   }
5968   return Changed;
5969 }
5970 
5971 /// Given an block with only a single landing pad and a unconditional branch
5972 /// try to find another basic block which this one can be merged with.  This
5973 /// handles cases where we have multiple invokes with unique landing pads, but
5974 /// a shared handler.
5975 ///
5976 /// We specifically choose to not worry about merging non-empty blocks
5977 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
5978 /// practice, the optimizer produces empty landing pad blocks quite frequently
5979 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
5980 /// sinking in this file)
5981 ///
5982 /// This is primarily a code size optimization.  We need to avoid performing
5983 /// any transform which might inhibit optimization (such as our ability to
5984 /// specialize a particular handler via tail commoning).  We do this by not
5985 /// merging any blocks which require us to introduce a phi.  Since the same
5986 /// values are flowing through both blocks, we don't lose any ability to
5987 /// specialize.  If anything, we make such specialization more likely.
5988 ///
5989 /// TODO - This transformation could remove entries from a phi in the target
5990 /// block when the inputs in the phi are the same for the two blocks being
5991 /// merged.  In some cases, this could result in removal of the PHI entirely.
5992 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5993                                  BasicBlock *BB) {
5994   auto Succ = BB->getUniqueSuccessor();
5995   assert(Succ);
5996   // If there's a phi in the successor block, we'd likely have to introduce
5997   // a phi into the merged landing pad block.
5998   if (isa<PHINode>(*Succ->begin()))
5999     return false;
6000 
6001   for (BasicBlock *OtherPred : predecessors(Succ)) {
6002     if (BB == OtherPred)
6003       continue;
6004     BasicBlock::iterator I = OtherPred->begin();
6005     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6006     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6007       continue;
6008     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6009       ;
6010     BranchInst *BI2 = dyn_cast<BranchInst>(I);
6011     if (!BI2 || !BI2->isIdenticalTo(BI))
6012       continue;
6013 
6014     // We've found an identical block.  Update our predecessors to take that
6015     // path instead and make ourselves dead.
6016     SmallPtrSet<BasicBlock *, 16> Preds;
6017     Preds.insert(pred_begin(BB), pred_end(BB));
6018     for (BasicBlock *Pred : Preds) {
6019       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6020       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
6021              "unexpected successor");
6022       II->setUnwindDest(OtherPred);
6023     }
6024 
6025     // The debug info in OtherPred doesn't cover the merged control flow that
6026     // used to go through BB.  We need to delete it or update it.
6027     for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
6028       Instruction &Inst = *I;
6029       I++;
6030       if (isa<DbgInfoIntrinsic>(Inst))
6031         Inst.eraseFromParent();
6032     }
6033 
6034     SmallPtrSet<BasicBlock *, 16> Succs;
6035     Succs.insert(succ_begin(BB), succ_end(BB));
6036     for (BasicBlock *Succ : Succs) {
6037       Succ->removePredecessor(BB);
6038     }
6039 
6040     IRBuilder<> Builder(BI);
6041     Builder.CreateUnreachable();
6042     BI->eraseFromParent();
6043     return true;
6044   }
6045   return false;
6046 }
6047 
6048 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6049   return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6050                                    : simplifyCondBranch(Branch, Builder);
6051 }
6052 
6053 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6054                                           IRBuilder<> &Builder) {
6055   BasicBlock *BB = BI->getParent();
6056   BasicBlock *Succ = BI->getSuccessor(0);
6057 
6058   // If the Terminator is the only non-phi instruction, simplify the block.
6059   // If LoopHeader is provided, check if the block or its successor is a loop
6060   // header. (This is for early invocations before loop simplify and
6061   // vectorization to keep canonical loop forms for nested loops. These blocks
6062   // can be eliminated when the pass is invoked later in the back-end.)
6063   // Note that if BB has only one predecessor then we do not introduce new
6064   // backedge, so we can eliminate BB.
6065   bool NeedCanonicalLoop =
6066       Options.NeedCanonicalLoop &&
6067       (LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
6068        (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
6069   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
6070   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6071       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
6072     return true;
6073 
6074   // If the only instruction in the block is a seteq/setne comparison against a
6075   // constant, try to simplify the block.
6076   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6077     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6078       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6079         ;
6080       if (I->isTerminator() &&
6081           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6082         return true;
6083     }
6084 
6085   // See if we can merge an empty landing pad block with another which is
6086   // equivalent.
6087   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6088     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6089       ;
6090     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
6091       return true;
6092   }
6093 
6094   // If this basic block is ONLY a compare and a branch, and if a predecessor
6095   // branches to us and our successor, fold the comparison into the
6096   // predecessor and use logical operations to update the incoming value
6097   // for PHI nodes in common successor.
6098   if (FoldBranchToCommonDest(BI, nullptr, &TTI, Options.BonusInstThreshold))
6099     return requestResimplify();
6100   return false;
6101 }
6102 
6103 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6104   BasicBlock *PredPred = nullptr;
6105   for (auto *P : predecessors(BB)) {
6106     BasicBlock *PPred = P->getSinglePredecessor();
6107     if (!PPred || (PredPred && PredPred != PPred))
6108       return nullptr;
6109     PredPred = PPred;
6110   }
6111   return PredPred;
6112 }
6113 
6114 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6115   BasicBlock *BB = BI->getParent();
6116   if (!Options.SimplifyCondBranch)
6117     return false;
6118 
6119   // Conditional branch
6120   if (isValueEqualityComparison(BI)) {
6121     // If we only have one predecessor, and if it is a branch on this value,
6122     // see if that predecessor totally determines the outcome of this
6123     // switch.
6124     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6125       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6126         return requestResimplify();
6127 
6128     // This block must be empty, except for the setcond inst, if it exists.
6129     // Ignore dbg intrinsics.
6130     auto I = BB->instructionsWithoutDebug().begin();
6131     if (&*I == BI) {
6132       if (FoldValueComparisonIntoPredecessors(BI, Builder))
6133         return requestResimplify();
6134     } else if (&*I == cast<Instruction>(BI->getCondition())) {
6135       ++I;
6136       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6137         return requestResimplify();
6138     }
6139   }
6140 
6141   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6142   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6143     return true;
6144 
6145   // If this basic block has dominating predecessor blocks and the dominating
6146   // blocks' conditions imply BI's condition, we know the direction of BI.
6147   Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6148   if (Imp) {
6149     // Turn this into a branch on constant.
6150     auto *OldCond = BI->getCondition();
6151     ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6152                              : ConstantInt::getFalse(BB->getContext());
6153     BI->setCondition(TorF);
6154     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6155     return requestResimplify();
6156   }
6157 
6158   // If this basic block is ONLY a compare and a branch, and if a predecessor
6159   // branches to us and one of our successors, fold the comparison into the
6160   // predecessor and use logical operations to pick the right destination.
6161   if (FoldBranchToCommonDest(BI, nullptr, &TTI, Options.BonusInstThreshold))
6162     return requestResimplify();
6163 
6164   // We have a conditional branch to two blocks that are only reachable
6165   // from BI.  We know that the condbr dominates the two blocks, so see if
6166   // there is any identical code in the "then" and "else" blocks.  If so, we
6167   // can hoist it up to the branching block.
6168   if (BI->getSuccessor(0)->getSinglePredecessor()) {
6169     if (BI->getSuccessor(1)->getSinglePredecessor()) {
6170       if (HoistCommon && Options.HoistCommonInsts)
6171         if (HoistThenElseCodeToIf(BI, TTI))
6172           return requestResimplify();
6173     } else {
6174       // If Successor #1 has multiple preds, we may be able to conditionally
6175       // execute Successor #0 if it branches to Successor #1.
6176       Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6177       if (Succ0TI->getNumSuccessors() == 1 &&
6178           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6179         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6180           return requestResimplify();
6181     }
6182   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6183     // If Successor #0 has multiple preds, we may be able to conditionally
6184     // execute Successor #1 if it branches to Successor #0.
6185     Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6186     if (Succ1TI->getNumSuccessors() == 1 &&
6187         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6188       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6189         return requestResimplify();
6190   }
6191 
6192   // If this is a branch on a phi node in the current block, thread control
6193   // through this block if any PHI node entries are constants.
6194   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6195     if (PN->getParent() == BI->getParent())
6196       if (FoldCondBranchOnPHI(BI, DL, Options.AC))
6197         return requestResimplify();
6198 
6199   // Scan predecessor blocks for conditional branches.
6200   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
6201     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
6202       if (PBI != BI && PBI->isConditional())
6203         if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI))
6204           return requestResimplify();
6205 
6206   // Look for diamond patterns.
6207   if (MergeCondStores)
6208     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6209       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6210         if (PBI != BI && PBI->isConditional())
6211           if (mergeConditionalStores(PBI, BI, DL, TTI))
6212             return requestResimplify();
6213 
6214   return false;
6215 }
6216 
6217 /// Check if passing a value to an instruction will cause undefined behavior.
6218 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
6219   Constant *C = dyn_cast<Constant>(V);
6220   if (!C)
6221     return false;
6222 
6223   if (I->use_empty())
6224     return false;
6225 
6226   if (C->isNullValue() || isa<UndefValue>(C)) {
6227     // Only look at the first use, avoid hurting compile time with long uselists
6228     User *Use = *I->user_begin();
6229 
6230     // Now make sure that there are no instructions in between that can alter
6231     // control flow (eg. calls)
6232     for (BasicBlock::iterator
6233              i = ++BasicBlock::iterator(I),
6234              UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
6235          i != UI; ++i)
6236       if (i == I->getParent()->end() || i->mayHaveSideEffects())
6237         return false;
6238 
6239     // Look through GEPs. A load from a GEP derived from NULL is still undefined
6240     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6241       if (GEP->getPointerOperand() == I)
6242         return passingValueIsAlwaysUndefined(V, GEP);
6243 
6244     // Look through bitcasts.
6245     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6246       return passingValueIsAlwaysUndefined(V, BC);
6247 
6248     // Load from null is undefined.
6249     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6250       if (!LI->isVolatile())
6251         return !NullPointerIsDefined(LI->getFunction(),
6252                                      LI->getPointerAddressSpace());
6253 
6254     // Store to null is undefined.
6255     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6256       if (!SI->isVolatile())
6257         return (!NullPointerIsDefined(SI->getFunction(),
6258                                       SI->getPointerAddressSpace())) &&
6259                SI->getPointerOperand() == I;
6260 
6261     // A call to null is undefined.
6262     if (auto *CB = dyn_cast<CallBase>(Use))
6263       return !NullPointerIsDefined(CB->getFunction()) &&
6264              CB->getCalledOperand() == I;
6265   }
6266   return false;
6267 }
6268 
6269 /// If BB has an incoming value that will always trigger undefined behavior
6270 /// (eg. null pointer dereference), remove the branch leading here.
6271 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
6272   for (PHINode &PHI : BB->phis())
6273     for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6274       if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6275         Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
6276         IRBuilder<> Builder(T);
6277         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6278           BB->removePredecessor(PHI.getIncomingBlock(i));
6279           // Turn uncoditional branches into unreachables and remove the dead
6280           // destination from conditional branches.
6281           if (BI->isUnconditional())
6282             Builder.CreateUnreachable();
6283           else
6284             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
6285                                                        : BI->getSuccessor(0));
6286           BI->eraseFromParent();
6287           return true;
6288         }
6289         // TODO: SwitchInst.
6290       }
6291 
6292   return false;
6293 }
6294 
6295 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
6296   bool Changed = false;
6297 
6298   assert(BB && BB->getParent() && "Block not embedded in function!");
6299   assert(BB->getTerminator() && "Degenerate basic block encountered!");
6300 
6301   // Remove basic blocks that have no predecessors (except the entry block)...
6302   // or that just have themself as a predecessor.  These are unreachable.
6303   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
6304       BB->getSinglePredecessor() == BB) {
6305     LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
6306     DeleteDeadBlock(BB);
6307     return true;
6308   }
6309 
6310   // Check to see if we can constant propagate this terminator instruction
6311   // away...
6312   Changed |= ConstantFoldTerminator(BB, true);
6313 
6314   // Check for and eliminate duplicate PHI nodes in this block.
6315   Changed |= EliminateDuplicatePHINodes(BB);
6316 
6317   // Check for and remove branches that will always cause undefined behavior.
6318   Changed |= removeUndefIntroducingPredecessor(BB);
6319 
6320   // Merge basic blocks into their predecessor if there is only one distinct
6321   // pred, and if there is only one distinct successor of the predecessor, and
6322   // if there are no PHI nodes.
6323   if (MergeBlockIntoPredecessor(BB))
6324     return true;
6325 
6326   if (SinkCommon && Options.SinkCommonInsts)
6327     Changed |= SinkCommonCodeFromPredecessors(BB);
6328 
6329   IRBuilder<> Builder(BB);
6330 
6331   if (Options.FoldTwoEntryPHINode) {
6332     // If there is a trivial two-entry PHI node in this basic block, and we can
6333     // eliminate it, do so now.
6334     if (auto *PN = dyn_cast<PHINode>(BB->begin()))
6335       if (PN->getNumIncomingValues() == 2)
6336         Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
6337   }
6338 
6339   Instruction *Terminator = BB->getTerminator();
6340   Builder.SetInsertPoint(Terminator);
6341   switch (Terminator->getOpcode()) {
6342   case Instruction::Br:
6343     Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
6344     break;
6345   case Instruction::Ret:
6346     Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder);
6347     break;
6348   case Instruction::Resume:
6349     Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
6350     break;
6351   case Instruction::CleanupRet:
6352     Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
6353     break;
6354   case Instruction::Switch:
6355     Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
6356     break;
6357   case Instruction::Unreachable:
6358     Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
6359     break;
6360   case Instruction::IndirectBr:
6361     Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
6362     break;
6363   }
6364 
6365   return Changed;
6366 }
6367 
6368 bool SimplifyCFGOpt::run(BasicBlock *BB) {
6369   bool Changed = false;
6370 
6371   // Repeated simplify BB as long as resimplification is requested.
6372   do {
6373     Resimplify = false;
6374 
6375     // Perform one round of simplifcation. Resimplify flag will be set if
6376     // another iteration is requested.
6377     Changed |= simplifyOnce(BB);
6378   } while (Resimplify);
6379 
6380   return Changed;
6381 }
6382 
6383 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6384                        const SimplifyCFGOptions &Options,
6385                        SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
6386   return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
6387                         Options)
6388       .run(BB);
6389 }
6390