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