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