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