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