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