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