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