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