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