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