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