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