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