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