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