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