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     // Conservatively return false if I is an inline-asm instruction. Sinking
1635     // and merging inline-asm instructions can potentially create arguments
1636     // that cannot satisfy the inline-asm constraints.
1637     // If the instruction has nomerge attribute, return false.
1638     if (const auto *C = dyn_cast<CallBase>(I))
1639       if (C->isInlineAsm() || C->cannotMerge())
1640         return false;
1641 
1642     // Each instruction must have zero or one use.
1643     if (HasUse && !I->hasOneUse())
1644       return false;
1645     if (!HasUse && !I->user_empty())
1646       return false;
1647   }
1648 
1649   const Instruction *I0 = Insts.front();
1650   for (auto *I : Insts)
1651     if (!I->isSameOperationAs(I0))
1652       return false;
1653 
1654   // All instructions in Insts are known to be the same opcode. If they have a
1655   // use, check that the only user is a PHI or in the same block as the
1656   // instruction, because if a user is in the same block as an instruction we're
1657   // contemplating sinking, it must already be determined to be sinkable.
1658   if (HasUse) {
1659     auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1660     auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1661     if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1662           auto *U = cast<Instruction>(*I->user_begin());
1663           return (PNUse &&
1664                   PNUse->getParent() == Succ &&
1665                   PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1666                  U->getParent() == I->getParent();
1667         }))
1668       return false;
1669   }
1670 
1671   // Because SROA can't handle speculating stores of selects, try not to sink
1672   // loads, stores or lifetime markers of allocas when we'd have to create a
1673   // PHI for the address operand. Also, because it is likely that loads or
1674   // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1675   // them.
1676   // This can cause code churn which can have unintended consequences down
1677   // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1678   // FIXME: This is a workaround for a deficiency in SROA - see
1679   // https://llvm.org/bugs/show_bug.cgi?id=30188
1680   if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1681         return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1682       }))
1683     return false;
1684   if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1685         return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1686       }))
1687     return false;
1688   if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1689         return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1690       }))
1691     return false;
1692 
1693   for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1694     Value *Op = I0->getOperand(OI);
1695     if (Op->getType()->isTokenTy())
1696       // Don't touch any operand of token type.
1697       return false;
1698 
1699     auto SameAsI0 = [&I0, OI](const Instruction *I) {
1700       assert(I->getNumOperands() == I0->getNumOperands());
1701       return I->getOperand(OI) == I0->getOperand(OI);
1702     };
1703     if (!all_of(Insts, SameAsI0)) {
1704       if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1705           !canReplaceOperandWithVariable(I0, OI))
1706         // We can't create a PHI from this GEP.
1707         return false;
1708       // Don't create indirect calls! The called value is the final operand.
1709       if (isa<CallBase>(I0) && OI == OE - 1) {
1710         // FIXME: if the call was *already* indirect, we should do this.
1711         return false;
1712       }
1713       for (auto *I : Insts)
1714         PHIOperands[I].push_back(I->getOperand(OI));
1715     }
1716   }
1717   return true;
1718 }
1719 
1720 // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1721 // instruction of every block in Blocks to their common successor, commoning
1722 // into one instruction.
1723 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
1724   auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1725 
1726   // canSinkLastInstruction returning true guarantees that every block has at
1727   // least one non-terminator instruction.
1728   SmallVector<Instruction*,4> Insts;
1729   for (auto *BB : Blocks) {
1730     Instruction *I = BB->getTerminator();
1731     do {
1732       I = I->getPrevNode();
1733     } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1734     if (!isa<DbgInfoIntrinsic>(I))
1735       Insts.push_back(I);
1736   }
1737 
1738   // The only checking we need to do now is that all users of all instructions
1739   // are the same PHI node. canSinkLastInstruction should have checked this but
1740   // it is slightly over-aggressive - it gets confused by commutative instructions
1741   // so double-check it here.
1742   Instruction *I0 = Insts.front();
1743   if (!I0->user_empty()) {
1744     auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1745     if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1746           auto *U = cast<Instruction>(*I->user_begin());
1747           return U == PNUse;
1748         }))
1749       return false;
1750   }
1751 
1752   // We don't need to do any more checking here; canSinkLastInstruction should
1753   // have done it all for us.
1754   SmallVector<Value*, 4> NewOperands;
1755   for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1756     // This check is different to that in canSinkLastInstruction. There, we
1757     // cared about the global view once simplifycfg (and instcombine) have
1758     // completed - it takes into account PHIs that become trivially
1759     // simplifiable.  However here we need a more local view; if an operand
1760     // differs we create a PHI and rely on instcombine to clean up the very
1761     // small mess we may make.
1762     bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1763       return I->getOperand(O) != I0->getOperand(O);
1764     });
1765     if (!NeedPHI) {
1766       NewOperands.push_back(I0->getOperand(O));
1767       continue;
1768     }
1769 
1770     // Create a new PHI in the successor block and populate it.
1771     auto *Op = I0->getOperand(O);
1772     assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1773     auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1774                                Op->getName() + ".sink", &BBEnd->front());
1775     for (auto *I : Insts)
1776       PN->addIncoming(I->getOperand(O), I->getParent());
1777     NewOperands.push_back(PN);
1778   }
1779 
1780   // Arbitrarily use I0 as the new "common" instruction; remap its operands
1781   // and move it to the start of the successor block.
1782   for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1783     I0->getOperandUse(O).set(NewOperands[O]);
1784   I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1785 
1786   // Update metadata and IR flags, and merge debug locations.
1787   for (auto *I : Insts)
1788     if (I != I0) {
1789       // The debug location for the "common" instruction is the merged locations
1790       // of all the commoned instructions.  We start with the original location
1791       // of the "common" instruction and iteratively merge each location in the
1792       // loop below.
1793       // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1794       // However, as N-way merge for CallInst is rare, so we use simplified API
1795       // instead of using complex API for N-way merge.
1796       I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1797       combineMetadataForCSE(I0, I, true);
1798       I0->andIRFlags(I);
1799     }
1800 
1801   if (!I0->user_empty()) {
1802     // canSinkLastInstruction checked that all instructions were used by
1803     // one and only one PHI node. Find that now, RAUW it to our common
1804     // instruction and nuke it.
1805     auto *PN = cast<PHINode>(*I0->user_begin());
1806     PN->replaceAllUsesWith(I0);
1807     PN->eraseFromParent();
1808   }
1809 
1810   // Finally nuke all instructions apart from the common instruction.
1811   for (auto *I : Insts)
1812     if (I != I0)
1813       I->eraseFromParent();
1814 
1815   return true;
1816 }
1817 
1818 namespace {
1819 
1820   // LockstepReverseIterator - Iterates through instructions
1821   // in a set of blocks in reverse order from the first non-terminator.
1822   // For example (assume all blocks have size n):
1823   //   LockstepReverseIterator I([B1, B2, B3]);
1824   //   *I-- = [B1[n], B2[n], B3[n]];
1825   //   *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1826   //   *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1827   //   ...
1828   class LockstepReverseIterator {
1829     ArrayRef<BasicBlock*> Blocks;
1830     SmallVector<Instruction*,4> Insts;
1831     bool Fail;
1832 
1833   public:
1834     LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
1835       reset();
1836     }
1837 
1838     void reset() {
1839       Fail = false;
1840       Insts.clear();
1841       for (auto *BB : Blocks) {
1842         Instruction *Inst = BB->getTerminator();
1843         for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1844           Inst = Inst->getPrevNode();
1845         if (!Inst) {
1846           // Block wasn't big enough.
1847           Fail = true;
1848           return;
1849         }
1850         Insts.push_back(Inst);
1851       }
1852     }
1853 
1854     bool isValid() const {
1855       return !Fail;
1856     }
1857 
1858     void operator--() {
1859       if (Fail)
1860         return;
1861       for (auto *&Inst : Insts) {
1862         for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1863           Inst = Inst->getPrevNode();
1864         // Already at beginning of block.
1865         if (!Inst) {
1866           Fail = true;
1867           return;
1868         }
1869       }
1870     }
1871 
1872     ArrayRef<Instruction*> operator * () const {
1873       return Insts;
1874     }
1875   };
1876 
1877 } // end anonymous namespace
1878 
1879 /// Check whether BB's predecessors end with unconditional branches. If it is
1880 /// true, sink any common code from the predecessors to BB.
1881 /// We also allow one predecessor to end with conditional branch (but no more
1882 /// than one).
1883 static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
1884                                            DomTreeUpdater *DTU) {
1885   // We support two situations:
1886   //   (1) all incoming arcs are unconditional
1887   //   (2) one incoming arc is conditional
1888   //
1889   // (2) is very common in switch defaults and
1890   // else-if patterns;
1891   //
1892   //   if (a) f(1);
1893   //   else if (b) f(2);
1894   //
1895   // produces:
1896   //
1897   //       [if]
1898   //      /    \
1899   //    [f(1)] [if]
1900   //      |     | \
1901   //      |     |  |
1902   //      |  [f(2)]|
1903   //       \    | /
1904   //        [ end ]
1905   //
1906   // [end] has two unconditional predecessor arcs and one conditional. The
1907   // conditional refers to the implicit empty 'else' arc. This conditional
1908   // arc can also be caused by an empty default block in a switch.
1909   //
1910   // In this case, we attempt to sink code from all *unconditional* arcs.
1911   // If we can sink instructions from these arcs (determined during the scan
1912   // phase below) we insert a common successor for all unconditional arcs and
1913   // connect that to [end], to enable sinking:
1914   //
1915   //       [if]
1916   //      /    \
1917   //    [x(1)] [if]
1918   //      |     | \
1919   //      |     |  \
1920   //      |  [x(2)] |
1921   //       \   /    |
1922   //   [sink.split] |
1923   //         \     /
1924   //         [ end ]
1925   //
1926   SmallVector<BasicBlock*,4> UnconditionalPreds;
1927   Instruction *Cond = nullptr;
1928   for (auto *B : predecessors(BB)) {
1929     auto *T = B->getTerminator();
1930     if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1931       UnconditionalPreds.push_back(B);
1932     else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1933       Cond = T;
1934     else
1935       return false;
1936   }
1937   if (UnconditionalPreds.size() < 2)
1938     return false;
1939 
1940   // We take a two-step approach to tail sinking. First we scan from the end of
1941   // each block upwards in lockstep. If the n'th instruction from the end of each
1942   // block can be sunk, those instructions are added to ValuesToSink and we
1943   // carry on. If we can sink an instruction but need to PHI-merge some operands
1944   // (because they're not identical in each instruction) we add these to
1945   // PHIOperands.
1946   unsigned ScanIdx = 0;
1947   SmallPtrSet<Value*,4> InstructionsToSink;
1948   DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
1949   LockstepReverseIterator LRI(UnconditionalPreds);
1950   while (LRI.isValid() &&
1951          canSinkInstructions(*LRI, PHIOperands)) {
1952     LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
1953                       << "\n");
1954     InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1955     ++ScanIdx;
1956     --LRI;
1957   }
1958 
1959   // If no instructions can be sunk, early-return.
1960   if (ScanIdx == 0)
1961     return false;
1962 
1963   bool Changed = false;
1964 
1965   auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1966     unsigned NumPHIdValues = 0;
1967     for (auto *I : *LRI)
1968       for (auto *V : PHIOperands[I])
1969         if (InstructionsToSink.count(V) == 0)
1970           ++NumPHIdValues;
1971     LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1972     unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1973     if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1974         NumPHIInsts++;
1975 
1976     return NumPHIInsts <= 1;
1977   };
1978 
1979   if (Cond) {
1980     // Check if we would actually sink anything first! This mutates the CFG and
1981     // adds an extra block. The goal in doing this is to allow instructions that
1982     // couldn't be sunk before to be sunk - obviously, speculatable instructions
1983     // (such as trunc, add) can be sunk and predicated already. So we check that
1984     // we're going to sink at least one non-speculatable instruction.
1985     LRI.reset();
1986     unsigned Idx = 0;
1987     bool Profitable = false;
1988     while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1989       if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1990         Profitable = true;
1991         break;
1992       }
1993       --LRI;
1994       ++Idx;
1995     }
1996     if (!Profitable)
1997       return false;
1998 
1999     LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2000     // We have a conditional edge and we're going to sink some instructions.
2001     // Insert a new block postdominating all blocks we're going to sink from.
2002     if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2003       // Edges couldn't be split.
2004       return false;
2005     Changed = true;
2006   }
2007 
2008   // Now that we've analyzed all potential sinking candidates, perform the
2009   // actual sink. We iteratively sink the last non-terminator of the source
2010   // blocks into their common successor unless doing so would require too
2011   // many PHI instructions to be generated (currently only one PHI is allowed
2012   // per sunk instruction).
2013   //
2014   // We can use InstructionsToSink to discount values needing PHI-merging that will
2015   // actually be sunk in a later iteration. This allows us to be more
2016   // aggressive in what we sink. This does allow a false positive where we
2017   // sink presuming a later value will also be sunk, but stop half way through
2018   // and never actually sink it which means we produce more PHIs than intended.
2019   // This is unlikely in practice though.
2020   unsigned SinkIdx = 0;
2021   for (; SinkIdx != ScanIdx; ++SinkIdx) {
2022     LLVM_DEBUG(dbgs() << "SINK: Sink: "
2023                       << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2024                       << "\n");
2025 
2026     // Because we've sunk every instruction in turn, the current instruction to
2027     // sink is always at index 0.
2028     LRI.reset();
2029     if (!ProfitableToSinkInstruction(LRI)) {
2030       // Too many PHIs would be created.
2031       LLVM_DEBUG(
2032           dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2033       break;
2034     }
2035 
2036     if (!sinkLastInstruction(UnconditionalPreds)) {
2037       LLVM_DEBUG(
2038           dbgs()
2039           << "SINK: stopping here, failed to actually sink instruction!\n");
2040       break;
2041     }
2042 
2043     NumSinkCommonInstrs++;
2044     Changed = true;
2045   }
2046   if (SinkIdx != 0)
2047     ++NumSinkCommonCode;
2048   return Changed;
2049 }
2050 
2051 /// Determine if we can hoist sink a sole store instruction out of a
2052 /// conditional block.
2053 ///
2054 /// We are looking for code like the following:
2055 ///   BrBB:
2056 ///     store i32 %add, i32* %arrayidx2
2057 ///     ... // No other stores or function calls (we could be calling a memory
2058 ///     ... // function).
2059 ///     %cmp = icmp ult %x, %y
2060 ///     br i1 %cmp, label %EndBB, label %ThenBB
2061 ///   ThenBB:
2062 ///     store i32 %add5, i32* %arrayidx2
2063 ///     br label EndBB
2064 ///   EndBB:
2065 ///     ...
2066 ///   We are going to transform this into:
2067 ///   BrBB:
2068 ///     store i32 %add, i32* %arrayidx2
2069 ///     ... //
2070 ///     %cmp = icmp ult %x, %y
2071 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
2072 ///     store i32 %add.add5, i32* %arrayidx2
2073 ///     ...
2074 ///
2075 /// \return The pointer to the value of the previous store if the store can be
2076 ///         hoisted into the predecessor block. 0 otherwise.
2077 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
2078                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
2079   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2080   if (!StoreToHoist)
2081     return nullptr;
2082 
2083   // Volatile or atomic.
2084   if (!StoreToHoist->isSimple())
2085     return nullptr;
2086 
2087   Value *StorePtr = StoreToHoist->getPointerOperand();
2088 
2089   // Look for a store to the same pointer in BrBB.
2090   unsigned MaxNumInstToLookAt = 9;
2091   // Skip pseudo probe intrinsic calls which are not really killing any memory
2092   // accesses.
2093   for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2094     if (!MaxNumInstToLookAt)
2095       break;
2096     --MaxNumInstToLookAt;
2097 
2098     // Could be calling an instruction that affects memory like free().
2099     if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
2100       return nullptr;
2101 
2102     if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2103       // Found the previous store make sure it stores to the same location.
2104       if (SI->getPointerOperand() == StorePtr)
2105         // Found the previous store, return its value operand.
2106         return SI->getValueOperand();
2107       return nullptr; // Unknown store.
2108     }
2109   }
2110 
2111   return nullptr;
2112 }
2113 
2114 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2115 /// converted to selects.
2116 static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
2117                                            BasicBlock *EndBB,
2118                                            unsigned &SpeculatedInstructions,
2119                                            InstructionCost &Cost,
2120                                            const TargetTransformInfo &TTI) {
2121   TargetTransformInfo::TargetCostKind CostKind =
2122     BB->getParent()->hasMinSize()
2123     ? TargetTransformInfo::TCK_CodeSize
2124     : TargetTransformInfo::TCK_SizeAndLatency;
2125 
2126   bool HaveRewritablePHIs = false;
2127   for (PHINode &PN : EndBB->phis()) {
2128     Value *OrigV = PN.getIncomingValueForBlock(BB);
2129     Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2130 
2131     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2132     // Skip PHIs which are trivial.
2133     if (ThenV == OrigV)
2134       continue;
2135 
2136     Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2137                                    CmpInst::BAD_ICMP_PREDICATE, CostKind);
2138 
2139     // Don't convert to selects if we could remove undefined behavior instead.
2140     if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2141         passingValueIsAlwaysUndefined(ThenV, &PN))
2142       return false;
2143 
2144     HaveRewritablePHIs = true;
2145     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2146     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2147     if (!OrigCE && !ThenCE)
2148       continue; // Known safe and cheap.
2149 
2150     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2151         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
2152       return false;
2153     InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2154     InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2155     InstructionCost MaxCost =
2156         2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2157     if (OrigCost + ThenCost > MaxCost)
2158       return false;
2159 
2160     // Account for the cost of an unfolded ConstantExpr which could end up
2161     // getting expanded into Instructions.
2162     // FIXME: This doesn't account for how many operations are combined in the
2163     // constant expression.
2164     ++SpeculatedInstructions;
2165     if (SpeculatedInstructions > 1)
2166       return false;
2167   }
2168 
2169   return HaveRewritablePHIs;
2170 }
2171 
2172 /// Speculate a conditional basic block flattening the CFG.
2173 ///
2174 /// Note that this is a very risky transform currently. Speculating
2175 /// instructions like this is most often not desirable. Instead, there is an MI
2176 /// pass which can do it with full awareness of the resource constraints.
2177 /// However, some cases are "obvious" and we should do directly. An example of
2178 /// this is speculating a single, reasonably cheap instruction.
2179 ///
2180 /// There is only one distinct advantage to flattening the CFG at the IR level:
2181 /// it makes very common but simplistic optimizations such as are common in
2182 /// instcombine and the DAG combiner more powerful by removing CFG edges and
2183 /// modeling their effects with easier to reason about SSA value graphs.
2184 ///
2185 ///
2186 /// An illustration of this transform is turning this IR:
2187 /// \code
2188 ///   BB:
2189 ///     %cmp = icmp ult %x, %y
2190 ///     br i1 %cmp, label %EndBB, label %ThenBB
2191 ///   ThenBB:
2192 ///     %sub = sub %x, %y
2193 ///     br label BB2
2194 ///   EndBB:
2195 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2196 ///     ...
2197 /// \endcode
2198 ///
2199 /// Into this IR:
2200 /// \code
2201 ///   BB:
2202 ///     %cmp = icmp ult %x, %y
2203 ///     %sub = sub %x, %y
2204 ///     %cond = select i1 %cmp, 0, %sub
2205 ///     ...
2206 /// \endcode
2207 ///
2208 /// \returns true if the conditional block is removed.
2209 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2210                                             const TargetTransformInfo &TTI) {
2211   // Be conservative for now. FP select instruction can often be expensive.
2212   Value *BrCond = BI->getCondition();
2213   if (isa<FCmpInst>(BrCond))
2214     return false;
2215 
2216   BasicBlock *BB = BI->getParent();
2217   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2218   InstructionCost Budget =
2219       PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2220 
2221   // If ThenBB is actually on the false edge of the conditional branch, remember
2222   // to swap the select operands later.
2223   bool Invert = false;
2224   if (ThenBB != BI->getSuccessor(0)) {
2225     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2226     Invert = true;
2227   }
2228   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2229 
2230   // Keep a count of how many times instructions are used within ThenBB when
2231   // they are candidates for sinking into ThenBB. Specifically:
2232   // - They are defined in BB, and
2233   // - They have no side effects, and
2234   // - All of their uses are in ThenBB.
2235   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2236 
2237   SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2238 
2239   unsigned SpeculatedInstructions = 0;
2240   Value *SpeculatedStoreValue = nullptr;
2241   StoreInst *SpeculatedStore = nullptr;
2242   for (BasicBlock::iterator BBI = ThenBB->begin(),
2243                             BBE = std::prev(ThenBB->end());
2244        BBI != BBE; ++BBI) {
2245     Instruction *I = &*BBI;
2246     // Skip debug info.
2247     if (isa<DbgInfoIntrinsic>(I)) {
2248       SpeculatedDbgIntrinsics.push_back(I);
2249       continue;
2250     }
2251 
2252     // Skip pseudo probes. The consequence is we lose track of the branch
2253     // probability for ThenBB, which is fine since the optimization here takes
2254     // place regardless of the branch probability.
2255     if (isa<PseudoProbeInst>(I)) {
2256       continue;
2257     }
2258 
2259     // Only speculatively execute a single instruction (not counting the
2260     // terminator) for now.
2261     ++SpeculatedInstructions;
2262     if (SpeculatedInstructions > 1)
2263       return false;
2264 
2265     // Don't hoist the instruction if it's unsafe or expensive.
2266     if (!isSafeToSpeculativelyExecute(I) &&
2267         !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2268                                   I, BB, ThenBB, EndBB))))
2269       return false;
2270     if (!SpeculatedStoreValue &&
2271         computeSpeculationCost(I, TTI) >
2272             PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2273       return false;
2274 
2275     // Store the store speculation candidate.
2276     if (SpeculatedStoreValue)
2277       SpeculatedStore = cast<StoreInst>(I);
2278 
2279     // Do not hoist the instruction if any of its operands are defined but not
2280     // used in BB. The transformation will prevent the operand from
2281     // being sunk into the use block.
2282     for (Use &Op : I->operands()) {
2283       Instruction *OpI = dyn_cast<Instruction>(Op);
2284       if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2285         continue; // Not a candidate for sinking.
2286 
2287       ++SinkCandidateUseCounts[OpI];
2288     }
2289   }
2290 
2291   // Consider any sink candidates which are only used in ThenBB as costs for
2292   // speculation. Note, while we iterate over a DenseMap here, we are summing
2293   // and so iteration order isn't significant.
2294   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
2295            I = SinkCandidateUseCounts.begin(),
2296            E = SinkCandidateUseCounts.end();
2297        I != E; ++I)
2298     if (I->first->hasNUses(I->second)) {
2299       ++SpeculatedInstructions;
2300       if (SpeculatedInstructions > 1)
2301         return false;
2302     }
2303 
2304   // Check that we can insert the selects and that it's not too expensive to do
2305   // so.
2306   bool Convert = SpeculatedStore != nullptr;
2307   InstructionCost Cost = 0;
2308   Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2309                                             SpeculatedInstructions,
2310                                             Cost, TTI);
2311   if (!Convert || Cost > Budget)
2312     return false;
2313 
2314   // If we get here, we can hoist the instruction and if-convert.
2315   LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2316 
2317   // Insert a select of the value of the speculated store.
2318   if (SpeculatedStoreValue) {
2319     IRBuilder<NoFolder> Builder(BI);
2320     Value *TrueV = SpeculatedStore->getValueOperand();
2321     Value *FalseV = SpeculatedStoreValue;
2322     if (Invert)
2323       std::swap(TrueV, FalseV);
2324     Value *S = Builder.CreateSelect(
2325         BrCond, TrueV, FalseV, "spec.store.select", BI);
2326     SpeculatedStore->setOperand(0, S);
2327     SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2328                                          SpeculatedStore->getDebugLoc());
2329   }
2330 
2331   // Metadata can be dependent on the condition we are hoisting above.
2332   // Conservatively strip all metadata on the instruction. Drop the debug loc
2333   // to avoid making it appear as if the condition is a constant, which would
2334   // be misleading while debugging.
2335   for (auto &I : *ThenBB) {
2336     if (!SpeculatedStoreValue || &I != SpeculatedStore)
2337       I.setDebugLoc(DebugLoc());
2338     I.dropUnknownNonDebugMetadata();
2339   }
2340 
2341   // A hoisted conditional probe should be treated as dangling so that it will
2342   // not be over-counted when the samples collected on the non-conditional path
2343   // are counted towards the conditional path. We leave it for the counts
2344   // inference algorithm to figure out a proper count for a danglng probe.
2345   moveAndDanglePseudoProbes(ThenBB, BI);
2346 
2347   // Hoist the instructions.
2348   BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2349                            ThenBB->begin(), std::prev(ThenBB->end()));
2350 
2351   // Insert selects and rewrite the PHI operands.
2352   IRBuilder<NoFolder> Builder(BI);
2353   for (PHINode &PN : EndBB->phis()) {
2354     unsigned OrigI = PN.getBasicBlockIndex(BB);
2355     unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2356     Value *OrigV = PN.getIncomingValue(OrigI);
2357     Value *ThenV = PN.getIncomingValue(ThenI);
2358 
2359     // Skip PHIs which are trivial.
2360     if (OrigV == ThenV)
2361       continue;
2362 
2363     // Create a select whose true value is the speculatively executed value and
2364     // false value is the pre-existing value. Swap them if the branch
2365     // destinations were inverted.
2366     Value *TrueV = ThenV, *FalseV = OrigV;
2367     if (Invert)
2368       std::swap(TrueV, FalseV);
2369     Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
2370     PN.setIncomingValue(OrigI, V);
2371     PN.setIncomingValue(ThenI, V);
2372   }
2373 
2374   // Remove speculated dbg intrinsics.
2375   // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2376   // dbg value for the different flows and inserting it after the select.
2377   for (Instruction *I : SpeculatedDbgIntrinsics)
2378     I->eraseFromParent();
2379 
2380   ++NumSpeculations;
2381   return true;
2382 }
2383 
2384 /// Return true if we can thread a branch across this block.
2385 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2386   int Size = 0;
2387 
2388   for (Instruction &I : BB->instructionsWithoutDebug()) {
2389     if (Size > MaxSmallBlockSize)
2390       return false; // Don't clone large BB's.
2391 
2392     // Can't fold blocks that contain noduplicate or convergent calls.
2393     if (CallInst *CI = dyn_cast<CallInst>(&I))
2394       if (CI->cannotDuplicate() || CI->isConvergent())
2395         return false;
2396 
2397     // We will delete Phis while threading, so Phis should not be accounted in
2398     // block's size
2399     if (!isa<PHINode>(I))
2400       ++Size;
2401 
2402     // We can only support instructions that do not define values that are
2403     // live outside of the current basic block.
2404     for (User *U : I.users()) {
2405       Instruction *UI = cast<Instruction>(U);
2406       if (UI->getParent() != BB || isa<PHINode>(UI))
2407         return false;
2408     }
2409 
2410     // Looks ok, continue checking.
2411   }
2412 
2413   return true;
2414 }
2415 
2416 /// If we have a conditional branch on a PHI node value that is defined in the
2417 /// same block as the branch and if any PHI entries are constants, thread edges
2418 /// corresponding to that entry to be branches to their ultimate destination.
2419 static bool FoldCondBranchOnPHI(BranchInst *BI, DomTreeUpdater *DTU,
2420                                 const DataLayout &DL, AssumptionCache *AC) {
2421   BasicBlock *BB = BI->getParent();
2422   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
2423   // NOTE: we currently cannot transform this case if the PHI node is used
2424   // outside of the block.
2425   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2426     return false;
2427 
2428   // Degenerate case of a single entry PHI.
2429   if (PN->getNumIncomingValues() == 1) {
2430     FoldSingleEntryPHINodes(PN->getParent());
2431     return true;
2432   }
2433 
2434   // Now we know that this block has multiple preds and two succs.
2435   if (!BlockIsSimpleEnoughToThreadThrough(BB))
2436     return false;
2437 
2438   // Okay, this is a simple enough basic block.  See if any phi values are
2439   // constants.
2440   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2441     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
2442     if (!CB || !CB->getType()->isIntegerTy(1))
2443       continue;
2444 
2445     // Okay, we now know that all edges from PredBB should be revectored to
2446     // branch to RealDest.
2447     BasicBlock *PredBB = PN->getIncomingBlock(i);
2448     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
2449 
2450     if (RealDest == BB)
2451       continue; // Skip self loops.
2452     // Skip if the predecessor's terminator is an indirect branch.
2453     if (isa<IndirectBrInst>(PredBB->getTerminator()))
2454       continue;
2455 
2456     SmallVector<DominatorTree::UpdateType, 3> Updates;
2457 
2458     // The dest block might have PHI nodes, other predecessors and other
2459     // difficult cases.  Instead of being smart about this, just insert a new
2460     // block that jumps to the destination block, effectively splitting
2461     // the edge we are about to create.
2462     BasicBlock *EdgeBB =
2463         BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2464                            RealDest->getParent(), RealDest);
2465     BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
2466     Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
2467     CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
2468 
2469     // Update PHI nodes.
2470     AddPredecessorToBlock(RealDest, EdgeBB, BB);
2471 
2472     // BB may have instructions that are being threaded over.  Clone these
2473     // instructions into EdgeBB.  We know that there will be no uses of the
2474     // cloned instructions outside of EdgeBB.
2475     BasicBlock::iterator InsertPt = EdgeBB->begin();
2476     DenseMap<Value *, Value *> TranslateMap; // Track translated values.
2477     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2478       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2479         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2480         continue;
2481       }
2482       // Clone the instruction.
2483       Instruction *N = BBI->clone();
2484       if (BBI->hasName())
2485         N->setName(BBI->getName() + ".c");
2486 
2487       // Update operands due to translation.
2488       for (Use &Op : N->operands()) {
2489         DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
2490         if (PI != TranslateMap.end())
2491           Op = PI->second;
2492       }
2493 
2494       // Check for trivial simplification.
2495       if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
2496         if (!BBI->use_empty())
2497           TranslateMap[&*BBI] = V;
2498         if (!N->mayHaveSideEffects()) {
2499           N->deleteValue(); // Instruction folded away, don't need actual inst
2500           N = nullptr;
2501         }
2502       } else {
2503         if (!BBI->use_empty())
2504           TranslateMap[&*BBI] = N;
2505       }
2506       if (N) {
2507         // Insert the new instruction into its new home.
2508         EdgeBB->getInstList().insert(InsertPt, N);
2509 
2510         // Register the new instruction with the assumption cache if necessary.
2511         if (AC && match(N, m_Intrinsic<Intrinsic::assume>()))
2512           AC->registerAssumption(cast<IntrinsicInst>(N));
2513       }
2514     }
2515 
2516     // Loop over all of the edges from PredBB to BB, changing them to branch
2517     // to EdgeBB instead.
2518     Instruction *PredBBTI = PredBB->getTerminator();
2519     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2520       if (PredBBTI->getSuccessor(i) == BB) {
2521         BB->removePredecessor(PredBB);
2522         PredBBTI->setSuccessor(i, EdgeBB);
2523       }
2524 
2525     Updates.push_back({DominatorTree::Insert, PredBB, EdgeBB});
2526     Updates.push_back({DominatorTree::Delete, PredBB, BB});
2527 
2528     if (DTU)
2529       DTU->applyUpdates(Updates);
2530 
2531     // Recurse, simplifying any other constants.
2532     return FoldCondBranchOnPHI(BI, DTU, DL, AC) || true;
2533   }
2534 
2535   return false;
2536 }
2537 
2538 /// Given a BB that starts with the specified two-entry PHI node,
2539 /// see if we can eliminate it.
2540 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2541                                 DomTreeUpdater *DTU, const DataLayout &DL) {
2542   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
2543   // statement", which has a very simple dominance structure.  Basically, we
2544   // are trying to find the condition that is being branched on, which
2545   // subsequently causes this merge to happen.  We really want control
2546   // dependence information for this check, but simplifycfg can't keep it up
2547   // to date, and this catches most of the cases we care about anyway.
2548   BasicBlock *BB = PN->getParent();
2549 
2550   BasicBlock *IfTrue, *IfFalse;
2551   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
2552   if (!IfCond ||
2553       // Don't bother if the branch will be constant folded trivially.
2554       isa<ConstantInt>(IfCond))
2555     return false;
2556 
2557   // Okay, we found that we can merge this two-entry phi node into a select.
2558   // Doing so would require us to fold *all* two entry phi nodes in this block.
2559   // At some point this becomes non-profitable (particularly if the target
2560   // doesn't support cmov's).  Only do this transformation if there are two or
2561   // fewer PHI nodes in this block.
2562   unsigned NumPhis = 0;
2563   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2564     if (NumPhis > 2)
2565       return false;
2566 
2567   // Loop over the PHI's seeing if we can promote them all to select
2568   // instructions.  While we are at it, keep track of the instructions
2569   // that need to be moved to the dominating block.
2570   SmallPtrSet<Instruction *, 4> AggressiveInsts;
2571   InstructionCost Cost = 0;
2572   InstructionCost Budget =
2573       TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2574 
2575   bool Changed = false;
2576   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2577     PHINode *PN = cast<PHINode>(II++);
2578     if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
2579       PN->replaceAllUsesWith(V);
2580       PN->eraseFromParent();
2581       Changed = true;
2582       continue;
2583     }
2584 
2585     if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
2586                              Cost, Budget, TTI) ||
2587         !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
2588                              Cost, Budget, TTI))
2589       return Changed;
2590   }
2591 
2592   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
2593   // we ran out of PHIs then we simplified them all.
2594   PN = dyn_cast<PHINode>(BB->begin());
2595   if (!PN)
2596     return true;
2597 
2598   // Return true if at least one of these is a 'not', and another is either
2599   // a 'not' too, or a constant.
2600   auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
2601     if (!match(V0, m_Not(m_Value())))
2602       std::swap(V0, V1);
2603     auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
2604     return match(V0, m_Not(m_Value())) && match(V1, Invertible);
2605   };
2606 
2607   // Don't fold i1 branches on PHIs which contain binary operators or
2608   // select form of or/ands, unless one of the incoming values is an 'not' and
2609   // another one is freely invertible.
2610   // These can often be turned into switches and other things.
2611   auto IsBinOpOrAnd = [](Value *V) {
2612     return match(
2613         V, m_CombineOr(m_BinOp(), m_CombineOr(m_LogicalAnd(), m_LogicalOr())));
2614   };
2615   if (PN->getType()->isIntegerTy(1) &&
2616       (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
2617        IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
2618       !CanHoistNotFromBothValues(PN->getIncomingValue(0),
2619                                  PN->getIncomingValue(1)))
2620     return Changed;
2621 
2622   // If all PHI nodes are promotable, check to make sure that all instructions
2623   // in the predecessor blocks can be promoted as well. If not, we won't be able
2624   // to get rid of the control flow, so it's not worth promoting to select
2625   // instructions.
2626   BasicBlock *DomBlock = nullptr;
2627   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2628   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2629   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
2630     IfBlock1 = nullptr;
2631   } else {
2632     DomBlock = *pred_begin(IfBlock1);
2633     for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
2634       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I) &&
2635           !isa<PseudoProbeInst>(I)) {
2636         // This is not an aggressive instruction that we can promote.
2637         // Because of this, we won't be able to get rid of the control flow, so
2638         // the xform is not worth it.
2639         return Changed;
2640       }
2641   }
2642 
2643   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
2644     IfBlock2 = nullptr;
2645   } else {
2646     DomBlock = *pred_begin(IfBlock2);
2647     for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
2648       if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I) &&
2649           !isa<PseudoProbeInst>(I)) {
2650         // This is not an aggressive instruction that we can promote.
2651         // Because of this, we won't be able to get rid of the control flow, so
2652         // the xform is not worth it.
2653         return Changed;
2654       }
2655   }
2656   assert(DomBlock && "Failed to find root DomBlock");
2657 
2658   LLVM_DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond
2659                     << "  T: " << IfTrue->getName()
2660                     << "  F: " << IfFalse->getName() << "\n");
2661 
2662   // If we can still promote the PHI nodes after this gauntlet of tests,
2663   // do all of the PHI's now.
2664   Instruction *InsertPt = DomBlock->getTerminator();
2665   IRBuilder<NoFolder> Builder(InsertPt);
2666 
2667   // Move all 'aggressive' instructions, which are defined in the
2668   // conditional parts of the if's up to the dominating block.
2669   if (IfBlock1)
2670     hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
2671   if (IfBlock2)
2672     hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
2673 
2674   // Propagate fast-math-flags from phi nodes to replacement selects.
2675   IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2676   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2677     if (isa<FPMathOperator>(PN))
2678       Builder.setFastMathFlags(PN->getFastMathFlags());
2679 
2680     // Change the PHI node into a select instruction.
2681     Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
2682     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
2683 
2684     Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2685     PN->replaceAllUsesWith(Sel);
2686     Sel->takeName(PN);
2687     PN->eraseFromParent();
2688   }
2689 
2690   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2691   // has been flattened.  Change DomBlock to jump directly to our new block to
2692   // avoid other simplifycfg's kicking in on the diamond.
2693   Instruction *OldTI = DomBlock->getTerminator();
2694   Builder.SetInsertPoint(OldTI);
2695   Builder.CreateBr(BB);
2696 
2697   SmallVector<DominatorTree::UpdateType, 3> Updates;
2698   if (DTU) {
2699     Updates.push_back({DominatorTree::Insert, DomBlock, BB});
2700     for (auto *Successor : successors(DomBlock))
2701       Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
2702   }
2703 
2704   OldTI->eraseFromParent();
2705   if (DTU)
2706     DTU->applyUpdates(Updates);
2707 
2708   return true;
2709 }
2710 
2711 /// If we found a conditional branch that goes to two returning blocks,
2712 /// try to merge them together into one return,
2713 /// introducing a select if the return values disagree.
2714 bool SimplifyCFGOpt::SimplifyCondBranchToTwoReturns(BranchInst *BI,
2715                                                     IRBuilder<> &Builder) {
2716   auto *BB = BI->getParent();
2717   assert(BI->isConditional() && "Must be a conditional branch");
2718   BasicBlock *TrueSucc = BI->getSuccessor(0);
2719   BasicBlock *FalseSucc = BI->getSuccessor(1);
2720   // NOTE: destinations may match, this could be degenerate uncond branch.
2721   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2722   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
2723 
2724   // Check to ensure both blocks are empty (just a return) or optionally empty
2725   // with PHI nodes.  If there are other instructions, merging would cause extra
2726   // computation on one path or the other.
2727   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2728     return false;
2729   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
2730     return false;
2731 
2732   Builder.SetInsertPoint(BI);
2733   // Okay, we found a branch that is going to two return nodes.  If
2734   // there is no return value for this function, just change the
2735   // branch into a return.
2736   if (FalseRet->getNumOperands() == 0) {
2737     TrueSucc->removePredecessor(BB);
2738     FalseSucc->removePredecessor(BB);
2739     Builder.CreateRetVoid();
2740     EraseTerminatorAndDCECond(BI);
2741     if (DTU) {
2742       SmallVector<DominatorTree::UpdateType, 2> Updates;
2743       Updates.push_back({DominatorTree::Delete, BB, TrueSucc});
2744       if (TrueSucc != FalseSucc)
2745         Updates.push_back({DominatorTree::Delete, BB, FalseSucc});
2746       DTU->applyUpdates(Updates);
2747     }
2748     return true;
2749   }
2750 
2751   // Otherwise, figure out what the true and false return values are
2752   // so we can insert a new select instruction.
2753   Value *TrueValue = TrueRet->getReturnValue();
2754   Value *FalseValue = FalseRet->getReturnValue();
2755 
2756   // Unwrap any PHI nodes in the return blocks.
2757   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2758     if (TVPN->getParent() == TrueSucc)
2759       TrueValue = TVPN->getIncomingValueForBlock(BB);
2760   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2761     if (FVPN->getParent() == FalseSucc)
2762       FalseValue = FVPN->getIncomingValueForBlock(BB);
2763 
2764   // In order for this transformation to be safe, we must be able to
2765   // unconditionally execute both operands to the return.  This is
2766   // normally the case, but we could have a potentially-trapping
2767   // constant expression that prevents this transformation from being
2768   // safe.
2769   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2770     if (TCV->canTrap())
2771       return false;
2772   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2773     if (FCV->canTrap())
2774       return false;
2775 
2776   // Okay, we collected all the mapped values and checked them for sanity, and
2777   // defined to really do this transformation.  First, update the CFG.
2778   TrueSucc->removePredecessor(BB);
2779   FalseSucc->removePredecessor(BB);
2780 
2781   // Insert select instructions where needed.
2782   Value *BrCond = BI->getCondition();
2783   if (TrueValue) {
2784     // Insert a select if the results differ.
2785     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2786     } else if (isa<UndefValue>(TrueValue)) {
2787       TrueValue = FalseValue;
2788     } else {
2789       TrueValue =
2790           Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
2791     }
2792   }
2793 
2794   Value *RI =
2795       !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2796 
2797   (void)RI;
2798 
2799   LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2800                     << "\n  " << *BI << "\nNewRet = " << *RI << "\nTRUEBLOCK: "
2801                     << *TrueSucc << "\nFALSEBLOCK: " << *FalseSucc);
2802 
2803   EraseTerminatorAndDCECond(BI);
2804   if (DTU) {
2805     SmallVector<DominatorTree::UpdateType, 2> Updates;
2806     Updates.push_back({DominatorTree::Delete, BB, TrueSucc});
2807     if (TrueSucc != FalseSucc)
2808       Updates.push_back({DominatorTree::Delete, BB, FalseSucc});
2809     DTU->applyUpdates(Updates);
2810   }
2811 
2812   return true;
2813 }
2814 
2815 /// Return true if either PBI or BI has branch weight available, and store
2816 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2817 /// not have branch weight, use 1:1 as its weight.
2818 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2819                                    uint64_t &PredTrueWeight,
2820                                    uint64_t &PredFalseWeight,
2821                                    uint64_t &SuccTrueWeight,
2822                                    uint64_t &SuccFalseWeight) {
2823   bool PredHasWeights =
2824       PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2825   bool SuccHasWeights =
2826       BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2827   if (PredHasWeights || SuccHasWeights) {
2828     if (!PredHasWeights)
2829       PredTrueWeight = PredFalseWeight = 1;
2830     if (!SuccHasWeights)
2831       SuccTrueWeight = SuccFalseWeight = 1;
2832     return true;
2833   } else {
2834     return false;
2835   }
2836 }
2837 
2838 // Determine if the two branches share a common destination,
2839 // and deduce a glue that we need to use to join branch's conditions
2840 // to arrive at the common destination.
2841 static Optional<std::pair<Instruction::BinaryOps, bool>>
2842 CheckIfCondBranchesShareCommonDestination(BranchInst *BI, BranchInst *PBI) {
2843   assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
2844          "Both blocks must end with a conditional branches.");
2845   assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&
2846          "PredBB must be a predecessor of BB.");
2847 
2848   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2849     return {{Instruction::Or, false}};
2850   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2851     return {{Instruction::And, false}};
2852   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2853     return {{Instruction::And, true}};
2854   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2855     return {{Instruction::Or, true}};
2856   return None;
2857 }
2858 
2859 static bool PerformBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI,
2860                                              DomTreeUpdater *DTU,
2861                                              MemorySSAUpdater *MSSAU) {
2862   BasicBlock *BB = BI->getParent();
2863   BasicBlock *PredBlock = PBI->getParent();
2864 
2865   // Determine if the two branches share a common destination.
2866   Instruction::BinaryOps Opc;
2867   bool InvertPredCond;
2868   std::tie(Opc, InvertPredCond) =
2869       *CheckIfCondBranchesShareCommonDestination(BI, PBI);
2870 
2871   LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2872 
2873   IRBuilder<> Builder(PBI);
2874   // The builder is used to create instructions to eliminate the branch in BB.
2875   // If BB's terminator has !annotation metadata, add it to the new
2876   // instructions.
2877   Builder.CollectMetadataToCopy(BB->getTerminator(),
2878                                 {LLVMContext::MD_annotation});
2879 
2880   // If we need to invert the condition in the pred block to match, do so now.
2881   if (InvertPredCond) {
2882     Value *NewCond = PBI->getCondition();
2883     if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2884       CmpInst *CI = cast<CmpInst>(NewCond);
2885       CI->setPredicate(CI->getInversePredicate());
2886     } else {
2887       NewCond =
2888           Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
2889     }
2890 
2891     PBI->setCondition(NewCond);
2892     PBI->swapSuccessors();
2893   }
2894 
2895   BasicBlock *UniqueSucc =
2896       PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
2897 
2898   // Before cloning instructions, notify the successor basic block that it
2899   // is about to have a new predecessor. This will update PHI nodes,
2900   // which will allow us to update live-out uses of bonus instructions.
2901   AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
2902 
2903   // Try to update branch weights.
2904   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2905   if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2906                              SuccTrueWeight, SuccFalseWeight)) {
2907     SmallVector<uint64_t, 8> NewWeights;
2908 
2909     if (PBI->getSuccessor(0) == BB) {
2910       // PBI: br i1 %x, BB, FalseDest
2911       // BI:  br i1 %y, UniqueSucc, FalseDest
2912       // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2913       NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2914       // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2915       //               TrueWeight for PBI * FalseWeight for BI.
2916       // We assume that total weights of a BranchInst can fit into 32 bits.
2917       // Therefore, we will not have overflow using 64-bit arithmetic.
2918       NewWeights.push_back(PredFalseWeight *
2919                                (SuccFalseWeight + SuccTrueWeight) +
2920                            PredTrueWeight * SuccFalseWeight);
2921     } else {
2922       // PBI: br i1 %x, TrueDest, BB
2923       // BI:  br i1 %y, TrueDest, UniqueSucc
2924       // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2925       //              FalseWeight for PBI * TrueWeight for BI.
2926       NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
2927                            PredFalseWeight * SuccTrueWeight);
2928       // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2929       NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2930     }
2931 
2932     // Halve the weights if any of them cannot fit in an uint32_t
2933     FitWeights(NewWeights);
2934 
2935     SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
2936     setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
2937 
2938     // TODO: If BB is reachable from all paths through PredBlock, then we
2939     // could replace PBI's branch probabilities with BI's.
2940   } else
2941     PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2942 
2943   // Now, update the CFG.
2944   PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
2945 
2946   if (DTU)
2947     DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
2948                        {DominatorTree::Delete, PredBlock, BB}});
2949 
2950   // If BI was a loop latch, it may have had associated loop metadata.
2951   // We need to copy it to the new latch, that is, PBI.
2952   if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2953     PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2954 
2955   ValueToValueMapTy VMap; // maps original values to cloned values
2956   CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap);
2957 
2958   // Now that the Cond was cloned into the predecessor basic block,
2959   // or/and the two conditions together.
2960   Instruction *NewCond = cast<Instruction>(Builder.CreateBinOp(
2961       Opc, PBI->getCondition(), VMap[BI->getCondition()], "or.cond"));
2962   PBI->setCondition(NewCond);
2963 
2964   // Copy any debug value intrinsics into the end of PredBlock.
2965   for (Instruction &I : *BB) {
2966     if (isa<DbgInfoIntrinsic>(I)) {
2967       Instruction *NewI = I.clone();
2968       RemapInstruction(NewI, VMap,
2969                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2970       NewI->insertBefore(PBI);
2971     }
2972   }
2973 
2974   ++NumFoldBranchToCommonDest;
2975   return true;
2976 }
2977 
2978 /// If this basic block is simple enough, and if a predecessor branches to us
2979 /// and one of our successors, fold the block into the predecessor and use
2980 /// logical operations to pick the right destination.
2981 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU,
2982                                   MemorySSAUpdater *MSSAU,
2983                                   const TargetTransformInfo *TTI,
2984                                   unsigned BonusInstThreshold) {
2985   // If this block ends with an unconditional branch,
2986   // let SpeculativelyExecuteBB() deal with it.
2987   if (!BI->isConditional())
2988     return false;
2989 
2990   BasicBlock *BB = BI->getParent();
2991 
2992   const unsigned PredCount = pred_size(BB);
2993 
2994   bool Changed = false;
2995 
2996   TargetTransformInfo::TargetCostKind CostKind =
2997     BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
2998                                   : TargetTransformInfo::TCK_SizeAndLatency;
2999 
3000   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3001 
3002   if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
3003       Cond->getParent() != BB || !Cond->hasOneUse())
3004     return Changed;
3005 
3006   // Only allow this transformation if computing the condition doesn't involve
3007   // too many instructions and these involved instructions can be executed
3008   // unconditionally. We denote all involved instructions except the condition
3009   // as "bonus instructions", and only allow this transformation when the
3010   // number of the bonus instructions we'll need to create when cloning into
3011   // each predecessor does not exceed a certain threshold.
3012   unsigned NumBonusInsts = 0;
3013   for (Instruction &I : *BB) {
3014     // Don't check the branch condition comparison itself.
3015     if (&I == Cond)
3016       continue;
3017     // Ignore dbg intrinsics, and the terminator.
3018     if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3019       continue;
3020     // I must be safe to execute unconditionally.
3021     if (!isSafeToSpeculativelyExecute(&I))
3022       return Changed;
3023 
3024     // Account for the cost of duplicating this instruction into each
3025     // predecessor.
3026     NumBonusInsts += PredCount;
3027     // Early exits once we reach the limit.
3028     if (NumBonusInsts > BonusInstThreshold)
3029       return Changed;
3030   }
3031 
3032   // Cond is known to be a compare or binary operator.  Check to make sure that
3033   // neither operand is a potentially-trapping constant expression.
3034   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
3035     if (CE->canTrap())
3036       return Changed;
3037   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
3038     if (CE->canTrap())
3039       return Changed;
3040 
3041   // Finally, don't infinitely unroll conditional loops.
3042   if (is_contained(successors(BB), BB))
3043     return Changed;
3044 
3045   for (BasicBlock *PredBlock : predecessors(BB)) {
3046     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3047 
3048     // Check that we have two conditional branches.  If there is a PHI node in
3049     // the common successor, verify that the same value flows in from both
3050     // blocks.
3051     if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3052       continue;
3053 
3054     // Determine if the two branches share a common destination.
3055     Instruction::BinaryOps Opc;
3056     bool InvertPredCond;
3057     if (auto Recepie = CheckIfCondBranchesShareCommonDestination(BI, PBI))
3058       std::tie(Opc, InvertPredCond) = *Recepie;
3059     else
3060       continue;
3061 
3062     // Check the cost of inserting the necessary logic before performing the
3063     // transformation.
3064     if (TTI) {
3065       Type *Ty = BI->getCondition()->getType();
3066       InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
3067       if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3068           !isa<CmpInst>(PBI->getCondition())))
3069         Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3070 
3071       if (Cost > BranchFoldThreshold)
3072         continue;
3073     }
3074 
3075     return PerformBranchToCommonDestFolding(BI, PBI, DTU, MSSAU);
3076   }
3077   return Changed;
3078 }
3079 
3080 // If there is only one store in BB1 and BB2, return it, otherwise return
3081 // nullptr.
3082 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
3083   StoreInst *S = nullptr;
3084   for (auto *BB : {BB1, BB2}) {
3085     if (!BB)
3086       continue;
3087     for (auto &I : *BB)
3088       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3089         if (S)
3090           // Multiple stores seen.
3091           return nullptr;
3092         else
3093           S = SI;
3094       }
3095   }
3096   return S;
3097 }
3098 
3099 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
3100                                               Value *AlternativeV = nullptr) {
3101   // PHI is going to be a PHI node that allows the value V that is defined in
3102   // BB to be referenced in BB's only successor.
3103   //
3104   // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3105   // doesn't matter to us what the other operand is (it'll never get used). We
3106   // could just create a new PHI with an undef incoming value, but that could
3107   // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3108   // other PHI. So here we directly look for some PHI in BB's successor with V
3109   // as an incoming operand. If we find one, we use it, else we create a new
3110   // one.
3111   //
3112   // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3113   // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3114   // where OtherBB is the single other predecessor of BB's only successor.
3115   PHINode *PHI = nullptr;
3116   BasicBlock *Succ = BB->getSingleSuccessor();
3117 
3118   for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3119     if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3120       PHI = cast<PHINode>(I);
3121       if (!AlternativeV)
3122         break;
3123 
3124       assert(Succ->hasNPredecessors(2));
3125       auto PredI = pred_begin(Succ);
3126       BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3127       if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3128         break;
3129       PHI = nullptr;
3130     }
3131   if (PHI)
3132     return PHI;
3133 
3134   // If V is not an instruction defined in BB, just return it.
3135   if (!AlternativeV &&
3136       (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3137     return V;
3138 
3139   PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3140   PHI->addIncoming(V, BB);
3141   for (BasicBlock *PredBB : predecessors(Succ))
3142     if (PredBB != BB)
3143       PHI->addIncoming(
3144           AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3145   return PHI;
3146 }
3147 
3148 static bool mergeConditionalStoreToAddress(
3149     BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3150     BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3151     DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3152   // For every pointer, there must be exactly two stores, one coming from
3153   // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3154   // store (to any address) in PTB,PFB or QTB,QFB.
3155   // FIXME: We could relax this restriction with a bit more work and performance
3156   // testing.
3157   StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3158   StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3159   if (!PStore || !QStore)
3160     return false;
3161 
3162   // Now check the stores are compatible.
3163   if (!QStore->isUnordered() || !PStore->isUnordered())
3164     return false;
3165 
3166   // Check that sinking the store won't cause program behavior changes. Sinking
3167   // the store out of the Q blocks won't change any behavior as we're sinking
3168   // from a block to its unconditional successor. But we're moving a store from
3169   // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3170   // So we need to check that there are no aliasing loads or stores in
3171   // QBI, QTB and QFB. We also need to check there are no conflicting memory
3172   // operations between PStore and the end of its parent block.
3173   //
3174   // The ideal way to do this is to query AliasAnalysis, but we don't
3175   // preserve AA currently so that is dangerous. Be super safe and just
3176   // check there are no other memory operations at all.
3177   for (auto &I : *QFB->getSinglePredecessor())
3178     if (I.mayReadOrWriteMemory())
3179       return false;
3180   for (auto &I : *QFB)
3181     if (&I != QStore && I.mayReadOrWriteMemory())
3182       return false;
3183   if (QTB)
3184     for (auto &I : *QTB)
3185       if (&I != QStore && I.mayReadOrWriteMemory())
3186         return false;
3187   for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3188        I != E; ++I)
3189     if (&*I != PStore && I->mayReadOrWriteMemory())
3190       return false;
3191 
3192   // If we're not in aggressive mode, we only optimize if we have some
3193   // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3194   auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3195     if (!BB)
3196       return true;
3197     // Heuristic: if the block can be if-converted/phi-folded and the
3198     // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3199     // thread this store.
3200     InstructionCost Cost = 0;
3201     InstructionCost Budget =
3202         PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3203     for (auto &I : BB->instructionsWithoutDebug()) {
3204       // Consider terminator instruction to be free.
3205       if (I.isTerminator())
3206         continue;
3207       // If this is one the stores that we want to speculate out of this BB,
3208       // then don't count it's cost, consider it to be free.
3209       if (auto *S = dyn_cast<StoreInst>(&I))
3210         if (llvm::find(FreeStores, S))
3211           continue;
3212       // Else, we have a white-list of instructions that we are ak speculating.
3213       if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3214         return false; // Not in white-list - not worthwhile folding.
3215       // And finally, if this is a non-free instruction that we are okay
3216       // speculating, ensure that we consider the speculation budget.
3217       Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3218       if (Cost > Budget)
3219         return false; // Eagerly refuse to fold as soon as we're out of budget.
3220     }
3221     assert(Cost <= Budget &&
3222            "When we run out of budget we will eagerly return from within the "
3223            "per-instruction loop.");
3224     return true;
3225   };
3226 
3227   const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3228   if (!MergeCondStoresAggressively &&
3229       (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3230        !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3231     return false;
3232 
3233   // If PostBB has more than two predecessors, we need to split it so we can
3234   // sink the store.
3235   if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3236     // We know that QFB's only successor is PostBB. And QFB has a single
3237     // predecessor. If QTB exists, then its only successor is also PostBB.
3238     // If QTB does not exist, then QFB's only predecessor has a conditional
3239     // branch to QFB and PostBB.
3240     BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3241     BasicBlock *NewBB =
3242         SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3243     if (!NewBB)
3244       return false;
3245     PostBB = NewBB;
3246   }
3247 
3248   // OK, we're going to sink the stores to PostBB. The store has to be
3249   // conditional though, so first create the predicate.
3250   Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3251                      ->getCondition();
3252   Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3253                      ->getCondition();
3254 
3255   Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3256                                                 PStore->getParent());
3257   Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3258                                                 QStore->getParent(), PPHI);
3259 
3260   IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3261 
3262   Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3263   Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3264 
3265   if (InvertPCond)
3266     PPred = QB.CreateNot(PPred);
3267   if (InvertQCond)
3268     QPred = QB.CreateNot(QPred);
3269   Value *CombinedPred = QB.CreateOr(PPred, QPred);
3270 
3271   auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
3272                                       /*Unreachable=*/false,
3273                                       /*BranchWeights=*/nullptr, DTU);
3274   QB.SetInsertPoint(T);
3275   StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3276   AAMDNodes AAMD;
3277   PStore->getAAMetadata(AAMD, /*Merge=*/false);
3278   PStore->getAAMetadata(AAMD, /*Merge=*/true);
3279   SI->setAAMetadata(AAMD);
3280   // Choose the minimum alignment. If we could prove both stores execute, we
3281   // could use biggest one.  In this case, though, we only know that one of the
3282   // stores executes.  And we don't know it's safe to take the alignment from a
3283   // store that doesn't execute.
3284   SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3285 
3286   QStore->eraseFromParent();
3287   PStore->eraseFromParent();
3288 
3289   return true;
3290 }
3291 
3292 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3293                                    DomTreeUpdater *DTU, const DataLayout &DL,
3294                                    const TargetTransformInfo &TTI) {
3295   // The intention here is to find diamonds or triangles (see below) where each
3296   // conditional block contains a store to the same address. Both of these
3297   // stores are conditional, so they can't be unconditionally sunk. But it may
3298   // be profitable to speculatively sink the stores into one merged store at the
3299   // end, and predicate the merged store on the union of the two conditions of
3300   // PBI and QBI.
3301   //
3302   // This can reduce the number of stores executed if both of the conditions are
3303   // true, and can allow the blocks to become small enough to be if-converted.
3304   // This optimization will also chain, so that ladders of test-and-set
3305   // sequences can be if-converted away.
3306   //
3307   // We only deal with simple diamonds or triangles:
3308   //
3309   //     PBI       or      PBI        or a combination of the two
3310   //    /   \               | \
3311   //   PTB  PFB             |  PFB
3312   //    \   /               | /
3313   //     QBI                QBI
3314   //    /  \                | \
3315   //   QTB  QFB             |  QFB
3316   //    \  /                | /
3317   //    PostBB            PostBB
3318   //
3319   // We model triangles as a type of diamond with a nullptr "true" block.
3320   // Triangles are canonicalized so that the fallthrough edge is represented by
3321   // a true condition, as in the diagram above.
3322   BasicBlock *PTB = PBI->getSuccessor(0);
3323   BasicBlock *PFB = PBI->getSuccessor(1);
3324   BasicBlock *QTB = QBI->getSuccessor(0);
3325   BasicBlock *QFB = QBI->getSuccessor(1);
3326   BasicBlock *PostBB = QFB->getSingleSuccessor();
3327 
3328   // Make sure we have a good guess for PostBB. If QTB's only successor is
3329   // QFB, then QFB is a better PostBB.
3330   if (QTB->getSingleSuccessor() == QFB)
3331     PostBB = QFB;
3332 
3333   // If we couldn't find a good PostBB, stop.
3334   if (!PostBB)
3335     return false;
3336 
3337   bool InvertPCond = false, InvertQCond = false;
3338   // Canonicalize fallthroughs to the true branches.
3339   if (PFB == QBI->getParent()) {
3340     std::swap(PFB, PTB);
3341     InvertPCond = true;
3342   }
3343   if (QFB == PostBB) {
3344     std::swap(QFB, QTB);
3345     InvertQCond = true;
3346   }
3347 
3348   // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3349   // and QFB may not. Model fallthroughs as a nullptr block.
3350   if (PTB == QBI->getParent())
3351     PTB = nullptr;
3352   if (QTB == PostBB)
3353     QTB = nullptr;
3354 
3355   // Legality bailouts. We must have at least the non-fallthrough blocks and
3356   // the post-dominating block, and the non-fallthroughs must only have one
3357   // predecessor.
3358   auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3359     return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3360   };
3361   if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3362       !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3363     return false;
3364   if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3365       (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3366     return false;
3367   if (!QBI->getParent()->hasNUses(2))
3368     return false;
3369 
3370   // OK, this is a sequence of two diamonds or triangles.
3371   // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3372   SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3373   for (auto *BB : {PTB, PFB}) {
3374     if (!BB)
3375       continue;
3376     for (auto &I : *BB)
3377       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3378         PStoreAddresses.insert(SI->getPointerOperand());
3379   }
3380   for (auto *BB : {QTB, QFB}) {
3381     if (!BB)
3382       continue;
3383     for (auto &I : *BB)
3384       if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3385         QStoreAddresses.insert(SI->getPointerOperand());
3386   }
3387 
3388   set_intersect(PStoreAddresses, QStoreAddresses);
3389   // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3390   // clear what it contains.
3391   auto &CommonAddresses = PStoreAddresses;
3392 
3393   bool Changed = false;
3394   for (auto *Address : CommonAddresses)
3395     Changed |=
3396         mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
3397                                        InvertPCond, InvertQCond, DTU, DL, TTI);
3398   return Changed;
3399 }
3400 
3401 /// If the previous block ended with a widenable branch, determine if reusing
3402 /// the target block is profitable and legal.  This will have the effect of
3403 /// "widening" PBI, but doesn't require us to reason about hosting safety.
3404 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3405                                            DomTreeUpdater *DTU) {
3406   // TODO: This can be generalized in two important ways:
3407   // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3408   //    values from the PBI edge.
3409   // 2) We can sink side effecting instructions into BI's fallthrough
3410   //    successor provided they doesn't contribute to computation of
3411   //    BI's condition.
3412   Value *CondWB, *WC;
3413   BasicBlock *IfTrueBB, *IfFalseBB;
3414   if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3415       IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3416     return false;
3417   if (!IfFalseBB->phis().empty())
3418     return false; // TODO
3419   // Use lambda to lazily compute expensive condition after cheap ones.
3420   auto NoSideEffects = [](BasicBlock &BB) {
3421     return !llvm::any_of(BB, [](const Instruction &I) {
3422         return I.mayWriteToMemory() || I.mayHaveSideEffects();
3423       });
3424   };
3425   if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
3426       BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
3427       NoSideEffects(*BI->getParent())) {
3428     auto *OldSuccessor = BI->getSuccessor(1);
3429     OldSuccessor->removePredecessor(BI->getParent());
3430     BI->setSuccessor(1, IfFalseBB);
3431     if (DTU)
3432       DTU->applyUpdates(
3433           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
3434            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
3435     return true;
3436   }
3437   if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
3438       BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
3439       NoSideEffects(*BI->getParent())) {
3440     auto *OldSuccessor = BI->getSuccessor(0);
3441     OldSuccessor->removePredecessor(BI->getParent());
3442     BI->setSuccessor(0, IfFalseBB);
3443     if (DTU)
3444       DTU->applyUpdates(
3445           {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
3446            {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
3447     return true;
3448   }
3449   return false;
3450 }
3451 
3452 /// If we have a conditional branch as a predecessor of another block,
3453 /// this function tries to simplify it.  We know
3454 /// that PBI and BI are both conditional branches, and BI is in one of the
3455 /// successor blocks of PBI - PBI branches to BI.
3456 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3457                                            DomTreeUpdater *DTU,
3458                                            const DataLayout &DL,
3459                                            const TargetTransformInfo &TTI) {
3460   assert(PBI->isConditional() && BI->isConditional());
3461   BasicBlock *BB = BI->getParent();
3462 
3463   // If this block ends with a branch instruction, and if there is a
3464   // predecessor that ends on a branch of the same condition, make
3465   // this conditional branch redundant.
3466   if (PBI->getCondition() == BI->getCondition() &&
3467       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3468     // Okay, the outcome of this conditional branch is statically
3469     // knowable.  If this block had a single pred, handle specially.
3470     if (BB->getSinglePredecessor()) {
3471       // Turn this into a branch on constant.
3472       bool CondIsTrue = PBI->getSuccessor(0) == BB;
3473       BI->setCondition(
3474           ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3475       return true; // Nuke the branch on constant.
3476     }
3477 
3478     // Otherwise, if there are multiple predecessors, insert a PHI that merges
3479     // in the constant and simplify the block result.  Subsequent passes of
3480     // simplifycfg will thread the block.
3481     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3482       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3483       PHINode *NewPN = PHINode::Create(
3484           Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3485           BI->getCondition()->getName() + ".pr", &BB->front());
3486       // Okay, we're going to insert the PHI node.  Since PBI is not the only
3487       // predecessor, compute the PHI'd conditional value for all of the preds.
3488       // Any predecessor where the condition is not computable we keep symbolic.
3489       for (pred_iterator PI = PB; PI != PE; ++PI) {
3490         BasicBlock *P = *PI;
3491         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3492             PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3493             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3494           bool CondIsTrue = PBI->getSuccessor(0) == BB;
3495           NewPN->addIncoming(
3496               ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3497               P);
3498         } else {
3499           NewPN->addIncoming(BI->getCondition(), P);
3500         }
3501       }
3502 
3503       BI->setCondition(NewPN);
3504       return true;
3505     }
3506   }
3507 
3508   // If the previous block ended with a widenable branch, determine if reusing
3509   // the target block is profitable and legal.  This will have the effect of
3510   // "widening" PBI, but doesn't require us to reason about hosting safety.
3511   if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
3512     return true;
3513 
3514   if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3515     if (CE->canTrap())
3516       return false;
3517 
3518   // If both branches are conditional and both contain stores to the same
3519   // address, remove the stores from the conditionals and create a conditional
3520   // merged store at the end.
3521   if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
3522     return true;
3523 
3524   // If this is a conditional branch in an empty block, and if any
3525   // predecessors are a conditional branch to one of our destinations,
3526   // fold the conditions into logical ops and one cond br.
3527 
3528   // Ignore dbg intrinsics.
3529   if (&*BB->instructionsWithoutDebug().begin() != BI)
3530     return false;
3531 
3532   int PBIOp, BIOp;
3533   if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3534     PBIOp = 0;
3535     BIOp = 0;
3536   } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3537     PBIOp = 0;
3538     BIOp = 1;
3539   } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3540     PBIOp = 1;
3541     BIOp = 0;
3542   } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3543     PBIOp = 1;
3544     BIOp = 1;
3545   } else {
3546     return false;
3547   }
3548 
3549   // Check to make sure that the other destination of this branch
3550   // isn't BB itself.  If so, this is an infinite loop that will
3551   // keep getting unwound.
3552   if (PBI->getSuccessor(PBIOp) == BB)
3553     return false;
3554 
3555   // Do not perform this transformation if it would require
3556   // insertion of a large number of select instructions. For targets
3557   // without predication/cmovs, this is a big pessimization.
3558 
3559   // Also do not perform this transformation if any phi node in the common
3560   // destination block can trap when reached by BB or PBB (PR17073). In that
3561   // case, it would be unsafe to hoist the operation into a select instruction.
3562 
3563   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3564   BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
3565   unsigned NumPhis = 0;
3566   for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3567        ++II, ++NumPhis) {
3568     if (NumPhis > 2) // Disable this xform.
3569       return false;
3570 
3571     PHINode *PN = cast<PHINode>(II);
3572     Value *BIV = PN->getIncomingValueForBlock(BB);
3573     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3574       if (CE->canTrap())
3575         return false;
3576 
3577     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3578     Value *PBIV = PN->getIncomingValue(PBBIdx);
3579     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3580       if (CE->canTrap())
3581         return false;
3582   }
3583 
3584   // Finally, if everything is ok, fold the branches to logical ops.
3585   BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3586 
3587   LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
3588                     << "AND: " << *BI->getParent());
3589 
3590   SmallVector<DominatorTree::UpdateType, 5> Updates;
3591 
3592   // If OtherDest *is* BB, then BB is a basic block with a single conditional
3593   // branch in it, where one edge (OtherDest) goes back to itself but the other
3594   // exits.  We don't *know* that the program avoids the infinite loop
3595   // (even though that seems likely).  If we do this xform naively, we'll end up
3596   // recursively unpeeling the loop.  Since we know that (after the xform is
3597   // done) that the block *is* infinite if reached, we just make it an obviously
3598   // infinite loop with no cond branch.
3599   if (OtherDest == BB) {
3600     // Insert it at the end of the function, because it's either code,
3601     // or it won't matter if it's hot. :)
3602     BasicBlock *InfLoopBlock =
3603         BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3604     BranchInst::Create(InfLoopBlock, InfLoopBlock);
3605     Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
3606     OtherDest = InfLoopBlock;
3607   }
3608 
3609   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3610 
3611   // BI may have other predecessors.  Because of this, we leave
3612   // it alone, but modify PBI.
3613 
3614   // Make sure we get to CommonDest on True&True directions.
3615   Value *PBICond = PBI->getCondition();
3616   IRBuilder<NoFolder> Builder(PBI);
3617   if (PBIOp)
3618     PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3619 
3620   Value *BICond = BI->getCondition();
3621   if (BIOp)
3622     BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3623 
3624   // Merge the conditions.
3625   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
3626 
3627   // Modify PBI to branch on the new condition to the new dests.
3628   PBI->setCondition(Cond);
3629   PBI->setSuccessor(0, CommonDest);
3630   PBI->setSuccessor(1, OtherDest);
3631 
3632   Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
3633   Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
3634 
3635   if (DTU)
3636     DTU->applyUpdates(Updates);
3637 
3638   // Update branch weight for PBI.
3639   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3640   uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3641   bool HasWeights =
3642       extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3643                              SuccTrueWeight, SuccFalseWeight);
3644   if (HasWeights) {
3645     PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3646     PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3647     SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3648     SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3649     // The weight to CommonDest should be PredCommon * SuccTotal +
3650     //                                    PredOther * SuccCommon.
3651     // The weight to OtherDest should be PredOther * SuccOther.
3652     uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3653                                   PredOther * SuccCommon,
3654                               PredOther * SuccOther};
3655     // Halve the weights if any of them cannot fit in an uint32_t
3656     FitWeights(NewWeights);
3657 
3658     setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
3659   }
3660 
3661   // OtherDest may have phi nodes.  If so, add an entry from PBI's
3662   // block that are identical to the entries for BI's block.
3663   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3664 
3665   // We know that the CommonDest already had an edge from PBI to
3666   // it.  If it has PHIs though, the PHIs may have different
3667   // entries for BB and PBI's BB.  If so, insert a select to make
3668   // them agree.
3669   for (PHINode &PN : CommonDest->phis()) {
3670     Value *BIV = PN.getIncomingValueForBlock(BB);
3671     unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
3672     Value *PBIV = PN.getIncomingValue(PBBIdx);
3673     if (BIV != PBIV) {
3674       // Insert a select in PBI to pick the right value.
3675       SelectInst *NV = cast<SelectInst>(
3676           Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3677       PN.setIncomingValue(PBBIdx, NV);
3678       // Although the select has the same condition as PBI, the original branch
3679       // weights for PBI do not apply to the new select because the select's
3680       // 'logical' edges are incoming edges of the phi that is eliminated, not
3681       // the outgoing edges of PBI.
3682       if (HasWeights) {
3683         uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3684         uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3685         uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3686         uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3687         // The weight to PredCommonDest should be PredCommon * SuccTotal.
3688         // The weight to PredOtherDest should be PredOther * SuccCommon.
3689         uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3690                                   PredOther * SuccCommon};
3691 
3692         FitWeights(NewWeights);
3693 
3694         setBranchWeights(NV, NewWeights[0], NewWeights[1]);
3695       }
3696     }
3697   }
3698 
3699   LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3700   LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3701 
3702   // This basic block is probably dead.  We know it has at least
3703   // one fewer predecessor.
3704   return true;
3705 }
3706 
3707 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3708 // true or to FalseBB if Cond is false.
3709 // Takes care of updating the successors and removing the old terminator.
3710 // Also makes sure not to introduce new successors by assuming that edges to
3711 // non-successor TrueBBs and FalseBBs aren't reachable.
3712 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
3713                                                 Value *Cond, BasicBlock *TrueBB,
3714                                                 BasicBlock *FalseBB,
3715                                                 uint32_t TrueWeight,
3716                                                 uint32_t FalseWeight) {
3717   auto *BB = OldTerm->getParent();
3718   // Remove any superfluous successor edges from the CFG.
3719   // First, figure out which successors to preserve.
3720   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3721   // successor.
3722   BasicBlock *KeepEdge1 = TrueBB;
3723   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3724 
3725   SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
3726 
3727   // Then remove the rest.
3728   for (BasicBlock *Succ : successors(OldTerm)) {
3729     // Make sure only to keep exactly one copy of each edge.
3730     if (Succ == KeepEdge1)
3731       KeepEdge1 = nullptr;
3732     else if (Succ == KeepEdge2)
3733       KeepEdge2 = nullptr;
3734     else {
3735       Succ->removePredecessor(BB,
3736                               /*KeepOneInputPHIs=*/true);
3737 
3738       if (Succ != TrueBB && Succ != FalseBB)
3739         RemovedSuccessors.insert(Succ);
3740     }
3741   }
3742 
3743   IRBuilder<> Builder(OldTerm);
3744   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3745 
3746   // Insert an appropriate new terminator.
3747   if (!KeepEdge1 && !KeepEdge2) {
3748     if (TrueBB == FalseBB) {
3749       // We were only looking for one successor, and it was present.
3750       // Create an unconditional branch to it.
3751       Builder.CreateBr(TrueBB);
3752     } else {
3753       // We found both of the successors we were looking for.
3754       // Create a conditional branch sharing the condition of the select.
3755       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3756       if (TrueWeight != FalseWeight)
3757         setBranchWeights(NewBI, TrueWeight, FalseWeight);
3758     }
3759   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3760     // Neither of the selected blocks were successors, so this
3761     // terminator must be unreachable.
3762     new UnreachableInst(OldTerm->getContext(), OldTerm);
3763   } else {
3764     // One of the selected values was a successor, but the other wasn't.
3765     // Insert an unconditional branch to the one that was found;
3766     // the edge to the one that wasn't must be unreachable.
3767     if (!KeepEdge1) {
3768       // Only TrueBB was found.
3769       Builder.CreateBr(TrueBB);
3770     } else {
3771       // Only FalseBB was found.
3772       Builder.CreateBr(FalseBB);
3773     }
3774   }
3775 
3776   EraseTerminatorAndDCECond(OldTerm);
3777 
3778   if (DTU) {
3779     SmallVector<DominatorTree::UpdateType, 2> Updates;
3780     Updates.reserve(RemovedSuccessors.size());
3781     for (auto *RemovedSuccessor : RemovedSuccessors)
3782       Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
3783     DTU->applyUpdates(Updates);
3784   }
3785 
3786   return true;
3787 }
3788 
3789 // Replaces
3790 //   (switch (select cond, X, Y)) on constant X, Y
3791 // with a branch - conditional if X and Y lead to distinct BBs,
3792 // unconditional otherwise.
3793 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
3794                                             SelectInst *Select) {
3795   // Check for constant integer values in the select.
3796   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3797   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3798   if (!TrueVal || !FalseVal)
3799     return false;
3800 
3801   // Find the relevant condition and destinations.
3802   Value *Condition = Select->getCondition();
3803   BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3804   BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
3805 
3806   // Get weight for TrueBB and FalseBB.
3807   uint32_t TrueWeight = 0, FalseWeight = 0;
3808   SmallVector<uint64_t, 8> Weights;
3809   bool HasWeights = HasBranchWeights(SI);
3810   if (HasWeights) {
3811     GetBranchWeights(SI, Weights);
3812     if (Weights.size() == 1 + SI->getNumCases()) {
3813       TrueWeight =
3814           (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
3815       FalseWeight =
3816           (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
3817     }
3818   }
3819 
3820   // Perform the actual simplification.
3821   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3822                                     FalseWeight);
3823 }
3824 
3825 // Replaces
3826 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
3827 //                             blockaddress(@fn, BlockB)))
3828 // with
3829 //   (br cond, BlockA, BlockB).
3830 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
3831                                                 SelectInst *SI) {
3832   // Check that both operands of the select are block addresses.
3833   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3834   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3835   if (!TBA || !FBA)
3836     return false;
3837 
3838   // Extract the actual blocks.
3839   BasicBlock *TrueBB = TBA->getBasicBlock();
3840   BasicBlock *FalseBB = FBA->getBasicBlock();
3841 
3842   // Perform the actual simplification.
3843   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3844                                     0);
3845 }
3846 
3847 /// This is called when we find an icmp instruction
3848 /// (a seteq/setne with a constant) as the only instruction in a
3849 /// block that ends with an uncond branch.  We are looking for a very specific
3850 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
3851 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3852 /// default value goes to an uncond block with a seteq in it, we get something
3853 /// like:
3854 ///
3855 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
3856 /// DEFAULT:
3857 ///   %tmp = icmp eq i8 %A, 92
3858 ///   br label %end
3859 /// end:
3860 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3861 ///
3862 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3863 /// the PHI, merging the third icmp into the switch.
3864 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
3865     ICmpInst *ICI, IRBuilder<> &Builder) {
3866   BasicBlock *BB = ICI->getParent();
3867 
3868   // If the block has any PHIs in it or the icmp has multiple uses, it is too
3869   // complex.
3870   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3871     return false;
3872 
3873   Value *V = ICI->getOperand(0);
3874   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3875 
3876   // The pattern we're looking for is where our only predecessor is a switch on
3877   // 'V' and this block is the default case for the switch.  In this case we can
3878   // fold the compared value into the switch to simplify things.
3879   BasicBlock *Pred = BB->getSinglePredecessor();
3880   if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3881     return false;
3882 
3883   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3884   if (SI->getCondition() != V)
3885     return false;
3886 
3887   // If BB is reachable on a non-default case, then we simply know the value of
3888   // V in this block.  Substitute it and constant fold the icmp instruction
3889   // away.
3890   if (SI->getDefaultDest() != BB) {
3891     ConstantInt *VVal = SI->findCaseDest(BB);
3892     assert(VVal && "Should have a unique destination value");
3893     ICI->setOperand(0, VVal);
3894 
3895     if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
3896       ICI->replaceAllUsesWith(V);
3897       ICI->eraseFromParent();
3898     }
3899     // BB is now empty, so it is likely to simplify away.
3900     return requestResimplify();
3901   }
3902 
3903   // Ok, the block is reachable from the default dest.  If the constant we're
3904   // comparing exists in one of the other edges, then we can constant fold ICI
3905   // and zap it.
3906   if (SI->findCaseValue(Cst) != SI->case_default()) {
3907     Value *V;
3908     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3909       V = ConstantInt::getFalse(BB->getContext());
3910     else
3911       V = ConstantInt::getTrue(BB->getContext());
3912 
3913     ICI->replaceAllUsesWith(V);
3914     ICI->eraseFromParent();
3915     // BB is now empty, so it is likely to simplify away.
3916     return requestResimplify();
3917   }
3918 
3919   // The use of the icmp has to be in the 'end' block, by the only PHI node in
3920   // the block.
3921   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3922   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3923   if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3924       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3925     return false;
3926 
3927   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3928   // true in the PHI.
3929   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3930   Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3931 
3932   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3933     std::swap(DefaultCst, NewCst);
3934 
3935   // Replace ICI (which is used by the PHI for the default value) with true or
3936   // false depending on if it is EQ or NE.
3937   ICI->replaceAllUsesWith(DefaultCst);
3938   ICI->eraseFromParent();
3939 
3940   SmallVector<DominatorTree::UpdateType, 2> Updates;
3941 
3942   // Okay, the switch goes to this block on a default value.  Add an edge from
3943   // the switch to the merge point on the compared value.
3944   BasicBlock *NewBB =
3945       BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
3946   {
3947     SwitchInstProfUpdateWrapper SIW(*SI);
3948     auto W0 = SIW.getSuccessorWeight(0);
3949     SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
3950     if (W0) {
3951       NewW = ((uint64_t(*W0) + 1) >> 1);
3952       SIW.setSuccessorWeight(0, *NewW);
3953     }
3954     SIW.addCase(Cst, NewBB, NewW);
3955     Updates.push_back({DominatorTree::Insert, Pred, NewBB});
3956   }
3957 
3958   // NewBB branches to the phi block, add the uncond branch and the phi entry.
3959   Builder.SetInsertPoint(NewBB);
3960   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3961   Builder.CreateBr(SuccBlock);
3962   Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
3963   PHIUse->addIncoming(NewCst, NewBB);
3964   if (DTU)
3965     DTU->applyUpdates(Updates);
3966   return true;
3967 }
3968 
3969 /// The specified branch is a conditional branch.
3970 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3971 /// fold it into a switch instruction if so.
3972 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
3973                                                IRBuilder<> &Builder,
3974                                                const DataLayout &DL) {
3975   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3976   if (!Cond)
3977     return false;
3978 
3979   // Change br (X == 0 | X == 1), T, F into a switch instruction.
3980   // If this is a bunch of seteq's or'd together, or if it's a bunch of
3981   // 'setne's and'ed together, collect them.
3982 
3983   // Try to gather values from a chain of and/or to be turned into a switch
3984   ConstantComparesGatherer ConstantCompare(Cond, DL);
3985   // Unpack the result
3986   SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
3987   Value *CompVal = ConstantCompare.CompValue;
3988   unsigned UsedICmps = ConstantCompare.UsedICmps;
3989   Value *ExtraCase = ConstantCompare.Extra;
3990 
3991   // If we didn't have a multiply compared value, fail.
3992   if (!CompVal)
3993     return false;
3994 
3995   // Avoid turning single icmps into a switch.
3996   if (UsedICmps <= 1)
3997     return false;
3998 
3999   bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4000 
4001   // There might be duplicate constants in the list, which the switch
4002   // instruction can't handle, remove them now.
4003   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4004   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4005 
4006   // If Extra was used, we require at least two switch values to do the
4007   // transformation.  A switch with one value is just a conditional branch.
4008   if (ExtraCase && Values.size() < 2)
4009     return false;
4010 
4011   // TODO: Preserve branch weight metadata, similarly to how
4012   // FoldValueComparisonIntoPredecessors preserves it.
4013 
4014   // Figure out which block is which destination.
4015   BasicBlock *DefaultBB = BI->getSuccessor(1);
4016   BasicBlock *EdgeBB = BI->getSuccessor(0);
4017   if (!TrueWhenEqual)
4018     std::swap(DefaultBB, EdgeBB);
4019 
4020   BasicBlock *BB = BI->getParent();
4021 
4022   // MSAN does not like undefs as branch condition which can be introduced
4023   // with "explicit branch".
4024   if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
4025     return false;
4026 
4027   LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4028                     << " cases into SWITCH.  BB is:\n"
4029                     << *BB);
4030 
4031   SmallVector<DominatorTree::UpdateType, 2> Updates;
4032 
4033   // If there are any extra values that couldn't be folded into the switch
4034   // then we evaluate them with an explicit branch first. Split the block
4035   // right before the condbr to handle it.
4036   if (ExtraCase) {
4037     BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4038                                    /*MSSAU=*/nullptr, "switch.early.test");
4039 
4040     // Remove the uncond branch added to the old block.
4041     Instruction *OldTI = BB->getTerminator();
4042     Builder.SetInsertPoint(OldTI);
4043 
4044     if (TrueWhenEqual)
4045       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4046     else
4047       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4048 
4049     OldTI->eraseFromParent();
4050 
4051     Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4052 
4053     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4054     // for the edge we just added.
4055     AddPredecessorToBlock(EdgeBB, BB, NewBB);
4056 
4057     LLVM_DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
4058                       << "\nEXTRABB = " << *BB);
4059     BB = NewBB;
4060   }
4061 
4062   Builder.SetInsertPoint(BI);
4063   // Convert pointer to int before we switch.
4064   if (CompVal->getType()->isPointerTy()) {
4065     CompVal = Builder.CreatePtrToInt(
4066         CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4067   }
4068 
4069   // Create the new switch instruction now.
4070   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4071 
4072   // Add all of the 'cases' to the switch instruction.
4073   for (unsigned i = 0, e = Values.size(); i != e; ++i)
4074     New->addCase(Values[i], EdgeBB);
4075 
4076   // We added edges from PI to the EdgeBB.  As such, if there were any
4077   // PHI nodes in EdgeBB, they need entries to be added corresponding to
4078   // the number of edges added.
4079   for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4080     PHINode *PN = cast<PHINode>(BBI);
4081     Value *InVal = PN->getIncomingValueForBlock(BB);
4082     for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4083       PN->addIncoming(InVal, BB);
4084   }
4085 
4086   // Erase the old branch instruction.
4087   EraseTerminatorAndDCECond(BI);
4088   if (DTU)
4089     DTU->applyUpdates(Updates);
4090 
4091   LLVM_DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
4092   return true;
4093 }
4094 
4095 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4096   if (isa<PHINode>(RI->getValue()))
4097     return simplifyCommonResume(RI);
4098   else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4099            RI->getValue() == RI->getParent()->getFirstNonPHI())
4100     // The resume must unwind the exception that caused control to branch here.
4101     return simplifySingleResume(RI);
4102 
4103   return false;
4104 }
4105 
4106 // Check if cleanup block is empty
4107 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4108   for (Instruction &I : R) {
4109     auto *II = dyn_cast<IntrinsicInst>(&I);
4110     if (!II)
4111       return false;
4112 
4113     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4114     switch (IntrinsicID) {
4115     case Intrinsic::dbg_declare:
4116     case Intrinsic::dbg_value:
4117     case Intrinsic::dbg_label:
4118     case Intrinsic::lifetime_end:
4119       break;
4120     default:
4121       return false;
4122     }
4123   }
4124   return true;
4125 }
4126 
4127 // Simplify resume that is shared by several landing pads (phi of landing pad).
4128 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4129   BasicBlock *BB = RI->getParent();
4130 
4131   // Check that there are no other instructions except for debug and lifetime
4132   // intrinsics between the phi's and resume instruction.
4133   if (!isCleanupBlockEmpty(
4134           make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4135     return false;
4136 
4137   SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4138   auto *PhiLPInst = cast<PHINode>(RI->getValue());
4139 
4140   // Check incoming blocks to see if any of them are trivial.
4141   for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4142        Idx++) {
4143     auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4144     auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4145 
4146     // If the block has other successors, we can not delete it because
4147     // it has other dependents.
4148     if (IncomingBB->getUniqueSuccessor() != BB)
4149       continue;
4150 
4151     auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4152     // Not the landing pad that caused the control to branch here.
4153     if (IncomingValue != LandingPad)
4154       continue;
4155 
4156     if (isCleanupBlockEmpty(
4157             make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4158       TrivialUnwindBlocks.insert(IncomingBB);
4159   }
4160 
4161   // If no trivial unwind blocks, don't do any simplifications.
4162   if (TrivialUnwindBlocks.empty())
4163     return false;
4164 
4165   // Turn all invokes that unwind here into calls.
4166   for (auto *TrivialBB : TrivialUnwindBlocks) {
4167     // Blocks that will be simplified should be removed from the phi node.
4168     // Note there could be multiple edges to the resume block, and we need
4169     // to remove them all.
4170     while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4171       BB->removePredecessor(TrivialBB, true);
4172 
4173     for (BasicBlock *Pred :
4174          llvm::make_early_inc_range(predecessors(TrivialBB))) {
4175       removeUnwindEdge(Pred, DTU);
4176       ++NumInvokes;
4177     }
4178 
4179     // In each SimplifyCFG run, only the current processed block can be erased.
4180     // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4181     // of erasing TrivialBB, we only remove the branch to the common resume
4182     // block so that we can later erase the resume block since it has no
4183     // predecessors.
4184     TrivialBB->getTerminator()->eraseFromParent();
4185     new UnreachableInst(RI->getContext(), TrivialBB);
4186     if (DTU)
4187       DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4188   }
4189 
4190   // Delete the resume block if all its predecessors have been removed.
4191   if (pred_empty(BB)) {
4192     if (DTU)
4193       DTU->deleteBB(BB);
4194     else
4195       BB->eraseFromParent();
4196   }
4197 
4198   return !TrivialUnwindBlocks.empty();
4199 }
4200 
4201 // Simplify resume that is only used by a single (non-phi) landing pad.
4202 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4203   BasicBlock *BB = RI->getParent();
4204   auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4205   assert(RI->getValue() == LPInst &&
4206          "Resume must unwind the exception that caused control to here");
4207 
4208   // Check that there are no other instructions except for debug intrinsics.
4209   if (!isCleanupBlockEmpty(
4210           make_range<Instruction *>(LPInst->getNextNode(), RI)))
4211     return false;
4212 
4213   // Turn all invokes that unwind here into calls and delete the basic block.
4214   for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
4215     removeUnwindEdge(Pred, DTU);
4216     ++NumInvokes;
4217   }
4218 
4219   // The landingpad is now unreachable.  Zap it.
4220   if (DTU)
4221     DTU->deleteBB(BB);
4222   else
4223     BB->eraseFromParent();
4224   return true;
4225 }
4226 
4227 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
4228   // If this is a trivial cleanup pad that executes no instructions, it can be
4229   // eliminated.  If the cleanup pad continues to the caller, any predecessor
4230   // that is an EH pad will be updated to continue to the caller and any
4231   // predecessor that terminates with an invoke instruction will have its invoke
4232   // instruction converted to a call instruction.  If the cleanup pad being
4233   // simplified does not continue to the caller, each predecessor will be
4234   // updated to continue to the unwind destination of the cleanup pad being
4235   // simplified.
4236   BasicBlock *BB = RI->getParent();
4237   CleanupPadInst *CPInst = RI->getCleanupPad();
4238   if (CPInst->getParent() != BB)
4239     // This isn't an empty cleanup.
4240     return false;
4241 
4242   // We cannot kill the pad if it has multiple uses.  This typically arises
4243   // from unreachable basic blocks.
4244   if (!CPInst->hasOneUse())
4245     return false;
4246 
4247   // Check that there are no other instructions except for benign intrinsics.
4248   if (!isCleanupBlockEmpty(
4249           make_range<Instruction *>(CPInst->getNextNode(), RI)))
4250     return false;
4251 
4252   // If the cleanup return we are simplifying unwinds to the caller, this will
4253   // set UnwindDest to nullptr.
4254   BasicBlock *UnwindDest = RI->getUnwindDest();
4255   Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4256 
4257   // We're about to remove BB from the control flow.  Before we do, sink any
4258   // PHINodes into the unwind destination.  Doing this before changing the
4259   // control flow avoids some potentially slow checks, since we can currently
4260   // be certain that UnwindDest and BB have no common predecessors (since they
4261   // are both EH pads).
4262   if (UnwindDest) {
4263     // First, go through the PHI nodes in UnwindDest and update any nodes that
4264     // reference the block we are removing
4265     for (BasicBlock::iterator I = UnwindDest->begin(),
4266                               IE = DestEHPad->getIterator();
4267          I != IE; ++I) {
4268       PHINode *DestPN = cast<PHINode>(I);
4269 
4270       int Idx = DestPN->getBasicBlockIndex(BB);
4271       // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4272       assert(Idx != -1);
4273       // This PHI node has an incoming value that corresponds to a control
4274       // path through the cleanup pad we are removing.  If the incoming
4275       // value is in the cleanup pad, it must be a PHINode (because we
4276       // verified above that the block is otherwise empty).  Otherwise, the
4277       // value is either a constant or a value that dominates the cleanup
4278       // pad being removed.
4279       //
4280       // Because BB and UnwindDest are both EH pads, all of their
4281       // predecessors must unwind to these blocks, and since no instruction
4282       // can have multiple unwind destinations, there will be no overlap in
4283       // incoming blocks between SrcPN and DestPN.
4284       Value *SrcVal = DestPN->getIncomingValue(Idx);
4285       PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4286 
4287       // Remove the entry for the block we are deleting.
4288       DestPN->removeIncomingValue(Idx, false);
4289 
4290       if (SrcPN && SrcPN->getParent() == BB) {
4291         // If the incoming value was a PHI node in the cleanup pad we are
4292         // removing, we need to merge that PHI node's incoming values into
4293         // DestPN.
4294         for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
4295              SrcIdx != SrcE; ++SrcIdx) {
4296           DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
4297                               SrcPN->getIncomingBlock(SrcIdx));
4298         }
4299       } else {
4300         // Otherwise, the incoming value came from above BB and
4301         // so we can just reuse it.  We must associate all of BB's
4302         // predecessors with this value.
4303         for (auto *pred : predecessors(BB)) {
4304           DestPN->addIncoming(SrcVal, pred);
4305         }
4306       }
4307     }
4308 
4309     // Sink any remaining PHI nodes directly into UnwindDest.
4310     Instruction *InsertPt = DestEHPad;
4311     for (BasicBlock::iterator I = BB->begin(),
4312                               IE = BB->getFirstNonPHI()->getIterator();
4313          I != IE;) {
4314       // The iterator must be incremented here because the instructions are
4315       // being moved to another block.
4316       PHINode *PN = cast<PHINode>(I++);
4317       if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB))
4318         // If the PHI node has no uses or all of its uses are in this basic
4319         // block (meaning they are debug or lifetime intrinsics), just leave
4320         // it.  It will be erased when we erase BB below.
4321         continue;
4322 
4323       // Otherwise, sink this PHI node into UnwindDest.
4324       // Any predecessors to UnwindDest which are not already represented
4325       // must be back edges which inherit the value from the path through
4326       // BB.  In this case, the PHI value must reference itself.
4327       for (auto *pred : predecessors(UnwindDest))
4328         if (pred != BB)
4329           PN->addIncoming(PN, pred);
4330       PN->moveBefore(InsertPt);
4331     }
4332   }
4333 
4334   std::vector<DominatorTree::UpdateType> Updates;
4335 
4336   // We use make_early_inc_range here because we may remove some predecessors.
4337   for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) {
4338     if (UnwindDest == nullptr) {
4339       if (DTU)
4340         DTU->applyUpdates(Updates);
4341       Updates.clear();
4342       removeUnwindEdge(PredBB, DTU);
4343       ++NumInvokes;
4344     } else {
4345       Instruction *TI = PredBB->getTerminator();
4346       TI->replaceUsesOfWith(BB, UnwindDest);
4347       Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
4348       Updates.push_back({DominatorTree::Delete, PredBB, BB});
4349     }
4350   }
4351 
4352   if (DTU) {
4353     DTU->applyUpdates(Updates);
4354     DTU->deleteBB(BB);
4355   } else
4356     // The cleanup pad is now unreachable.  Zap it.
4357     BB->eraseFromParent();
4358 
4359   return true;
4360 }
4361 
4362 // Try to merge two cleanuppads together.
4363 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4364   // Skip any cleanuprets which unwind to caller, there is nothing to merge
4365   // with.
4366   BasicBlock *UnwindDest = RI->getUnwindDest();
4367   if (!UnwindDest)
4368     return false;
4369 
4370   // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4371   // be safe to merge without code duplication.
4372   if (UnwindDest->getSinglePredecessor() != RI->getParent())
4373     return false;
4374 
4375   // Verify that our cleanuppad's unwind destination is another cleanuppad.
4376   auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4377   if (!SuccessorCleanupPad)
4378     return false;
4379 
4380   CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4381   // Replace any uses of the successor cleanupad with the predecessor pad
4382   // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4383   // funclet bundle operands.
4384   SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4385   // Remove the old cleanuppad.
4386   SuccessorCleanupPad->eraseFromParent();
4387   // Now, we simply replace the cleanupret with a branch to the unwind
4388   // destination.
4389   BranchInst::Create(UnwindDest, RI->getParent());
4390   RI->eraseFromParent();
4391 
4392   return true;
4393 }
4394 
4395 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4396   // It is possible to transiantly have an undef cleanuppad operand because we
4397   // have deleted some, but not all, dead blocks.
4398   // Eventually, this block will be deleted.
4399   if (isa<UndefValue>(RI->getOperand(0)))
4400     return false;
4401 
4402   if (mergeCleanupPad(RI))
4403     return true;
4404 
4405   if (removeEmptyCleanup(RI, DTU))
4406     return true;
4407 
4408   return false;
4409 }
4410 
4411 bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4412   BasicBlock *BB = RI->getParent();
4413   if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4414     return false;
4415 
4416   // Find predecessors that end with branches.
4417   SmallVector<BasicBlock *, 8> UncondBranchPreds;
4418   SmallVector<BranchInst *, 8> CondBranchPreds;
4419   for (BasicBlock *P : predecessors(BB)) {
4420     Instruction *PTI = P->getTerminator();
4421     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4422       if (BI->isUnconditional())
4423         UncondBranchPreds.push_back(P);
4424       else
4425         CondBranchPreds.push_back(BI);
4426     }
4427   }
4428 
4429   // If we found some, do the transformation!
4430   if (!UncondBranchPreds.empty() && DupRet) {
4431     while (!UncondBranchPreds.empty()) {
4432       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4433       LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
4434                         << "INTO UNCOND BRANCH PRED: " << *Pred);
4435       (void)FoldReturnIntoUncondBranch(RI, BB, Pred, DTU);
4436     }
4437 
4438     // If we eliminated all predecessors of the block, delete the block now.
4439     if (pred_empty(BB)) {
4440       // We know there are no successors, so just nuke the block.
4441       if (DTU)
4442         DTU->deleteBB(BB);
4443       else
4444         BB->eraseFromParent();
4445     }
4446 
4447     return true;
4448   }
4449 
4450   // Check out all of the conditional branches going to this return
4451   // instruction.  If any of them just select between returns, change the
4452   // branch itself into a select/return pair.
4453   while (!CondBranchPreds.empty()) {
4454     BranchInst *BI = CondBranchPreds.pop_back_val();
4455 
4456     // Check to see if the non-BB successor is also a return block.
4457     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4458         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4459         SimplifyCondBranchToTwoReturns(BI, Builder))
4460       return true;
4461   }
4462   return false;
4463 }
4464 
4465 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4466   BasicBlock *BB = UI->getParent();
4467 
4468   bool Changed = false;
4469 
4470   // If there are any instructions immediately before the unreachable that can
4471   // be removed, do so.
4472   while (UI->getIterator() != BB->begin()) {
4473     BasicBlock::iterator BBI = UI->getIterator();
4474     --BBI;
4475     // Do not delete instructions that can have side effects which might cause
4476     // the unreachable to not be reachable; specifically, calls and volatile
4477     // operations may have this effect.
4478     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4479       break;
4480 
4481     if (BBI->mayHaveSideEffects()) {
4482       if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4483         if (SI->isVolatile())
4484           break;
4485       } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4486         if (LI->isVolatile())
4487           break;
4488       } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4489         if (RMWI->isVolatile())
4490           break;
4491       } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4492         if (CXI->isVolatile())
4493           break;
4494       } else if (isa<CatchPadInst>(BBI)) {
4495         // A catchpad may invoke exception object constructors and such, which
4496         // in some languages can be arbitrary code, so be conservative by
4497         // default.
4498         // For CoreCLR, it just involves a type test, so can be removed.
4499         if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4500             EHPersonality::CoreCLR)
4501           break;
4502       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4503                  !isa<LandingPadInst>(BBI)) {
4504         break;
4505       }
4506       // Note that deleting LandingPad's here is in fact okay, although it
4507       // involves a bit of subtle reasoning. If this inst is a LandingPad,
4508       // all the predecessors of this block will be the unwind edges of Invokes,
4509       // and we can therefore guarantee this block will be erased.
4510     }
4511 
4512     // Delete this instruction (any uses are guaranteed to be dead)
4513     if (!BBI->use_empty())
4514       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4515     BBI->eraseFromParent();
4516     Changed = true;
4517   }
4518 
4519   // If the unreachable instruction is the first in the block, take a gander
4520   // at all of the predecessors of this instruction, and simplify them.
4521   if (&BB->front() != UI)
4522     return Changed;
4523 
4524   std::vector<DominatorTree::UpdateType> Updates;
4525 
4526   SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4527   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4528     auto *Predecessor = Preds[i];
4529     Instruction *TI = Predecessor->getTerminator();
4530     IRBuilder<> Builder(TI);
4531     if (auto *BI = dyn_cast<BranchInst>(TI)) {
4532       // We could either have a proper unconditional branch,
4533       // or a degenerate conditional branch with matching destinations.
4534       if (all_of(BI->successors(),
4535                  [BB](auto *Successor) { return Successor == BB; })) {
4536         new UnreachableInst(TI->getContext(), TI);
4537         TI->eraseFromParent();
4538         Changed = true;
4539       } else {
4540         assert(BI->isConditional() && "Can't get here with an uncond branch.");
4541         Value* Cond = BI->getCondition();
4542         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4543                "The destinations are guaranteed to be different here.");
4544         if (BI->getSuccessor(0) == BB) {
4545           Builder.CreateAssumption(Builder.CreateNot(Cond));
4546           Builder.CreateBr(BI->getSuccessor(1));
4547         } else {
4548           assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
4549           Builder.CreateAssumption(Cond);
4550           Builder.CreateBr(BI->getSuccessor(0));
4551         }
4552         EraseTerminatorAndDCECond(BI);
4553         Changed = true;
4554       }
4555       Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4556     } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4557       SwitchInstProfUpdateWrapper SU(*SI);
4558       for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
4559         if (i->getCaseSuccessor() != BB) {
4560           ++i;
4561           continue;
4562         }
4563         BB->removePredecessor(SU->getParent());
4564         i = SU.removeCase(i);
4565         e = SU->case_end();
4566         Changed = true;
4567       }
4568       // Note that the default destination can't be removed!
4569       if (SI->getDefaultDest() != BB)
4570         Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4571     } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4572       if (II->getUnwindDest() == BB) {
4573         if (DTU)
4574           DTU->applyUpdates(Updates);
4575         Updates.clear();
4576         removeUnwindEdge(TI->getParent(), DTU);
4577         Changed = true;
4578       }
4579     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4580       if (CSI->getUnwindDest() == BB) {
4581         if (DTU)
4582           DTU->applyUpdates(Updates);
4583         Updates.clear();
4584         removeUnwindEdge(TI->getParent(), DTU);
4585         Changed = true;
4586         continue;
4587       }
4588 
4589       for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4590                                              E = CSI->handler_end();
4591            I != E; ++I) {
4592         if (*I == BB) {
4593           CSI->removeHandler(I);
4594           --I;
4595           --E;
4596           Changed = true;
4597         }
4598       }
4599       Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4600       if (CSI->getNumHandlers() == 0) {
4601         if (CSI->hasUnwindDest()) {
4602           // Redirect all predecessors of the block containing CatchSwitchInst
4603           // to instead branch to the CatchSwitchInst's unwind destination.
4604           for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
4605             Updates.push_back({DominatorTree::Insert, PredecessorOfPredecessor,
4606                                CSI->getUnwindDest()});
4607             Updates.push_back(
4608                 {DominatorTree::Delete, PredecessorOfPredecessor, Predecessor});
4609           }
4610           Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
4611         } else {
4612           // Rewrite all preds to unwind to caller (or from invoke to call).
4613           if (DTU)
4614             DTU->applyUpdates(Updates);
4615           Updates.clear();
4616           SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
4617           for (BasicBlock *EHPred : EHPreds)
4618             removeUnwindEdge(EHPred, DTU);
4619         }
4620         // The catchswitch is no longer reachable.
4621         new UnreachableInst(CSI->getContext(), CSI);
4622         CSI->eraseFromParent();
4623         Changed = true;
4624       }
4625     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4626       (void)CRI;
4627       assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
4628              "Expected to always have an unwind to BB.");
4629       Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4630       new UnreachableInst(TI->getContext(), TI);
4631       TI->eraseFromParent();
4632       Changed = true;
4633     }
4634   }
4635 
4636   if (DTU)
4637     DTU->applyUpdates(Updates);
4638 
4639   // If this block is now dead, remove it.
4640   if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4641     // We know there are no successors, so just nuke the block.
4642     if (DTU)
4643       DTU->deleteBB(BB);
4644     else
4645       BB->eraseFromParent();
4646     return true;
4647   }
4648 
4649   return Changed;
4650 }
4651 
4652 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4653   assert(Cases.size() >= 1);
4654 
4655   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4656   for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4657     if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4658       return false;
4659   }
4660   return true;
4661 }
4662 
4663 static void createUnreachableSwitchDefault(SwitchInst *Switch,
4664                                            DomTreeUpdater *DTU) {
4665   LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4666   auto *BB = Switch->getParent();
4667   BasicBlock *NewDefaultBlock = SplitBlockPredecessors(
4668       Switch->getDefaultDest(), Switch->getParent(), "", DTU);
4669   auto *OrigDefaultBlock = Switch->getDefaultDest();
4670   Switch->setDefaultDest(&*NewDefaultBlock);
4671   if (DTU)
4672     DTU->applyUpdates({{DominatorTree::Insert, BB, &*NewDefaultBlock},
4673                        {DominatorTree::Delete, BB, OrigDefaultBlock}});
4674   SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front(), DTU);
4675   SmallVector<DominatorTree::UpdateType, 2> Updates;
4676   for (auto *Successor : successors(NewDefaultBlock))
4677     Updates.push_back({DominatorTree::Delete, NewDefaultBlock, Successor});
4678   auto *NewTerminator = NewDefaultBlock->getTerminator();
4679   new UnreachableInst(Switch->getContext(), NewTerminator);
4680   EraseTerminatorAndDCECond(NewTerminator);
4681   if (DTU)
4682     DTU->applyUpdates(Updates);
4683 }
4684 
4685 /// Turn a switch with two reachable destinations into an integer range
4686 /// comparison and branch.
4687 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
4688                                              IRBuilder<> &Builder) {
4689   assert(SI->getNumCases() > 1 && "Degenerate switch?");
4690 
4691   bool HasDefault =
4692       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4693 
4694   auto *BB = SI->getParent();
4695 
4696   // Partition the cases into two sets with different destinations.
4697   BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4698   BasicBlock *DestB = nullptr;
4699   SmallVector<ConstantInt *, 16> CasesA;
4700   SmallVector<ConstantInt *, 16> CasesB;
4701 
4702   for (auto Case : SI->cases()) {
4703     BasicBlock *Dest = Case.getCaseSuccessor();
4704     if (!DestA)
4705       DestA = Dest;
4706     if (Dest == DestA) {
4707       CasesA.push_back(Case.getCaseValue());
4708       continue;
4709     }
4710     if (!DestB)
4711       DestB = Dest;
4712     if (Dest == DestB) {
4713       CasesB.push_back(Case.getCaseValue());
4714       continue;
4715     }
4716     return false; // More than two destinations.
4717   }
4718 
4719   assert(DestA && DestB &&
4720          "Single-destination switch should have been folded.");
4721   assert(DestA != DestB);
4722   assert(DestB != SI->getDefaultDest());
4723   assert(!CasesB.empty() && "There must be non-default cases.");
4724   assert(!CasesA.empty() || HasDefault);
4725 
4726   // Figure out if one of the sets of cases form a contiguous range.
4727   SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4728   BasicBlock *ContiguousDest = nullptr;
4729   BasicBlock *OtherDest = nullptr;
4730   if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4731     ContiguousCases = &CasesA;
4732     ContiguousDest = DestA;
4733     OtherDest = DestB;
4734   } else if (CasesAreContiguous(CasesB)) {
4735     ContiguousCases = &CasesB;
4736     ContiguousDest = DestB;
4737     OtherDest = DestA;
4738   } else
4739     return false;
4740 
4741   // Start building the compare and branch.
4742 
4743   Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4744   Constant *NumCases =
4745       ConstantInt::get(Offset->getType(), ContiguousCases->size());
4746 
4747   Value *Sub = SI->getCondition();
4748   if (!Offset->isNullValue())
4749     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4750 
4751   Value *Cmp;
4752   // If NumCases overflowed, then all possible values jump to the successor.
4753   if (NumCases->isNullValue() && !ContiguousCases->empty())
4754     Cmp = ConstantInt::getTrue(SI->getContext());
4755   else
4756     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4757   BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4758 
4759   // Update weight for the newly-created conditional branch.
4760   if (HasBranchWeights(SI)) {
4761     SmallVector<uint64_t, 8> Weights;
4762     GetBranchWeights(SI, Weights);
4763     if (Weights.size() == 1 + SI->getNumCases()) {
4764       uint64_t TrueWeight = 0;
4765       uint64_t FalseWeight = 0;
4766       for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4767         if (SI->getSuccessor(I) == ContiguousDest)
4768           TrueWeight += Weights[I];
4769         else
4770           FalseWeight += Weights[I];
4771       }
4772       while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4773         TrueWeight /= 2;
4774         FalseWeight /= 2;
4775       }
4776       setBranchWeights(NewBI, TrueWeight, FalseWeight);
4777     }
4778   }
4779 
4780   // Prune obsolete incoming values off the successors' PHI nodes.
4781   for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4782     unsigned PreviousEdges = ContiguousCases->size();
4783     if (ContiguousDest == SI->getDefaultDest())
4784       ++PreviousEdges;
4785     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4786       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4787   }
4788   for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4789     unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4790     if (OtherDest == SI->getDefaultDest())
4791       ++PreviousEdges;
4792     for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4793       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4794   }
4795 
4796   // Clean up the default block - it may have phis or other instructions before
4797   // the unreachable terminator.
4798   if (!HasDefault)
4799     createUnreachableSwitchDefault(SI, DTU);
4800 
4801   auto *UnreachableDefault = SI->getDefaultDest();
4802 
4803   // Drop the switch.
4804   SI->eraseFromParent();
4805 
4806   if (!HasDefault && DTU)
4807     DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}});
4808 
4809   return true;
4810 }
4811 
4812 /// Compute masked bits for the condition of a switch
4813 /// and use it to remove dead cases.
4814 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
4815                                      AssumptionCache *AC,
4816                                      const DataLayout &DL) {
4817   Value *Cond = SI->getCondition();
4818   unsigned Bits = Cond->getType()->getIntegerBitWidth();
4819   KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
4820 
4821   // We can also eliminate cases by determining that their values are outside of
4822   // the limited range of the condition based on how many significant (non-sign)
4823   // bits are in the condition value.
4824   unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4825   unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4826 
4827   // Gather dead cases.
4828   SmallVector<ConstantInt *, 8> DeadCases;
4829   SmallMapVector<BasicBlock *, int, 8> NumPerSuccessorCases;
4830   for (auto &Case : SI->cases()) {
4831     auto *Successor = Case.getCaseSuccessor();
4832     ++NumPerSuccessorCases[Successor];
4833     const APInt &CaseVal = Case.getCaseValue()->getValue();
4834     if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
4835         (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4836       DeadCases.push_back(Case.getCaseValue());
4837       --NumPerSuccessorCases[Successor];
4838       LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
4839                         << " is dead.\n");
4840     }
4841   }
4842 
4843   // If we can prove that the cases must cover all possible values, the
4844   // default destination becomes dead and we can remove it.  If we know some
4845   // of the bits in the value, we can use that to more precisely compute the
4846   // number of possible unique case values.
4847   bool HasDefault =
4848       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4849   const unsigned NumUnknownBits =
4850       Bits - (Known.Zero | Known.One).countPopulation();
4851   assert(NumUnknownBits <= Bits);
4852   if (HasDefault && DeadCases.empty() &&
4853       NumUnknownBits < 64 /* avoid overflow */ &&
4854       SI->getNumCases() == (1ULL << NumUnknownBits)) {
4855     createUnreachableSwitchDefault(SI, DTU);
4856     return true;
4857   }
4858 
4859   if (DeadCases.empty())
4860     return false;
4861 
4862   SwitchInstProfUpdateWrapper SIW(*SI);
4863   for (ConstantInt *DeadCase : DeadCases) {
4864     SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4865     assert(CaseI != SI->case_default() &&
4866            "Case was not found. Probably mistake in DeadCases forming.");
4867     // Prune unused values from PHI nodes.
4868     CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4869     SIW.removeCase(CaseI);
4870   }
4871 
4872   std::vector<DominatorTree::UpdateType> Updates;
4873   for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
4874     if (I.second == 0)
4875       Updates.push_back({DominatorTree::Delete, SI->getParent(), I.first});
4876   if (DTU)
4877     DTU->applyUpdates(Updates);
4878 
4879   return true;
4880 }
4881 
4882 /// If BB would be eligible for simplification by
4883 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4884 /// by an unconditional branch), look at the phi node for BB in the successor
4885 /// block and see if the incoming value is equal to CaseValue. If so, return
4886 /// the phi node, and set PhiIndex to BB's index in the phi node.
4887 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4888                                               BasicBlock *BB, int *PhiIndex) {
4889   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4890     return nullptr; // BB must be empty to be a candidate for simplification.
4891   if (!BB->getSinglePredecessor())
4892     return nullptr; // BB must be dominated by the switch.
4893 
4894   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4895   if (!Branch || !Branch->isUnconditional())
4896     return nullptr; // Terminator must be unconditional branch.
4897 
4898   BasicBlock *Succ = Branch->getSuccessor(0);
4899 
4900   for (PHINode &PHI : Succ->phis()) {
4901     int Idx = PHI.getBasicBlockIndex(BB);
4902     assert(Idx >= 0 && "PHI has no entry for predecessor?");
4903 
4904     Value *InValue = PHI.getIncomingValue(Idx);
4905     if (InValue != CaseValue)
4906       continue;
4907 
4908     *PhiIndex = Idx;
4909     return &PHI;
4910   }
4911 
4912   return nullptr;
4913 }
4914 
4915 /// Try to forward the condition of a switch instruction to a phi node
4916 /// dominated by the switch, if that would mean that some of the destination
4917 /// blocks of the switch can be folded away. Return true if a change is made.
4918 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4919   using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4920 
4921   ForwardingNodesMap ForwardingNodes;
4922   BasicBlock *SwitchBlock = SI->getParent();
4923   bool Changed = false;
4924   for (auto &Case : SI->cases()) {
4925     ConstantInt *CaseValue = Case.getCaseValue();
4926     BasicBlock *CaseDest = Case.getCaseSuccessor();
4927 
4928     // Replace phi operands in successor blocks that are using the constant case
4929     // value rather than the switch condition variable:
4930     //   switchbb:
4931     //   switch i32 %x, label %default [
4932     //     i32 17, label %succ
4933     //   ...
4934     //   succ:
4935     //     %r = phi i32 ... [ 17, %switchbb ] ...
4936     // -->
4937     //     %r = phi i32 ... [ %x, %switchbb ] ...
4938 
4939     for (PHINode &Phi : CaseDest->phis()) {
4940       // This only works if there is exactly 1 incoming edge from the switch to
4941       // a phi. If there is >1, that means multiple cases of the switch map to 1
4942       // value in the phi, and that phi value is not the switch condition. Thus,
4943       // this transform would not make sense (the phi would be invalid because
4944       // a phi can't have different incoming values from the same block).
4945       int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4946       if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4947           count(Phi.blocks(), SwitchBlock) == 1) {
4948         Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
4949         Changed = true;
4950       }
4951     }
4952 
4953     // Collect phi nodes that are indirectly using this switch's case constants.
4954     int PhiIdx;
4955     if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4956       ForwardingNodes[Phi].push_back(PhiIdx);
4957   }
4958 
4959   for (auto &ForwardingNode : ForwardingNodes) {
4960     PHINode *Phi = ForwardingNode.first;
4961     SmallVectorImpl<int> &Indexes = ForwardingNode.second;
4962     if (Indexes.size() < 2)
4963       continue;
4964 
4965     for (int Index : Indexes)
4966       Phi->setIncomingValue(Index, SI->getCondition());
4967     Changed = true;
4968   }
4969 
4970   return Changed;
4971 }
4972 
4973 /// Return true if the backend will be able to handle
4974 /// initializing an array of constants like C.
4975 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4976   if (C->isThreadDependent())
4977     return false;
4978   if (C->isDLLImportDependent())
4979     return false;
4980 
4981   if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4982       !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4983       !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4984     return false;
4985 
4986   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
4987     if (!CE->isGEPWithNoNotionalOverIndexing())
4988       return false;
4989     if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4990       return false;
4991   }
4992 
4993   if (!TTI.shouldBuildLookupTablesForConstant(C))
4994     return false;
4995 
4996   return true;
4997 }
4998 
4999 /// If V is a Constant, return it. Otherwise, try to look up
5000 /// its constant value in ConstantPool, returning 0 if it's not there.
5001 static Constant *
5002 LookupConstant(Value *V,
5003                const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5004   if (Constant *C = dyn_cast<Constant>(V))
5005     return C;
5006   return ConstantPool.lookup(V);
5007 }
5008 
5009 /// Try to fold instruction I into a constant. This works for
5010 /// simple instructions such as binary operations where both operands are
5011 /// constant or can be replaced by constants from the ConstantPool. Returns the
5012 /// resulting constant on success, 0 otherwise.
5013 static Constant *
5014 ConstantFold(Instruction *I, const DataLayout &DL,
5015              const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5016   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
5017     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
5018     if (!A)
5019       return nullptr;
5020     if (A->isAllOnesValue())
5021       return LookupConstant(Select->getTrueValue(), ConstantPool);
5022     if (A->isNullValue())
5023       return LookupConstant(Select->getFalseValue(), ConstantPool);
5024     return nullptr;
5025   }
5026 
5027   SmallVector<Constant *, 4> COps;
5028   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
5029     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
5030       COps.push_back(A);
5031     else
5032       return nullptr;
5033   }
5034 
5035   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
5036     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
5037                                            COps[1], DL);
5038   }
5039 
5040   return ConstantFoldInstOperands(I, COps, DL);
5041 }
5042 
5043 /// Try to determine the resulting constant values in phi nodes
5044 /// at the common destination basic block, *CommonDest, for one of the case
5045 /// destionations CaseDest corresponding to value CaseVal (0 for the default
5046 /// case), of a switch instruction SI.
5047 static bool
5048 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
5049                BasicBlock **CommonDest,
5050                SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
5051                const DataLayout &DL, const TargetTransformInfo &TTI) {
5052   // The block from which we enter the common destination.
5053   BasicBlock *Pred = SI->getParent();
5054 
5055   // If CaseDest is empty except for some side-effect free instructions through
5056   // which we can constant-propagate the CaseVal, continue to its successor.
5057   SmallDenseMap<Value *, Constant *> ConstantPool;
5058   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
5059   for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
5060     if (I.isTerminator()) {
5061       // If the terminator is a simple branch, continue to the next block.
5062       if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
5063         return false;
5064       Pred = CaseDest;
5065       CaseDest = I.getSuccessor(0);
5066     } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
5067       // Instruction is side-effect free and constant.
5068 
5069       // If the instruction has uses outside this block or a phi node slot for
5070       // the block, it is not safe to bypass the instruction since it would then
5071       // no longer dominate all its uses.
5072       for (auto &Use : I.uses()) {
5073         User *User = Use.getUser();
5074         if (Instruction *I = dyn_cast<Instruction>(User))
5075           if (I->getParent() == CaseDest)
5076             continue;
5077         if (PHINode *Phi = dyn_cast<PHINode>(User))
5078           if (Phi->getIncomingBlock(Use) == CaseDest)
5079             continue;
5080         return false;
5081       }
5082 
5083       ConstantPool.insert(std::make_pair(&I, C));
5084     } else {
5085       break;
5086     }
5087   }
5088 
5089   // If we did not have a CommonDest before, use the current one.
5090   if (!*CommonDest)
5091     *CommonDest = CaseDest;
5092   // If the destination isn't the common one, abort.
5093   if (CaseDest != *CommonDest)
5094     return false;
5095 
5096   // Get the values for this case from phi nodes in the destination block.
5097   for (PHINode &PHI : (*CommonDest)->phis()) {
5098     int Idx = PHI.getBasicBlockIndex(Pred);
5099     if (Idx == -1)
5100       continue;
5101 
5102     Constant *ConstVal =
5103         LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
5104     if (!ConstVal)
5105       return false;
5106 
5107     // Be conservative about which kinds of constants we support.
5108     if (!ValidLookupTableConstant(ConstVal, TTI))
5109       return false;
5110 
5111     Res.push_back(std::make_pair(&PHI, ConstVal));
5112   }
5113 
5114   return Res.size() > 0;
5115 }
5116 
5117 // Helper function used to add CaseVal to the list of cases that generate
5118 // Result. Returns the updated number of cases that generate this result.
5119 static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
5120                                  SwitchCaseResultVectorTy &UniqueResults,
5121                                  Constant *Result) {
5122   for (auto &I : UniqueResults) {
5123     if (I.first == Result) {
5124       I.second.push_back(CaseVal);
5125       return I.second.size();
5126     }
5127   }
5128   UniqueResults.push_back(
5129       std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5130   return 1;
5131 }
5132 
5133 // Helper function that initializes a map containing
5134 // results for the PHI node of the common destination block for a switch
5135 // instruction. Returns false if multiple PHI nodes have been found or if
5136 // there is not a common destination block for the switch.
5137 static bool
5138 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
5139                       SwitchCaseResultVectorTy &UniqueResults,
5140                       Constant *&DefaultResult, const DataLayout &DL,
5141                       const TargetTransformInfo &TTI,
5142                       uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
5143   for (auto &I : SI->cases()) {
5144     ConstantInt *CaseVal = I.getCaseValue();
5145 
5146     // Resulting value at phi nodes for this case value.
5147     SwitchCaseResultsTy Results;
5148     if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5149                         DL, TTI))
5150       return false;
5151 
5152     // Only one value per case is permitted.
5153     if (Results.size() > 1)
5154       return false;
5155 
5156     // Add the case->result mapping to UniqueResults.
5157     const uintptr_t NumCasesForResult =
5158         MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5159 
5160     // Early out if there are too many cases for this result.
5161     if (NumCasesForResult > MaxCasesPerResult)
5162       return false;
5163 
5164     // Early out if there are too many unique results.
5165     if (UniqueResults.size() > MaxUniqueResults)
5166       return false;
5167 
5168     // Check the PHI consistency.
5169     if (!PHI)
5170       PHI = Results[0].first;
5171     else if (PHI != Results[0].first)
5172       return false;
5173   }
5174   // Find the default result value.
5175   SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5176   BasicBlock *DefaultDest = SI->getDefaultDest();
5177   GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5178                  DL, TTI);
5179   // If the default value is not found abort unless the default destination
5180   // is unreachable.
5181   DefaultResult =
5182       DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5183   if ((!DefaultResult &&
5184        !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5185     return false;
5186 
5187   return true;
5188 }
5189 
5190 // Helper function that checks if it is possible to transform a switch with only
5191 // two cases (or two cases + default) that produces a result into a select.
5192 // Example:
5193 // switch (a) {
5194 //   case 10:                %0 = icmp eq i32 %a, 10
5195 //     return 10;            %1 = select i1 %0, i32 10, i32 4
5196 //   case 20:        ---->   %2 = icmp eq i32 %a, 20
5197 //     return 2;             %3 = select i1 %2, i32 2, i32 %1
5198 //   default:
5199 //     return 4;
5200 // }
5201 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
5202                                    Constant *DefaultResult, Value *Condition,
5203                                    IRBuilder<> &Builder) {
5204   assert(ResultVector.size() == 2 &&
5205          "We should have exactly two unique results at this point");
5206   // If we are selecting between only two cases transform into a simple
5207   // select or a two-way select if default is possible.
5208   if (ResultVector[0].second.size() == 1 &&
5209       ResultVector[1].second.size() == 1) {
5210     ConstantInt *const FirstCase = ResultVector[0].second[0];
5211     ConstantInt *const SecondCase = ResultVector[1].second[0];
5212 
5213     bool DefaultCanTrigger = DefaultResult;
5214     Value *SelectValue = ResultVector[1].first;
5215     if (DefaultCanTrigger) {
5216       Value *const ValueCompare =
5217           Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5218       SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5219                                          DefaultResult, "switch.select");
5220     }
5221     Value *const ValueCompare =
5222         Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5223     return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5224                                 SelectValue, "switch.select");
5225   }
5226 
5227   return nullptr;
5228 }
5229 
5230 // Helper function to cleanup a switch instruction that has been converted into
5231 // a select, fixing up PHI nodes and basic blocks.
5232 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
5233                                               Value *SelectValue,
5234                                               IRBuilder<> &Builder,
5235                                               DomTreeUpdater *DTU) {
5236   std::vector<DominatorTree::UpdateType> Updates;
5237 
5238   BasicBlock *SelectBB = SI->getParent();
5239   BasicBlock *DestBB = PHI->getParent();
5240 
5241   if (!is_contained(predecessors(DestBB), SelectBB))
5242     Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
5243   Builder.CreateBr(DestBB);
5244 
5245   // Remove the switch.
5246 
5247   while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5248     PHI->removeIncomingValue(SelectBB);
5249   PHI->addIncoming(SelectValue, SelectBB);
5250 
5251   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5252     BasicBlock *Succ = SI->getSuccessor(i);
5253 
5254     if (Succ == DestBB)
5255       continue;
5256     Succ->removePredecessor(SelectBB);
5257     Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
5258   }
5259   SI->eraseFromParent();
5260   if (DTU)
5261     DTU->applyUpdates(Updates);
5262 }
5263 
5264 /// If the switch is only used to initialize one or more
5265 /// phi nodes in a common successor block with only two different
5266 /// constant values, replace the switch with select.
5267 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5268                            DomTreeUpdater *DTU, const DataLayout &DL,
5269                            const TargetTransformInfo &TTI) {
5270   Value *const Cond = SI->getCondition();
5271   PHINode *PHI = nullptr;
5272   BasicBlock *CommonDest = nullptr;
5273   Constant *DefaultResult;
5274   SwitchCaseResultVectorTy UniqueResults;
5275   // Collect all the cases that will deliver the same value from the switch.
5276   if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5277                              DL, TTI, 2, 1))
5278     return false;
5279   // Selects choose between maximum two values.
5280   if (UniqueResults.size() != 2)
5281     return false;
5282   assert(PHI != nullptr && "PHI for value select not found");
5283 
5284   Builder.SetInsertPoint(SI);
5285   Value *SelectValue =
5286       ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
5287   if (SelectValue) {
5288     RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder, DTU);
5289     return true;
5290   }
5291   // The switch couldn't be converted into a select.
5292   return false;
5293 }
5294 
5295 namespace {
5296 
5297 /// This class represents a lookup table that can be used to replace a switch.
5298 class SwitchLookupTable {
5299 public:
5300   /// Create a lookup table to use as a switch replacement with the contents
5301   /// of Values, using DefaultValue to fill any holes in the table.
5302   SwitchLookupTable(
5303       Module &M, uint64_t TableSize, ConstantInt *Offset,
5304       const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5305       Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5306 
5307   /// Build instructions with Builder to retrieve the value at
5308   /// the position given by Index in the lookup table.
5309   Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5310 
5311   /// Return true if a table with TableSize elements of
5312   /// type ElementType would fit in a target-legal register.
5313   static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5314                                  Type *ElementType);
5315 
5316 private:
5317   // Depending on the contents of the table, it can be represented in
5318   // different ways.
5319   enum {
5320     // For tables where each element contains the same value, we just have to
5321     // store that single value and return it for each lookup.
5322     SingleValueKind,
5323 
5324     // For tables where there is a linear relationship between table index
5325     // and values. We calculate the result with a simple multiplication
5326     // and addition instead of a table lookup.
5327     LinearMapKind,
5328 
5329     // For small tables with integer elements, we can pack them into a bitmap
5330     // that fits into a target-legal register. Values are retrieved by
5331     // shift and mask operations.
5332     BitMapKind,
5333 
5334     // The table is stored as an array of values. Values are retrieved by load
5335     // instructions from the table.
5336     ArrayKind
5337   } Kind;
5338 
5339   // For SingleValueKind, this is the single value.
5340   Constant *SingleValue = nullptr;
5341 
5342   // For BitMapKind, this is the bitmap.
5343   ConstantInt *BitMap = nullptr;
5344   IntegerType *BitMapElementTy = nullptr;
5345 
5346   // For LinearMapKind, these are the constants used to derive the value.
5347   ConstantInt *LinearOffset = nullptr;
5348   ConstantInt *LinearMultiplier = nullptr;
5349 
5350   // For ArrayKind, this is the array.
5351   GlobalVariable *Array = nullptr;
5352 };
5353 
5354 } // end anonymous namespace
5355 
5356 SwitchLookupTable::SwitchLookupTable(
5357     Module &M, uint64_t TableSize, ConstantInt *Offset,
5358     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5359     Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5360   assert(Values.size() && "Can't build lookup table without values!");
5361   assert(TableSize >= Values.size() && "Can't fit values in table!");
5362 
5363   // If all values in the table are equal, this is that value.
5364   SingleValue = Values.begin()->second;
5365 
5366   Type *ValueType = Values.begin()->second->getType();
5367 
5368   // Build up the table contents.
5369   SmallVector<Constant *, 64> TableContents(TableSize);
5370   for (size_t I = 0, E = Values.size(); I != E; ++I) {
5371     ConstantInt *CaseVal = Values[I].first;
5372     Constant *CaseRes = Values[I].second;
5373     assert(CaseRes->getType() == ValueType);
5374 
5375     uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5376     TableContents[Idx] = CaseRes;
5377 
5378     if (CaseRes != SingleValue)
5379       SingleValue = nullptr;
5380   }
5381 
5382   // Fill in any holes in the table with the default result.
5383   if (Values.size() < TableSize) {
5384     assert(DefaultValue &&
5385            "Need a default value to fill the lookup table holes.");
5386     assert(DefaultValue->getType() == ValueType);
5387     for (uint64_t I = 0; I < TableSize; ++I) {
5388       if (!TableContents[I])
5389         TableContents[I] = DefaultValue;
5390     }
5391 
5392     if (DefaultValue != SingleValue)
5393       SingleValue = nullptr;
5394   }
5395 
5396   // If each element in the table contains the same value, we only need to store
5397   // that single value.
5398   if (SingleValue) {
5399     Kind = SingleValueKind;
5400     return;
5401   }
5402 
5403   // Check if we can derive the value with a linear transformation from the
5404   // table index.
5405   if (isa<IntegerType>(ValueType)) {
5406     bool LinearMappingPossible = true;
5407     APInt PrevVal;
5408     APInt DistToPrev;
5409     assert(TableSize >= 2 && "Should be a SingleValue table.");
5410     // Check if there is the same distance between two consecutive values.
5411     for (uint64_t I = 0; I < TableSize; ++I) {
5412       ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5413       if (!ConstVal) {
5414         // This is an undef. We could deal with it, but undefs in lookup tables
5415         // are very seldom. It's probably not worth the additional complexity.
5416         LinearMappingPossible = false;
5417         break;
5418       }
5419       const APInt &Val = ConstVal->getValue();
5420       if (I != 0) {
5421         APInt Dist = Val - PrevVal;
5422         if (I == 1) {
5423           DistToPrev = Dist;
5424         } else if (Dist != DistToPrev) {
5425           LinearMappingPossible = false;
5426           break;
5427         }
5428       }
5429       PrevVal = Val;
5430     }
5431     if (LinearMappingPossible) {
5432       LinearOffset = cast<ConstantInt>(TableContents[0]);
5433       LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5434       Kind = LinearMapKind;
5435       ++NumLinearMaps;
5436       return;
5437     }
5438   }
5439 
5440   // If the type is integer and the table fits in a register, build a bitmap.
5441   if (WouldFitInRegister(DL, TableSize, ValueType)) {
5442     IntegerType *IT = cast<IntegerType>(ValueType);
5443     APInt TableInt(TableSize * IT->getBitWidth(), 0);
5444     for (uint64_t I = TableSize; I > 0; --I) {
5445       TableInt <<= IT->getBitWidth();
5446       // Insert values into the bitmap. Undef values are set to zero.
5447       if (!isa<UndefValue>(TableContents[I - 1])) {
5448         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5449         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5450       }
5451     }
5452     BitMap = ConstantInt::get(M.getContext(), TableInt);
5453     BitMapElementTy = IT;
5454     Kind = BitMapKind;
5455     ++NumBitMaps;
5456     return;
5457   }
5458 
5459   // Store the table in an array.
5460   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5461   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5462 
5463   Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5464                              GlobalVariable::PrivateLinkage, Initializer,
5465                              "switch.table." + FuncName);
5466   Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5467   // Set the alignment to that of an array items. We will be only loading one
5468   // value out of it.
5469   Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5470   Kind = ArrayKind;
5471 }
5472 
5473 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5474   switch (Kind) {
5475   case SingleValueKind:
5476     return SingleValue;
5477   case LinearMapKind: {
5478     // Derive the result value from the input value.
5479     Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5480                                           false, "switch.idx.cast");
5481     if (!LinearMultiplier->isOne())
5482       Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5483     if (!LinearOffset->isZero())
5484       Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5485     return Result;
5486   }
5487   case BitMapKind: {
5488     // Type of the bitmap (e.g. i59).
5489     IntegerType *MapTy = BitMap->getType();
5490 
5491     // Cast Index to the same type as the bitmap.
5492     // Note: The Index is <= the number of elements in the table, so
5493     // truncating it to the width of the bitmask is safe.
5494     Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5495 
5496     // Multiply the shift amount by the element width.
5497     ShiftAmt = Builder.CreateMul(
5498         ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5499         "switch.shiftamt");
5500 
5501     // Shift down.
5502     Value *DownShifted =
5503         Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5504     // Mask off.
5505     return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5506   }
5507   case ArrayKind: {
5508     // Make sure the table index will not overflow when treated as signed.
5509     IntegerType *IT = cast<IntegerType>(Index->getType());
5510     uint64_t TableSize =
5511         Array->getInitializer()->getType()->getArrayNumElements();
5512     if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5513       Index = Builder.CreateZExt(
5514           Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5515           "switch.tableidx.zext");
5516 
5517     Value *GEPIndices[] = {Builder.getInt32(0), Index};
5518     Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5519                                            GEPIndices, "switch.gep");
5520     return Builder.CreateLoad(
5521         cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
5522         "switch.load");
5523   }
5524   }
5525   llvm_unreachable("Unknown lookup table kind!");
5526 }
5527 
5528 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5529                                            uint64_t TableSize,
5530                                            Type *ElementType) {
5531   auto *IT = dyn_cast<IntegerType>(ElementType);
5532   if (!IT)
5533     return false;
5534   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5535   // are <= 15, we could try to narrow the type.
5536 
5537   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5538   if (TableSize >= UINT_MAX / IT->getBitWidth())
5539     return false;
5540   return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5541 }
5542 
5543 /// Determine whether a lookup table should be built for this switch, based on
5544 /// the number of cases, size of the table, and the types of the results.
5545 static bool
5546 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5547                        const TargetTransformInfo &TTI, const DataLayout &DL,
5548                        const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5549   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5550     return false; // TableSize overflowed, or mul below might overflow.
5551 
5552   bool AllTablesFitInRegister = true;
5553   bool HasIllegalType = false;
5554   for (const auto &I : ResultTypes) {
5555     Type *Ty = I.second;
5556 
5557     // Saturate this flag to true.
5558     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5559 
5560     // Saturate this flag to false.
5561     AllTablesFitInRegister =
5562         AllTablesFitInRegister &&
5563         SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5564 
5565     // If both flags saturate, we're done. NOTE: This *only* works with
5566     // saturating flags, and all flags have to saturate first due to the
5567     // non-deterministic behavior of iterating over a dense map.
5568     if (HasIllegalType && !AllTablesFitInRegister)
5569       break;
5570   }
5571 
5572   // If each table would fit in a register, we should build it anyway.
5573   if (AllTablesFitInRegister)
5574     return true;
5575 
5576   // Don't build a table that doesn't fit in-register if it has illegal types.
5577   if (HasIllegalType)
5578     return false;
5579 
5580   // The table density should be at least 40%. This is the same criterion as for
5581   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5582   // FIXME: Find the best cut-off.
5583   return SI->getNumCases() * 10 >= TableSize * 4;
5584 }
5585 
5586 /// Try to reuse the switch table index compare. Following pattern:
5587 /// \code
5588 ///     if (idx < tablesize)
5589 ///        r = table[idx]; // table does not contain default_value
5590 ///     else
5591 ///        r = default_value;
5592 ///     if (r != default_value)
5593 ///        ...
5594 /// \endcode
5595 /// Is optimized to:
5596 /// \code
5597 ///     cond = idx < tablesize;
5598 ///     if (cond)
5599 ///        r = table[idx];
5600 ///     else
5601 ///        r = default_value;
5602 ///     if (cond)
5603 ///        ...
5604 /// \endcode
5605 /// Jump threading will then eliminate the second if(cond).
5606 static void reuseTableCompare(
5607     User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5608     Constant *DefaultValue,
5609     const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5610   ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5611   if (!CmpInst)
5612     return;
5613 
5614   // We require that the compare is in the same block as the phi so that jump
5615   // threading can do its work afterwards.
5616   if (CmpInst->getParent() != PhiBlock)
5617     return;
5618 
5619   Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5620   if (!CmpOp1)
5621     return;
5622 
5623   Value *RangeCmp = RangeCheckBranch->getCondition();
5624   Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5625   Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5626 
5627   // Check if the compare with the default value is constant true or false.
5628   Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5629                                                  DefaultValue, CmpOp1, true);
5630   if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5631     return;
5632 
5633   // Check if the compare with the case values is distinct from the default
5634   // compare result.
5635   for (auto ValuePair : Values) {
5636     Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5637                                                 ValuePair.second, CmpOp1, true);
5638     if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5639       return;
5640     assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5641            "Expect true or false as compare result.");
5642   }
5643 
5644   // Check if the branch instruction dominates the phi node. It's a simple
5645   // dominance check, but sufficient for our needs.
5646   // Although this check is invariant in the calling loops, it's better to do it
5647   // at this late stage. Practically we do it at most once for a switch.
5648   BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5649   for (BasicBlock *Pred : predecessors(PhiBlock)) {
5650     if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5651       return;
5652   }
5653 
5654   if (DefaultConst == FalseConst) {
5655     // The compare yields the same result. We can replace it.
5656     CmpInst->replaceAllUsesWith(RangeCmp);
5657     ++NumTableCmpReuses;
5658   } else {
5659     // The compare yields the same result, just inverted. We can replace it.
5660     Value *InvertedTableCmp = BinaryOperator::CreateXor(
5661         RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5662         RangeCheckBranch);
5663     CmpInst->replaceAllUsesWith(InvertedTableCmp);
5664     ++NumTableCmpReuses;
5665   }
5666 }
5667 
5668 /// If the switch is only used to initialize one or more phi nodes in a common
5669 /// successor block with different constant values, replace the switch with
5670 /// lookup tables.
5671 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5672                                 DomTreeUpdater *DTU, const DataLayout &DL,
5673                                 const TargetTransformInfo &TTI) {
5674   assert(SI->getNumCases() > 1 && "Degenerate switch?");
5675 
5676   BasicBlock *BB = SI->getParent();
5677   Function *Fn = BB->getParent();
5678   // Only build lookup table when we have a target that supports it or the
5679   // attribute is not set.
5680   if (!TTI.shouldBuildLookupTables() ||
5681       (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
5682     return false;
5683 
5684   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5685   // split off a dense part and build a lookup table for that.
5686 
5687   // FIXME: This creates arrays of GEPs to constant strings, which means each
5688   // GEP needs a runtime relocation in PIC code. We should just build one big
5689   // string and lookup indices into that.
5690 
5691   // Ignore switches with less than three cases. Lookup tables will not make
5692   // them faster, so we don't analyze them.
5693   if (SI->getNumCases() < 3)
5694     return false;
5695 
5696   // Figure out the corresponding result for each case value and phi node in the
5697   // common destination, as well as the min and max case values.
5698   assert(!SI->cases().empty());
5699   SwitchInst::CaseIt CI = SI->case_begin();
5700   ConstantInt *MinCaseVal = CI->getCaseValue();
5701   ConstantInt *MaxCaseVal = CI->getCaseValue();
5702 
5703   BasicBlock *CommonDest = nullptr;
5704 
5705   using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5706   SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5707 
5708   SmallDenseMap<PHINode *, Constant *> DefaultResults;
5709   SmallDenseMap<PHINode *, Type *> ResultTypes;
5710   SmallVector<PHINode *, 4> PHIs;
5711 
5712   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5713     ConstantInt *CaseVal = CI->getCaseValue();
5714     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5715       MinCaseVal = CaseVal;
5716     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5717       MaxCaseVal = CaseVal;
5718 
5719     // Resulting value at phi nodes for this case value.
5720     using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5721     ResultsTy Results;
5722     if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5723                         Results, DL, TTI))
5724       return false;
5725 
5726     // Append the result from this case to the list for each phi.
5727     for (const auto &I : Results) {
5728       PHINode *PHI = I.first;
5729       Constant *Value = I.second;
5730       if (!ResultLists.count(PHI))
5731         PHIs.push_back(PHI);
5732       ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5733     }
5734   }
5735 
5736   // Keep track of the result types.
5737   for (PHINode *PHI : PHIs) {
5738     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5739   }
5740 
5741   uint64_t NumResults = ResultLists[PHIs[0]].size();
5742   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5743   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5744   bool TableHasHoles = (NumResults < TableSize);
5745 
5746   // If the table has holes, we need a constant result for the default case
5747   // or a bitmask that fits in a register.
5748   SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5749   bool HasDefaultResults =
5750       GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5751                      DefaultResultsList, DL, TTI);
5752 
5753   bool NeedMask = (TableHasHoles && !HasDefaultResults);
5754   if (NeedMask) {
5755     // As an extra penalty for the validity test we require more cases.
5756     if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5757       return false;
5758     if (!DL.fitsInLegalInteger(TableSize))
5759       return false;
5760   }
5761 
5762   for (const auto &I : DefaultResultsList) {
5763     PHINode *PHI = I.first;
5764     Constant *Result = I.second;
5765     DefaultResults[PHI] = Result;
5766   }
5767 
5768   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5769     return false;
5770 
5771   std::vector<DominatorTree::UpdateType> Updates;
5772 
5773   // Create the BB that does the lookups.
5774   Module &Mod = *CommonDest->getParent()->getParent();
5775   BasicBlock *LookupBB = BasicBlock::Create(
5776       Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5777 
5778   // Compute the table index value.
5779   Builder.SetInsertPoint(SI);
5780   Value *TableIndex;
5781   if (MinCaseVal->isNullValue())
5782     TableIndex = SI->getCondition();
5783   else
5784     TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5785                                    "switch.tableidx");
5786 
5787   // Compute the maximum table size representable by the integer type we are
5788   // switching upon.
5789   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5790   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5791   assert(MaxTableSize >= TableSize &&
5792          "It is impossible for a switch to have more entries than the max "
5793          "representable value of its input integer type's size.");
5794 
5795   // If the default destination is unreachable, or if the lookup table covers
5796   // all values of the conditional variable, branch directly to the lookup table
5797   // BB. Otherwise, check that the condition is within the case range.
5798   const bool DefaultIsReachable =
5799       !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5800   const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5801   BranchInst *RangeCheckBranch = nullptr;
5802 
5803   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5804     Builder.CreateBr(LookupBB);
5805     Updates.push_back({DominatorTree::Insert, BB, LookupBB});
5806     // Note: We call removeProdecessor later since we need to be able to get the
5807     // PHI value for the default case in case we're using a bit mask.
5808   } else {
5809     Value *Cmp = Builder.CreateICmpULT(
5810         TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5811     RangeCheckBranch =
5812         Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5813     Updates.push_back({DominatorTree::Insert, BB, LookupBB});
5814   }
5815 
5816   // Populate the BB that does the lookups.
5817   Builder.SetInsertPoint(LookupBB);
5818 
5819   if (NeedMask) {
5820     // Before doing the lookup, we do the hole check. The LookupBB is therefore
5821     // re-purposed to do the hole check, and we create a new LookupBB.
5822     BasicBlock *MaskBB = LookupBB;
5823     MaskBB->setName("switch.hole_check");
5824     LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5825                                   CommonDest->getParent(), CommonDest);
5826 
5827     // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
5828     // unnecessary illegal types.
5829     uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5830     APInt MaskInt(TableSizePowOf2, 0);
5831     APInt One(TableSizePowOf2, 1);
5832     // Build bitmask; fill in a 1 bit for every case.
5833     const ResultListTy &ResultList = ResultLists[PHIs[0]];
5834     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5835       uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5836                          .getLimitedValue();
5837       MaskInt |= One << Idx;
5838     }
5839     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5840 
5841     // Get the TableIndex'th bit of the bitmask.
5842     // If this bit is 0 (meaning hole) jump to the default destination,
5843     // else continue with table lookup.
5844     IntegerType *MapTy = TableMask->getType();
5845     Value *MaskIndex =
5846         Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5847     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5848     Value *LoBit = Builder.CreateTrunc(
5849         Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5850     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5851     Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
5852     Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
5853     Builder.SetInsertPoint(LookupBB);
5854     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
5855   }
5856 
5857   if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5858     // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
5859     // do not delete PHINodes here.
5860     SI->getDefaultDest()->removePredecessor(BB,
5861                                             /*KeepOneInputPHIs=*/true);
5862     Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
5863   }
5864 
5865   bool ReturnedEarly = false;
5866   for (PHINode *PHI : PHIs) {
5867     const ResultListTy &ResultList = ResultLists[PHI];
5868 
5869     // If using a bitmask, use any value to fill the lookup table holes.
5870     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5871     StringRef FuncName = Fn->getName();
5872     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5873                             FuncName);
5874 
5875     Value *Result = Table.BuildLookup(TableIndex, Builder);
5876 
5877     // If the result is used to return immediately from the function, we want to
5878     // do that right here.
5879     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5880         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5881       Builder.CreateRet(Result);
5882       ReturnedEarly = true;
5883       break;
5884     }
5885 
5886     // Do a small peephole optimization: re-use the switch table compare if
5887     // possible.
5888     if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5889       BasicBlock *PhiBlock = PHI->getParent();
5890       // Search for compare instructions which use the phi.
5891       for (auto *User : PHI->users()) {
5892         reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5893       }
5894     }
5895 
5896     PHI->addIncoming(Result, LookupBB);
5897   }
5898 
5899   if (!ReturnedEarly) {
5900     Builder.CreateBr(CommonDest);
5901     Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
5902   }
5903 
5904   // Remove the switch.
5905   SmallSetVector<BasicBlock *, 8> RemovedSuccessors;
5906   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5907     BasicBlock *Succ = SI->getSuccessor(i);
5908 
5909     if (Succ == SI->getDefaultDest())
5910       continue;
5911     Succ->removePredecessor(BB);
5912     RemovedSuccessors.insert(Succ);
5913   }
5914   SI->eraseFromParent();
5915 
5916   if (DTU) {
5917     for (BasicBlock *RemovedSuccessor : RemovedSuccessors)
5918       Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
5919     DTU->applyUpdates(Updates);
5920   }
5921 
5922   ++NumLookupTables;
5923   if (NeedMask)
5924     ++NumLookupTablesHoles;
5925   return true;
5926 }
5927 
5928 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5929   // See also SelectionDAGBuilder::isDense(), which this function was based on.
5930   uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5931   uint64_t Range = Diff + 1;
5932   uint64_t NumCases = Values.size();
5933   // 40% is the default density for building a jump table in optsize/minsize mode.
5934   uint64_t MinDensity = 40;
5935 
5936   return NumCases * 100 >= Range * MinDensity;
5937 }
5938 
5939 /// Try to transform a switch that has "holes" in it to a contiguous sequence
5940 /// of cases.
5941 ///
5942 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5943 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5944 ///
5945 /// This converts a sparse switch into a dense switch which allows better
5946 /// lowering and could also allow transforming into a lookup table.
5947 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5948                               const DataLayout &DL,
5949                               const TargetTransformInfo &TTI) {
5950   auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5951   if (CondTy->getIntegerBitWidth() > 64 ||
5952       !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5953     return false;
5954   // Only bother with this optimization if there are more than 3 switch cases;
5955   // SDAG will only bother creating jump tables for 4 or more cases.
5956   if (SI->getNumCases() < 4)
5957     return false;
5958 
5959   // This transform is agnostic to the signedness of the input or case values. We
5960   // can treat the case values as signed or unsigned. We can optimize more common
5961   // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5962   // as signed.
5963   SmallVector<int64_t,4> Values;
5964   for (auto &C : SI->cases())
5965     Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5966   llvm::sort(Values);
5967 
5968   // If the switch is already dense, there's nothing useful to do here.
5969   if (isSwitchDense(Values))
5970     return false;
5971 
5972   // First, transform the values such that they start at zero and ascend.
5973   int64_t Base = Values[0];
5974   for (auto &V : Values)
5975     V -= (uint64_t)(Base);
5976 
5977   // Now we have signed numbers that have been shifted so that, given enough
5978   // precision, there are no negative values. Since the rest of the transform
5979   // is bitwise only, we switch now to an unsigned representation.
5980 
5981   // This transform can be done speculatively because it is so cheap - it
5982   // results in a single rotate operation being inserted.
5983   // FIXME: It's possible that optimizing a switch on powers of two might also
5984   // be beneficial - flag values are often powers of two and we could use a CLZ
5985   // as the key function.
5986 
5987   // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
5988   // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
5989   // less than 64.
5990   unsigned Shift = 64;
5991   for (auto &V : Values)
5992     Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
5993   assert(Shift < 64);
5994   if (Shift > 0)
5995     for (auto &V : Values)
5996       V = (int64_t)((uint64_t)V >> Shift);
5997 
5998   if (!isSwitchDense(Values))
5999     // Transform didn't create a dense switch.
6000     return false;
6001 
6002   // The obvious transform is to shift the switch condition right and emit a
6003   // check that the condition actually cleanly divided by GCD, i.e.
6004   //   C & (1 << Shift - 1) == 0
6005   // inserting a new CFG edge to handle the case where it didn't divide cleanly.
6006   //
6007   // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
6008   // shift and puts the shifted-off bits in the uppermost bits. If any of these
6009   // are nonzero then the switch condition will be very large and will hit the
6010   // default case.
6011 
6012   auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
6013   Builder.SetInsertPoint(SI);
6014   auto *ShiftC = ConstantInt::get(Ty, Shift);
6015   auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
6016   auto *LShr = Builder.CreateLShr(Sub, ShiftC);
6017   auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
6018   auto *Rot = Builder.CreateOr(LShr, Shl);
6019   SI->replaceUsesOfWith(SI->getCondition(), Rot);
6020 
6021   for (auto Case : SI->cases()) {
6022     auto *Orig = Case.getCaseValue();
6023     auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
6024     Case.setValue(
6025         cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
6026   }
6027   return true;
6028 }
6029 
6030 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
6031   BasicBlock *BB = SI->getParent();
6032 
6033   if (isValueEqualityComparison(SI)) {
6034     // If we only have one predecessor, and if it is a branch on this value,
6035     // see if that predecessor totally determines the outcome of this switch.
6036     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6037       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
6038         return requestResimplify();
6039 
6040     Value *Cond = SI->getCondition();
6041     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
6042       if (SimplifySwitchOnSelect(SI, Select))
6043         return requestResimplify();
6044 
6045     // If the block only contains the switch, see if we can fold the block
6046     // away into any preds.
6047     if (SI == &*BB->instructionsWithoutDebug().begin())
6048       if (FoldValueComparisonIntoPredecessors(SI, Builder))
6049         return requestResimplify();
6050   }
6051 
6052   // Try to transform the switch into an icmp and a branch.
6053   if (TurnSwitchRangeIntoICmp(SI, Builder))
6054     return requestResimplify();
6055 
6056   // Remove unreachable cases.
6057   if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
6058     return requestResimplify();
6059 
6060   if (switchToSelect(SI, Builder, DTU, DL, TTI))
6061     return requestResimplify();
6062 
6063   if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
6064     return requestResimplify();
6065 
6066   // The conversion from switch to lookup tables results in difficult-to-analyze
6067   // code and makes pruning branches much harder. This is a problem if the
6068   // switch expression itself can still be restricted as a result of inlining or
6069   // CVP. Therefore, only apply this transformation during late stages of the
6070   // optimisation pipeline.
6071   if (Options.ConvertSwitchToLookupTable &&
6072       SwitchToLookupTable(SI, Builder, DTU, DL, TTI))
6073     return requestResimplify();
6074 
6075   if (ReduceSwitchRange(SI, Builder, DL, TTI))
6076     return requestResimplify();
6077 
6078   return false;
6079 }
6080 
6081 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
6082   BasicBlock *BB = IBI->getParent();
6083   bool Changed = false;
6084 
6085   // Eliminate redundant destinations.
6086   SmallPtrSet<Value *, 8> Succs;
6087   SmallSetVector<BasicBlock *, 8> RemovedSuccs;
6088   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
6089     BasicBlock *Dest = IBI->getDestination(i);
6090     if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
6091       if (!Dest->hasAddressTaken())
6092         RemovedSuccs.insert(Dest);
6093       Dest->removePredecessor(BB);
6094       IBI->removeDestination(i);
6095       --i;
6096       --e;
6097       Changed = true;
6098     }
6099   }
6100 
6101   if (DTU) {
6102     std::vector<DominatorTree::UpdateType> Updates;
6103     Updates.reserve(RemovedSuccs.size());
6104     for (auto *RemovedSucc : RemovedSuccs)
6105       Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
6106     DTU->applyUpdates(Updates);
6107   }
6108 
6109   if (IBI->getNumDestinations() == 0) {
6110     // If the indirectbr has no successors, change it to unreachable.
6111     new UnreachableInst(IBI->getContext(), IBI);
6112     EraseTerminatorAndDCECond(IBI);
6113     return true;
6114   }
6115 
6116   if (IBI->getNumDestinations() == 1) {
6117     // If the indirectbr has one successor, change it to a direct branch.
6118     BranchInst::Create(IBI->getDestination(0), IBI);
6119     EraseTerminatorAndDCECond(IBI);
6120     return true;
6121   }
6122 
6123   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
6124     if (SimplifyIndirectBrOnSelect(IBI, SI))
6125       return requestResimplify();
6126   }
6127   return Changed;
6128 }
6129 
6130 /// Given an block with only a single landing pad and a unconditional branch
6131 /// try to find another basic block which this one can be merged with.  This
6132 /// handles cases where we have multiple invokes with unique landing pads, but
6133 /// a shared handler.
6134 ///
6135 /// We specifically choose to not worry about merging non-empty blocks
6136 /// here.  That is a PRE/scheduling problem and is best solved elsewhere.  In
6137 /// practice, the optimizer produces empty landing pad blocks quite frequently
6138 /// when dealing with exception dense code.  (see: instcombine, gvn, if-else
6139 /// sinking in this file)
6140 ///
6141 /// This is primarily a code size optimization.  We need to avoid performing
6142 /// any transform which might inhibit optimization (such as our ability to
6143 /// specialize a particular handler via tail commoning).  We do this by not
6144 /// merging any blocks which require us to introduce a phi.  Since the same
6145 /// values are flowing through both blocks, we don't lose any ability to
6146 /// specialize.  If anything, we make such specialization more likely.
6147 ///
6148 /// TODO - This transformation could remove entries from a phi in the target
6149 /// block when the inputs in the phi are the same for the two blocks being
6150 /// merged.  In some cases, this could result in removal of the PHI entirely.
6151 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
6152                                  BasicBlock *BB, DomTreeUpdater *DTU) {
6153   auto Succ = BB->getUniqueSuccessor();
6154   assert(Succ);
6155   // If there's a phi in the successor block, we'd likely have to introduce
6156   // a phi into the merged landing pad block.
6157   if (isa<PHINode>(*Succ->begin()))
6158     return false;
6159 
6160   for (BasicBlock *OtherPred : predecessors(Succ)) {
6161     if (BB == OtherPred)
6162       continue;
6163     BasicBlock::iterator I = OtherPred->begin();
6164     LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6165     if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6166       continue;
6167     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6168       ;
6169     BranchInst *BI2 = dyn_cast<BranchInst>(I);
6170     if (!BI2 || !BI2->isIdenticalTo(BI))
6171       continue;
6172 
6173     std::vector<DominatorTree::UpdateType> Updates;
6174 
6175     // We've found an identical block.  Update our predecessors to take that
6176     // path instead and make ourselves dead.
6177     SmallPtrSet<BasicBlock *, 16> Preds;
6178     Preds.insert(pred_begin(BB), pred_end(BB));
6179     for (BasicBlock *Pred : Preds) {
6180       InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6181       assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
6182              "unexpected successor");
6183       II->setUnwindDest(OtherPred);
6184       Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
6185       Updates.push_back({DominatorTree::Delete, Pred, BB});
6186     }
6187 
6188     // The debug info in OtherPred doesn't cover the merged control flow that
6189     // used to go through BB.  We need to delete it or update it.
6190     for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
6191       Instruction &Inst = *I;
6192       I++;
6193       if (isa<DbgInfoIntrinsic>(Inst))
6194         Inst.eraseFromParent();
6195     }
6196 
6197     SmallPtrSet<BasicBlock *, 16> Succs;
6198     Succs.insert(succ_begin(BB), succ_end(BB));
6199     for (BasicBlock *Succ : Succs) {
6200       Succ->removePredecessor(BB);
6201       Updates.push_back({DominatorTree::Delete, BB, Succ});
6202     }
6203 
6204     IRBuilder<> Builder(BI);
6205     Builder.CreateUnreachable();
6206     BI->eraseFromParent();
6207     if (DTU)
6208       DTU->applyUpdates(Updates);
6209     return true;
6210   }
6211   return false;
6212 }
6213 
6214 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6215   return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6216                                    : simplifyCondBranch(Branch, Builder);
6217 }
6218 
6219 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6220                                           IRBuilder<> &Builder) {
6221   BasicBlock *BB = BI->getParent();
6222   BasicBlock *Succ = BI->getSuccessor(0);
6223 
6224   // If the Terminator is the only non-phi instruction, simplify the block.
6225   // If LoopHeader is provided, check if the block or its successor is a loop
6226   // header. (This is for early invocations before loop simplify and
6227   // vectorization to keep canonical loop forms for nested loops. These blocks
6228   // can be eliminated when the pass is invoked later in the back-end.)
6229   // Note that if BB has only one predecessor then we do not introduce new
6230   // backedge, so we can eliminate BB.
6231   bool NeedCanonicalLoop =
6232       Options.NeedCanonicalLoop &&
6233       (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
6234        (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
6235   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator();
6236   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6237       !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
6238     return true;
6239 
6240   // If the only instruction in the block is a seteq/setne comparison against a
6241   // constant, try to simplify the block.
6242   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6243     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6244       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6245         ;
6246       if (I->isTerminator() &&
6247           tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6248         return true;
6249     }
6250 
6251   // See if we can merge an empty landing pad block with another which is
6252   // equivalent.
6253   if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6254     for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6255       ;
6256     if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU))
6257       return true;
6258   }
6259 
6260   // If this basic block is ONLY a compare and a branch, and if a predecessor
6261   // branches to us and our successor, fold the comparison into the
6262   // predecessor and use logical operations to update the incoming value
6263   // for PHI nodes in common successor.
6264   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6265                              Options.BonusInstThreshold))
6266     return requestResimplify();
6267   return false;
6268 }
6269 
6270 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6271   BasicBlock *PredPred = nullptr;
6272   for (auto *P : predecessors(BB)) {
6273     BasicBlock *PPred = P->getSinglePredecessor();
6274     if (!PPred || (PredPred && PredPred != PPred))
6275       return nullptr;
6276     PredPred = PPred;
6277   }
6278   return PredPred;
6279 }
6280 
6281 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6282   BasicBlock *BB = BI->getParent();
6283   if (!Options.SimplifyCondBranch)
6284     return false;
6285 
6286   // Conditional branch
6287   if (isValueEqualityComparison(BI)) {
6288     // If we only have one predecessor, and if it is a branch on this value,
6289     // see if that predecessor totally determines the outcome of this
6290     // switch.
6291     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6292       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6293         return requestResimplify();
6294 
6295     // This block must be empty, except for the setcond inst, if it exists.
6296     // Ignore dbg and pseudo intrinsics.
6297     auto I = BB->instructionsWithoutDebug(true).begin();
6298     if (&*I == BI) {
6299       if (FoldValueComparisonIntoPredecessors(BI, Builder))
6300         return requestResimplify();
6301     } else if (&*I == cast<Instruction>(BI->getCondition())) {
6302       ++I;
6303       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6304         return requestResimplify();
6305     }
6306   }
6307 
6308   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6309   if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6310     return true;
6311 
6312   // If this basic block has dominating predecessor blocks and the dominating
6313   // blocks' conditions imply BI's condition, we know the direction of BI.
6314   Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6315   if (Imp) {
6316     // Turn this into a branch on constant.
6317     auto *OldCond = BI->getCondition();
6318     ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6319                              : ConstantInt::getFalse(BB->getContext());
6320     BI->setCondition(TorF);
6321     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6322     return requestResimplify();
6323   }
6324 
6325   // If this basic block is ONLY a compare and a branch, and if a predecessor
6326   // branches to us and one of our successors, fold the comparison into the
6327   // predecessor and use logical operations to pick the right destination.
6328   if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6329                              Options.BonusInstThreshold))
6330     return requestResimplify();
6331 
6332   // We have a conditional branch to two blocks that are only reachable
6333   // from BI.  We know that the condbr dominates the two blocks, so see if
6334   // there is any identical code in the "then" and "else" blocks.  If so, we
6335   // can hoist it up to the branching block.
6336   if (BI->getSuccessor(0)->getSinglePredecessor()) {
6337     if (BI->getSuccessor(1)->getSinglePredecessor()) {
6338       if (HoistCommon && Options.HoistCommonInsts)
6339         if (HoistThenElseCodeToIf(BI, TTI))
6340           return requestResimplify();
6341     } else {
6342       // If Successor #1 has multiple preds, we may be able to conditionally
6343       // execute Successor #0 if it branches to Successor #1.
6344       Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6345       if (Succ0TI->getNumSuccessors() == 1 &&
6346           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6347         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6348           return requestResimplify();
6349     }
6350   } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6351     // If Successor #0 has multiple preds, we may be able to conditionally
6352     // execute Successor #1 if it branches to Successor #0.
6353     Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6354     if (Succ1TI->getNumSuccessors() == 1 &&
6355         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6356       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6357         return requestResimplify();
6358   }
6359 
6360   // If this is a branch on a phi node in the current block, thread control
6361   // through this block if any PHI node entries are constants.
6362   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6363     if (PN->getParent() == BI->getParent())
6364       if (FoldCondBranchOnPHI(BI, DTU, DL, Options.AC))
6365         return requestResimplify();
6366 
6367   // Scan predecessor blocks for conditional branches.
6368   for (BasicBlock *Pred : predecessors(BB))
6369     if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
6370       if (PBI != BI && PBI->isConditional())
6371         if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
6372           return requestResimplify();
6373 
6374   // Look for diamond patterns.
6375   if (MergeCondStores)
6376     if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6377       if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6378         if (PBI != BI && PBI->isConditional())
6379           if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
6380             return requestResimplify();
6381 
6382   return false;
6383 }
6384 
6385 /// Check if passing a value to an instruction will cause undefined behavior.
6386 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
6387   Constant *C = dyn_cast<Constant>(V);
6388   if (!C)
6389     return false;
6390 
6391   if (I->use_empty())
6392     return false;
6393 
6394   if (C->isNullValue() || isa<UndefValue>(C)) {
6395     // Only look at the first use, avoid hurting compile time with long uselists
6396     User *Use = *I->user_begin();
6397 
6398     // Now make sure that there are no instructions in between that can alter
6399     // control flow (eg. calls)
6400     for (BasicBlock::iterator
6401              i = ++BasicBlock::iterator(I),
6402              UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
6403          i != UI; ++i)
6404       if (i == I->getParent()->end() || i->mayHaveSideEffects())
6405         return false;
6406 
6407     // Look through GEPs. A load from a GEP derived from NULL is still undefined
6408     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6409       if (GEP->getPointerOperand() == I) {
6410         if (!GEP->isInBounds() || !GEP->hasAllZeroIndices())
6411           PtrValueMayBeModified = true;
6412         return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
6413       }
6414 
6415     // Look through bitcasts.
6416     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6417       return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified);
6418 
6419     // Load from null is undefined.
6420     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6421       if (!LI->isVolatile())
6422         return !NullPointerIsDefined(LI->getFunction(),
6423                                      LI->getPointerAddressSpace());
6424 
6425     // Store to null is undefined.
6426     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6427       if (!SI->isVolatile())
6428         return (!NullPointerIsDefined(SI->getFunction(),
6429                                       SI->getPointerAddressSpace())) &&
6430                SI->getPointerOperand() == I;
6431 
6432     if (auto *CB = dyn_cast<CallBase>(Use)) {
6433       if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
6434         return false;
6435       // A call to null is undefined.
6436       if (CB->getCalledOperand() == I)
6437         return true;
6438 
6439       if (C->isNullValue()) {
6440         for (const llvm::Use &Arg : CB->args())
6441           if (Arg == I) {
6442             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6443             if (CB->isPassingUndefUB(ArgIdx) &&
6444                 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) {
6445               // Passing null to a nonnnull+noundef argument is undefined.
6446               return !PtrValueMayBeModified;
6447             }
6448           }
6449       } else if (isa<UndefValue>(C)) {
6450         // Passing undef to a noundef argument is undefined.
6451         for (const llvm::Use &Arg : CB->args())
6452           if (Arg == I) {
6453             unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6454             if (CB->isPassingUndefUB(ArgIdx)) {
6455               // Passing undef to a noundef argument is undefined.
6456               return true;
6457             }
6458           }
6459       }
6460     }
6461   }
6462   return false;
6463 }
6464 
6465 /// If BB has an incoming value that will always trigger undefined behavior
6466 /// (eg. null pointer dereference), remove the branch leading here.
6467 static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
6468                                               DomTreeUpdater *DTU) {
6469   for (PHINode &PHI : BB->phis())
6470     for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6471       if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6472         BasicBlock *Predecessor = PHI.getIncomingBlock(i);
6473         Instruction *T = Predecessor->getTerminator();
6474         IRBuilder<> Builder(T);
6475         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6476           BB->removePredecessor(Predecessor);
6477           // Turn uncoditional branches into unreachables and remove the dead
6478           // destination from conditional branches.
6479           if (BI->isUnconditional())
6480             Builder.CreateUnreachable();
6481           else
6482             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
6483                                                        : BI->getSuccessor(0));
6484           BI->eraseFromParent();
6485           if (DTU)
6486             DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
6487           return true;
6488         }
6489         // TODO: SwitchInst.
6490       }
6491 
6492   return false;
6493 }
6494 
6495 bool SimplifyCFGOpt::simplifyOnceImpl(BasicBlock *BB) {
6496   bool Changed = false;
6497 
6498   assert(BB && BB->getParent() && "Block not embedded in function!");
6499   assert(BB->getTerminator() && "Degenerate basic block encountered!");
6500 
6501   // Remove basic blocks that have no predecessors (except the entry block)...
6502   // or that just have themself as a predecessor.  These are unreachable.
6503   if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
6504       BB->getSinglePredecessor() == BB) {
6505     LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
6506     DeleteDeadBlock(BB, DTU);
6507     return true;
6508   }
6509 
6510   // Check to see if we can constant propagate this terminator instruction
6511   // away...
6512   Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
6513                                     /*TLI=*/nullptr, DTU);
6514 
6515   // Check for and eliminate duplicate PHI nodes in this block.
6516   Changed |= EliminateDuplicatePHINodes(BB);
6517 
6518   // Check for and remove branches that will always cause undefined behavior.
6519   Changed |= removeUndefIntroducingPredecessor(BB, DTU);
6520 
6521   // Merge basic blocks into their predecessor if there is only one distinct
6522   // pred, and if there is only one distinct successor of the predecessor, and
6523   // if there are no PHI nodes.
6524   if (MergeBlockIntoPredecessor(BB, DTU))
6525     return true;
6526 
6527   if (SinkCommon && Options.SinkCommonInsts)
6528     Changed |= SinkCommonCodeFromPredecessors(BB, DTU);
6529 
6530   IRBuilder<> Builder(BB);
6531 
6532   if (Options.FoldTwoEntryPHINode) {
6533     // If there is a trivial two-entry PHI node in this basic block, and we can
6534     // eliminate it, do so now.
6535     if (auto *PN = dyn_cast<PHINode>(BB->begin()))
6536       if (PN->getNumIncomingValues() == 2)
6537         Changed |= FoldTwoEntryPHINode(PN, TTI, DTU, DL);
6538   }
6539 
6540   Instruction *Terminator = BB->getTerminator();
6541   Builder.SetInsertPoint(Terminator);
6542   switch (Terminator->getOpcode()) {
6543   case Instruction::Br:
6544     Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
6545     break;
6546   case Instruction::Ret:
6547     Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder);
6548     break;
6549   case Instruction::Resume:
6550     Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
6551     break;
6552   case Instruction::CleanupRet:
6553     Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
6554     break;
6555   case Instruction::Switch:
6556     Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
6557     break;
6558   case Instruction::Unreachable:
6559     Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
6560     break;
6561   case Instruction::IndirectBr:
6562     Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
6563     break;
6564   }
6565 
6566   return Changed;
6567 }
6568 
6569 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
6570   bool Changed = simplifyOnceImpl(BB);
6571 
6572   return Changed;
6573 }
6574 
6575 bool SimplifyCFGOpt::run(BasicBlock *BB) {
6576   bool Changed = false;
6577 
6578   // Repeated simplify BB as long as resimplification is requested.
6579   do {
6580     Resimplify = false;
6581 
6582     // Perform one round of simplifcation. Resimplify flag will be set if
6583     // another iteration is requested.
6584     Changed |= simplifyOnce(BB);
6585   } while (Resimplify);
6586 
6587   return Changed;
6588 }
6589 
6590 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6591                        DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
6592                        ArrayRef<WeakVH> LoopHeaders) {
6593   return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
6594                         Options)
6595       .run(BB);
6596 }
6597