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