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       PStore->getValueOperand()->getType() !=
3737           QStore->getValueOperand()->getType())
3738     return false;
3739 
3740   // Check that sinking the store won't cause program behavior changes. Sinking
3741   // the store out of the Q blocks won't change any behavior as we're sinking
3742   // from a block to its unconditional successor. But we're moving a store from
3743   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3744   // So we need to check that there are no aliasing loads or stores in
3745   // QBI, QTB and QFB. We also need to check there are no conflicting memory
3746   // operations between PStore and the end of its parent block.
3747   //
3748   // The ideal way to do this is to query AliasAnalysis, but we don't
3749   // preserve AA currently so that is dangerous. Be super safe and just
3750   // check there are no other memory operations at all.
3751   for (auto &I : *QFB->getSinglePredecessor())
3752     if (I.mayReadOrWriteMemory())
3753       return false;
3754   for (auto &I : *QFB)
3755     if (&I != QStore && I.mayReadOrWriteMemory())
3756       return false;
3757   if (QTB)
3758     for (auto &I : *QTB)
3759       if (&I != QStore && I.mayReadOrWriteMemory())
3760         return false;
3761   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3762        I != E; ++I)
3763     if (&*I != PStore && I->mayReadOrWriteMemory())
3764       return false;
3765 
3766   // If we're not in aggressive mode, we only optimize if we have some
3767   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3768   auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3769     if (!BB)
3770       return true;
3771     // Heuristic: if the block can be if-converted/phi-folded and the
3772     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3773     // thread this store.
3774     InstructionCost Cost = 0;
3775     InstructionCost Budget =
3776         PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3777     for (auto &I : BB->instructionsWithoutDebug(false)) {
3778       // Consider terminator instruction to be free.
3779       if (I.isTerminator())
3780         continue;
3781       // If this is one the stores that we want to speculate out of this BB,
3782       // then don't count it's cost, consider it to be free.
3783       if (auto *S = dyn_cast<StoreInst>(&I))
3784         if (llvm::find(FreeStores, S))
3785           continue;
3786       // Else, we have a white-list of instructions that we are ak speculating.
3787       if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3788         return false; // Not in white-list - not worthwhile folding.
3789       // And finally, if this is a non-free instruction that we are okay
3790       // speculating, ensure that we consider the speculation budget.
3791       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3792       if (Cost > Budget)
3793         return false; // Eagerly refuse to fold as soon as we're out of budget.
3794     }
3795     assert(Cost <= Budget &&
3796            "When we run out of budget we will eagerly return from within the "
3797            "per-instruction loop.");
3798     return true;
3799   };
3800 
3801   const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3802   if (!MergeCondStoresAggressively &&
3803       (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3804        !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3805     return false;
3806 
3807   // If PostBB has more than two predecessors, we need to split it so we can
3808   // sink the store.
3809   if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3810     // We know that QFB's only successor is PostBB. And QFB has a single
3811     // predecessor. If QTB exists, then its only successor is also PostBB.
3812     // If QTB does not exist, then QFB's only predecessor has a conditional
3813     // branch to QFB and PostBB.
3814     BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3815     BasicBlock *NewBB =
3816         SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3817     if (!NewBB)
3818       return false;
3819     PostBB = NewBB;
3820   }
3821 
3822   // OK, we're going to sink the stores to PostBB. The store has to be
3823   // conditional though, so first create the predicate.
3824   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3825                      ->getCondition();
3826   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3827                      ->getCondition();
3828 
3829   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3830                                                 PStore->getParent());
3831   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3832                                                 QStore->getParent(), PPHI);
3833 
3834   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3835 
3836   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3837   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3838 
3839   if (InvertPCond)
3840     PPred = QB.CreateNot(PPred);
3841   if (InvertQCond)
3842     QPred = QB.CreateNot(QPred);
3843   Value *CombinedPred = QB.CreateOr(PPred, QPred);
3844 
3845   auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
3846                                       /*Unreachable=*/false,
3847                                       /*BranchWeights=*/nullptr, DTU);
3848   QB.SetInsertPoint(T);
3849   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3850   SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
3851   // Choose the minimum alignment. If we could prove both stores execute, we
3852   // could use biggest one.  In this case, though, we only know that one of the
3853   // stores executes.  And we don't know it's safe to take the alignment from a
3854   // store that doesn't execute.
3855   SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3856 
3857   QStore->eraseFromParent();
3858   PStore->eraseFromParent();
3859 
3860   return true;
3861 }
3862 
3863 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3864                                    DomTreeUpdater *DTU, const DataLayout &DL,
3865                                    const TargetTransformInfo &TTI) {
3866   // The intention here is to find diamonds or triangles (see below) where each
3867   // conditional block contains a store to the same address. Both of these
3868   // stores are conditional, so they can't be unconditionally sunk. But it may
3869   // be profitable to speculatively sink the stores into one merged store at the
3870   // end, and predicate the merged store on the union of the two conditions of
3871   // PBI and QBI.
3872   //
3873   // This can reduce the number of stores executed if both of the conditions are
3874   // true, and can allow the blocks to become small enough to be if-converted.
3875   // This optimization will also chain, so that ladders of test-and-set
3876   // sequences can be if-converted away.
3877   //
3878   // We only deal with simple diamonds or triangles:
3879   //
3880   //     PBI       or      PBI        or a combination of the two
3881   //    /   \               | \
3882   //   PTB  PFB             |  PFB
3883   //    \   /               | /
3884   //     QBI                QBI
3885   //    /  \                | \
3886   //   QTB  QFB             |  QFB
3887   //    \  /                | /
3888   //    PostBB            PostBB
3889   //
3890   // We model triangles as a type of diamond with a nullptr "true" block.
3891   // Triangles are canonicalized so that the fallthrough edge is represented by
3892   // a true condition, as in the diagram above.
3893   BasicBlock *PTB = PBI->getSuccessor(0);
3894   BasicBlock *PFB = PBI->getSuccessor(1);
3895   BasicBlock *QTB = QBI->getSuccessor(0);
3896   BasicBlock *QFB = QBI->getSuccessor(1);
3897   BasicBlock *PostBB = QFB->getSingleSuccessor();
3898 
3899   // Make sure we have a good guess for PostBB. If QTB's only successor is
3900   // QFB, then QFB is a better PostBB.
3901   if (QTB->getSingleSuccessor() == QFB)
3902     PostBB = QFB;
3903 
3904   // If we couldn't find a good PostBB, stop.
3905   if (!PostBB)
3906     return false;
3907 
3908   bool InvertPCond = false, InvertQCond = false;
3909   // Canonicalize fallthroughs to the true branches.
3910   if (PFB == QBI->getParent()) {
3911     std::swap(PFB, PTB);
3912     InvertPCond = true;
3913   }
3914   if (QFB == PostBB) {
3915     std::swap(QFB, QTB);
3916     InvertQCond = true;
3917   }
3918 
3919   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3920   // and QFB may not. Model fallthroughs as a nullptr block.
3921   if (PTB == QBI->getParent())
3922     PTB = nullptr;
3923   if (QTB == PostBB)
3924     QTB = nullptr;
3925 
3926   // Legality bailouts. We must have at least the non-fallthrough blocks and
3927   // the post-dominating block, and the non-fallthroughs must only have one
3928   // predecessor.
3929   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3930     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3931   };
3932   if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3933       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3934     return false;
3935   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3936       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3937     return false;
3938   if (!QBI->getParent()->hasNUses(2))
3939     return false;
3940 
3941   // OK, this is a sequence of two diamonds or triangles.
3942   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3943   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3944   for (auto *BB : {PTB, PFB}) {
3945     if (!BB)
3946       continue;
3947     for (auto &I : *BB)
3948       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3949         PStoreAddresses.insert(SI->getPointerOperand());
3950   }
3951   for (auto *BB : {QTB, QFB}) {
3952     if (!BB)
3953       continue;
3954     for (auto &I : *BB)
3955       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3956         QStoreAddresses.insert(SI->getPointerOperand());
3957   }
3958 
3959   set_intersect(PStoreAddresses, QStoreAddresses);
3960   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3961   // clear what it contains.
3962   auto &CommonAddresses = PStoreAddresses;
3963 
3964   bool Changed = false;
3965   for (auto *Address : CommonAddresses)
3966     Changed |=
3967         mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
3968                                        InvertPCond, InvertQCond, DTU, DL, TTI);
3969   return Changed;
3970 }
3971 
3972 /// If the previous block ended with a widenable branch, determine if reusing
3973 /// the target block is profitable and legal.  This will have the effect of
3974 /// "widening" PBI, but doesn't require us to reason about hosting safety.
3975 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3976                                            DomTreeUpdater *DTU) {
3977   // TODO: This can be generalized in two important ways:
3978   // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3979   //    values from the PBI edge.
3980   // 2) We can sink side effecting instructions into BI's fallthrough
3981   //    successor provided they doesn't contribute to computation of
3982   //    BI's condition.
3983   Value *CondWB, *WC;
3984   BasicBlock *IfTrueBB, *IfFalseBB;
3985   if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3986       IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3987     return false;
3988   if (!IfFalseBB->phis().empty())
3989     return false; // TODO
3990   // Use lambda to lazily compute expensive condition after cheap ones.
3991   auto NoSideEffects = [](BasicBlock &BB) {
3992     return llvm::none_of(BB, [](const Instruction &I) {
3993         return I.mayWriteToMemory() || I.mayHaveSideEffects();
3994       });
3995   };
3996   if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
3997       BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
3998       NoSideEffects(*BI->getParent())) {
3999     auto *OldSuccessor = BI->getSuccessor(1);
4000     OldSuccessor->removePredecessor(BI->getParent());
4001     BI->setSuccessor(1, IfFalseBB);
4002     if (DTU)
4003       DTU->applyUpdates(
4004           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4005            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4006     return true;
4007   }
4008   if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4009       BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4010       NoSideEffects(*BI->getParent())) {
4011     auto *OldSuccessor = BI->getSuccessor(0);
4012     OldSuccessor->removePredecessor(BI->getParent());
4013     BI->setSuccessor(0, IfFalseBB);
4014     if (DTU)
4015       DTU->applyUpdates(
4016           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4017            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4018     return true;
4019   }
4020   return false;
4021 }
4022 
4023 /// If we have a conditional branch as a predecessor of another block,
4024 /// this function tries to simplify it.  We know
4025 /// that PBI and BI are both conditional branches, and BI is in one of the
4026 /// successor blocks of PBI - PBI branches to BI.
4027 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
4028                                            DomTreeUpdater *DTU,
4029                                            const DataLayout &DL,
4030                                            const TargetTransformInfo &TTI) {
4031   assert(PBI->isConditional() && BI->isConditional());
4032   BasicBlock *BB = BI->getParent();
4033 
4034   // If this block ends with a branch instruction, and if there is a
4035   // predecessor that ends on a branch of the same condition, make
4036   // this conditional branch redundant.
4037   if (PBI->getCondition() == BI->getCondition() &&
4038       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4039     // Okay, the outcome of this conditional branch is statically
4040     // knowable.  If this block had a single pred, handle specially.
4041     if (BB->getSinglePredecessor()) {
4042       // Turn this into a branch on constant.
4043       bool CondIsTrue = PBI->getSuccessor(0) == BB;
4044       BI->setCondition(
4045           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4046       return true; // Nuke the branch on constant.
4047     }
4048 
4049     // Otherwise, if there are multiple predecessors, insert a PHI that merges
4050     // in the constant and simplify the block result.  Subsequent passes of
4051     // simplifycfg will thread the block.
4052     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
4053       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
4054       PHINode *NewPN = PHINode::Create(
4055           Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
4056           BI->getCondition()->getName() + ".pr", &BB->front());
4057       // Okay, we're going to insert the PHI node.  Since PBI is not the only
4058       // predecessor, compute the PHI'd conditional value for all of the preds.
4059       // Any predecessor where the condition is not computable we keep symbolic.
4060       for (pred_iterator PI = PB; PI != PE; ++PI) {
4061         BasicBlock *P = *PI;
4062         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
4063             PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
4064             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4065           bool CondIsTrue = PBI->getSuccessor(0) == BB;
4066           NewPN->addIncoming(
4067               ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
4068               P);
4069         } else {
4070           NewPN->addIncoming(BI->getCondition(), P);
4071         }
4072       }
4073 
4074       BI->setCondition(NewPN);
4075       return true;
4076     }
4077   }
4078 
4079   // If the previous block ended with a widenable branch, determine if reusing
4080   // the target block is profitable and legal.  This will have the effect of
4081   // "widening" PBI, but doesn't require us to reason about hosting safety.
4082   if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4083     return true;
4084 
4085   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
4086     if (CE->canTrap())
4087       return false;
4088 
4089   // If both branches are conditional and both contain stores to the same
4090   // address, remove the stores from the conditionals and create a conditional
4091   // merged store at the end.
4092   if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4093     return true;
4094 
4095   // If this is a conditional branch in an empty block, and if any
4096   // predecessors are a conditional branch to one of our destinations,
4097   // fold the conditions into logical ops and one cond br.
4098 
4099   // Ignore dbg intrinsics.
4100   if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4101     return false;
4102 
4103   int PBIOp, BIOp;
4104   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4105     PBIOp = 0;
4106     BIOp = 0;
4107   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4108     PBIOp = 0;
4109     BIOp = 1;
4110   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4111     PBIOp = 1;
4112     BIOp = 0;
4113   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4114     PBIOp = 1;
4115     BIOp = 1;
4116   } else {
4117     return false;
4118   }
4119 
4120   // Check to make sure that the other destination of this branch
4121   // isn't BB itself.  If so, this is an infinite loop that will
4122   // keep getting unwound.
4123   if (PBI->getSuccessor(PBIOp) == BB)
4124     return false;
4125 
4126   // Do not perform this transformation if it would require
4127   // insertion of a large number of select instructions. For targets
4128   // without predication/cmovs, this is a big pessimization.
4129 
4130   // Also do not perform this transformation if any phi node in the common
4131   // destination block can trap when reached by BB or PBB (PR17073). In that
4132   // case, it would be unsafe to hoist the operation into a select instruction.
4133 
4134   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4135   BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4136   unsigned NumPhis = 0;
4137   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4138        ++II, ++NumPhis) {
4139     if (NumPhis > 2) // Disable this xform.
4140       return false;
4141 
4142     PHINode *PN = cast<PHINode>(II);
4143     Value *BIV = PN->getIncomingValueForBlock(BB);
4144     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
4145       if (CE->canTrap())
4146         return false;
4147 
4148     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
4149     Value *PBIV = PN->getIncomingValue(PBBIdx);
4150     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
4151       if (CE->canTrap())
4152         return false;
4153   }
4154 
4155   // Finally, if everything is ok, fold the branches to logical ops.
4156   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4157 
4158   LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4159                     << "AND: " << *BI->getParent());
4160 
4161   SmallVector<DominatorTree::UpdateType, 5> Updates;
4162 
4163   // If OtherDest *is* BB, then BB is a basic block with a single conditional
4164   // branch in it, where one edge (OtherDest) goes back to itself but the other
4165   // exits.  We don't *know* that the program avoids the infinite loop
4166   // (even though that seems likely).  If we do this xform naively, we'll end up
4167   // recursively unpeeling the loop.  Since we know that (after the xform is
4168   // done) that the block *is* infinite if reached, we just make it an obviously
4169   // infinite loop with no cond branch.
4170   if (OtherDest == BB) {
4171     // Insert it at the end of the function, because it's either code,
4172     // or it won't matter if it's hot. :)
4173     BasicBlock *InfLoopBlock =
4174         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4175     BranchInst::Create(InfLoopBlock, InfLoopBlock);
4176     if (DTU)
4177       Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4178     OtherDest = InfLoopBlock;
4179   }
4180 
4181   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4182 
4183   // BI may have other predecessors.  Because of this, we leave
4184   // it alone, but modify PBI.
4185 
4186   // Make sure we get to CommonDest on True&True directions.
4187   Value *PBICond = PBI->getCondition();
4188   IRBuilder<NoFolder> Builder(PBI);
4189   if (PBIOp)
4190     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4191 
4192   Value *BICond = BI->getCondition();
4193   if (BIOp)
4194     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4195 
4196   // Merge the conditions.
4197   Value *Cond =
4198       createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4199 
4200   // Modify PBI to branch on the new condition to the new dests.
4201   PBI->setCondition(Cond);
4202   PBI->setSuccessor(0, CommonDest);
4203   PBI->setSuccessor(1, OtherDest);
4204 
4205   if (DTU) {
4206     Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4207     Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4208 
4209     DTU->applyUpdates(Updates);
4210   }
4211 
4212   // Update branch weight for PBI.
4213   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4214   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4215   bool HasWeights =
4216       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4217                              SuccTrueWeight, SuccFalseWeight);
4218   if (HasWeights) {
4219     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4220     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4221     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4222     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4223     // The weight to CommonDest should be PredCommon * SuccTotal +
4224     //                                    PredOther * SuccCommon.
4225     // The weight to OtherDest should be PredOther * SuccOther.
4226     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4227                                   PredOther * SuccCommon,
4228                               PredOther * SuccOther};
4229     // Halve the weights if any of them cannot fit in an uint32_t
4230     FitWeights(NewWeights);
4231 
4232     setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4233   }
4234 
4235   // OtherDest may have phi nodes.  If so, add an entry from PBI's
4236   // block that are identical to the entries for BI's block.
4237   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4238 
4239   // We know that the CommonDest already had an edge from PBI to
4240   // it.  If it has PHIs though, the PHIs may have different
4241   // entries for BB and PBI's BB.  If so, insert a select to make
4242   // them agree.
4243   for (PHINode &PN : CommonDest->phis()) {
4244     Value *BIV = PN.getIncomingValueForBlock(BB);
4245     unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4246     Value *PBIV = PN.getIncomingValue(PBBIdx);
4247     if (BIV != PBIV) {
4248       // Insert a select in PBI to pick the right value.
4249       SelectInst *NV = cast<SelectInst>(
4250           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4251       PN.setIncomingValue(PBBIdx, NV);
4252       // Although the select has the same condition as PBI, the original branch
4253       // weights for PBI do not apply to the new select because the select's
4254       // 'logical' edges are incoming edges of the phi that is eliminated, not
4255       // the outgoing edges of PBI.
4256       if (HasWeights) {
4257         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4258         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4259         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4260         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4261         // The weight to PredCommonDest should be PredCommon * SuccTotal.
4262         // The weight to PredOtherDest should be PredOther * SuccCommon.
4263         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4264                                   PredOther * SuccCommon};
4265 
4266         FitWeights(NewWeights);
4267 
4268         setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4269       }
4270     }
4271   }
4272 
4273   LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4274   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4275 
4276   // This basic block is probably dead.  We know it has at least
4277   // one fewer predecessor.
4278   return true;
4279 }
4280 
4281 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4282 // true or to FalseBB if Cond is false.
4283 // Takes care of updating the successors and removing the old terminator.
4284 // Also makes sure not to introduce new successors by assuming that edges to
4285 // non-successor TrueBBs and FalseBBs aren't reachable.
4286 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4287                                                 Value *Cond, BasicBlock *TrueBB,
4288                                                 BasicBlock *FalseBB,
4289                                                 uint32_t TrueWeight,
4290                                                 uint32_t FalseWeight) {
4291   auto *BB = OldTerm->getParent();
4292   // Remove any superfluous successor edges from the CFG.
4293   // First, figure out which successors to preserve.
4294   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4295   // successor.
4296   BasicBlock *KeepEdge1 = TrueBB;
4297   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4298 
4299   SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4300 
4301   // Then remove the rest.
4302   for (BasicBlock *Succ : successors(OldTerm)) {
4303     // Make sure only to keep exactly one copy of each edge.
4304     if (Succ == KeepEdge1)
4305       KeepEdge1 = nullptr;
4306     else if (Succ == KeepEdge2)
4307       KeepEdge2 = nullptr;
4308     else {
4309       Succ->removePredecessor(BB,
4310                               /*KeepOneInputPHIs=*/true);
4311 
4312       if (Succ != TrueBB && Succ != FalseBB)
4313         RemovedSuccessors.insert(Succ);
4314     }
4315   }
4316 
4317   IRBuilder<> Builder(OldTerm);
4318   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4319 
4320   // Insert an appropriate new terminator.
4321   if (!KeepEdge1 && !KeepEdge2) {
4322     if (TrueBB == FalseBB) {
4323       // We were only looking for one successor, and it was present.
4324       // Create an unconditional branch to it.
4325       Builder.CreateBr(TrueBB);
4326     } else {
4327       // We found both of the successors we were looking for.
4328       // Create a conditional branch sharing the condition of the select.
4329       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4330       if (TrueWeight != FalseWeight)
4331         setBranchWeights(NewBI, TrueWeight, FalseWeight);
4332     }
4333   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4334     // Neither of the selected blocks were successors, so this
4335     // terminator must be unreachable.
4336     new UnreachableInst(OldTerm->getContext(), OldTerm);
4337   } else {
4338     // One of the selected values was a successor, but the other wasn't.
4339     // Insert an unconditional branch to the one that was found;
4340     // the edge to the one that wasn't must be unreachable.
4341     if (!KeepEdge1) {
4342       // Only TrueBB was found.
4343       Builder.CreateBr(TrueBB);
4344     } else {
4345       // Only FalseBB was found.
4346       Builder.CreateBr(FalseBB);
4347     }
4348   }
4349 
4350   EraseTerminatorAndDCECond(OldTerm);
4351 
4352   if (DTU) {
4353     SmallVector<DominatorTree::UpdateType, 2> Updates;
4354     Updates.reserve(RemovedSuccessors.size());
4355     for (auto *RemovedSuccessor : RemovedSuccessors)
4356       Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4357     DTU->applyUpdates(Updates);
4358   }
4359 
4360   return true;
4361 }
4362 
4363 // Replaces
4364 //   (switch (select cond, X, Y)) on constant X, Y
4365 // with a branch - conditional if X and Y lead to distinct BBs,
4366 // unconditional otherwise.
4367 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4368                                             SelectInst *Select) {
4369   // Check for constant integer values in the select.
4370   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4371   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4372   if (!TrueVal || !FalseVal)
4373     return false;
4374 
4375   // Find the relevant condition and destinations.
4376   Value *Condition = Select->getCondition();
4377   BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4378   BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4379 
4380   // Get weight for TrueBB and FalseBB.
4381   uint32_t TrueWeight = 0, FalseWeight = 0;
4382   SmallVector<uint64_t, 8> Weights;
4383   bool HasWeights = HasBranchWeights(SI);
4384   if (HasWeights) {
4385     GetBranchWeights(SI, Weights);
4386     if (Weights.size() == 1 + SI->getNumCases()) {
4387       TrueWeight =
4388           (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4389       FalseWeight =
4390           (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4391     }
4392   }
4393 
4394   // Perform the actual simplification.
4395   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4396                                     FalseWeight);
4397 }
4398 
4399 // Replaces
4400 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
4401 //                             blockaddress(@fn, BlockB)))
4402 // with
4403 //   (br cond, BlockA, BlockB).
4404 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4405                                                 SelectInst *SI) {
4406   // Check that both operands of the select are block addresses.
4407   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4408   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4409   if (!TBA || !FBA)
4410     return false;
4411 
4412   // Extract the actual blocks.
4413   BasicBlock *TrueBB = TBA->getBasicBlock();
4414   BasicBlock *FalseBB = FBA->getBasicBlock();
4415 
4416   // Perform the actual simplification.
4417   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4418                                     0);
4419 }
4420 
4421 /// This is called when we find an icmp instruction
4422 /// (a seteq/setne with a constant) as the only instruction in a
4423 /// block that ends with an uncond branch.  We are looking for a very specific
4424 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
4425 /// this case, we merge the first two "or's of icmp" into a switch, but then the
4426 /// default value goes to an uncond block with a seteq in it, we get something
4427 /// like:
4428 ///
4429 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
4430 /// DEFAULT:
4431 ///   %tmp = icmp eq i8 %A, 92
4432 ///   br label %end
4433 /// end:
4434 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4435 ///
4436 /// We prefer to split the edge to 'end' so that there is a true/false entry to
4437 /// the PHI, merging the third icmp into the switch.
4438 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4439     ICmpInst *ICI, IRBuilder<> &Builder) {
4440   BasicBlock *BB = ICI->getParent();
4441 
4442   // If the block has any PHIs in it or the icmp has multiple uses, it is too
4443   // complex.
4444   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4445     return false;
4446 
4447   Value *V = ICI->getOperand(0);
4448   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4449 
4450   // The pattern we're looking for is where our only predecessor is a switch on
4451   // 'V' and this block is the default case for the switch.  In this case we can
4452   // fold the compared value into the switch to simplify things.
4453   BasicBlock *Pred = BB->getSinglePredecessor();
4454   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4455     return false;
4456 
4457   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4458   if (SI->getCondition() != V)
4459     return false;
4460 
4461   // If BB is reachable on a non-default case, then we simply know the value of
4462   // V in this block.  Substitute it and constant fold the icmp instruction
4463   // away.
4464   if (SI->getDefaultDest() != BB) {
4465     ConstantInt *VVal = SI->findCaseDest(BB);
4466     assert(VVal && "Should have a unique destination value");
4467     ICI->setOperand(0, VVal);
4468 
4469     if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
4470       ICI->replaceAllUsesWith(V);
4471       ICI->eraseFromParent();
4472     }
4473     // BB is now empty, so it is likely to simplify away.
4474     return requestResimplify();
4475   }
4476 
4477   // Ok, the block is reachable from the default dest.  If the constant we're
4478   // comparing exists in one of the other edges, then we can constant fold ICI
4479   // and zap it.
4480   if (SI->findCaseValue(Cst) != SI->case_default()) {
4481     Value *V;
4482     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4483       V = ConstantInt::getFalse(BB->getContext());
4484     else
4485       V = ConstantInt::getTrue(BB->getContext());
4486 
4487     ICI->replaceAllUsesWith(V);
4488     ICI->eraseFromParent();
4489     // BB is now empty, so it is likely to simplify away.
4490     return requestResimplify();
4491   }
4492 
4493   // The use of the icmp has to be in the 'end' block, by the only PHI node in
4494   // the block.
4495   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4496   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4497   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4498       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4499     return false;
4500 
4501   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4502   // true in the PHI.
4503   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4504   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4505 
4506   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4507     std::swap(DefaultCst, NewCst);
4508 
4509   // Replace ICI (which is used by the PHI for the default value) with true or
4510   // false depending on if it is EQ or NE.
4511   ICI->replaceAllUsesWith(DefaultCst);
4512   ICI->eraseFromParent();
4513 
4514   SmallVector<DominatorTree::UpdateType, 2> Updates;
4515 
4516   // Okay, the switch goes to this block on a default value.  Add an edge from
4517   // the switch to the merge point on the compared value.
4518   BasicBlock *NewBB =
4519       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4520   {
4521     SwitchInstProfUpdateWrapper SIW(*SI);
4522     auto W0 = SIW.getSuccessorWeight(0);
4523     SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
4524     if (W0) {
4525       NewW = ((uint64_t(*W0) + 1) >> 1);
4526       SIW.setSuccessorWeight(0, *NewW);
4527     }
4528     SIW.addCase(Cst, NewBB, NewW);
4529     if (DTU)
4530       Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4531   }
4532 
4533   // NewBB branches to the phi block, add the uncond branch and the phi entry.
4534   Builder.SetInsertPoint(NewBB);
4535   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4536   Builder.CreateBr(SuccBlock);
4537   PHIUse->addIncoming(NewCst, NewBB);
4538   if (DTU) {
4539     Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4540     DTU->applyUpdates(Updates);
4541   }
4542   return true;
4543 }
4544 
4545 /// The specified branch is a conditional branch.
4546 /// Check to see if it is branching on an or/and chain of icmp instructions, and
4547 /// fold it into a switch instruction if so.
4548 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4549                                                IRBuilder<> &Builder,
4550                                                const DataLayout &DL) {
4551   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4552   if (!Cond)
4553     return false;
4554 
4555   // Change br (X == 0 | X == 1), T, F into a switch instruction.
4556   // If this is a bunch of seteq's or'd together, or if it's a bunch of
4557   // 'setne's and'ed together, collect them.
4558 
4559   // Try to gather values from a chain of and/or to be turned into a switch
4560   ConstantComparesGatherer ConstantCompare(Cond, DL);
4561   // Unpack the result
4562   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4563   Value *CompVal = ConstantCompare.CompValue;
4564   unsigned UsedICmps = ConstantCompare.UsedICmps;
4565   Value *ExtraCase = ConstantCompare.Extra;
4566 
4567   // If we didn't have a multiply compared value, fail.
4568   if (!CompVal)
4569     return false;
4570 
4571   // Avoid turning single icmps into a switch.
4572   if (UsedICmps <= 1)
4573     return false;
4574 
4575   bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4576 
4577   // There might be duplicate constants in the list, which the switch
4578   // instruction can't handle, remove them now.
4579   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4580   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4581 
4582   // If Extra was used, we require at least two switch values to do the
4583   // transformation.  A switch with one value is just a conditional branch.
4584   if (ExtraCase && Values.size() < 2)
4585     return false;
4586 
4587   // TODO: Preserve branch weight metadata, similarly to how
4588   // FoldValueComparisonIntoPredecessors preserves it.
4589 
4590   // Figure out which block is which destination.
4591   BasicBlock *DefaultBB = BI->getSuccessor(1);
4592   BasicBlock *EdgeBB = BI->getSuccessor(0);
4593   if (!TrueWhenEqual)
4594     std::swap(DefaultBB, EdgeBB);
4595 
4596   BasicBlock *BB = BI->getParent();
4597 
4598   LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4599                     << " cases into SWITCH.  BB is:\n"
4600                     << *BB);
4601 
4602   SmallVector<DominatorTree::UpdateType, 2> Updates;
4603 
4604   // If there are any extra values that couldn't be folded into the switch
4605   // then we evaluate them with an explicit branch first. Split the block
4606   // right before the condbr to handle it.
4607   if (ExtraCase) {
4608     BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4609                                    /*MSSAU=*/nullptr, "switch.early.test");
4610 
4611     // Remove the uncond branch added to the old block.
4612     Instruction *OldTI = BB->getTerminator();
4613     Builder.SetInsertPoint(OldTI);
4614 
4615     // There can be an unintended UB if extra values are Poison. Before the
4616     // transformation, extra values may not be evaluated according to the
4617     // condition, and it will not raise UB. But after transformation, we are
4618     // evaluating extra values before checking the condition, and it will raise
4619     // UB. It can be solved by adding freeze instruction to extra values.
4620     AssumptionCache *AC = Options.AC;
4621 
4622     if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4623       ExtraCase = Builder.CreateFreeze(ExtraCase);
4624 
4625     if (TrueWhenEqual)
4626       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4627     else
4628       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4629 
4630     OldTI->eraseFromParent();
4631 
4632     if (DTU)
4633       Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4634 
4635     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4636     // for the edge we just added.
4637     AddPredecessorToBlock(EdgeBB, BB, NewBB);
4638 
4639     LLVM_DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
4640                       << "\nEXTRABB = " << *BB);
4641     BB = NewBB;
4642   }
4643 
4644   Builder.SetInsertPoint(BI);
4645   // Convert pointer to int before we switch.
4646   if (CompVal->getType()->isPointerTy()) {
4647     CompVal = Builder.CreatePtrToInt(
4648         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4649   }
4650 
4651   // Create the new switch instruction now.
4652   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4653 
4654   // Add all of the 'cases' to the switch instruction.
4655   for (unsigned i = 0, e = Values.size(); i != e; ++i)
4656     New->addCase(Values[i], EdgeBB);
4657 
4658   // We added edges from PI to the EdgeBB.  As such, if there were any
4659   // PHI nodes in EdgeBB, they need entries to be added corresponding to
4660   // the number of edges added.
4661   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4662     PHINode *PN = cast<PHINode>(BBI);
4663     Value *InVal = PN->getIncomingValueForBlock(BB);
4664     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4665       PN->addIncoming(InVal, BB);
4666   }
4667 
4668   // Erase the old branch instruction.
4669   EraseTerminatorAndDCECond(BI);
4670   if (DTU)
4671     DTU->applyUpdates(Updates);
4672 
4673   LLVM_DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
4674   return true;
4675 }
4676 
4677 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4678   if (isa<PHINode>(RI->getValue()))
4679     return simplifyCommonResume(RI);
4680   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4681            RI->getValue() == RI->getParent()->getFirstNonPHI())
4682     // The resume must unwind the exception that caused control to branch here.
4683     return simplifySingleResume(RI);
4684 
4685   return false;
4686 }
4687 
4688 // Check if cleanup block is empty
4689 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4690   for (Instruction &I : R) {
4691     auto *II = dyn_cast<IntrinsicInst>(&I);
4692     if (!II)
4693       return false;
4694 
4695     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4696     switch (IntrinsicID) {
4697     case Intrinsic::dbg_declare:
4698     case Intrinsic::dbg_value:
4699     case Intrinsic::dbg_label:
4700     case Intrinsic::lifetime_end:
4701       break;
4702     default:
4703       return false;
4704     }
4705   }
4706   return true;
4707 }
4708 
4709 // Simplify resume that is shared by several landing pads (phi of landing pad).
4710 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4711   BasicBlock *BB = RI->getParent();
4712 
4713   // Check that there are no other instructions except for debug and lifetime
4714   // intrinsics between the phi's and resume instruction.
4715   if (!isCleanupBlockEmpty(
4716           make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4717     return false;
4718 
4719   SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4720   auto *PhiLPInst = cast<PHINode>(RI->getValue());
4721 
4722   // Check incoming blocks to see if any of them are trivial.
4723   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4724        Idx++) {
4725     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4726     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4727 
4728     // If the block has other successors, we can not delete it because
4729     // it has other dependents.
4730     if (IncomingBB->getUniqueSuccessor() != BB)
4731       continue;
4732 
4733     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4734     // Not the landing pad that caused the control to branch here.
4735     if (IncomingValue != LandingPad)
4736       continue;
4737 
4738     if (isCleanupBlockEmpty(
4739             make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4740       TrivialUnwindBlocks.insert(IncomingBB);
4741   }
4742 
4743   // If no trivial unwind blocks, don't do any simplifications.
4744   if (TrivialUnwindBlocks.empty())
4745     return false;
4746 
4747   // Turn all invokes that unwind here into calls.
4748   for (auto *TrivialBB : TrivialUnwindBlocks) {
4749     // Blocks that will be simplified should be removed from the phi node.
4750     // Note there could be multiple edges to the resume block, and we need
4751     // to remove them all.
4752     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4753       BB->removePredecessor(TrivialBB, true);
4754 
4755     for (BasicBlock *Pred :
4756          llvm::make_early_inc_range(predecessors(TrivialBB))) {
4757       removeUnwindEdge(Pred, DTU);
4758       ++NumInvokes;
4759     }
4760 
4761     // In each SimplifyCFG run, only the current processed block can be erased.
4762     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4763     // of erasing TrivialBB, we only remove the branch to the common resume
4764     // block so that we can later erase the resume block since it has no
4765     // predecessors.
4766     TrivialBB->getTerminator()->eraseFromParent();
4767     new UnreachableInst(RI->getContext(), TrivialBB);
4768     if (DTU)
4769       DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4770   }
4771 
4772   // Delete the resume block if all its predecessors have been removed.
4773   if (pred_empty(BB))
4774     DeleteDeadBlock(BB, DTU);
4775 
4776   return !TrivialUnwindBlocks.empty();
4777 }
4778 
4779 // Simplify resume that is only used by a single (non-phi) landing pad.
4780 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4781   BasicBlock *BB = RI->getParent();
4782   auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4783   assert(RI->getValue() == LPInst &&
4784          "Resume must unwind the exception that caused control to here");
4785 
4786   // Check that there are no other instructions except for debug intrinsics.
4787   if (!isCleanupBlockEmpty(
4788           make_range<Instruction *>(LPInst->getNextNode(), RI)))
4789     return false;
4790 
4791   // Turn all invokes that unwind here into calls and delete the basic block.
4792   for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
4793     removeUnwindEdge(Pred, DTU);
4794     ++NumInvokes;
4795   }
4796 
4797   // The landingpad is now unreachable.  Zap it.
4798   DeleteDeadBlock(BB, DTU);
4799   return true;
4800 }
4801 
4802 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
4803   // If this is a trivial cleanup pad that executes no instructions, it can be
4804   // eliminated.  If the cleanup pad continues to the caller, any predecessor
4805   // that is an EH pad will be updated to continue to the caller and any
4806   // predecessor that terminates with an invoke instruction will have its invoke
4807   // instruction converted to a call instruction.  If the cleanup pad being
4808   // simplified does not continue to the caller, each predecessor will be
4809   // updated to continue to the unwind destination of the cleanup pad being
4810   // simplified.
4811   BasicBlock *BB = RI->getParent();
4812   CleanupPadInst *CPInst = RI->getCleanupPad();
4813   if (CPInst->getParent() != BB)
4814     // This isn't an empty cleanup.
4815     return false;
4816 
4817   // We cannot kill the pad if it has multiple uses.  This typically arises
4818   // from unreachable basic blocks.
4819   if (!CPInst->hasOneUse())
4820     return false;
4821 
4822   // Check that there are no other instructions except for benign intrinsics.
4823   if (!isCleanupBlockEmpty(
4824           make_range<Instruction *>(CPInst->getNextNode(), RI)))
4825     return false;
4826 
4827   // If the cleanup return we are simplifying unwinds to the caller, this will
4828   // set UnwindDest to nullptr.
4829   BasicBlock *UnwindDest = RI->getUnwindDest();
4830   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4831 
4832   // We're about to remove BB from the control flow.  Before we do, sink any
4833   // PHINodes into the unwind destination.  Doing this before changing the
4834   // control flow avoids some potentially slow checks, since we can currently
4835   // be certain that UnwindDest and BB have no common predecessors (since they
4836   // are both EH pads).
4837   if (UnwindDest) {
4838     // First, go through the PHI nodes in UnwindDest and update any nodes that
4839     // reference the block we are removing
4840     for (PHINode &DestPN : UnwindDest->phis()) {
4841       int Idx = DestPN.getBasicBlockIndex(BB);
4842       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4843       assert(Idx != -1);
4844       // This PHI node has an incoming value that corresponds to a control
4845       // path through the cleanup pad we are removing.  If the incoming
4846       // value is in the cleanup pad, it must be a PHINode (because we
4847       // verified above that the block is otherwise empty).  Otherwise, the
4848       // value is either a constant or a value that dominates the cleanup
4849       // pad being removed.
4850       //
4851       // Because BB and UnwindDest are both EH pads, all of their
4852       // predecessors must unwind to these blocks, and since no instruction
4853       // can have multiple unwind destinations, there will be no overlap in
4854       // incoming blocks between SrcPN and DestPN.
4855       Value *SrcVal = DestPN.getIncomingValue(Idx);
4856       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4857 
4858       bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4859       for (auto *Pred : predecessors(BB)) {
4860         Value *Incoming =
4861             NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4862         DestPN.addIncoming(Incoming, Pred);
4863       }
4864     }
4865 
4866     // Sink any remaining PHI nodes directly into UnwindDest.
4867     Instruction *InsertPt = DestEHPad;
4868     for (PHINode &PN : make_early_inc_range(BB->phis())) {
4869       if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4870         // If the PHI node has no uses or all of its uses are in this basic
4871         // block (meaning they are debug or lifetime intrinsics), just leave
4872         // it.  It will be erased when we erase BB below.
4873         continue;
4874 
4875       // Otherwise, sink this PHI node into UnwindDest.
4876       // Any predecessors to UnwindDest which are not already represented
4877       // must be back edges which inherit the value from the path through
4878       // BB.  In this case, the PHI value must reference itself.
4879       for (auto *pred : predecessors(UnwindDest))
4880         if (pred != BB)
4881           PN.addIncoming(&PN, pred);
4882       PN.moveBefore(InsertPt);
4883       // Also, add a dummy incoming value for the original BB itself,
4884       // so that the PHI is well-formed until we drop said predecessor.
4885       PN.addIncoming(UndefValue::get(PN.getType()), BB);
4886     }
4887   }
4888 
4889   std::vector<DominatorTree::UpdateType> Updates;
4890 
4891   // We use make_early_inc_range here because we will remove all predecessors.
4892   for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) {
4893     if (UnwindDest == nullptr) {
4894       if (DTU) {
4895         DTU->applyUpdates(Updates);
4896         Updates.clear();
4897       }
4898       removeUnwindEdge(PredBB, DTU);
4899       ++NumInvokes;
4900     } else {
4901       BB->removePredecessor(PredBB);
4902       Instruction *TI = PredBB->getTerminator();
4903       TI->replaceUsesOfWith(BB, UnwindDest);
4904       if (DTU) {
4905         Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
4906         Updates.push_back({DominatorTree::Delete, PredBB, BB});
4907       }
4908     }
4909   }
4910 
4911   if (DTU)
4912     DTU->applyUpdates(Updates);
4913 
4914   DeleteDeadBlock(BB, DTU);
4915 
4916   return true;
4917 }
4918 
4919 // Try to merge two cleanuppads together.
4920 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4921   // Skip any cleanuprets which unwind to caller, there is nothing to merge
4922   // with.
4923   BasicBlock *UnwindDest = RI->getUnwindDest();
4924   if (!UnwindDest)
4925     return false;
4926 
4927   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4928   // be safe to merge without code duplication.
4929   if (UnwindDest->getSinglePredecessor() != RI->getParent())
4930     return false;
4931 
4932   // Verify that our cleanuppad's unwind destination is another cleanuppad.
4933   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4934   if (!SuccessorCleanupPad)
4935     return false;
4936 
4937   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4938   // Replace any uses of the successor cleanupad with the predecessor pad
4939   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4940   // funclet bundle operands.
4941   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4942   // Remove the old cleanuppad.
4943   SuccessorCleanupPad->eraseFromParent();
4944   // Now, we simply replace the cleanupret with a branch to the unwind
4945   // destination.
4946   BranchInst::Create(UnwindDest, RI->getParent());
4947   RI->eraseFromParent();
4948 
4949   return true;
4950 }
4951 
4952 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4953   // It is possible to transiantly have an undef cleanuppad operand because we
4954   // have deleted some, but not all, dead blocks.
4955   // Eventually, this block will be deleted.
4956   if (isa<UndefValue>(RI->getOperand(0)))
4957     return false;
4958 
4959   if (mergeCleanupPad(RI))
4960     return true;
4961 
4962   if (removeEmptyCleanup(RI, DTU))
4963     return true;
4964 
4965   return false;
4966 }
4967 
4968 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
4969 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4970   BasicBlock *BB = UI->getParent();
4971 
4972   bool Changed = false;
4973 
4974   // If there are any instructions immediately before the unreachable that can
4975   // be removed, do so.
4976   while (UI->getIterator() != BB->begin()) {
4977     BasicBlock::iterator BBI = UI->getIterator();
4978     --BBI;
4979 
4980     if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
4981       break; // Can not drop any more instructions. We're done here.
4982     // Otherwise, this instruction can be freely erased,
4983     // even if it is not side-effect free.
4984 
4985     // Note that deleting EH's here is in fact okay, although it involves a bit
4986     // of subtle reasoning. If this inst is an EH, all the predecessors of this
4987     // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
4988     // and we can therefore guarantee this block will be erased.
4989 
4990     // Delete this instruction (any uses are guaranteed to be dead)
4991     BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
4992     BBI->eraseFromParent();
4993     Changed = true;
4994   }
4995 
4996   // If the unreachable instruction is the first in the block, take a gander
4997   // at all of the predecessors of this instruction, and simplify them.
4998   if (&BB->front() != UI)
4999     return Changed;
5000 
5001   std::vector<DominatorTree::UpdateType> Updates;
5002 
5003   SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5004   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
5005     auto *Predecessor = Preds[i];
5006     Instruction *TI = Predecessor->getTerminator();
5007     IRBuilder<> Builder(TI);
5008     if (auto *BI = dyn_cast<BranchInst>(TI)) {
5009       // We could either have a proper unconditional branch,
5010       // or a degenerate conditional branch with matching destinations.
5011       if (all_of(BI->successors(),
5012                  [BB](auto *Successor) { return Successor == BB; })) {
5013         new UnreachableInst(TI->getContext(), TI);
5014         TI->eraseFromParent();
5015         Changed = true;
5016       } else {
5017         assert(BI->isConditional() && "Can't get here with an uncond branch.");
5018         Value* Cond = BI->getCondition();
5019         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5020                "The destinations are guaranteed to be different here.");
5021         if (BI->getSuccessor(0) == BB) {
5022           Builder.CreateAssumption(Builder.CreateNot(Cond));
5023           Builder.CreateBr(BI->getSuccessor(1));
5024         } else {
5025           assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5026           Builder.CreateAssumption(Cond);
5027           Builder.CreateBr(BI->getSuccessor(0));
5028         }
5029         EraseTerminatorAndDCECond(BI);
5030         Changed = true;
5031       }
5032       if (DTU)
5033         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5034     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
5035       SwitchInstProfUpdateWrapper SU(*SI);
5036       for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5037         if (i->getCaseSuccessor() != BB) {
5038           ++i;
5039           continue;
5040         }
5041         BB->removePredecessor(SU->getParent());
5042         i = SU.removeCase(i);
5043         e = SU->case_end();
5044         Changed = true;
5045       }
5046       // Note that the default destination can't be removed!
5047       if (DTU && SI->getDefaultDest() != BB)
5048         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5049     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5050       if (II->getUnwindDest() == BB) {
5051         if (DTU) {
5052           DTU->applyUpdates(Updates);
5053           Updates.clear();
5054         }
5055         removeUnwindEdge(TI->getParent(), DTU);
5056         Changed = true;
5057       }
5058     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5059       if (CSI->getUnwindDest() == BB) {
5060         if (DTU) {
5061           DTU->applyUpdates(Updates);
5062           Updates.clear();
5063         }
5064         removeUnwindEdge(TI->getParent(), DTU);
5065         Changed = true;
5066         continue;
5067       }
5068 
5069       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5070                                              E = CSI->handler_end();
5071            I != E; ++I) {
5072         if (*I == BB) {
5073           CSI->removeHandler(I);
5074           --I;
5075           --E;
5076           Changed = true;
5077         }
5078       }
5079       if (DTU)
5080         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5081       if (CSI->getNumHandlers() == 0) {
5082         if (CSI->hasUnwindDest()) {
5083           // Redirect all predecessors of the block containing CatchSwitchInst
5084           // to instead branch to the CatchSwitchInst's unwind destination.
5085           if (DTU) {
5086             for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
5087               Updates.push_back({DominatorTree::Insert,
5088                                  PredecessorOfPredecessor,
5089                                  CSI->getUnwindDest()});
5090               Updates.push_back({DominatorTree::Delete,
5091                                  PredecessorOfPredecessor, Predecessor});
5092             }
5093           }
5094           Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
5095         } else {
5096           // Rewrite all preds to unwind to caller (or from invoke to call).
5097           if (DTU) {
5098             DTU->applyUpdates(Updates);
5099             Updates.clear();
5100           }
5101           SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
5102           for (BasicBlock *EHPred : EHPreds)
5103             removeUnwindEdge(EHPred, DTU);
5104         }
5105         // The catchswitch is no longer reachable.
5106         new UnreachableInst(CSI->getContext(), CSI);
5107         CSI->eraseFromParent();
5108         Changed = true;
5109       }
5110     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5111       (void)CRI;
5112       assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5113              "Expected to always have an unwind to BB.");
5114       if (DTU)
5115         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5116       new UnreachableInst(TI->getContext(), TI);
5117       TI->eraseFromParent();
5118       Changed = true;
5119     }
5120   }
5121 
5122   if (DTU)
5123     DTU->applyUpdates(Updates);
5124 
5125   // If this block is now dead, remove it.
5126   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5127     DeleteDeadBlock(BB, DTU);
5128     return true;
5129   }
5130 
5131   return Changed;
5132 }
5133 
5134 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
5135   assert(Cases.size() >= 1);
5136 
5137   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
5138   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
5139     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
5140       return false;
5141   }
5142   return true;
5143 }
5144 
5145 static void createUnreachableSwitchDefault(SwitchInst *Switch,
5146                                            DomTreeUpdater *DTU) {
5147   LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
5148   auto *BB = Switch->getParent();
5149   auto *OrigDefaultBlock = Switch->getDefaultDest();
5150   OrigDefaultBlock->removePredecessor(BB);
5151   BasicBlock *NewDefaultBlock = BasicBlock::Create(
5152       BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
5153       OrigDefaultBlock);
5154   new UnreachableInst(Switch->getContext(), NewDefaultBlock);
5155   Switch->setDefaultDest(&*NewDefaultBlock);
5156   if (DTU) {
5157     SmallVector<DominatorTree::UpdateType, 2> Updates;
5158     Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
5159     if (!is_contained(successors(BB), OrigDefaultBlock))
5160       Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
5161     DTU->applyUpdates(Updates);
5162   }
5163 }
5164 
5165 /// Turn a switch with two reachable destinations into an integer range
5166 /// comparison and branch.
5167 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
5168                                              IRBuilder<> &Builder) {
5169   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5170 
5171   bool HasDefault =
5172       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5173 
5174   auto *BB = SI->getParent();
5175 
5176   // Partition the cases into two sets with different destinations.
5177   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
5178   BasicBlock *DestB = nullptr;
5179   SmallVector<ConstantInt *, 16> CasesA;
5180   SmallVector<ConstantInt *, 16> CasesB;
5181 
5182   for (auto Case : SI->cases()) {
5183     BasicBlock *Dest = Case.getCaseSuccessor();
5184     if (!DestA)
5185       DestA = Dest;
5186     if (Dest == DestA) {
5187       CasesA.push_back(Case.getCaseValue());
5188       continue;
5189     }
5190     if (!DestB)
5191       DestB = Dest;
5192     if (Dest == DestB) {
5193       CasesB.push_back(Case.getCaseValue());
5194       continue;
5195     }
5196     return false; // More than two destinations.
5197   }
5198 
5199   assert(DestA && DestB &&
5200          "Single-destination switch should have been folded.");
5201   assert(DestA != DestB);
5202   assert(DestB != SI->getDefaultDest());
5203   assert(!CasesB.empty() && "There must be non-default cases.");
5204   assert(!CasesA.empty() || HasDefault);
5205 
5206   // Figure out if one of the sets of cases form a contiguous range.
5207   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
5208   BasicBlock *ContiguousDest = nullptr;
5209   BasicBlock *OtherDest = nullptr;
5210   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
5211     ContiguousCases = &CasesA;
5212     ContiguousDest = DestA;
5213     OtherDest = DestB;
5214   } else if (CasesAreContiguous(CasesB)) {
5215     ContiguousCases = &CasesB;
5216     ContiguousDest = DestB;
5217     OtherDest = DestA;
5218   } else
5219     return false;
5220 
5221   // Start building the compare and branch.
5222 
5223   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
5224   Constant *NumCases =
5225       ConstantInt::get(Offset->getType(), ContiguousCases->size());
5226 
5227   Value *Sub = SI->getCondition();
5228   if (!Offset->isNullValue())
5229     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
5230 
5231   Value *Cmp;
5232   // If NumCases overflowed, then all possible values jump to the successor.
5233   if (NumCases->isNullValue() && !ContiguousCases->empty())
5234     Cmp = ConstantInt::getTrue(SI->getContext());
5235   else
5236     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
5237   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
5238 
5239   // Update weight for the newly-created conditional branch.
5240   if (HasBranchWeights(SI)) {
5241     SmallVector<uint64_t, 8> Weights;
5242     GetBranchWeights(SI, Weights);
5243     if (Weights.size() == 1 + SI->getNumCases()) {
5244       uint64_t TrueWeight = 0;
5245       uint64_t FalseWeight = 0;
5246       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
5247         if (SI->getSuccessor(I) == ContiguousDest)
5248           TrueWeight += Weights[I];
5249         else
5250           FalseWeight += Weights[I];
5251       }
5252       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
5253         TrueWeight /= 2;
5254         FalseWeight /= 2;
5255       }
5256       setBranchWeights(NewBI, TrueWeight, FalseWeight);
5257     }
5258   }
5259 
5260   // Prune obsolete incoming values off the successors' PHI nodes.
5261   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
5262     unsigned PreviousEdges = ContiguousCases->size();
5263     if (ContiguousDest == SI->getDefaultDest())
5264       ++PreviousEdges;
5265     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5266       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5267   }
5268   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
5269     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
5270     if (OtherDest == SI->getDefaultDest())
5271       ++PreviousEdges;
5272     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5273       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5274   }
5275 
5276   // Clean up the default block - it may have phis or other instructions before
5277   // the unreachable terminator.
5278   if (!HasDefault)
5279     createUnreachableSwitchDefault(SI, DTU);
5280 
5281   auto *UnreachableDefault = SI->getDefaultDest();
5282 
5283   // Drop the switch.
5284   SI->eraseFromParent();
5285 
5286   if (!HasDefault && DTU)
5287     DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}});
5288 
5289   return true;
5290 }
5291 
5292 /// Compute masked bits for the condition of a switch
5293 /// and use it to remove dead cases.
5294 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
5295                                      AssumptionCache *AC,
5296                                      const DataLayout &DL) {
5297   Value *Cond = SI->getCondition();
5298   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
5299 
5300   // We can also eliminate cases by determining that their values are outside of
5301   // the limited range of the condition based on how many significant (non-sign)
5302   // bits are in the condition value.
5303   unsigned MaxSignificantBitsInCond =
5304       ComputeMaxSignificantBits(Cond, DL, 0, AC, SI);
5305 
5306   // Gather dead cases.
5307   SmallVector<ConstantInt *, 8> DeadCases;
5308   SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
5309   SmallVector<BasicBlock *, 8> UniqueSuccessors;
5310   for (auto &Case : SI->cases()) {
5311     auto *Successor = Case.getCaseSuccessor();
5312     if (DTU) {
5313       if (!NumPerSuccessorCases.count(Successor))
5314         UniqueSuccessors.push_back(Successor);
5315       ++NumPerSuccessorCases[Successor];
5316     }
5317     const APInt &CaseVal = Case.getCaseValue()->getValue();
5318     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
5319         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
5320       DeadCases.push_back(Case.getCaseValue());
5321       if (DTU)
5322         --NumPerSuccessorCases[Successor];
5323       LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
5324                         << " is dead.\n");
5325     }
5326   }
5327 
5328   // If we can prove that the cases must cover all possible values, the
5329   // default destination becomes dead and we can remove it.  If we know some
5330   // of the bits in the value, we can use that to more precisely compute the
5331   // number of possible unique case values.
5332   bool HasDefault =
5333       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5334   const unsigned NumUnknownBits =
5335       Known.getBitWidth() - (Known.Zero | Known.One).countPopulation();
5336   assert(NumUnknownBits <= Known.getBitWidth());
5337   if (HasDefault && DeadCases.empty() &&
5338       NumUnknownBits < 64 /* avoid overflow */ &&
5339       SI->getNumCases() == (1ULL << NumUnknownBits)) {
5340     createUnreachableSwitchDefault(SI, DTU);
5341     return true;
5342   }
5343 
5344   if (DeadCases.empty())
5345     return false;
5346 
5347   SwitchInstProfUpdateWrapper SIW(*SI);
5348   for (ConstantInt *DeadCase : DeadCases) {
5349     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
5350     assert(CaseI != SI->case_default() &&
5351            "Case was not found. Probably mistake in DeadCases forming.");
5352     // Prune unused values from PHI nodes.
5353     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
5354     SIW.removeCase(CaseI);
5355   }
5356 
5357   if (DTU) {
5358     std::vector<DominatorTree::UpdateType> Updates;
5359     for (auto *Successor : UniqueSuccessors)
5360       if (NumPerSuccessorCases[Successor] == 0)
5361         Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
5362     DTU->applyUpdates(Updates);
5363   }
5364 
5365   return true;
5366 }
5367 
5368 /// If BB would be eligible for simplification by
5369 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
5370 /// by an unconditional branch), look at the phi node for BB in the successor
5371 /// block and see if the incoming value is equal to CaseValue. If so, return
5372 /// the phi node, and set PhiIndex to BB's index in the phi node.
5373 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
5374                                               BasicBlock *BB, int *PhiIndex) {
5375   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
5376     return nullptr; // BB must be empty to be a candidate for simplification.
5377   if (!BB->getSinglePredecessor())
5378     return nullptr; // BB must be dominated by the switch.
5379 
5380   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
5381   if (!Branch || !Branch->isUnconditional())
5382     return nullptr; // Terminator must be unconditional branch.
5383 
5384   BasicBlock *Succ = Branch->getSuccessor(0);
5385 
5386   for (PHINode &PHI : Succ->phis()) {
5387     int Idx = PHI.getBasicBlockIndex(BB);
5388     assert(Idx >= 0 && "PHI has no entry for predecessor?");
5389 
5390     Value *InValue = PHI.getIncomingValue(Idx);
5391     if (InValue != CaseValue)
5392       continue;
5393 
5394     *PhiIndex = Idx;
5395     return &PHI;
5396   }
5397 
5398   return nullptr;
5399 }
5400 
5401 /// Try to forward the condition of a switch instruction to a phi node
5402 /// dominated by the switch, if that would mean that some of the destination
5403 /// blocks of the switch can be folded away. Return true if a change is made.
5404 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
5405   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
5406 
5407   ForwardingNodesMap ForwardingNodes;
5408   BasicBlock *SwitchBlock = SI->getParent();
5409   bool Changed = false;
5410   for (auto &Case : SI->cases()) {
5411     ConstantInt *CaseValue = Case.getCaseValue();
5412     BasicBlock *CaseDest = Case.getCaseSuccessor();
5413 
5414     // Replace phi operands in successor blocks that are using the constant case
5415     // value rather than the switch condition variable:
5416     //   switchbb:
5417     //   switch i32 %x, label %default [
5418     //     i32 17, label %succ
5419     //   ...
5420     //   succ:
5421     //     %r = phi i32 ... [ 17, %switchbb ] ...
5422     // -->
5423     //     %r = phi i32 ... [ %x, %switchbb ] ...
5424 
5425     for (PHINode &Phi : CaseDest->phis()) {
5426       // This only works if there is exactly 1 incoming edge from the switch to
5427       // a phi. If there is >1, that means multiple cases of the switch map to 1
5428       // value in the phi, and that phi value is not the switch condition. Thus,
5429       // this transform would not make sense (the phi would be invalid because
5430       // a phi can't have different incoming values from the same block).
5431       int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
5432       if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
5433           count(Phi.blocks(), SwitchBlock) == 1) {
5434         Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
5435         Changed = true;
5436       }
5437     }
5438 
5439     // Collect phi nodes that are indirectly using this switch's case constants.
5440     int PhiIdx;
5441     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
5442       ForwardingNodes[Phi].push_back(PhiIdx);
5443   }
5444 
5445   for (auto &ForwardingNode : ForwardingNodes) {
5446     PHINode *Phi = ForwardingNode.first;
5447     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
5448     if (Indexes.size() < 2)
5449       continue;
5450 
5451     for (int Index : Indexes)
5452       Phi->setIncomingValue(Index, SI->getCondition());
5453     Changed = true;
5454   }
5455 
5456   return Changed;
5457 }
5458 
5459 /// Return true if the backend will be able to handle
5460 /// initializing an array of constants like C.
5461 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
5462   if (C->isThreadDependent())
5463     return false;
5464   if (C->isDLLImportDependent())
5465     return false;
5466 
5467   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
5468       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
5469       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
5470     return false;
5471 
5472   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5473     // Pointer casts and in-bounds GEPs will not prohibit the backend from
5474     // materializing the array of constants.
5475     Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
5476     if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI))
5477       return false;
5478   }
5479 
5480   if (!TTI.shouldBuildLookupTablesForConstant(C))
5481     return false;
5482 
5483   return true;
5484 }
5485 
5486 /// If V is a Constant, return it. Otherwise, try to look up
5487 /// its constant value in ConstantPool, returning 0 if it's not there.
5488 static Constant *
5489 LookupConstant(Value *V,
5490                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5491   if (Constant *C = dyn_cast<Constant>(V))
5492     return C;
5493   return ConstantPool.lookup(V);
5494 }
5495 
5496 /// Try to fold instruction I into a constant. This works for
5497 /// simple instructions such as binary operations where both operands are
5498 /// constant or can be replaced by constants from the ConstantPool. Returns the
5499 /// resulting constant on success, 0 otherwise.
5500 static Constant *
5501 ConstantFold(Instruction *I, const DataLayout &DL,
5502              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5503   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
5504     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
5505     if (!A)
5506       return nullptr;
5507     if (A->isAllOnesValue())
5508       return LookupConstant(Select->getTrueValue(), ConstantPool);
5509     if (A->isNullValue())
5510       return LookupConstant(Select->getFalseValue(), ConstantPool);
5511     return nullptr;
5512   }
5513 
5514   SmallVector<Constant *, 4> COps;
5515   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
5516     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
5517       COps.push_back(A);
5518     else
5519       return nullptr;
5520   }
5521 
5522   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
5523     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
5524                                            COps[1], DL);
5525   }
5526 
5527   return ConstantFoldInstOperands(I, COps, DL);
5528 }
5529 
5530 /// Try to determine the resulting constant values in phi nodes
5531 /// at the common destination basic block, *CommonDest, for one of the case
5532 /// destionations CaseDest corresponding to value CaseVal (0 for the default
5533 /// case), of a switch instruction SI.
5534 static bool
5535 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
5536                BasicBlock **CommonDest,
5537                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
5538                const DataLayout &DL, const TargetTransformInfo &TTI) {
5539   // The block from which we enter the common destination.
5540   BasicBlock *Pred = SI->getParent();
5541 
5542   // If CaseDest is empty except for some side-effect free instructions through
5543   // which we can constant-propagate the CaseVal, continue to its successor.
5544   SmallDenseMap<Value *, Constant *> ConstantPool;
5545   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
5546   for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) {
5547     if (I.isTerminator()) {
5548       // If the terminator is a simple branch, continue to the next block.
5549       if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
5550         return false;
5551       Pred = CaseDest;
5552       CaseDest = I.getSuccessor(0);
5553     } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
5554       // Instruction is side-effect free and constant.
5555 
5556       // If the instruction has uses outside this block or a phi node slot for
5557       // the block, it is not safe to bypass the instruction since it would then
5558       // no longer dominate all its uses.
5559       for (auto &Use : I.uses()) {
5560         User *User = Use.getUser();
5561         if (Instruction *I = dyn_cast<Instruction>(User))
5562           if (I->getParent() == CaseDest)
5563             continue;
5564         if (PHINode *Phi = dyn_cast<PHINode>(User))
5565           if (Phi->getIncomingBlock(Use) == CaseDest)
5566             continue;
5567         return false;
5568       }
5569 
5570       ConstantPool.insert(std::make_pair(&I, C));
5571     } else {
5572       break;
5573     }
5574   }
5575 
5576   // If we did not have a CommonDest before, use the current one.
5577   if (!*CommonDest)
5578     *CommonDest = CaseDest;
5579   // If the destination isn't the common one, abort.
5580   if (CaseDest != *CommonDest)
5581     return false;
5582 
5583   // Get the values for this case from phi nodes in the destination block.
5584   for (PHINode &PHI : (*CommonDest)->phis()) {
5585     int Idx = PHI.getBasicBlockIndex(Pred);
5586     if (Idx == -1)
5587       continue;
5588 
5589     Constant *ConstVal =
5590         LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
5591     if (!ConstVal)
5592       return false;
5593 
5594     // Be conservative about which kinds of constants we support.
5595     if (!ValidLookupTableConstant(ConstVal, TTI))
5596       return false;
5597 
5598     Res.push_back(std::make_pair(&PHI, ConstVal));
5599   }
5600 
5601   return Res.size() > 0;
5602 }
5603 
5604 // Helper function used to add CaseVal to the list of cases that generate
5605 // Result. Returns the updated number of cases that generate this result.
5606 static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
5607                                  SwitchCaseResultVectorTy &UniqueResults,
5608                                  Constant *Result) {
5609   for (auto &I : UniqueResults) {
5610     if (I.first == Result) {
5611       I.second.push_back(CaseVal);
5612       return I.second.size();
5613     }
5614   }
5615   UniqueResults.push_back(
5616       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5617   return 1;
5618 }
5619 
5620 // Helper function that initializes a map containing
5621 // results for the PHI node of the common destination block for a switch
5622 // instruction. Returns false if multiple PHI nodes have been found or if
5623 // there is not a common destination block for the switch.
5624 static bool
5625 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
5626                       SwitchCaseResultVectorTy &UniqueResults,
5627                       Constant *&DefaultResult, const DataLayout &DL,
5628                       const TargetTransformInfo &TTI,
5629                       uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
5630   for (auto &I : SI->cases()) {
5631     ConstantInt *CaseVal = I.getCaseValue();
5632 
5633     // Resulting value at phi nodes for this case value.
5634     SwitchCaseResultsTy Results;
5635     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5636                         DL, TTI))
5637       return false;
5638 
5639     // Only one value per case is permitted.
5640     if (Results.size() > 1)
5641       return false;
5642 
5643     // Add the case->result mapping to UniqueResults.
5644     const uintptr_t NumCasesForResult =
5645         MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5646 
5647     // Early out if there are too many cases for this result.
5648     if (NumCasesForResult > MaxCasesPerResult)
5649       return false;
5650 
5651     // Early out if there are too many unique results.
5652     if (UniqueResults.size() > MaxUniqueResults)
5653       return false;
5654 
5655     // Check the PHI consistency.
5656     if (!PHI)
5657       PHI = Results[0].first;
5658     else if (PHI != Results[0].first)
5659       return false;
5660   }
5661   // Find the default result value.
5662   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5663   BasicBlock *DefaultDest = SI->getDefaultDest();
5664   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5665                  DL, TTI);
5666   // If the default value is not found abort unless the default destination
5667   // is unreachable.
5668   DefaultResult =
5669       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5670   if ((!DefaultResult &&
5671        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5672     return false;
5673 
5674   return true;
5675 }
5676 
5677 // Helper function that checks if it is possible to transform a switch with only
5678 // two cases (or two cases + default) that produces a result into a select.
5679 // Example:
5680 // switch (a) {
5681 //   case 10:                %0 = icmp eq i32 %a, 10
5682 //     return 10;            %1 = select i1 %0, i32 10, i32 4
5683 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
5684 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
5685 //   default:
5686 //     return 4;
5687 // }
5688 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
5689                                    Constant *DefaultResult, Value *Condition,
5690                                    IRBuilder<> &Builder) {
5691   // If we are selecting between only two cases transform into a simple
5692   // select or a two-way select if default is possible.
5693   if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
5694       ResultVector[1].second.size() == 1) {
5695     ConstantInt *const FirstCase = ResultVector[0].second[0];
5696     ConstantInt *const SecondCase = ResultVector[1].second[0];
5697 
5698     bool DefaultCanTrigger = DefaultResult;
5699     Value *SelectValue = ResultVector[1].first;
5700     if (DefaultCanTrigger) {
5701       Value *const ValueCompare =
5702           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5703       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5704                                          DefaultResult, "switch.select");
5705     }
5706     Value *const ValueCompare =
5707         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5708     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5709                                 SelectValue, "switch.select");
5710   }
5711 
5712   // Handle the degenerate case where two cases have the same value.
5713   if (ResultVector.size() == 1 && ResultVector[0].second.size() == 2 &&
5714       DefaultResult) {
5715     Value *Cmp1 = Builder.CreateICmpEQ(
5716         Condition, ResultVector[0].second[0], "switch.selectcmp.case1");
5717     Value *Cmp2 = Builder.CreateICmpEQ(
5718         Condition, ResultVector[0].second[1], "switch.selectcmp.case2");
5719     Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
5720     return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5721   }
5722 
5723   return nullptr;
5724 }
5725 
5726 // Helper function to cleanup a switch instruction that has been converted into
5727 // a select, fixing up PHI nodes and basic blocks.
5728 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
5729                                               Value *SelectValue,
5730                                               IRBuilder<> &Builder,
5731                                               DomTreeUpdater *DTU) {
5732   std::vector<DominatorTree::UpdateType> Updates;
5733 
5734   BasicBlock *SelectBB = SI->getParent();
5735   BasicBlock *DestBB = PHI->getParent();
5736 
5737   if (DTU && !is_contained(predecessors(DestBB), SelectBB))
5738     Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
5739   Builder.CreateBr(DestBB);
5740 
5741   // Remove the switch.
5742 
5743   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5744     PHI->removeIncomingValue(SelectBB);
5745   PHI->addIncoming(SelectValue, SelectBB);
5746 
5747   SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
5748   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5749     BasicBlock *Succ = SI->getSuccessor(i);
5750 
5751     if (Succ == DestBB)
5752       continue;
5753     Succ->removePredecessor(SelectBB);
5754     if (DTU && RemovedSuccessors.insert(Succ).second)
5755       Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
5756   }
5757   SI->eraseFromParent();
5758   if (DTU)
5759     DTU->applyUpdates(Updates);
5760 }
5761 
5762 /// If the switch is only used to initialize one or more
5763 /// phi nodes in a common successor block with only two different
5764 /// constant values, replace the switch with select.
5765 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5766                            DomTreeUpdater *DTU, const DataLayout &DL,
5767                            const TargetTransformInfo &TTI) {
5768   Value *const Cond = SI->getCondition();
5769   PHINode *PHI = nullptr;
5770   BasicBlock *CommonDest = nullptr;
5771   Constant *DefaultResult;
5772   SwitchCaseResultVectorTy UniqueResults;
5773   // Collect all the cases that will deliver the same value from the switch.
5774   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5775                              DL, TTI, /*MaxUniqueResults*/2,
5776                              /*MaxCasesPerResult*/2))
5777     return false;
5778   assert(PHI != nullptr && "PHI for value select not found");
5779 
5780   Builder.SetInsertPoint(SI);
5781   Value *SelectValue =
5782       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
5783   if (SelectValue) {
5784     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder, DTU);
5785     return true;
5786   }
5787   // The switch couldn't be converted into a select.
5788   return false;
5789 }
5790 
5791 namespace {
5792 
5793 /// This class represents a lookup table that can be used to replace a switch.
5794 class SwitchLookupTable {
5795 public:
5796   /// Create a lookup table to use as a switch replacement with the contents
5797   /// of Values, using DefaultValue to fill any holes in the table.
5798   SwitchLookupTable(
5799       Module &M, uint64_t TableSize, ConstantInt *Offset,
5800       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5801       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5802 
5803   /// Build instructions with Builder to retrieve the value at
5804   /// the position given by Index in the lookup table.
5805   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5806 
5807   /// Return true if a table with TableSize elements of
5808   /// type ElementType would fit in a target-legal register.
5809   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5810                                  Type *ElementType);
5811 
5812 private:
5813   // Depending on the contents of the table, it can be represented in
5814   // different ways.
5815   enum {
5816     // For tables where each element contains the same value, we just have to
5817     // store that single value and return it for each lookup.
5818     SingleValueKind,
5819 
5820     // For tables where there is a linear relationship between table index
5821     // and values. We calculate the result with a simple multiplication
5822     // and addition instead of a table lookup.
5823     LinearMapKind,
5824 
5825     // For small tables with integer elements, we can pack them into a bitmap
5826     // that fits into a target-legal register. Values are retrieved by
5827     // shift and mask operations.
5828     BitMapKind,
5829 
5830     // The table is stored as an array of values. Values are retrieved by load
5831     // instructions from the table.
5832     ArrayKind
5833   } Kind;
5834 
5835   // For SingleValueKind, this is the single value.
5836   Constant *SingleValue = nullptr;
5837 
5838   // For BitMapKind, this is the bitmap.
5839   ConstantInt *BitMap = nullptr;
5840   IntegerType *BitMapElementTy = nullptr;
5841 
5842   // For LinearMapKind, these are the constants used to derive the value.
5843   ConstantInt *LinearOffset = nullptr;
5844   ConstantInt *LinearMultiplier = nullptr;
5845 
5846   // For ArrayKind, this is the array.
5847   GlobalVariable *Array = nullptr;
5848 };
5849 
5850 } // end anonymous namespace
5851 
5852 SwitchLookupTable::SwitchLookupTable(
5853     Module &M, uint64_t TableSize, ConstantInt *Offset,
5854     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5855     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5856   assert(Values.size() && "Can't build lookup table without values!");
5857   assert(TableSize >= Values.size() && "Can't fit values in table!");
5858 
5859   // If all values in the table are equal, this is that value.
5860   SingleValue = Values.begin()->second;
5861 
5862   Type *ValueType = Values.begin()->second->getType();
5863 
5864   // Build up the table contents.
5865   SmallVector<Constant *, 64> TableContents(TableSize);
5866   for (size_t I = 0, E = Values.size(); I != E; ++I) {
5867     ConstantInt *CaseVal = Values[I].first;
5868     Constant *CaseRes = Values[I].second;
5869     assert(CaseRes->getType() == ValueType);
5870 
5871     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5872     TableContents[Idx] = CaseRes;
5873 
5874     if (CaseRes != SingleValue)
5875       SingleValue = nullptr;
5876   }
5877 
5878   // Fill in any holes in the table with the default result.
5879   if (Values.size() < TableSize) {
5880     assert(DefaultValue &&
5881            "Need a default value to fill the lookup table holes.");
5882     assert(DefaultValue->getType() == ValueType);
5883     for (uint64_t I = 0; I < TableSize; ++I) {
5884       if (!TableContents[I])
5885         TableContents[I] = DefaultValue;
5886     }
5887 
5888     if (DefaultValue != SingleValue)
5889       SingleValue = nullptr;
5890   }
5891 
5892   // If each element in the table contains the same value, we only need to store
5893   // that single value.
5894   if (SingleValue) {
5895     Kind = SingleValueKind;
5896     return;
5897   }
5898 
5899   // Check if we can derive the value with a linear transformation from the
5900   // table index.
5901   if (isa<IntegerType>(ValueType)) {
5902     bool LinearMappingPossible = true;
5903     APInt PrevVal;
5904     APInt DistToPrev;
5905     assert(TableSize >= 2 && "Should be a SingleValue table.");
5906     // Check if there is the same distance between two consecutive values.
5907     for (uint64_t I = 0; I < TableSize; ++I) {
5908       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5909       if (!ConstVal) {
5910         // This is an undef. We could deal with it, but undefs in lookup tables
5911         // are very seldom. It's probably not worth the additional complexity.
5912         LinearMappingPossible = false;
5913         break;
5914       }
5915       const APInt &Val = ConstVal->getValue();
5916       if (I != 0) {
5917         APInt Dist = Val - PrevVal;
5918         if (I == 1) {
5919           DistToPrev = Dist;
5920         } else if (Dist != DistToPrev) {
5921           LinearMappingPossible = false;
5922           break;
5923         }
5924       }
5925       PrevVal = Val;
5926     }
5927     if (LinearMappingPossible) {
5928       LinearOffset = cast<ConstantInt>(TableContents[0]);
5929       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5930       Kind = LinearMapKind;
5931       ++NumLinearMaps;
5932       return;
5933     }
5934   }
5935 
5936   // If the type is integer and the table fits in a register, build a bitmap.
5937   if (WouldFitInRegister(DL, TableSize, ValueType)) {
5938     IntegerType *IT = cast<IntegerType>(ValueType);
5939     APInt TableInt(TableSize * IT->getBitWidth(), 0);
5940     for (uint64_t I = TableSize; I > 0; --I) {
5941       TableInt <<= IT->getBitWidth();
5942       // Insert values into the bitmap. Undef values are set to zero.
5943       if (!isa<UndefValue>(TableContents[I - 1])) {
5944         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5945         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5946       }
5947     }
5948     BitMap = ConstantInt::get(M.getContext(), TableInt);
5949     BitMapElementTy = IT;
5950     Kind = BitMapKind;
5951     ++NumBitMaps;
5952     return;
5953   }
5954 
5955   // Store the table in an array.
5956   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5957   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5958 
5959   Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5960                              GlobalVariable::PrivateLinkage, Initializer,
5961                              "switch.table." + FuncName);
5962   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5963   // Set the alignment to that of an array items. We will be only loading one
5964   // value out of it.
5965   Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5966   Kind = ArrayKind;
5967 }
5968 
5969 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5970   switch (Kind) {
5971   case SingleValueKind:
5972     return SingleValue;
5973   case LinearMapKind: {
5974     // Derive the result value from the input value.
5975     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5976                                           false, "switch.idx.cast");
5977     if (!LinearMultiplier->isOne())
5978       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5979     if (!LinearOffset->isZero())
5980       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5981     return Result;
5982   }
5983   case BitMapKind: {
5984     // Type of the bitmap (e.g. i59).
5985     IntegerType *MapTy = BitMap->getType();
5986 
5987     // Cast Index to the same type as the bitmap.
5988     // Note: The Index is <= the number of elements in the table, so
5989     // truncating it to the width of the bitmask is safe.
5990     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5991 
5992     // Multiply the shift amount by the element width.
5993     ShiftAmt = Builder.CreateMul(
5994         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5995         "switch.shiftamt");
5996 
5997     // Shift down.
5998     Value *DownShifted =
5999         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
6000     // Mask off.
6001     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
6002   }
6003   case ArrayKind: {
6004     // Make sure the table index will not overflow when treated as signed.
6005     IntegerType *IT = cast<IntegerType>(Index->getType());
6006     uint64_t TableSize =
6007         Array->getInitializer()->getType()->getArrayNumElements();
6008     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
6009       Index = Builder.CreateZExt(
6010           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
6011           "switch.tableidx.zext");
6012 
6013     Value *GEPIndices[] = {Builder.getInt32(0), Index};
6014     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
6015                                            GEPIndices, "switch.gep");
6016     return Builder.CreateLoad(
6017         cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
6018         "switch.load");
6019   }
6020   }
6021   llvm_unreachable("Unknown lookup table kind!");
6022 }
6023 
6024 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
6025                                            uint64_t TableSize,
6026                                            Type *ElementType) {
6027   auto *IT = dyn_cast<IntegerType>(ElementType);
6028   if (!IT)
6029     return false;
6030   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
6031   // are <= 15, we could try to narrow the type.
6032 
6033   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
6034   if (TableSize >= UINT_MAX / IT->getBitWidth())
6035     return false;
6036   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
6037 }
6038 
6039 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI,
6040                                       const DataLayout &DL) {
6041   // Allow any legal type.
6042   if (TTI.isTypeLegal(Ty))
6043     return true;
6044 
6045   auto *IT = dyn_cast<IntegerType>(Ty);
6046   if (!IT)
6047     return false;
6048 
6049   // Also allow power of 2 integer types that have at least 8 bits and fit in
6050   // a register. These types are common in frontend languages and targets
6051   // usually support loads of these types.
6052   // TODO: We could relax this to any integer that fits in a register and rely
6053   // on ABI alignment and padding in the table to allow the load to be widened.
6054   // Or we could widen the constants and truncate the load.
6055   unsigned BitWidth = IT->getBitWidth();
6056   return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
6057          DL.fitsInLegalInteger(IT->getBitWidth());
6058 }
6059 
6060 /// Determine whether a lookup table should be built for this switch, based on
6061 /// the number of cases, size of the table, and the types of the results.
6062 // TODO: We could support larger than legal types by limiting based on the
6063 // number of loads required and/or table size. If the constants are small we
6064 // could use smaller table entries and extend after the load.
6065 static bool
6066 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
6067                        const TargetTransformInfo &TTI, const DataLayout &DL,
6068                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
6069   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
6070     return false; // TableSize overflowed, or mul below might overflow.
6071 
6072   bool AllTablesFitInRegister = true;
6073   bool HasIllegalType = false;
6074   for (const auto &I : ResultTypes) {
6075     Type *Ty = I.second;
6076 
6077     // Saturate this flag to true.
6078     HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
6079 
6080     // Saturate this flag to false.
6081     AllTablesFitInRegister =
6082         AllTablesFitInRegister &&
6083         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
6084 
6085     // If both flags saturate, we're done. NOTE: This *only* works with
6086     // saturating flags, and all flags have to saturate first due to the
6087     // non-deterministic behavior of iterating over a dense map.
6088     if (HasIllegalType && !AllTablesFitInRegister)
6089       break;
6090   }
6091 
6092   // If each table would fit in a register, we should build it anyway.
6093   if (AllTablesFitInRegister)
6094     return true;
6095 
6096   // Don't build a table that doesn't fit in-register if it has illegal types.
6097   if (HasIllegalType)
6098     return false;
6099 
6100   // The table density should be at least 40%. This is the same criterion as for
6101   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
6102   // FIXME: Find the best cut-off.
6103   return SI->getNumCases() * 10 >= TableSize * 4;
6104 }
6105 
6106 /// Try to reuse the switch table index compare. Following pattern:
6107 /// \code
6108 ///     if (idx < tablesize)
6109 ///        r = table[idx]; // table does not contain default_value
6110 ///     else
6111 ///        r = default_value;
6112 ///     if (r != default_value)
6113 ///        ...
6114 /// \endcode
6115 /// Is optimized to:
6116 /// \code
6117 ///     cond = idx < tablesize;
6118 ///     if (cond)
6119 ///        r = table[idx];
6120 ///     else
6121 ///        r = default_value;
6122 ///     if (cond)
6123 ///        ...
6124 /// \endcode
6125 /// Jump threading will then eliminate the second if(cond).
6126 static void reuseTableCompare(
6127     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
6128     Constant *DefaultValue,
6129     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
6130   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
6131   if (!CmpInst)
6132     return;
6133 
6134   // We require that the compare is in the same block as the phi so that jump
6135   // threading can do its work afterwards.
6136   if (CmpInst->getParent() != PhiBlock)
6137     return;
6138 
6139   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
6140   if (!CmpOp1)
6141     return;
6142 
6143   Value *RangeCmp = RangeCheckBranch->getCondition();
6144   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
6145   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
6146 
6147   // Check if the compare with the default value is constant true or false.
6148   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6149                                                  DefaultValue, CmpOp1, true);
6150   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
6151     return;
6152 
6153   // Check if the compare with the case values is distinct from the default
6154   // compare result.
6155   for (auto ValuePair : Values) {
6156     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6157                                                 ValuePair.second, CmpOp1, true);
6158     if (!CaseConst || CaseConst == DefaultConst ||
6159         (CaseConst != TrueConst && CaseConst != FalseConst))
6160       return;
6161   }
6162 
6163   // Check if the branch instruction dominates the phi node. It's a simple
6164   // dominance check, but sufficient for our needs.
6165   // Although this check is invariant in the calling loops, it's better to do it
6166   // at this late stage. Practically we do it at most once for a switch.
6167   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
6168   for (BasicBlock *Pred : predecessors(PhiBlock)) {
6169     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
6170       return;
6171   }
6172 
6173   if (DefaultConst == FalseConst) {
6174     // The compare yields the same result. We can replace it.
6175     CmpInst->replaceAllUsesWith(RangeCmp);
6176     ++NumTableCmpReuses;
6177   } else {
6178     // The compare yields the same result, just inverted. We can replace it.
6179     Value *InvertedTableCmp = BinaryOperator::CreateXor(
6180         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
6181         RangeCheckBranch);
6182     CmpInst->replaceAllUsesWith(InvertedTableCmp);
6183     ++NumTableCmpReuses;
6184   }
6185 }
6186 
6187 /// If the switch is only used to initialize one or more phi nodes in a common
6188 /// successor block with different constant values, replace the switch with
6189 /// lookup tables.
6190 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
6191                                 DomTreeUpdater *DTU, const DataLayout &DL,
6192                                 const TargetTransformInfo &TTI) {
6193   assert(SI->getNumCases() > 1 && "Degenerate switch?");
6194 
6195   BasicBlock *BB = SI->getParent();
6196   Function *Fn = BB->getParent();
6197   // Only build lookup table when we have a target that supports it or the
6198   // attribute is not set.
6199   if (!TTI.shouldBuildLookupTables() ||
6200       (Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
6201     return false;
6202 
6203   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
6204   // split off a dense part and build a lookup table for that.
6205 
6206   // FIXME: This creates arrays of GEPs to constant strings, which means each
6207   // GEP needs a runtime relocation in PIC code. We should just build one big
6208   // string and lookup indices into that.
6209 
6210   // Ignore switches with less than three cases. Lookup tables will not make
6211   // them faster, so we don't analyze them.
6212   if (SI->getNumCases() < 3)
6213     return false;
6214 
6215   // Figure out the corresponding result for each case value and phi node in the
6216   // common destination, as well as the min and max case values.
6217   assert(!SI->cases().empty());
6218   SwitchInst::CaseIt CI = SI->case_begin();
6219   ConstantInt *MinCaseVal = CI->getCaseValue();
6220   ConstantInt *MaxCaseVal = CI->getCaseValue();
6221 
6222   BasicBlock *CommonDest = nullptr;
6223 
6224   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
6225   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
6226 
6227   SmallDenseMap<PHINode *, Constant *> DefaultResults;
6228   SmallDenseMap<PHINode *, Type *> ResultTypes;
6229   SmallVector<PHINode *, 4> PHIs;
6230 
6231   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
6232     ConstantInt *CaseVal = CI->getCaseValue();
6233     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
6234       MinCaseVal = CaseVal;
6235     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
6236       MaxCaseVal = CaseVal;
6237 
6238     // Resulting value at phi nodes for this case value.
6239     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
6240     ResultsTy Results;
6241     if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
6242                         Results, DL, TTI))
6243       return false;
6244 
6245     // Append the result from this case to the list for each phi.
6246     for (const auto &I : Results) {
6247       PHINode *PHI = I.first;
6248       Constant *Value = I.second;
6249       if (!ResultLists.count(PHI))
6250         PHIs.push_back(PHI);
6251       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
6252     }
6253   }
6254 
6255   // Keep track of the result types.
6256   for (PHINode *PHI : PHIs) {
6257     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
6258   }
6259 
6260   uint64_t NumResults = ResultLists[PHIs[0]].size();
6261   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
6262   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
6263   bool TableHasHoles = (NumResults < TableSize);
6264 
6265   // If the table has holes, we need a constant result for the default case
6266   // or a bitmask that fits in a register.
6267   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
6268   bool HasDefaultResults =
6269       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
6270                      DefaultResultsList, DL, TTI);
6271 
6272   bool NeedMask = (TableHasHoles && !HasDefaultResults);
6273   if (NeedMask) {
6274     // As an extra penalty for the validity test we require more cases.
6275     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
6276       return false;
6277     if (!DL.fitsInLegalInteger(TableSize))
6278       return false;
6279   }
6280 
6281   for (const auto &I : DefaultResultsList) {
6282     PHINode *PHI = I.first;
6283     Constant *Result = I.second;
6284     DefaultResults[PHI] = Result;
6285   }
6286 
6287   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
6288     return false;
6289 
6290   std::vector<DominatorTree::UpdateType> Updates;
6291 
6292   // Create the BB that does the lookups.
6293   Module &Mod = *CommonDest->getParent()->getParent();
6294   BasicBlock *LookupBB = BasicBlock::Create(
6295       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
6296 
6297   // Compute the table index value.
6298   Builder.SetInsertPoint(SI);
6299   Value *TableIndex;
6300   if (MinCaseVal->isNullValue())
6301     TableIndex = SI->getCondition();
6302   else
6303     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
6304                                    "switch.tableidx");
6305 
6306   // Compute the maximum table size representable by the integer type we are
6307   // switching upon.
6308   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
6309   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
6310   assert(MaxTableSize >= TableSize &&
6311          "It is impossible for a switch to have more entries than the max "
6312          "representable value of its input integer type's size.");
6313 
6314   // If the default destination is unreachable, or if the lookup table covers
6315   // all values of the conditional variable, branch directly to the lookup table
6316   // BB. Otherwise, check that the condition is within the case range.
6317   const bool DefaultIsReachable =
6318       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
6319   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
6320   BranchInst *RangeCheckBranch = nullptr;
6321 
6322   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6323     Builder.CreateBr(LookupBB);
6324     if (DTU)
6325       Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6326     // Note: We call removeProdecessor later since we need to be able to get the
6327     // PHI value for the default case in case we're using a bit mask.
6328   } else {
6329     Value *Cmp = Builder.CreateICmpULT(
6330         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
6331     RangeCheckBranch =
6332         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
6333     if (DTU)
6334       Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6335   }
6336 
6337   // Populate the BB that does the lookups.
6338   Builder.SetInsertPoint(LookupBB);
6339 
6340   if (NeedMask) {
6341     // Before doing the lookup, we do the hole check. The LookupBB is therefore
6342     // re-purposed to do the hole check, and we create a new LookupBB.
6343     BasicBlock *MaskBB = LookupBB;
6344     MaskBB->setName("switch.hole_check");
6345     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
6346                                   CommonDest->getParent(), CommonDest);
6347 
6348     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
6349     // unnecessary illegal types.
6350     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
6351     APInt MaskInt(TableSizePowOf2, 0);
6352     APInt One(TableSizePowOf2, 1);
6353     // Build bitmask; fill in a 1 bit for every case.
6354     const ResultListTy &ResultList = ResultLists[PHIs[0]];
6355     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
6356       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
6357                          .getLimitedValue();
6358       MaskInt |= One << Idx;
6359     }
6360     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
6361 
6362     // Get the TableIndex'th bit of the bitmask.
6363     // If this bit is 0 (meaning hole) jump to the default destination,
6364     // else continue with table lookup.
6365     IntegerType *MapTy = TableMask->getType();
6366     Value *MaskIndex =
6367         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
6368     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
6369     Value *LoBit = Builder.CreateTrunc(
6370         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
6371     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
6372     if (DTU) {
6373       Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
6374       Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
6375     }
6376     Builder.SetInsertPoint(LookupBB);
6377     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
6378   }
6379 
6380   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6381     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
6382     // do not delete PHINodes here.
6383     SI->getDefaultDest()->removePredecessor(BB,
6384                                             /*KeepOneInputPHIs=*/true);
6385     if (DTU)
6386       Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
6387   }
6388 
6389   for (PHINode *PHI : PHIs) {
6390     const ResultListTy &ResultList = ResultLists[PHI];
6391 
6392     // If using a bitmask, use any value to fill the lookup table holes.
6393     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
6394     StringRef FuncName = Fn->getName();
6395     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
6396                             FuncName);
6397 
6398     Value *Result = Table.BuildLookup(TableIndex, Builder);
6399 
6400     // Do a small peephole optimization: re-use the switch table compare if
6401     // possible.
6402     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
6403       BasicBlock *PhiBlock = PHI->getParent();
6404       // Search for compare instructions which use the phi.
6405       for (auto *User : PHI->users()) {
6406         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
6407       }
6408     }
6409 
6410     PHI->addIncoming(Result, LookupBB);
6411   }
6412 
6413   Builder.CreateBr(CommonDest);
6414   if (DTU)
6415     Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
6416 
6417   // Remove the switch.
6418   SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
6419   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6420     BasicBlock *Succ = SI->getSuccessor(i);
6421 
6422     if (Succ == SI->getDefaultDest())
6423       continue;
6424     Succ->removePredecessor(BB);
6425     if (DTU && RemovedSuccessors.insert(Succ).second)
6426       Updates.push_back({DominatorTree::Delete, BB, Succ});
6427   }
6428   SI->eraseFromParent();
6429 
6430   if (DTU)
6431     DTU->applyUpdates(Updates);
6432 
6433   ++NumLookupTables;
6434   if (NeedMask)
6435     ++NumLookupTablesHoles;
6436   return true;
6437 }
6438 
6439 static bool isSwitchDense(ArrayRef<int64_t> Values) {
6440   // See also SelectionDAGBuilder::isDense(), which this function was based on.
6441   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
6442   uint64_t Range = Diff + 1;
6443   uint64_t NumCases = Values.size();
6444   // 40% is the default density for building a jump table in optsize/minsize mode.
6445   uint64_t MinDensity = 40;
6446 
6447   return NumCases * 100 >= Range * MinDensity;
6448 }
6449 
6450 /// Try to transform a switch that has "holes" in it to a contiguous sequence
6451 /// of cases.
6452 ///
6453 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
6454 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
6455 ///
6456 /// This converts a sparse switch into a dense switch which allows better
6457 /// lowering and could also allow transforming into a lookup table.
6458 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
6459                               const DataLayout &DL,
6460                               const TargetTransformInfo &TTI) {
6461   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
6462   if (CondTy->getIntegerBitWidth() > 64 ||
6463       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6464     return false;
6465   // Only bother with this optimization if there are more than 3 switch cases;
6466   // SDAG will only bother creating jump tables for 4 or more cases.
6467   if (SI->getNumCases() < 4)
6468     return false;
6469 
6470   // This transform is agnostic to the signedness of the input or case values. We
6471   // can treat the case values as signed or unsigned. We can optimize more common
6472   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
6473   // as signed.
6474   SmallVector<int64_t,4> Values;
6475   for (auto &C : SI->cases())
6476     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
6477   llvm::sort(Values);
6478 
6479   // If the switch is already dense, there's nothing useful to do here.
6480   if (isSwitchDense(Values))
6481     return false;
6482 
6483   // First, transform the values such that they start at zero and ascend.
6484   int64_t Base = Values[0];
6485   for (auto &V : Values)
6486     V -= (uint64_t)(Base);
6487 
6488   // Now we have signed numbers that have been shifted so that, given enough
6489   // precision, there are no negative values. Since the rest of the transform
6490   // is bitwise only, we switch now to an unsigned representation.
6491 
6492   // This transform can be done speculatively because it is so cheap - it
6493   // results in a single rotate operation being inserted.
6494   // FIXME: It's possible that optimizing a switch on powers of two might also
6495   // be beneficial - flag values are often powers of two and we could use a CLZ
6496   // as the key function.
6497 
6498   // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
6499   // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
6500   // less than 64.
6501   unsigned Shift = 64;
6502   for (auto &V : Values)
6503     Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
6504   assert(Shift < 64);
6505   if (Shift > 0)
6506     for (auto &V : Values)
6507       V = (int64_t)((uint64_t)V >> Shift);
6508 
6509   if (!isSwitchDense(Values))
6510     // Transform didn't create a dense switch.
6511     return false;
6512 
6513   // The obvious transform is to shift the switch condition right and emit a
6514   // check that the condition actually cleanly divided by GCD, i.e.
6515   //   C & (1 << Shift - 1) == 0
6516   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
6517   //
6518   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
6519   // shift and puts the shifted-off bits in the uppermost bits. If any of these
6520   // are nonzero then the switch condition will be very large and will hit the
6521   // default case.
6522 
6523   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
6524   Builder.SetInsertPoint(SI);
6525   auto *ShiftC = ConstantInt::get(Ty, Shift);
6526   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
6527   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
6528   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
6529   auto *Rot = Builder.CreateOr(LShr, Shl);
6530   SI->replaceUsesOfWith(SI->getCondition(), Rot);
6531 
6532   for (auto Case : SI->cases()) {
6533     auto *Orig = Case.getCaseValue();
6534     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
6535     Case.setValue(
6536         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
6537   }
6538   return true;
6539 }
6540 
6541 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
6542   BasicBlock *BB = SI->getParent();
6543 
6544   if (isValueEqualityComparison(SI)) {
6545     // If we only have one predecessor, and if it is a branch on this value,
6546     // see if that predecessor totally determines the outcome of this switch.
6547     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6548       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
6549         return requestResimplify();
6550 
6551     Value *Cond = SI->getCondition();
6552     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
6553       if (SimplifySwitchOnSelect(SI, Select))
6554         return requestResimplify();
6555 
6556     // If the block only contains the switch, see if we can fold the block
6557     // away into any preds.
6558     if (SI == &*BB->instructionsWithoutDebug(false).begin())
6559       if (FoldValueComparisonIntoPredecessors(SI, Builder))
6560         return requestResimplify();
6561   }
6562 
6563   // Try to transform the switch into an icmp and a branch.
6564   // The conversion from switch to comparison may lose information on
6565   // impossible switch values, so disable it early in the pipeline.
6566   if (Options.ConvertSwitchRangeToICmp && TurnSwitchRangeIntoICmp(SI, Builder))
6567     return requestResimplify();
6568 
6569   // Remove unreachable cases.
6570   if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
6571     return requestResimplify();
6572 
6573   if (switchToSelect(SI, Builder, DTU, DL, TTI))
6574     return requestResimplify();
6575 
6576   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
6577     return requestResimplify();
6578 
6579   // The conversion from switch to lookup tables results in difficult-to-analyze
6580   // code and makes pruning branches much harder. This is a problem if the
6581   // switch expression itself can still be restricted as a result of inlining or
6582   // CVP. Therefore, only apply this transformation during late stages of the
6583   // optimisation pipeline.
6584   if (Options.ConvertSwitchToLookupTable &&
6585       SwitchToLookupTable(SI, Builder, DTU, DL, TTI))
6586     return requestResimplify();
6587 
6588   if (ReduceSwitchRange(SI, Builder, DL, TTI))
6589     return requestResimplify();
6590 
6591   return false;
6592 }
6593 
6594 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
6595   BasicBlock *BB = IBI->getParent();
6596   bool Changed = false;
6597 
6598   // Eliminate redundant destinations.
6599   SmallPtrSet<Value *, 8> Succs;
6600   SmallSetVector<BasicBlock *, 8> RemovedSuccs;
6601   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
6602     BasicBlock *Dest = IBI->getDestination(i);
6603     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
6604       if (!Dest->hasAddressTaken())
6605         RemovedSuccs.insert(Dest);
6606       Dest->removePredecessor(BB);
6607       IBI->removeDestination(i);
6608       --i;
6609       --e;
6610       Changed = true;
6611     }
6612   }
6613 
6614   if (DTU) {
6615     std::vector<DominatorTree::UpdateType> Updates;
6616     Updates.reserve(RemovedSuccs.size());
6617     for (auto *RemovedSucc : RemovedSuccs)
6618       Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
6619     DTU->applyUpdates(Updates);
6620   }
6621 
6622   if (IBI->getNumDestinations() == 0) {
6623     // If the indirectbr has no successors, change it to unreachable.
6624     new UnreachableInst(IBI->getContext(), IBI);
6625     EraseTerminatorAndDCECond(IBI);
6626     return true;
6627   }
6628 
6629   if (IBI->getNumDestinations() == 1) {
6630     // If the indirectbr has one successor, change it to a direct branch.
6631     BranchInst::Create(IBI->getDestination(0), IBI);
6632     EraseTerminatorAndDCECond(IBI);
6633     return true;
6634   }
6635 
6636   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
6637     if (SimplifyIndirectBrOnSelect(IBI, SI))
6638       return requestResimplify();
6639   }
6640   return Changed;
6641 }
6642 
6643 /// Given an block with only a single landing pad and a unconditional branch
6644 /// try to find another basic block which this one can be merged with.  This
6645 /// handles cases where we have multiple invokes with unique landing pads, but
6646 /// a shared handler.
6647 ///
6648 /// We specifically choose to not worry about merging non-empty blocks
6649 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
6650 /// practice, the optimizer produces empty landing pad blocks quite frequently
6651 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
6652 /// sinking in this file)
6653 ///
6654 /// This is primarily a code size optimization.  We need to avoid performing
6655 /// any transform which might inhibit optimization (such as our ability to
6656 /// specialize a particular handler via tail commoning).  We do this by not
6657 /// merging any blocks which require us to introduce a phi.  Since the same
6658 /// values are flowing through both blocks, we don't lose any ability to
6659 /// specialize.  If anything, we make such specialization more likely.
6660 ///
6661 /// TODO - This transformation could remove entries from a phi in the target
6662 /// block when the inputs in the phi are the same for the two blocks being
6663 /// merged.  In some cases, this could result in removal of the PHI entirely.
6664 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
6665                                  BasicBlock *BB, DomTreeUpdater *DTU) {
6666   auto Succ = BB->getUniqueSuccessor();
6667   assert(Succ);
6668   // If there's a phi in the successor block, we'd likely have to introduce
6669   // a phi into the merged landing pad block.
6670   if (isa<PHINode>(*Succ->begin()))
6671     return false;
6672 
6673   for (BasicBlock *OtherPred : predecessors(Succ)) {
6674     if (BB == OtherPred)
6675       continue;
6676     BasicBlock::iterator I = OtherPred->begin();
6677     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6678     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6679       continue;
6680     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6681       ;
6682     BranchInst *BI2 = dyn_cast<BranchInst>(I);
6683     if (!BI2 || !BI2->isIdenticalTo(BI))
6684       continue;
6685 
6686     std::vector<DominatorTree::UpdateType> Updates;
6687 
6688     // We've found an identical block.  Update our predecessors to take that
6689     // path instead and make ourselves dead.
6690     SmallSetVector<BasicBlock *, 16> UniquePreds(pred_begin(BB), pred_end(BB));
6691     for (BasicBlock *Pred : UniquePreds) {
6692       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6693       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
6694              "unexpected successor");
6695       II->setUnwindDest(OtherPred);
6696       if (DTU) {
6697         Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
6698         Updates.push_back({DominatorTree::Delete, Pred, BB});
6699       }
6700     }
6701 
6702     // The debug info in OtherPred doesn't cover the merged control flow that
6703     // used to go through BB.  We need to delete it or update it.
6704     for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred))
6705       if (isa<DbgInfoIntrinsic>(Inst))
6706         Inst.eraseFromParent();
6707 
6708     SmallSetVector<BasicBlock *, 16> UniqueSuccs(succ_begin(BB), succ_end(BB));
6709     for (BasicBlock *Succ : UniqueSuccs) {
6710       Succ->removePredecessor(BB);
6711       if (DTU)
6712         Updates.push_back({DominatorTree::Delete, BB, Succ});
6713     }
6714 
6715     IRBuilder<> Builder(BI);
6716     Builder.CreateUnreachable();
6717     BI->eraseFromParent();
6718     if (DTU)
6719       DTU->applyUpdates(Updates);
6720     return true;
6721   }
6722   return false;
6723 }
6724 
6725 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6726   return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6727                                    : simplifyCondBranch(Branch, Builder);
6728 }
6729 
6730 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6731                                           IRBuilder<> &Builder) {
6732   BasicBlock *BB = BI->getParent();
6733   BasicBlock *Succ = BI->getSuccessor(0);
6734 
6735   // If the Terminator is the only non-phi instruction, simplify the block.
6736   // If LoopHeader is provided, check if the block or its successor is a loop
6737   // header. (This is for early invocations before loop simplify and
6738   // vectorization to keep canonical loop forms for nested loops. These blocks
6739   // can be eliminated when the pass is invoked later in the back-end.)
6740   // Note that if BB has only one predecessor then we do not introduce new
6741   // backedge, so we can eliminate BB.
6742   bool NeedCanonicalLoop =
6743       Options.NeedCanonicalLoop &&
6744       (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
6745        (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
6746   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator();
6747   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6748       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
6749     return true;
6750 
6751   // If the only instruction in the block is a seteq/setne comparison against a
6752   // constant, try to simplify the block.
6753   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6754     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6755       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6756         ;
6757       if (I->isTerminator() &&
6758           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6759         return true;
6760     }
6761 
6762   // See if we can merge an empty landing pad block with another which is
6763   // equivalent.
6764   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6765     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6766       ;
6767     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU))
6768       return true;
6769   }
6770 
6771   // If this basic block is ONLY a compare and a branch, and if a predecessor
6772   // branches to us and our successor, fold the comparison into the
6773   // predecessor and use logical operations to update the incoming value
6774   // for PHI nodes in common successor.
6775   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6776                              Options.BonusInstThreshold))
6777     return requestResimplify();
6778   return false;
6779 }
6780 
6781 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6782   BasicBlock *PredPred = nullptr;
6783   for (auto *P : predecessors(BB)) {
6784     BasicBlock *PPred = P->getSinglePredecessor();
6785     if (!PPred || (PredPred && PredPred != PPred))
6786       return nullptr;
6787     PredPred = PPred;
6788   }
6789   return PredPred;
6790 }
6791 
6792 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6793   assert(
6794       !isa<ConstantInt>(BI->getCondition()) &&
6795       BI->getSuccessor(0) != BI->getSuccessor(1) &&
6796       "Tautological conditional branch should have been eliminated already.");
6797 
6798   BasicBlock *BB = BI->getParent();
6799   if (!Options.SimplifyCondBranch)
6800     return false;
6801 
6802   // Conditional branch
6803   if (isValueEqualityComparison(BI)) {
6804     // If we only have one predecessor, and if it is a branch on this value,
6805     // see if that predecessor totally determines the outcome of this
6806     // switch.
6807     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6808       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6809         return requestResimplify();
6810 
6811     // This block must be empty, except for the setcond inst, if it exists.
6812     // Ignore dbg and pseudo intrinsics.
6813     auto I = BB->instructionsWithoutDebug(true).begin();
6814     if (&*I == BI) {
6815       if (FoldValueComparisonIntoPredecessors(BI, Builder))
6816         return requestResimplify();
6817     } else if (&*I == cast<Instruction>(BI->getCondition())) {
6818       ++I;
6819       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6820         return requestResimplify();
6821     }
6822   }
6823 
6824   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6825   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6826     return true;
6827 
6828   // If this basic block has dominating predecessor blocks and the dominating
6829   // blocks' conditions imply BI's condition, we know the direction of BI.
6830   Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6831   if (Imp) {
6832     // Turn this into a branch on constant.
6833     auto *OldCond = BI->getCondition();
6834     ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6835                              : ConstantInt::getFalse(BB->getContext());
6836     BI->setCondition(TorF);
6837     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6838     return requestResimplify();
6839   }
6840 
6841   // If this basic block is ONLY a compare and a branch, and if a predecessor
6842   // branches to us and one of our successors, fold the comparison into the
6843   // predecessor and use logical operations to pick the right destination.
6844   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6845                              Options.BonusInstThreshold))
6846     return requestResimplify();
6847 
6848   // We have a conditional branch to two blocks that are only reachable
6849   // from BI.  We know that the condbr dominates the two blocks, so see if
6850   // there is any identical code in the "then" and "else" blocks.  If so, we
6851   // can hoist it up to the branching block.
6852   if (BI->getSuccessor(0)->getSinglePredecessor()) {
6853     if (BI->getSuccessor(1)->getSinglePredecessor()) {
6854       if (HoistCommon &&
6855           HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts))
6856         return requestResimplify();
6857     } else {
6858       // If Successor #1 has multiple preds, we may be able to conditionally
6859       // execute Successor #0 if it branches to Successor #1.
6860       Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6861       if (Succ0TI->getNumSuccessors() == 1 &&
6862           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6863         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6864           return requestResimplify();
6865     }
6866   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6867     // If Successor #0 has multiple preds, we may be able to conditionally
6868     // execute Successor #1 if it branches to Successor #0.
6869     Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6870     if (Succ1TI->getNumSuccessors() == 1 &&
6871         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6872       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6873         return requestResimplify();
6874   }
6875 
6876   // If this is a branch on a phi node in the current block, thread control
6877   // through this block if any PHI node entries are constants.
6878   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6879     if (PN->getParent() == BI->getParent())
6880       if (FoldCondBranchOnPHI(BI, DTU, DL, Options.AC))
6881         return requestResimplify();
6882 
6883   // Scan predecessor blocks for conditional branches.
6884   for (BasicBlock *Pred : predecessors(BB))
6885     if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
6886       if (PBI != BI && PBI->isConditional())
6887         if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
6888           return requestResimplify();
6889 
6890   // Look for diamond patterns.
6891   if (MergeCondStores)
6892     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6893       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6894         if (PBI != BI && PBI->isConditional())
6895           if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
6896             return requestResimplify();
6897 
6898   return false;
6899 }
6900 
6901 /// Check if passing a value to an instruction will cause undefined behavior.
6902 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
6903   Constant *C = dyn_cast<Constant>(V);
6904   if (!C)
6905     return false;
6906 
6907   if (I->use_empty())
6908     return false;
6909 
6910   if (C->isNullValue() || isa<UndefValue>(C)) {
6911     // Only look at the first use, avoid hurting compile time with long uselists
6912     auto *Use = cast<Instruction>(*I->user_begin());
6913     // Bail out if Use is not in the same BB as I or Use == I or Use comes
6914     // before I in the block. The latter two can be the case if Use is a PHI
6915     // node.
6916     if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
6917       return false;
6918 
6919     // Now make sure that there are no instructions in between that can alter
6920     // control flow (eg. calls)
6921     auto InstrRange =
6922         make_range(std::next(I->getIterator()), Use->getIterator());
6923     if (any_of(InstrRange, [](Instruction &I) {
6924           return !isGuaranteedToTransferExecutionToSuccessor(&I);
6925         }))
6926       return false;
6927 
6928     // Look through GEPs. A load from a GEP derived from NULL is still undefined
6929     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6930       if (GEP->getPointerOperand() == I) {
6931         if (!GEP->isInBounds() || !GEP->hasAllZeroIndices())
6932           PtrValueMayBeModified = true;
6933         return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
6934       }
6935 
6936     // Look through bitcasts.
6937     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6938       return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified);
6939 
6940     // Load from null is undefined.
6941     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6942       if (!LI->isVolatile())
6943         return !NullPointerIsDefined(LI->getFunction(),
6944                                      LI->getPointerAddressSpace());
6945 
6946     // Store to null is undefined.
6947     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6948       if (!SI->isVolatile())
6949         return (!NullPointerIsDefined(SI->getFunction(),
6950                                       SI->getPointerAddressSpace())) &&
6951                SI->getPointerOperand() == I;
6952 
6953     if (auto *CB = dyn_cast<CallBase>(Use)) {
6954       if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
6955         return false;
6956       // A call to null is undefined.
6957       if (CB->getCalledOperand() == I)
6958         return true;
6959 
6960       if (C->isNullValue()) {
6961         for (const llvm::Use &Arg : CB->args())
6962           if (Arg == I) {
6963             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6964             if (CB->isPassingUndefUB(ArgIdx) &&
6965                 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) {
6966               // Passing null to a nonnnull+noundef argument is undefined.
6967               return !PtrValueMayBeModified;
6968             }
6969           }
6970       } else if (isa<UndefValue>(C)) {
6971         // Passing undef to a noundef argument is undefined.
6972         for (const llvm::Use &Arg : CB->args())
6973           if (Arg == I) {
6974             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6975             if (CB->isPassingUndefUB(ArgIdx)) {
6976               // Passing undef to a noundef argument is undefined.
6977               return true;
6978             }
6979           }
6980       }
6981     }
6982   }
6983   return false;
6984 }
6985 
6986 /// If BB has an incoming value that will always trigger undefined behavior
6987 /// (eg. null pointer dereference), remove the branch leading here.
6988 static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
6989                                               DomTreeUpdater *DTU) {
6990   for (PHINode &PHI : BB->phis())
6991     for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6992       if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6993         BasicBlock *Predecessor = PHI.getIncomingBlock(i);
6994         Instruction *T = Predecessor->getTerminator();
6995         IRBuilder<> Builder(T);
6996         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6997           BB->removePredecessor(Predecessor);
6998           // Turn uncoditional branches into unreachables and remove the dead
6999           // destination from conditional branches.
7000           if (BI->isUnconditional())
7001             Builder.CreateUnreachable();
7002           else {
7003             // Preserve guarding condition in assume, because it might not be
7004             // inferrable from any dominating condition.
7005             Value *Cond = BI->getCondition();
7006             if (BI->getSuccessor(0) == BB)
7007               Builder.CreateAssumption(Builder.CreateNot(Cond));
7008             else
7009               Builder.CreateAssumption(Cond);
7010             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
7011                                                        : BI->getSuccessor(0));
7012           }
7013           BI->eraseFromParent();
7014           if (DTU)
7015             DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
7016           return true;
7017         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
7018           // Redirect all branches leading to UB into
7019           // a newly created unreachable block.
7020           BasicBlock *Unreachable = BasicBlock::Create(
7021               Predecessor->getContext(), "unreachable", BB->getParent(), BB);
7022           Builder.SetInsertPoint(Unreachable);
7023           // The new block contains only one instruction: Unreachable
7024           Builder.CreateUnreachable();
7025           for (auto &Case : SI->cases())
7026             if (Case.getCaseSuccessor() == BB) {
7027               BB->removePredecessor(Predecessor);
7028               Case.setSuccessor(Unreachable);
7029             }
7030           if (SI->getDefaultDest() == BB) {
7031             BB->removePredecessor(Predecessor);
7032             SI->setDefaultDest(Unreachable);
7033           }
7034 
7035           if (DTU)
7036             DTU->applyUpdates(
7037                 { { DominatorTree::Insert, Predecessor, Unreachable },
7038                   { DominatorTree::Delete, Predecessor, BB } });
7039           return true;
7040         }
7041       }
7042 
7043   return false;
7044 }
7045 
7046 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
7047   bool Changed = false;
7048 
7049   assert(BB && BB->getParent() && "Block not embedded in function!");
7050   assert(BB->getTerminator() && "Degenerate basic block encountered!");
7051 
7052   // Remove basic blocks that have no predecessors (except the entry block)...
7053   // or that just have themself as a predecessor.  These are unreachable.
7054   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
7055       BB->getSinglePredecessor() == BB) {
7056     LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
7057     DeleteDeadBlock(BB, DTU);
7058     return true;
7059   }
7060 
7061   // Check to see if we can constant propagate this terminator instruction
7062   // away...
7063   Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
7064                                     /*TLI=*/nullptr, DTU);
7065 
7066   // Check for and eliminate duplicate PHI nodes in this block.
7067   Changed |= EliminateDuplicatePHINodes(BB);
7068 
7069   // Check for and remove branches that will always cause undefined behavior.
7070   if (removeUndefIntroducingPredecessor(BB, DTU))
7071     return requestResimplify();
7072 
7073   // Merge basic blocks into their predecessor if there is only one distinct
7074   // pred, and if there is only one distinct successor of the predecessor, and
7075   // if there are no PHI nodes.
7076   if (MergeBlockIntoPredecessor(BB, DTU))
7077     return true;
7078 
7079   if (SinkCommon && Options.SinkCommonInsts)
7080     if (SinkCommonCodeFromPredecessors(BB, DTU) ||
7081         MergeCompatibleInvokes(BB, DTU)) {
7082       // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
7083       // so we may now how duplicate PHI's.
7084       // Let's rerun EliminateDuplicatePHINodes() first,
7085       // before FoldTwoEntryPHINode() potentially converts them into select's,
7086       // after which we'd need a whole EarlyCSE pass run to cleanup them.
7087       return true;
7088     }
7089 
7090   IRBuilder<> Builder(BB);
7091 
7092   if (Options.FoldTwoEntryPHINode) {
7093     // If there is a trivial two-entry PHI node in this basic block, and we can
7094     // eliminate it, do so now.
7095     if (auto *PN = dyn_cast<PHINode>(BB->begin()))
7096       if (PN->getNumIncomingValues() == 2)
7097         if (FoldTwoEntryPHINode(PN, TTI, DTU, DL))
7098           return true;
7099   }
7100 
7101   Instruction *Terminator = BB->getTerminator();
7102   Builder.SetInsertPoint(Terminator);
7103   switch (Terminator->getOpcode()) {
7104   case Instruction::Br:
7105     Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
7106     break;
7107   case Instruction::Resume:
7108     Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
7109     break;
7110   case Instruction::CleanupRet:
7111     Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
7112     break;
7113   case Instruction::Switch:
7114     Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
7115     break;
7116   case Instruction::Unreachable:
7117     Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
7118     break;
7119   case Instruction::IndirectBr:
7120     Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
7121     break;
7122   }
7123 
7124   return Changed;
7125 }
7126 
7127 bool SimplifyCFGOpt::run(BasicBlock *BB) {
7128   bool Changed = false;
7129 
7130   // Repeated simplify BB as long as resimplification is requested.
7131   do {
7132     Resimplify = false;
7133 
7134     // Perform one round of simplifcation. Resimplify flag will be set if
7135     // another iteration is requested.
7136     Changed |= simplifyOnce(BB);
7137   } while (Resimplify);
7138 
7139   return Changed;
7140 }
7141 
7142 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
7143                        DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
7144                        ArrayRef<WeakVH> LoopHeaders) {
7145   return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
7146                         Options)
7147       .run(BB);
7148 }
7149