[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / lib / Transforms / Utils / SimplifyCFG.cpp
blob21f8d54703de273666bd18063a2101f87482769b
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/ScopeExit.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/DomTreeUpdater.h"
31 #include "llvm/Analysis/GuardUtils.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/MemorySSA.h"
34 #include "llvm/Analysis/MemorySSAUpdater.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/ConstantRange.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/IRBuilder.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/MDBuilder.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/NoFolder.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/PatternMatch.h"
60 #include "llvm/IR/ProfDataUtils.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Use.h"
63 #include "llvm/IR/User.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/IR/ValueHandle.h"
66 #include "llvm/Support/BranchProbability.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include "llvm/Transforms/Utils/Local.h"
76 #include "llvm/Transforms/Utils/ValueMapper.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <climits>
80 #include <cstddef>
81 #include <cstdint>
82 #include <iterator>
83 #include <map>
84 #include <set>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
89 using namespace llvm;
90 using namespace PatternMatch;
92 #define DEBUG_TYPE "simplifycfg"
94 cl::opt<bool> llvm::RequireAndPreserveDomTree(
95 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
97 cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
98 "into preserving DomTree,"));
100 // Chosen as 2 so as to be cheap, but still to have enough power to fold
101 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
102 // To catch this, we need to fold a compare and a select, hence '2' being the
103 // minimum reasonable default.
104 static cl::opt<unsigned> PHINodeFoldingThreshold(
105 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
106 cl::desc(
107 "Control the amount of phi node folding to perform (default = 2)"));
109 static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
110 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
111 cl::desc("Control the maximal total instruction cost that we are willing "
112 "to speculatively execute to fold a 2-entry PHI node into a "
113 "select (default = 4)"));
115 static cl::opt<bool>
116 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
117 cl::desc("Hoist common instructions up to the parent block"));
119 static cl::opt<bool>
120 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
121 cl::desc("Sink common instructions down to the end block"));
123 static cl::opt<bool> HoistCondStores(
124 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
125 cl::desc("Hoist conditional stores if an unconditional store precedes"));
127 static cl::opt<bool> MergeCondStores(
128 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
129 cl::desc("Hoist conditional stores even if an unconditional store does not "
130 "precede - hoist multiple conditional stores into a single "
131 "predicated store"));
133 static cl::opt<bool> MergeCondStoresAggressively(
134 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
135 cl::desc("When merging conditional stores, do so even if the resultant "
136 "basic blocks are unlikely to be if-converted as a result"));
138 static cl::opt<bool> SpeculateOneExpensiveInst(
139 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
140 cl::desc("Allow exactly one expensive instruction to be speculatively "
141 "executed"));
143 static cl::opt<unsigned> MaxSpeculationDepth(
144 "max-speculation-depth", cl::Hidden, cl::init(10),
145 cl::desc("Limit maximum recursion depth when calculating costs of "
146 "speculatively executed instructions"));
148 static cl::opt<int>
149 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
150 cl::init(10),
151 cl::desc("Max size of a block which is still considered "
152 "small enough to thread through"));
154 // Two is chosen to allow one negation and a logical combine.
155 static cl::opt<unsigned>
156 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
157 cl::init(2),
158 cl::desc("Maximum cost of combining conditions when "
159 "folding branches"));
161 static cl::opt<unsigned> BranchFoldToCommonDestVectorMultiplier(
162 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
163 cl::init(2),
164 cl::desc("Multiplier to apply to threshold when determining whether or not "
165 "to fold branch to common destination when vector operations are "
166 "present"));
168 static cl::opt<bool> EnableMergeCompatibleInvokes(
169 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
170 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
172 static cl::opt<unsigned> MaxSwitchCasesPerResult(
173 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
174 cl::desc("Limit cases to analyze when converting a switch to select"));
176 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
177 STATISTIC(NumLinearMaps,
178 "Number of switch instructions turned into linear mapping");
179 STATISTIC(NumLookupTables,
180 "Number of switch instructions turned into lookup tables");
181 STATISTIC(
182 NumLookupTablesHoles,
183 "Number of switch instructions turned into lookup tables (holes checked)");
184 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
185 STATISTIC(NumFoldValueComparisonIntoPredecessors,
186 "Number of value comparisons folded into predecessor basic blocks");
187 STATISTIC(NumFoldBranchToCommonDest,
188 "Number of branches folded into predecessor basic block");
189 STATISTIC(
190 NumHoistCommonCode,
191 "Number of common instruction 'blocks' hoisted up to the begin block");
192 STATISTIC(NumHoistCommonInstrs,
193 "Number of common instructions hoisted up to the begin block");
194 STATISTIC(NumSinkCommonCode,
195 "Number of common instruction 'blocks' sunk down to the end block");
196 STATISTIC(NumSinkCommonInstrs,
197 "Number of common instructions sunk down to the end block");
198 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
199 STATISTIC(NumInvokes,
200 "Number of invokes with empty resume blocks simplified into calls");
201 STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
202 STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
204 namespace {
206 // The first field contains the value that the switch produces when a certain
207 // case group is selected, and the second field is a vector containing the
208 // cases composing the case group.
209 using SwitchCaseResultVectorTy =
210 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
212 // The first field contains the phi node that generates a result of the switch
213 // and the second field contains the value generated for a certain case in the
214 // switch for that PHI.
215 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
217 /// ValueEqualityComparisonCase - Represents a case of a switch.
218 struct ValueEqualityComparisonCase {
219 ConstantInt *Value;
220 BasicBlock *Dest;
222 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
223 : Value(Value), Dest(Dest) {}
225 bool operator<(ValueEqualityComparisonCase RHS) const {
226 // Comparing pointers is ok as we only rely on the order for uniquing.
227 return Value < RHS.Value;
230 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
233 class SimplifyCFGOpt {
234 const TargetTransformInfo &TTI;
235 DomTreeUpdater *DTU;
236 const DataLayout &DL;
237 ArrayRef<WeakVH> LoopHeaders;
238 const SimplifyCFGOptions &Options;
239 bool Resimplify;
241 Value *isValueEqualityComparison(Instruction *TI);
242 BasicBlock *GetValueEqualityComparisonCases(
243 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
244 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
245 BasicBlock *Pred,
246 IRBuilder<> &Builder);
247 bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
248 Instruction *PTI,
249 IRBuilder<> &Builder);
250 bool FoldValueComparisonIntoPredecessors(Instruction *TI,
251 IRBuilder<> &Builder);
253 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
254 bool simplifySingleResume(ResumeInst *RI);
255 bool simplifyCommonResume(ResumeInst *RI);
256 bool simplifyCleanupReturn(CleanupReturnInst *RI);
257 bool simplifyUnreachable(UnreachableInst *UI);
258 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
259 bool simplifyIndirectBr(IndirectBrInst *IBI);
260 bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
261 bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
262 bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
264 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
265 IRBuilder<> &Builder);
267 bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI,
268 bool EqTermsOnly);
269 bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
270 const TargetTransformInfo &TTI);
271 bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
272 BasicBlock *TrueBB, BasicBlock *FalseBB,
273 uint32_t TrueWeight, uint32_t FalseWeight);
274 bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
275 const DataLayout &DL);
276 bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
277 bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
278 bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
280 public:
281 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
282 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
283 const SimplifyCFGOptions &Opts)
284 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
285 assert((!DTU || !DTU->hasPostDomTree()) &&
286 "SimplifyCFG is not yet capable of maintaining validity of a "
287 "PostDomTree, so don't ask for it.");
290 bool simplifyOnce(BasicBlock *BB);
291 bool run(BasicBlock *BB);
293 // Helper to set Resimplify and return change indication.
294 bool requestResimplify() {
295 Resimplify = true;
296 return true;
300 } // end anonymous namespace
302 /// Return true if all the PHI nodes in the basic block \p BB
303 /// receive compatible (identical) incoming values when coming from
304 /// all of the predecessor blocks that are specified in \p IncomingBlocks.
306 /// Note that if the values aren't exactly identical, but \p EquivalenceSet
307 /// is provided, and *both* of the values are present in the set,
308 /// then they are considered equal.
309 static bool IncomingValuesAreCompatible(
310 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
311 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
312 assert(IncomingBlocks.size() == 2 &&
313 "Only for a pair of incoming blocks at the time!");
315 // FIXME: it is okay if one of the incoming values is an `undef` value,
316 // iff the other incoming value is guaranteed to be a non-poison value.
317 // FIXME: it is okay if one of the incoming values is a `poison` value.
318 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
319 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
320 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
321 if (IV0 == IV1)
322 return true;
323 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
324 EquivalenceSet->contains(IV1))
325 return true;
326 return false;
330 /// Return true if it is safe to merge these two
331 /// terminator instructions together.
332 static bool
333 SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
334 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
335 if (SI1 == SI2)
336 return false; // Can't merge with self!
338 // It is not safe to merge these two switch instructions if they have a common
339 // successor, and if that successor has a PHI node, and if *that* PHI node has
340 // conflicting incoming values from the two switch blocks.
341 BasicBlock *SI1BB = SI1->getParent();
342 BasicBlock *SI2BB = SI2->getParent();
344 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
345 bool Fail = false;
346 for (BasicBlock *Succ : successors(SI2BB)) {
347 if (!SI1Succs.count(Succ))
348 continue;
349 if (IncomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
350 continue;
351 Fail = true;
352 if (FailBlocks)
353 FailBlocks->insert(Succ);
354 else
355 break;
358 return !Fail;
361 /// Update PHI nodes in Succ to indicate that there will now be entries in it
362 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
363 /// will be the same as those coming in from ExistPred, an existing predecessor
364 /// of Succ.
365 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
366 BasicBlock *ExistPred,
367 MemorySSAUpdater *MSSAU = nullptr) {
368 for (PHINode &PN : Succ->phis())
369 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
370 if (MSSAU)
371 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
372 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
375 /// Compute an abstract "cost" of speculating the given instruction,
376 /// which is assumed to be safe to speculate. TCC_Free means cheap,
377 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
378 /// expensive.
379 static InstructionCost computeSpeculationCost(const User *I,
380 const TargetTransformInfo &TTI) {
381 assert((!isa<Instruction>(I) ||
382 isSafeToSpeculativelyExecute(cast<Instruction>(I))) &&
383 "Instruction is not safe to speculatively execute!");
384 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
387 /// If we have a merge point of an "if condition" as accepted above,
388 /// return true if the specified value dominates the block. We
389 /// don't handle the true generality of domination here, just a special case
390 /// which works well enough for us.
392 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
393 /// see if V (which must be an instruction) and its recursive operands
394 /// that do not dominate BB have a combined cost lower than Budget and
395 /// are non-trapping. If both are true, the instruction is inserted into the
396 /// set and true is returned.
398 /// The cost for most non-trapping instructions is defined as 1 except for
399 /// Select whose cost is 2.
401 /// After this function returns, Cost is increased by the cost of
402 /// V plus its non-dominating operands. If that cost is greater than
403 /// Budget, false is returned and Cost is undefined.
404 static bool dominatesMergePoint(Value *V, BasicBlock *BB,
405 SmallPtrSetImpl<Instruction *> &AggressiveInsts,
406 InstructionCost &Cost,
407 InstructionCost Budget,
408 const TargetTransformInfo &TTI,
409 unsigned Depth = 0) {
410 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
411 // so limit the recursion depth.
412 // TODO: While this recursion limit does prevent pathological behavior, it
413 // would be better to track visited instructions to avoid cycles.
414 if (Depth == MaxSpeculationDepth)
415 return false;
417 Instruction *I = dyn_cast<Instruction>(V);
418 if (!I) {
419 // Non-instructions dominate all instructions and can be executed
420 // unconditionally.
421 return true;
423 BasicBlock *PBB = I->getParent();
425 // We don't want to allow weird loops that might have the "if condition" in
426 // the bottom of this block.
427 if (PBB == BB)
428 return false;
430 // If this instruction is defined in a block that contains an unconditional
431 // branch to BB, then it must be in the 'conditional' part of the "if
432 // statement". If not, it definitely dominates the region.
433 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
434 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
435 return true;
437 // If we have seen this instruction before, don't count it again.
438 if (AggressiveInsts.count(I))
439 return true;
441 // Okay, it looks like the instruction IS in the "condition". Check to
442 // see if it's a cheap instruction to unconditionally compute, and if it
443 // only uses stuff defined outside of the condition. If so, hoist it out.
444 if (!isSafeToSpeculativelyExecute(I))
445 return false;
447 Cost += computeSpeculationCost(I, TTI);
449 // Allow exactly one instruction to be speculated regardless of its cost
450 // (as long as it is safe to do so).
451 // This is intended to flatten the CFG even if the instruction is a division
452 // or other expensive operation. The speculation of an expensive instruction
453 // is expected to be undone in CodeGenPrepare if the speculation has not
454 // enabled further IR optimizations.
455 if (Cost > Budget &&
456 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
457 !Cost.isValid()))
458 return false;
460 // Okay, we can only really hoist these out if their operands do
461 // not take us over the cost threshold.
462 for (Use &Op : I->operands())
463 if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
464 Depth + 1))
465 return false;
466 // Okay, it's safe to do this! Remember this instruction.
467 AggressiveInsts.insert(I);
468 return true;
471 /// Extract ConstantInt from value, looking through IntToPtr
472 /// and PointerNullValue. Return NULL if value is not a constant int.
473 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
474 // Normal constant int.
475 ConstantInt *CI = dyn_cast<ConstantInt>(V);
476 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy() ||
477 DL.isNonIntegralPointerType(V->getType()))
478 return CI;
480 // This is some kind of pointer constant. Turn it into a pointer-sized
481 // ConstantInt if possible.
482 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
484 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
485 if (isa<ConstantPointerNull>(V))
486 return ConstantInt::get(PtrTy, 0);
488 // IntToPtr const int.
489 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
490 if (CE->getOpcode() == Instruction::IntToPtr)
491 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
492 // The constant is very likely to have the right type already.
493 if (CI->getType() == PtrTy)
494 return CI;
495 else
496 return cast<ConstantInt>(
497 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
499 return nullptr;
502 namespace {
504 /// Given a chain of or (||) or and (&&) comparison of a value against a
505 /// constant, this will try to recover the information required for a switch
506 /// structure.
507 /// It will depth-first traverse the chain of comparison, seeking for patterns
508 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
509 /// representing the different cases for the switch.
510 /// Note that if the chain is composed of '||' it will build the set of elements
511 /// that matches the comparisons (i.e. any of this value validate the chain)
512 /// while for a chain of '&&' it will build the set elements that make the test
513 /// fail.
514 struct ConstantComparesGatherer {
515 const DataLayout &DL;
517 /// Value found for the switch comparison
518 Value *CompValue = nullptr;
520 /// Extra clause to be checked before the switch
521 Value *Extra = nullptr;
523 /// Set of integers to match in switch
524 SmallVector<ConstantInt *, 8> Vals;
526 /// Number of comparisons matched in the and/or chain
527 unsigned UsedICmps = 0;
529 /// Construct and compute the result for the comparison instruction Cond
530 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
531 gather(Cond);
534 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
535 ConstantComparesGatherer &
536 operator=(const ConstantComparesGatherer &) = delete;
538 private:
539 /// Try to set the current value used for the comparison, it succeeds only if
540 /// it wasn't set before or if the new value is the same as the old one
541 bool setValueOnce(Value *NewVal) {
542 if (CompValue && CompValue != NewVal)
543 return false;
544 CompValue = NewVal;
545 return (CompValue != nullptr);
548 /// Try to match Instruction "I" as a comparison against a constant and
549 /// populates the array Vals with the set of values that match (or do not
550 /// match depending on isEQ).
551 /// Return false on failure. On success, the Value the comparison matched
552 /// against is placed in CompValue.
553 /// If CompValue is already set, the function is expected to fail if a match
554 /// is found but the value compared to is different.
555 bool matchInstruction(Instruction *I, bool isEQ) {
556 // If this is an icmp against a constant, handle this as one of the cases.
557 ICmpInst *ICI;
558 ConstantInt *C;
559 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
560 (C = GetConstantInt(I->getOperand(1), DL)))) {
561 return false;
564 Value *RHSVal;
565 const APInt *RHSC;
567 // Pattern match a special case
568 // (x & ~2^z) == y --> x == y || x == y|2^z
569 // This undoes a transformation done by instcombine to fuse 2 compares.
570 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
571 // It's a little bit hard to see why the following transformations are
572 // correct. Here is a CVC3 program to verify them for 64-bit values:
575 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
576 x : BITVECTOR(64);
577 y : BITVECTOR(64);
578 z : BITVECTOR(64);
579 mask : BITVECTOR(64) = BVSHL(ONE, z);
580 QUERY( (y & ~mask = y) =>
581 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
583 QUERY( (y | mask = y) =>
584 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
588 // Please note that each pattern must be a dual implication (<--> or
589 // iff). One directional implication can create spurious matches. If the
590 // implication is only one-way, an unsatisfiable condition on the left
591 // side can imply a satisfiable condition on the right side. Dual
592 // implication ensures that satisfiable conditions are transformed to
593 // other satisfiable conditions and unsatisfiable conditions are
594 // transformed to other unsatisfiable conditions.
596 // Here is a concrete example of a unsatisfiable condition on the left
597 // implying a satisfiable condition on the right:
599 // mask = (1 << z)
600 // (x & ~mask) == y --> (x == y || x == (y | mask))
602 // Substituting y = 3, z = 0 yields:
603 // (x & -2) == 3 --> (x == 3 || x == 2)
605 // Pattern match a special case:
607 QUERY( (y & ~mask = y) =>
608 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
611 if (match(ICI->getOperand(0),
612 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
613 APInt Mask = ~*RHSC;
614 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
615 // If we already have a value for the switch, it has to match!
616 if (!setValueOnce(RHSVal))
617 return false;
619 Vals.push_back(C);
620 Vals.push_back(
621 ConstantInt::get(C->getContext(),
622 C->getValue() | Mask));
623 UsedICmps++;
624 return true;
628 // Pattern match a special case:
630 QUERY( (y | mask = y) =>
631 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
634 if (match(ICI->getOperand(0),
635 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
636 APInt Mask = *RHSC;
637 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
638 // If we already have a value for the switch, it has to match!
639 if (!setValueOnce(RHSVal))
640 return false;
642 Vals.push_back(C);
643 Vals.push_back(ConstantInt::get(C->getContext(),
644 C->getValue() & ~Mask));
645 UsedICmps++;
646 return true;
650 // If we already have a value for the switch, it has to match!
651 if (!setValueOnce(ICI->getOperand(0)))
652 return false;
654 UsedICmps++;
655 Vals.push_back(C);
656 return ICI->getOperand(0);
659 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
660 ConstantRange Span =
661 ConstantRange::makeExactICmpRegion(ICI->getPredicate(), C->getValue());
663 // Shift the range if the compare is fed by an add. This is the range
664 // compare idiom as emitted by instcombine.
665 Value *CandidateVal = I->getOperand(0);
666 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
667 Span = Span.subtract(*RHSC);
668 CandidateVal = RHSVal;
671 // If this is an and/!= check, then we are looking to build the set of
672 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
673 // x != 0 && x != 1.
674 if (!isEQ)
675 Span = Span.inverse();
677 // If there are a ton of values, we don't want to make a ginormous switch.
678 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
679 return false;
682 // If we already have a value for the switch, it has to match!
683 if (!setValueOnce(CandidateVal))
684 return false;
686 // Add all values from the range to the set
687 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
688 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
690 UsedICmps++;
691 return true;
694 /// Given a potentially 'or'd or 'and'd together collection of icmp
695 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
696 /// the value being compared, and stick the list constants into the Vals
697 /// vector.
698 /// One "Extra" case is allowed to differ from the other.
699 void gather(Value *V) {
700 bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
702 // Keep a stack (SmallVector for efficiency) for depth-first traversal
703 SmallVector<Value *, 8> DFT;
704 SmallPtrSet<Value *, 8> Visited;
706 // Initialize
707 Visited.insert(V);
708 DFT.push_back(V);
710 while (!DFT.empty()) {
711 V = DFT.pop_back_val();
713 if (Instruction *I = dyn_cast<Instruction>(V)) {
714 // If it is a || (or && depending on isEQ), process the operands.
715 Value *Op0, *Op1;
716 if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
717 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
718 if (Visited.insert(Op1).second)
719 DFT.push_back(Op1);
720 if (Visited.insert(Op0).second)
721 DFT.push_back(Op0);
723 continue;
726 // Try to match the current instruction
727 if (matchInstruction(I, isEQ))
728 // Match succeed, continue the loop
729 continue;
732 // One element of the sequence of || (or &&) could not be match as a
733 // comparison against the same value as the others.
734 // We allow only one "Extra" case to be checked before the switch
735 if (!Extra) {
736 Extra = V;
737 continue;
739 // Failed to parse a proper sequence, abort now
740 CompValue = nullptr;
741 break;
746 } // end anonymous namespace
748 static void EraseTerminatorAndDCECond(Instruction *TI,
749 MemorySSAUpdater *MSSAU = nullptr) {
750 Instruction *Cond = nullptr;
751 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
752 Cond = dyn_cast<Instruction>(SI->getCondition());
753 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
754 if (BI->isConditional())
755 Cond = dyn_cast<Instruction>(BI->getCondition());
756 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
757 Cond = dyn_cast<Instruction>(IBI->getAddress());
760 TI->eraseFromParent();
761 if (Cond)
762 RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
765 /// Return true if the specified terminator checks
766 /// to see if a value is equal to constant integer value.
767 Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
768 Value *CV = nullptr;
769 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
770 // Do not permit merging of large switch instructions into their
771 // predecessors unless there is only one predecessor.
772 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
773 CV = SI->getCondition();
774 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
775 if (BI->isConditional() && BI->getCondition()->hasOneUse())
776 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
777 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
778 CV = ICI->getOperand(0);
781 // Unwrap any lossless ptrtoint cast.
782 if (CV) {
783 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
784 Value *Ptr = PTII->getPointerOperand();
785 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
786 CV = Ptr;
789 return CV;
792 /// Given a value comparison instruction,
793 /// decode all of the 'cases' that it represents and return the 'default' block.
794 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
795 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
796 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
797 Cases.reserve(SI->getNumCases());
798 for (auto Case : SI->cases())
799 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
800 Case.getCaseSuccessor()));
801 return SI->getDefaultDest();
804 BranchInst *BI = cast<BranchInst>(TI);
805 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
806 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
807 Cases.push_back(ValueEqualityComparisonCase(
808 GetConstantInt(ICI->getOperand(1), DL), Succ));
809 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
812 /// Given a vector of bb/value pairs, remove any entries
813 /// in the list that match the specified block.
814 static void
815 EliminateBlockCases(BasicBlock *BB,
816 std::vector<ValueEqualityComparisonCase> &Cases) {
817 llvm::erase_value(Cases, BB);
820 /// Return true if there are any keys in C1 that exist in C2 as well.
821 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
822 std::vector<ValueEqualityComparisonCase> &C2) {
823 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
825 // Make V1 be smaller than V2.
826 if (V1->size() > V2->size())
827 std::swap(V1, V2);
829 if (V1->empty())
830 return false;
831 if (V1->size() == 1) {
832 // Just scan V2.
833 ConstantInt *TheVal = (*V1)[0].Value;
834 for (unsigned i = 0, e = V2->size(); i != e; ++i)
835 if (TheVal == (*V2)[i].Value)
836 return true;
839 // Otherwise, just sort both lists and compare element by element.
840 array_pod_sort(V1->begin(), V1->end());
841 array_pod_sort(V2->begin(), V2->end());
842 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
843 while (i1 != e1 && i2 != e2) {
844 if ((*V1)[i1].Value == (*V2)[i2].Value)
845 return true;
846 if ((*V1)[i1].Value < (*V2)[i2].Value)
847 ++i1;
848 else
849 ++i2;
851 return false;
854 // Set branch weights on SwitchInst. This sets the metadata if there is at
855 // least one non-zero weight.
856 static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
857 // Check that there is at least one non-zero weight. Otherwise, pass
858 // nullptr to setMetadata which will erase the existing metadata.
859 MDNode *N = nullptr;
860 if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
861 N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
862 SI->setMetadata(LLVMContext::MD_prof, N);
865 // Similar to the above, but for branch and select instructions that take
866 // exactly 2 weights.
867 static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
868 uint32_t FalseWeight) {
869 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
870 // Check that there is at least one non-zero weight. Otherwise, pass
871 // nullptr to setMetadata which will erase the existing metadata.
872 MDNode *N = nullptr;
873 if (TrueWeight || FalseWeight)
874 N = MDBuilder(I->getParent()->getContext())
875 .createBranchWeights(TrueWeight, FalseWeight);
876 I->setMetadata(LLVMContext::MD_prof, N);
879 /// If TI is known to be a terminator instruction and its block is known to
880 /// only have a single predecessor block, check to see if that predecessor is
881 /// also a value comparison with the same value, and if that comparison
882 /// determines the outcome of this comparison. If so, simplify TI. This does a
883 /// very limited form of jump threading.
884 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
885 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
886 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
887 if (!PredVal)
888 return false; // Not a value comparison in predecessor.
890 Value *ThisVal = isValueEqualityComparison(TI);
891 assert(ThisVal && "This isn't a value comparison!!");
892 if (ThisVal != PredVal)
893 return false; // Different predicates.
895 // TODO: Preserve branch weight metadata, similarly to how
896 // FoldValueComparisonIntoPredecessors preserves it.
898 // Find out information about when control will move from Pred to TI's block.
899 std::vector<ValueEqualityComparisonCase> PredCases;
900 BasicBlock *PredDef =
901 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
902 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
904 // Find information about how control leaves this block.
905 std::vector<ValueEqualityComparisonCase> ThisCases;
906 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
907 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
909 // If TI's block is the default block from Pred's comparison, potentially
910 // simplify TI based on this knowledge.
911 if (PredDef == TI->getParent()) {
912 // If we are here, we know that the value is none of those cases listed in
913 // PredCases. If there are any cases in ThisCases that are in PredCases, we
914 // can simplify TI.
915 if (!ValuesOverlap(PredCases, ThisCases))
916 return false;
918 if (isa<BranchInst>(TI)) {
919 // Okay, one of the successors of this condbr is dead. Convert it to a
920 // uncond br.
921 assert(ThisCases.size() == 1 && "Branch can only have one case!");
922 // Insert the new branch.
923 Instruction *NI = Builder.CreateBr(ThisDef);
924 (void)NI;
926 // Remove PHI node entries for the dead edge.
927 ThisCases[0].Dest->removePredecessor(PredDef);
929 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
930 << "Through successor TI: " << *TI << "Leaving: " << *NI
931 << "\n");
933 EraseTerminatorAndDCECond(TI);
935 if (DTU)
936 DTU->applyUpdates(
937 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
939 return true;
942 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
943 // Okay, TI has cases that are statically dead, prune them away.
944 SmallPtrSet<Constant *, 16> DeadCases;
945 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946 DeadCases.insert(PredCases[i].Value);
948 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
949 << "Through successor TI: " << *TI);
951 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
952 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
953 --i;
954 auto *Successor = i->getCaseSuccessor();
955 if (DTU)
956 ++NumPerSuccessorCases[Successor];
957 if (DeadCases.count(i->getCaseValue())) {
958 Successor->removePredecessor(PredDef);
959 SI.removeCase(i);
960 if (DTU)
961 --NumPerSuccessorCases[Successor];
965 if (DTU) {
966 std::vector<DominatorTree::UpdateType> Updates;
967 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
968 if (I.second == 0)
969 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
970 DTU->applyUpdates(Updates);
973 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
974 return true;
977 // Otherwise, TI's block must correspond to some matched value. Find out
978 // which value (or set of values) this is.
979 ConstantInt *TIV = nullptr;
980 BasicBlock *TIBB = TI->getParent();
981 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
982 if (PredCases[i].Dest == TIBB) {
983 if (TIV)
984 return false; // Cannot handle multiple values coming to this block.
985 TIV = PredCases[i].Value;
987 assert(TIV && "No edge from pred to succ?");
989 // Okay, we found the one constant that our value can be if we get into TI's
990 // BB. Find out which successor will unconditionally be branched to.
991 BasicBlock *TheRealDest = nullptr;
992 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
993 if (ThisCases[i].Value == TIV) {
994 TheRealDest = ThisCases[i].Dest;
995 break;
998 // If not handled by any explicit cases, it is handled by the default case.
999 if (!TheRealDest)
1000 TheRealDest = ThisDef;
1002 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1004 // Remove PHI node entries for dead edges.
1005 BasicBlock *CheckEdge = TheRealDest;
1006 for (BasicBlock *Succ : successors(TIBB))
1007 if (Succ != CheckEdge) {
1008 if (Succ != TheRealDest)
1009 RemovedSuccs.insert(Succ);
1010 Succ->removePredecessor(TIBB);
1011 } else
1012 CheckEdge = nullptr;
1014 // Insert the new branch.
1015 Instruction *NI = Builder.CreateBr(TheRealDest);
1016 (void)NI;
1018 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1019 << "Through successor TI: " << *TI << "Leaving: " << *NI
1020 << "\n");
1022 EraseTerminatorAndDCECond(TI);
1023 if (DTU) {
1024 SmallVector<DominatorTree::UpdateType, 2> Updates;
1025 Updates.reserve(RemovedSuccs.size());
1026 for (auto *RemovedSucc : RemovedSuccs)
1027 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1028 DTU->applyUpdates(Updates);
1030 return true;
1033 namespace {
1035 /// This class implements a stable ordering of constant
1036 /// integers that does not depend on their address. This is important for
1037 /// applications that sort ConstantInt's to ensure uniqueness.
1038 struct ConstantIntOrdering {
1039 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1040 return LHS->getValue().ult(RHS->getValue());
1044 } // end anonymous namespace
1046 static int ConstantIntSortPredicate(ConstantInt *const *P1,
1047 ConstantInt *const *P2) {
1048 const ConstantInt *LHS = *P1;
1049 const ConstantInt *RHS = *P2;
1050 if (LHS == RHS)
1051 return 0;
1052 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1055 /// Get Weights of a given terminator, the default weight is at the front
1056 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1057 /// metadata.
1058 static void GetBranchWeights(Instruction *TI,
1059 SmallVectorImpl<uint64_t> &Weights) {
1060 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1061 assert(MD);
1062 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
1063 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
1064 Weights.push_back(CI->getValue().getZExtValue());
1067 // If TI is a conditional eq, the default case is the false case,
1068 // and the corresponding branch-weight data is at index 2. We swap the
1069 // default weight to be the first entry.
1070 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1071 assert(Weights.size() == 2);
1072 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
1073 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1074 std::swap(Weights.front(), Weights.back());
1078 /// Keep halving the weights until all can fit in uint32_t.
1079 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
1080 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
1081 if (Max > UINT_MAX) {
1082 unsigned Offset = 32 - countLeadingZeros(Max);
1083 for (uint64_t &I : Weights)
1084 I >>= Offset;
1088 static void CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
1089 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1090 Instruction *PTI = PredBlock->getTerminator();
1092 // If we have bonus instructions, clone them into the predecessor block.
1093 // Note that there may be multiple predecessor blocks, so we cannot move
1094 // bonus instructions to a predecessor block.
1095 for (Instruction &BonusInst : *BB) {
1096 if (isa<DbgInfoIntrinsic>(BonusInst) || BonusInst.isTerminator())
1097 continue;
1099 Instruction *NewBonusInst = BonusInst.clone();
1101 if (PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1102 // Unless the instruction has the same !dbg location as the original
1103 // branch, drop it. When we fold the bonus instructions we want to make
1104 // sure we reset their debug locations in order to avoid stepping on
1105 // dead code caused by folding dead branches.
1106 NewBonusInst->setDebugLoc(DebugLoc());
1109 RemapInstruction(NewBonusInst, VMap,
1110 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1111 VMap[&BonusInst] = NewBonusInst;
1113 // If we moved a load, we cannot any longer claim any knowledge about
1114 // its potential value. The previous information might have been valid
1115 // only given the branch precondition.
1116 // For an analogous reason, we must also drop all the metadata whose
1117 // semantics we don't understand. We *can* preserve !annotation, because
1118 // it is tied to the instruction itself, not the value or position.
1119 // Similarly strip attributes on call parameters that may cause UB in
1120 // location the call is moved to.
1121 NewBonusInst->dropUndefImplyingAttrsAndUnknownMetadata(
1122 LLVMContext::MD_annotation);
1124 PredBlock->getInstList().insert(PTI->getIterator(), NewBonusInst);
1125 NewBonusInst->takeName(&BonusInst);
1126 BonusInst.setName(NewBonusInst->getName() + ".old");
1128 // Update (liveout) uses of bonus instructions,
1129 // now that the bonus instruction has been cloned into predecessor.
1130 // Note that we expect to be in a block-closed SSA form for this to work!
1131 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1132 auto *UI = cast<Instruction>(U.getUser());
1133 auto *PN = dyn_cast<PHINode>(UI);
1134 if (!PN) {
1135 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1136 "If the user is not a PHI node, then it should be in the same "
1137 "block as, and come after, the original bonus instruction.");
1138 continue; // Keep using the original bonus instruction.
1140 // Is this the block-closed SSA form PHI node?
1141 if (PN->getIncomingBlock(U) == BB)
1142 continue; // Great, keep using the original bonus instruction.
1143 // The only other alternative is an "use" when coming from
1144 // the predecessor block - here we should refer to the cloned bonus instr.
1145 assert(PN->getIncomingBlock(U) == PredBlock &&
1146 "Not in block-closed SSA form?");
1147 U.set(NewBonusInst);
1152 bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1153 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1154 BasicBlock *BB = TI->getParent();
1155 BasicBlock *Pred = PTI->getParent();
1157 SmallVector<DominatorTree::UpdateType, 32> Updates;
1159 // Figure out which 'cases' to copy from SI to PSI.
1160 std::vector<ValueEqualityComparisonCase> BBCases;
1161 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1163 std::vector<ValueEqualityComparisonCase> PredCases;
1164 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1166 // Based on whether the default edge from PTI goes to BB or not, fill in
1167 // PredCases and PredDefault with the new switch cases we would like to
1168 // build.
1169 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1171 // Update the branch weight metadata along the way
1172 SmallVector<uint64_t, 8> Weights;
1173 bool PredHasWeights = hasBranchWeightMD(*PTI);
1174 bool SuccHasWeights = hasBranchWeightMD(*TI);
1176 if (PredHasWeights) {
1177 GetBranchWeights(PTI, Weights);
1178 // branch-weight metadata is inconsistent here.
1179 if (Weights.size() != 1 + PredCases.size())
1180 PredHasWeights = SuccHasWeights = false;
1181 } else if (SuccHasWeights)
1182 // If there are no predecessor weights but there are successor weights,
1183 // populate Weights with 1, which will later be scaled to the sum of
1184 // successor's weights
1185 Weights.assign(1 + PredCases.size(), 1);
1187 SmallVector<uint64_t, 8> SuccWeights;
1188 if (SuccHasWeights) {
1189 GetBranchWeights(TI, SuccWeights);
1190 // branch-weight metadata is inconsistent here.
1191 if (SuccWeights.size() != 1 + BBCases.size())
1192 PredHasWeights = SuccHasWeights = false;
1193 } else if (PredHasWeights)
1194 SuccWeights.assign(1 + BBCases.size(), 1);
1196 if (PredDefault == BB) {
1197 // If this is the default destination from PTI, only the edges in TI
1198 // that don't occur in PTI, or that branch to BB will be activated.
1199 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1200 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1201 if (PredCases[i].Dest != BB)
1202 PTIHandled.insert(PredCases[i].Value);
1203 else {
1204 // The default destination is BB, we don't need explicit targets.
1205 std::swap(PredCases[i], PredCases.back());
1207 if (PredHasWeights || SuccHasWeights) {
1208 // Increase weight for the default case.
1209 Weights[0] += Weights[i + 1];
1210 std::swap(Weights[i + 1], Weights.back());
1211 Weights.pop_back();
1214 PredCases.pop_back();
1215 --i;
1216 --e;
1219 // Reconstruct the new switch statement we will be building.
1220 if (PredDefault != BBDefault) {
1221 PredDefault->removePredecessor(Pred);
1222 if (DTU && PredDefault != BB)
1223 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1224 PredDefault = BBDefault;
1225 ++NewSuccessors[BBDefault];
1228 unsigned CasesFromPred = Weights.size();
1229 uint64_t ValidTotalSuccWeight = 0;
1230 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1231 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1232 PredCases.push_back(BBCases[i]);
1233 ++NewSuccessors[BBCases[i].Dest];
1234 if (SuccHasWeights || PredHasWeights) {
1235 // The default weight is at index 0, so weight for the ith case
1236 // should be at index i+1. Scale the cases from successor by
1237 // PredDefaultWeight (Weights[0]).
1238 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1239 ValidTotalSuccWeight += SuccWeights[i + 1];
1243 if (SuccHasWeights || PredHasWeights) {
1244 ValidTotalSuccWeight += SuccWeights[0];
1245 // Scale the cases from predecessor by ValidTotalSuccWeight.
1246 for (unsigned i = 1; i < CasesFromPred; ++i)
1247 Weights[i] *= ValidTotalSuccWeight;
1248 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1249 Weights[0] *= SuccWeights[0];
1251 } else {
1252 // If this is not the default destination from PSI, only the edges
1253 // in SI that occur in PSI with a destination of BB will be
1254 // activated.
1255 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1256 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1257 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1258 if (PredCases[i].Dest == BB) {
1259 PTIHandled.insert(PredCases[i].Value);
1261 if (PredHasWeights || SuccHasWeights) {
1262 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1263 std::swap(Weights[i + 1], Weights.back());
1264 Weights.pop_back();
1267 std::swap(PredCases[i], PredCases.back());
1268 PredCases.pop_back();
1269 --i;
1270 --e;
1273 // Okay, now we know which constants were sent to BB from the
1274 // predecessor. Figure out where they will all go now.
1275 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1276 if (PTIHandled.count(BBCases[i].Value)) {
1277 // If this is one we are capable of getting...
1278 if (PredHasWeights || SuccHasWeights)
1279 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1280 PredCases.push_back(BBCases[i]);
1281 ++NewSuccessors[BBCases[i].Dest];
1282 PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1285 // If there are any constants vectored to BB that TI doesn't handle,
1286 // they must go to the default destination of TI.
1287 for (ConstantInt *I : PTIHandled) {
1288 if (PredHasWeights || SuccHasWeights)
1289 Weights.push_back(WeightsForHandled[I]);
1290 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1291 ++NewSuccessors[BBDefault];
1295 // Okay, at this point, we know which new successor Pred will get. Make
1296 // sure we update the number of entries in the PHI nodes for these
1297 // successors.
1298 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1299 if (DTU) {
1300 SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1301 Updates.reserve(Updates.size() + NewSuccessors.size());
1303 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1304 NewSuccessors) {
1305 for (auto I : seq(0, NewSuccessor.second)) {
1306 (void)I;
1307 AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1309 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1310 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1313 Builder.SetInsertPoint(PTI);
1314 // Convert pointer to int before we switch.
1315 if (CV->getType()->isPointerTy()) {
1316 CV =
1317 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1320 // Now that the successors are updated, create the new Switch instruction.
1321 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1322 NewSI->setDebugLoc(PTI->getDebugLoc());
1323 for (ValueEqualityComparisonCase &V : PredCases)
1324 NewSI->addCase(V.Value, V.Dest);
1326 if (PredHasWeights || SuccHasWeights) {
1327 // Halve the weights if any of them cannot fit in an uint32_t
1328 FitWeights(Weights);
1330 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1332 setBranchWeights(NewSI, MDWeights);
1335 EraseTerminatorAndDCECond(PTI);
1337 // Okay, last check. If BB is still a successor of PSI, then we must
1338 // have an infinite loop case. If so, add an infinitely looping block
1339 // to handle the case to preserve the behavior of the code.
1340 BasicBlock *InfLoopBlock = nullptr;
1341 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1342 if (NewSI->getSuccessor(i) == BB) {
1343 if (!InfLoopBlock) {
1344 // Insert it at the end of the function, because it's either code,
1345 // or it won't matter if it's hot. :)
1346 InfLoopBlock =
1347 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1348 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1349 if (DTU)
1350 Updates.push_back(
1351 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1353 NewSI->setSuccessor(i, InfLoopBlock);
1356 if (DTU) {
1357 if (InfLoopBlock)
1358 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1360 Updates.push_back({DominatorTree::Delete, Pred, BB});
1362 DTU->applyUpdates(Updates);
1365 ++NumFoldValueComparisonIntoPredecessors;
1366 return true;
1369 /// The specified terminator is a value equality comparison instruction
1370 /// (either a switch or a branch on "X == c").
1371 /// See if any of the predecessors of the terminator block are value comparisons
1372 /// on the same value. If so, and if safe to do so, fold them together.
1373 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1374 IRBuilder<> &Builder) {
1375 BasicBlock *BB = TI->getParent();
1376 Value *CV = isValueEqualityComparison(TI); // CondVal
1377 assert(CV && "Not a comparison?");
1379 bool Changed = false;
1381 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1382 while (!Preds.empty()) {
1383 BasicBlock *Pred = Preds.pop_back_val();
1384 Instruction *PTI = Pred->getTerminator();
1386 // Don't try to fold into itself.
1387 if (Pred == BB)
1388 continue;
1390 // See if the predecessor is a comparison with the same value.
1391 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1392 if (PCV != CV)
1393 continue;
1395 SmallSetVector<BasicBlock *, 4> FailBlocks;
1396 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1397 for (auto *Succ : FailBlocks) {
1398 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1399 return false;
1403 PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1404 Changed = true;
1406 return Changed;
1409 // If we would need to insert a select that uses the value of this invoke
1410 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1411 // can't hoist the invoke, as there is nowhere to put the select in this case.
1412 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1413 Instruction *I1, Instruction *I2) {
1414 for (BasicBlock *Succ : successors(BB1)) {
1415 for (const PHINode &PN : Succ->phis()) {
1416 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1417 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1418 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1419 return false;
1423 return true;
1426 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1428 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1429 /// in the two blocks up into the branch block. The caller of this function
1430 /// guarantees that BI's block dominates BB1 and BB2. If EqTermsOnly is given,
1431 /// only perform hoisting in case both blocks only contain a terminator. In that
1432 /// case, only the original BI will be replaced and selects for PHIs are added.
1433 bool SimplifyCFGOpt::HoistThenElseCodeToIf(BranchInst *BI,
1434 const TargetTransformInfo &TTI,
1435 bool EqTermsOnly) {
1436 // This does very trivial matching, with limited scanning, to find identical
1437 // instructions in the two blocks. In particular, we don't want to get into
1438 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1439 // such, we currently just scan for obviously identical instructions in an
1440 // identical order.
1441 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1442 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1444 // If either of the blocks has it's address taken, then we can't do this fold,
1445 // because the code we'd hoist would no longer run when we jump into the block
1446 // by it's address.
1447 if (BB1->hasAddressTaken() || BB2->hasAddressTaken())
1448 return false;
1450 BasicBlock::iterator BB1_Itr = BB1->begin();
1451 BasicBlock::iterator BB2_Itr = BB2->begin();
1453 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1454 // Skip debug info if it is not identical.
1455 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1456 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1457 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1458 while (isa<DbgInfoIntrinsic>(I1))
1459 I1 = &*BB1_Itr++;
1460 while (isa<DbgInfoIntrinsic>(I2))
1461 I2 = &*BB2_Itr++;
1463 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2))
1464 return false;
1466 BasicBlock *BIParent = BI->getParent();
1468 bool Changed = false;
1470 auto _ = make_scope_exit([&]() {
1471 if (Changed)
1472 ++NumHoistCommonCode;
1475 // Check if only hoisting terminators is allowed. This does not add new
1476 // instructions to the hoist location.
1477 if (EqTermsOnly) {
1478 // Skip any debug intrinsics, as they are free to hoist.
1479 auto *I1NonDbg = &*skipDebugIntrinsics(I1->getIterator());
1480 auto *I2NonDbg = &*skipDebugIntrinsics(I2->getIterator());
1481 if (!I1NonDbg->isIdenticalToWhenDefined(I2NonDbg))
1482 return false;
1483 if (!I1NonDbg->isTerminator())
1484 return false;
1485 // Now we know that we only need to hoist debug intrinsics and the
1486 // terminator. Let the loop below handle those 2 cases.
1489 do {
1490 // If we are hoisting the terminator instruction, don't move one (making a
1491 // broken BB), instead clone it, and remove BI.
1492 if (I1->isTerminator())
1493 goto HoistTerminator;
1495 // If we're going to hoist a call, make sure that the two instructions we're
1496 // commoning/hoisting are both marked with musttail, or neither of them is
1497 // marked as such. Otherwise, we might end up in a situation where we hoist
1498 // from a block where the terminator is a `ret` to a block where the terminator
1499 // is a `br`, and `musttail` calls expect to be followed by a return.
1500 auto *C1 = dyn_cast<CallInst>(I1);
1501 auto *C2 = dyn_cast<CallInst>(I2);
1502 if (C1 && C2)
1503 if (C1->isMustTailCall() != C2->isMustTailCall())
1504 return Changed;
1506 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1507 return Changed;
1509 // If any of the two call sites has nomerge attribute, stop hoisting.
1510 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1511 if (CB1->cannotMerge())
1512 return Changed;
1513 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1514 if (CB2->cannotMerge())
1515 return Changed;
1517 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1518 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1519 // The debug location is an integral part of a debug info intrinsic
1520 // and can't be separated from it or replaced. Instead of attempting
1521 // to merge locations, simply hoist both copies of the intrinsic.
1522 BIParent->getInstList().splice(BI->getIterator(),
1523 BB1->getInstList(), I1);
1524 BIParent->getInstList().splice(BI->getIterator(),
1525 BB2->getInstList(), I2);
1526 Changed = true;
1527 } else {
1528 // For a normal instruction, we just move one to right before the branch,
1529 // then replace all uses of the other with the first. Finally, we remove
1530 // the now redundant second instruction.
1531 BIParent->getInstList().splice(BI->getIterator(),
1532 BB1->getInstList(), I1);
1533 if (!I2->use_empty())
1534 I2->replaceAllUsesWith(I1);
1535 I1->andIRFlags(I2);
1536 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1537 LLVMContext::MD_range,
1538 LLVMContext::MD_fpmath,
1539 LLVMContext::MD_invariant_load,
1540 LLVMContext::MD_nonnull,
1541 LLVMContext::MD_invariant_group,
1542 LLVMContext::MD_align,
1543 LLVMContext::MD_dereferenceable,
1544 LLVMContext::MD_dereferenceable_or_null,
1545 LLVMContext::MD_mem_parallel_loop_access,
1546 LLVMContext::MD_access_group,
1547 LLVMContext::MD_preserve_access_index};
1548 combineMetadata(I1, I2, KnownIDs, true);
1550 // I1 and I2 are being combined into a single instruction. Its debug
1551 // location is the merged locations of the original instructions.
1552 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1554 I2->eraseFromParent();
1555 Changed = true;
1557 ++NumHoistCommonInstrs;
1559 I1 = &*BB1_Itr++;
1560 I2 = &*BB2_Itr++;
1561 // Skip debug info if it is not identical.
1562 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1563 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1564 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1565 while (isa<DbgInfoIntrinsic>(I1))
1566 I1 = &*BB1_Itr++;
1567 while (isa<DbgInfoIntrinsic>(I2))
1568 I2 = &*BB2_Itr++;
1570 } while (I1->isIdenticalToWhenDefined(I2));
1572 return true;
1574 HoistTerminator:
1575 // It may not be possible to hoist an invoke.
1576 // FIXME: Can we define a safety predicate for CallBr?
1577 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1578 return Changed;
1580 // TODO: callbr hoisting currently disabled pending further study.
1581 if (isa<CallBrInst>(I1))
1582 return Changed;
1584 for (BasicBlock *Succ : successors(BB1)) {
1585 for (PHINode &PN : Succ->phis()) {
1586 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1587 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1588 if (BB1V == BB2V)
1589 continue;
1591 // Check for passingValueIsAlwaysUndefined here because we would rather
1592 // eliminate undefined control flow then converting it to a select.
1593 if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1594 passingValueIsAlwaysUndefined(BB2V, &PN))
1595 return Changed;
1599 // Okay, it is safe to hoist the terminator.
1600 Instruction *NT = I1->clone();
1601 BIParent->getInstList().insert(BI->getIterator(), NT);
1602 if (!NT->getType()->isVoidTy()) {
1603 I1->replaceAllUsesWith(NT);
1604 I2->replaceAllUsesWith(NT);
1605 NT->takeName(I1);
1607 Changed = true;
1608 ++NumHoistCommonInstrs;
1610 // Ensure terminator gets a debug location, even an unknown one, in case
1611 // it involves inlinable calls.
1612 NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1614 // PHIs created below will adopt NT's merged DebugLoc.
1615 IRBuilder<NoFolder> Builder(NT);
1617 // Hoisting one of the terminators from our successor is a great thing.
1618 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1619 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1620 // nodes, so we insert select instruction to compute the final result.
1621 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1622 for (BasicBlock *Succ : successors(BB1)) {
1623 for (PHINode &PN : Succ->phis()) {
1624 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1625 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1626 if (BB1V == BB2V)
1627 continue;
1629 // These values do not agree. Insert a select instruction before NT
1630 // that determines the right value.
1631 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1632 if (!SI) {
1633 // Propagate fast-math-flags from phi node to its replacement select.
1634 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1635 if (isa<FPMathOperator>(PN))
1636 Builder.setFastMathFlags(PN.getFastMathFlags());
1638 SI = cast<SelectInst>(
1639 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1640 BB1V->getName() + "." + BB2V->getName(), BI));
1643 // Make the PHI node use the select for all incoming values for BB1/BB2
1644 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1645 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1646 PN.setIncomingValue(i, SI);
1650 SmallVector<DominatorTree::UpdateType, 4> Updates;
1652 // Update any PHI nodes in our new successors.
1653 for (BasicBlock *Succ : successors(BB1)) {
1654 AddPredecessorToBlock(Succ, BIParent, BB1);
1655 if (DTU)
1656 Updates.push_back({DominatorTree::Insert, BIParent, Succ});
1659 if (DTU)
1660 for (BasicBlock *Succ : successors(BI))
1661 Updates.push_back({DominatorTree::Delete, BIParent, Succ});
1663 EraseTerminatorAndDCECond(BI);
1664 if (DTU)
1665 DTU->applyUpdates(Updates);
1666 return Changed;
1669 // Check lifetime markers.
1670 static bool isLifeTimeMarker(const Instruction *I) {
1671 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1672 switch (II->getIntrinsicID()) {
1673 default:
1674 break;
1675 case Intrinsic::lifetime_start:
1676 case Intrinsic::lifetime_end:
1677 return true;
1680 return false;
1683 // TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1684 // into variables.
1685 static bool replacingOperandWithVariableIsCheap(const Instruction *I,
1686 int OpIdx) {
1687 return !isa<IntrinsicInst>(I);
1690 // All instructions in Insts belong to different blocks that all unconditionally
1691 // branch to a common successor. Analyze each instruction and return true if it
1692 // would be possible to sink them into their successor, creating one common
1693 // instruction instead. For every value that would be required to be provided by
1694 // PHI node (because an operand varies in each input block), add to PHIOperands.
1695 static bool canSinkInstructions(
1696 ArrayRef<Instruction *> Insts,
1697 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1698 // Prune out obviously bad instructions to move. Each instruction must have
1699 // exactly zero or one use, and we check later that use is by a single, common
1700 // PHI instruction in the successor.
1701 bool HasUse = !Insts.front()->user_empty();
1702 for (auto *I : Insts) {
1703 // These instructions may change or break semantics if moved.
1704 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1705 I->getType()->isTokenTy())
1706 return false;
1708 // Do not try to sink an instruction in an infinite loop - it can cause
1709 // this algorithm to infinite loop.
1710 if (I->getParent()->getSingleSuccessor() == I->getParent())
1711 return false;
1713 // Conservatively return false if I is an inline-asm instruction. Sinking
1714 // and merging inline-asm instructions can potentially create arguments
1715 // that cannot satisfy the inline-asm constraints.
1716 // If the instruction has nomerge attribute, return false.
1717 if (const auto *C = dyn_cast<CallBase>(I))
1718 if (C->isInlineAsm() || C->cannotMerge())
1719 return false;
1721 // Each instruction must have zero or one use.
1722 if (HasUse && !I->hasOneUse())
1723 return false;
1724 if (!HasUse && !I->user_empty())
1725 return false;
1728 const Instruction *I0 = Insts.front();
1729 for (auto *I : Insts)
1730 if (!I->isSameOperationAs(I0))
1731 return false;
1733 // All instructions in Insts are known to be the same opcode. If they have a
1734 // use, check that the only user is a PHI or in the same block as the
1735 // instruction, because if a user is in the same block as an instruction we're
1736 // contemplating sinking, it must already be determined to be sinkable.
1737 if (HasUse) {
1738 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1739 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1740 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1741 auto *U = cast<Instruction>(*I->user_begin());
1742 return (PNUse &&
1743 PNUse->getParent() == Succ &&
1744 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1745 U->getParent() == I->getParent();
1747 return false;
1750 // Because SROA can't handle speculating stores of selects, try not to sink
1751 // loads, stores or lifetime markers of allocas when we'd have to create a
1752 // PHI for the address operand. Also, because it is likely that loads or
1753 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1754 // them.
1755 // This can cause code churn which can have unintended consequences down
1756 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1757 // FIXME: This is a workaround for a deficiency in SROA - see
1758 // https://llvm.org/bugs/show_bug.cgi?id=30188
1759 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1760 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1762 return false;
1763 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1764 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1766 return false;
1767 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1768 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1770 return false;
1772 // For calls to be sinkable, they must all be indirect, or have same callee.
1773 // I.e. if we have two direct calls to different callees, we don't want to
1774 // turn that into an indirect call. Likewise, if we have an indirect call,
1775 // and a direct call, we don't actually want to have a single indirect call.
1776 if (isa<CallBase>(I0)) {
1777 auto IsIndirectCall = [](const Instruction *I) {
1778 return cast<CallBase>(I)->isIndirectCall();
1780 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1781 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1782 if (HaveIndirectCalls) {
1783 if (!AllCallsAreIndirect)
1784 return false;
1785 } else {
1786 // All callees must be identical.
1787 Value *Callee = nullptr;
1788 for (const Instruction *I : Insts) {
1789 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1790 if (!Callee)
1791 Callee = CurrCallee;
1792 else if (Callee != CurrCallee)
1793 return false;
1798 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1799 Value *Op = I0->getOperand(OI);
1800 if (Op->getType()->isTokenTy())
1801 // Don't touch any operand of token type.
1802 return false;
1804 auto SameAsI0 = [&I0, OI](const Instruction *I) {
1805 assert(I->getNumOperands() == I0->getNumOperands());
1806 return I->getOperand(OI) == I0->getOperand(OI);
1808 if (!all_of(Insts, SameAsI0)) {
1809 if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1810 !canReplaceOperandWithVariable(I0, OI))
1811 // We can't create a PHI from this GEP.
1812 return false;
1813 for (auto *I : Insts)
1814 PHIOperands[I].push_back(I->getOperand(OI));
1817 return true;
1820 // Assuming canSinkInstructions(Blocks) has returned true, sink the last
1821 // instruction of every block in Blocks to their common successor, commoning
1822 // into one instruction.
1823 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
1824 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1826 // canSinkInstructions returning true guarantees that every block has at
1827 // least one non-terminator instruction.
1828 SmallVector<Instruction*,4> Insts;
1829 for (auto *BB : Blocks) {
1830 Instruction *I = BB->getTerminator();
1831 do {
1832 I = I->getPrevNode();
1833 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1834 if (!isa<DbgInfoIntrinsic>(I))
1835 Insts.push_back(I);
1838 // The only checking we need to do now is that all users of all instructions
1839 // are the same PHI node. canSinkInstructions should have checked this but
1840 // it is slightly over-aggressive - it gets confused by commutative
1841 // instructions so double-check it here.
1842 Instruction *I0 = Insts.front();
1843 if (!I0->user_empty()) {
1844 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1845 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1846 auto *U = cast<Instruction>(*I->user_begin());
1847 return U == PNUse;
1849 return false;
1852 // We don't need to do any more checking here; canSinkInstructions should
1853 // have done it all for us.
1854 SmallVector<Value*, 4> NewOperands;
1855 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1856 // This check is different to that in canSinkInstructions. There, we
1857 // cared about the global view once simplifycfg (and instcombine) have
1858 // completed - it takes into account PHIs that become trivially
1859 // simplifiable. However here we need a more local view; if an operand
1860 // differs we create a PHI and rely on instcombine to clean up the very
1861 // small mess we may make.
1862 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1863 return I->getOperand(O) != I0->getOperand(O);
1865 if (!NeedPHI) {
1866 NewOperands.push_back(I0->getOperand(O));
1867 continue;
1870 // Create a new PHI in the successor block and populate it.
1871 auto *Op = I0->getOperand(O);
1872 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1873 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1874 Op->getName() + ".sink", &BBEnd->front());
1875 for (auto *I : Insts)
1876 PN->addIncoming(I->getOperand(O), I->getParent());
1877 NewOperands.push_back(PN);
1880 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1881 // and move it to the start of the successor block.
1882 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1883 I0->getOperandUse(O).set(NewOperands[O]);
1884 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1886 // Update metadata and IR flags, and merge debug locations.
1887 for (auto *I : Insts)
1888 if (I != I0) {
1889 // The debug location for the "common" instruction is the merged locations
1890 // of all the commoned instructions. We start with the original location
1891 // of the "common" instruction and iteratively merge each location in the
1892 // loop below.
1893 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1894 // However, as N-way merge for CallInst is rare, so we use simplified API
1895 // instead of using complex API for N-way merge.
1896 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1897 combineMetadataForCSE(I0, I, true);
1898 I0->andIRFlags(I);
1901 if (!I0->user_empty()) {
1902 // canSinkLastInstruction checked that all instructions were used by
1903 // one and only one PHI node. Find that now, RAUW it to our common
1904 // instruction and nuke it.
1905 auto *PN = cast<PHINode>(*I0->user_begin());
1906 PN->replaceAllUsesWith(I0);
1907 PN->eraseFromParent();
1910 // Finally nuke all instructions apart from the common instruction.
1911 for (auto *I : Insts)
1912 if (I != I0)
1913 I->eraseFromParent();
1915 return true;
1918 namespace {
1920 // LockstepReverseIterator - Iterates through instructions
1921 // in a set of blocks in reverse order from the first non-terminator.
1922 // For example (assume all blocks have size n):
1923 // LockstepReverseIterator I([B1, B2, B3]);
1924 // *I-- = [B1[n], B2[n], B3[n]];
1925 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1926 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1927 // ...
1928 class LockstepReverseIterator {
1929 ArrayRef<BasicBlock*> Blocks;
1930 SmallVector<Instruction*,4> Insts;
1931 bool Fail;
1933 public:
1934 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
1935 reset();
1938 void reset() {
1939 Fail = false;
1940 Insts.clear();
1941 for (auto *BB : Blocks) {
1942 Instruction *Inst = BB->getTerminator();
1943 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1944 Inst = Inst->getPrevNode();
1945 if (!Inst) {
1946 // Block wasn't big enough.
1947 Fail = true;
1948 return;
1950 Insts.push_back(Inst);
1954 bool isValid() const {
1955 return !Fail;
1958 void operator--() {
1959 if (Fail)
1960 return;
1961 for (auto *&Inst : Insts) {
1962 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1963 Inst = Inst->getPrevNode();
1964 // Already at beginning of block.
1965 if (!Inst) {
1966 Fail = true;
1967 return;
1972 void operator++() {
1973 if (Fail)
1974 return;
1975 for (auto *&Inst : Insts) {
1976 for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1977 Inst = Inst->getNextNode();
1978 // Already at end of block.
1979 if (!Inst) {
1980 Fail = true;
1981 return;
1986 ArrayRef<Instruction*> operator * () const {
1987 return Insts;
1991 } // end anonymous namespace
1993 /// Check whether BB's predecessors end with unconditional branches. If it is
1994 /// true, sink any common code from the predecessors to BB.
1995 static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
1996 DomTreeUpdater *DTU) {
1997 // We support two situations:
1998 // (1) all incoming arcs are unconditional
1999 // (2) there are non-unconditional incoming arcs
2001 // (2) is very common in switch defaults and
2002 // else-if patterns;
2004 // if (a) f(1);
2005 // else if (b) f(2);
2007 // produces:
2009 // [if]
2010 // / \
2011 // [f(1)] [if]
2012 // | | \
2013 // | | |
2014 // | [f(2)]|
2015 // \ | /
2016 // [ end ]
2018 // [end] has two unconditional predecessor arcs and one conditional. The
2019 // conditional refers to the implicit empty 'else' arc. This conditional
2020 // arc can also be caused by an empty default block in a switch.
2022 // In this case, we attempt to sink code from all *unconditional* arcs.
2023 // If we can sink instructions from these arcs (determined during the scan
2024 // phase below) we insert a common successor for all unconditional arcs and
2025 // connect that to [end], to enable sinking:
2027 // [if]
2028 // / \
2029 // [x(1)] [if]
2030 // | | \
2031 // | | \
2032 // | [x(2)] |
2033 // \ / |
2034 // [sink.split] |
2035 // \ /
2036 // [ end ]
2038 SmallVector<BasicBlock*,4> UnconditionalPreds;
2039 bool HaveNonUnconditionalPredecessors = false;
2040 for (auto *PredBB : predecessors(BB)) {
2041 auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2042 if (PredBr && PredBr->isUnconditional())
2043 UnconditionalPreds.push_back(PredBB);
2044 else
2045 HaveNonUnconditionalPredecessors = true;
2047 if (UnconditionalPreds.size() < 2)
2048 return false;
2050 // We take a two-step approach to tail sinking. First we scan from the end of
2051 // each block upwards in lockstep. If the n'th instruction from the end of each
2052 // block can be sunk, those instructions are added to ValuesToSink and we
2053 // carry on. If we can sink an instruction but need to PHI-merge some operands
2054 // (because they're not identical in each instruction) we add these to
2055 // PHIOperands.
2056 int ScanIdx = 0;
2057 SmallPtrSet<Value*,4> InstructionsToSink;
2058 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
2059 LockstepReverseIterator LRI(UnconditionalPreds);
2060 while (LRI.isValid() &&
2061 canSinkInstructions(*LRI, PHIOperands)) {
2062 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2063 << "\n");
2064 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2065 ++ScanIdx;
2066 --LRI;
2069 // If no instructions can be sunk, early-return.
2070 if (ScanIdx == 0)
2071 return false;
2073 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2075 if (!followedByDeoptOrUnreachable) {
2076 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2077 // actually sink before encountering instruction that is unprofitable to
2078 // sink?
2079 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2080 unsigned NumPHIdValues = 0;
2081 for (auto *I : *LRI)
2082 for (auto *V : PHIOperands[I]) {
2083 if (!InstructionsToSink.contains(V))
2084 ++NumPHIdValues;
2085 // FIXME: this check is overly optimistic. We may end up not sinking
2086 // said instruction, due to the very same profitability check.
2087 // See @creating_too_many_phis in sink-common-code.ll.
2089 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2090 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2091 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2092 NumPHIInsts++;
2094 return NumPHIInsts <= 1;
2097 // We've determined that we are going to sink last ScanIdx instructions,
2098 // and recorded them in InstructionsToSink. Now, some instructions may be
2099 // unprofitable to sink. But that determination depends on the instructions
2100 // that we are going to sink.
2102 // First, forward scan: find the first instruction unprofitable to sink,
2103 // recording all the ones that are profitable to sink.
2104 // FIXME: would it be better, after we detect that not all are profitable.
2105 // to either record the profitable ones, or erase the unprofitable ones?
2106 // Maybe we need to choose (at runtime) the one that will touch least
2107 // instrs?
2108 LRI.reset();
2109 int Idx = 0;
2110 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2111 while (Idx < ScanIdx) {
2112 if (!ProfitableToSinkInstruction(LRI)) {
2113 // Too many PHIs would be created.
2114 LLVM_DEBUG(
2115 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2116 break;
2118 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2119 --LRI;
2120 ++Idx;
2123 // If no instructions can be sunk, early-return.
2124 if (Idx == 0)
2125 return false;
2127 // Did we determine that (only) some instructions are unprofitable to sink?
2128 if (Idx < ScanIdx) {
2129 // Okay, some instructions are unprofitable.
2130 ScanIdx = Idx;
2131 InstructionsToSink = InstructionsProfitableToSink;
2133 // But, that may make other instructions unprofitable, too.
2134 // So, do a backward scan, do any earlier instructions become
2135 // unprofitable?
2136 assert(
2137 !ProfitableToSinkInstruction(LRI) &&
2138 "We already know that the last instruction is unprofitable to sink");
2139 ++LRI;
2140 --Idx;
2141 while (Idx >= 0) {
2142 // If we detect that an instruction becomes unprofitable to sink,
2143 // all earlier instructions won't be sunk either,
2144 // so preemptively keep InstructionsProfitableToSink in sync.
2145 // FIXME: is this the most performant approach?
2146 for (auto *I : *LRI)
2147 InstructionsProfitableToSink.erase(I);
2148 if (!ProfitableToSinkInstruction(LRI)) {
2149 // Everything starting with this instruction won't be sunk.
2150 ScanIdx = Idx;
2151 InstructionsToSink = InstructionsProfitableToSink;
2153 ++LRI;
2154 --Idx;
2158 // If no instructions can be sunk, early-return.
2159 if (ScanIdx == 0)
2160 return false;
2163 bool Changed = false;
2165 if (HaveNonUnconditionalPredecessors) {
2166 if (!followedByDeoptOrUnreachable) {
2167 // It is always legal to sink common instructions from unconditional
2168 // predecessors. However, if not all predecessors are unconditional,
2169 // this transformation might be pessimizing. So as a rule of thumb,
2170 // don't do it unless we'd sink at least one non-speculatable instruction.
2171 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2172 LRI.reset();
2173 int Idx = 0;
2174 bool Profitable = false;
2175 while (Idx < ScanIdx) {
2176 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2177 Profitable = true;
2178 break;
2180 --LRI;
2181 ++Idx;
2183 if (!Profitable)
2184 return false;
2187 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2188 // We have a conditional edge and we're going to sink some instructions.
2189 // Insert a new block postdominating all blocks we're going to sink from.
2190 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2191 // Edges couldn't be split.
2192 return false;
2193 Changed = true;
2196 // Now that we've analyzed all potential sinking candidates, perform the
2197 // actual sink. We iteratively sink the last non-terminator of the source
2198 // blocks into their common successor unless doing so would require too
2199 // many PHI instructions to be generated (currently only one PHI is allowed
2200 // per sunk instruction).
2202 // We can use InstructionsToSink to discount values needing PHI-merging that will
2203 // actually be sunk in a later iteration. This allows us to be more
2204 // aggressive in what we sink. This does allow a false positive where we
2205 // sink presuming a later value will also be sunk, but stop half way through
2206 // and never actually sink it which means we produce more PHIs than intended.
2207 // This is unlikely in practice though.
2208 int SinkIdx = 0;
2209 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2210 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2211 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2212 << "\n");
2214 // Because we've sunk every instruction in turn, the current instruction to
2215 // sink is always at index 0.
2216 LRI.reset();
2218 if (!sinkLastInstruction(UnconditionalPreds)) {
2219 LLVM_DEBUG(
2220 dbgs()
2221 << "SINK: stopping here, failed to actually sink instruction!\n");
2222 break;
2225 NumSinkCommonInstrs++;
2226 Changed = true;
2228 if (SinkIdx != 0)
2229 ++NumSinkCommonCode;
2230 return Changed;
2233 namespace {
2235 struct CompatibleSets {
2236 using SetTy = SmallVector<InvokeInst *, 2>;
2238 SmallVector<SetTy, 1> Sets;
2240 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2242 SetTy &getCompatibleSet(InvokeInst *II);
2244 void insert(InvokeInst *II);
2247 CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2248 // Perform a linear scan over all the existing sets, see if the new `invoke`
2249 // is compatible with any particular set. Since we know that all the `invokes`
2250 // within a set are compatible, only check the first `invoke` in each set.
2251 // WARNING: at worst, this has quadratic complexity.
2252 for (CompatibleSets::SetTy &Set : Sets) {
2253 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2254 return Set;
2257 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2258 return Sets.emplace_back();
2261 void CompatibleSets::insert(InvokeInst *II) {
2262 getCompatibleSet(II).emplace_back(II);
2265 bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2266 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2268 // Can we theoretically merge these `invoke`s?
2269 auto IsIllegalToMerge = [](InvokeInst *II) {
2270 return II->cannotMerge() || II->isInlineAsm();
2272 if (any_of(Invokes, IsIllegalToMerge))
2273 return false;
2275 // Either both `invoke`s must be direct,
2276 // or both `invoke`s must be indirect.
2277 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2278 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2279 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2280 if (HaveIndirectCalls) {
2281 if (!AllCallsAreIndirect)
2282 return false;
2283 } else {
2284 // All callees must be identical.
2285 Value *Callee = nullptr;
2286 for (InvokeInst *II : Invokes) {
2287 Value *CurrCallee = II->getCalledOperand();
2288 assert(CurrCallee && "There is always a called operand.");
2289 if (!Callee)
2290 Callee = CurrCallee;
2291 else if (Callee != CurrCallee)
2292 return false;
2296 // Either both `invoke`s must not have a normal destination,
2297 // or both `invoke`s must have a normal destination,
2298 auto HasNormalDest = [](InvokeInst *II) {
2299 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2301 if (any_of(Invokes, HasNormalDest)) {
2302 // Do not merge `invoke` that does not have a normal destination with one
2303 // that does have a normal destination, even though doing so would be legal.
2304 if (!all_of(Invokes, HasNormalDest))
2305 return false;
2307 // All normal destinations must be identical.
2308 BasicBlock *NormalBB = nullptr;
2309 for (InvokeInst *II : Invokes) {
2310 BasicBlock *CurrNormalBB = II->getNormalDest();
2311 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2312 if (!NormalBB)
2313 NormalBB = CurrNormalBB;
2314 else if (NormalBB != CurrNormalBB)
2315 return false;
2318 // In the normal destination, the incoming values for these two `invoke`s
2319 // must be compatible.
2320 SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2321 if (!IncomingValuesAreCompatible(
2322 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2323 &EquivalenceSet))
2324 return false;
2327 #ifndef NDEBUG
2328 // All unwind destinations must be identical.
2329 // We know that because we have started from said unwind destination.
2330 BasicBlock *UnwindBB = nullptr;
2331 for (InvokeInst *II : Invokes) {
2332 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2333 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2334 if (!UnwindBB)
2335 UnwindBB = CurrUnwindBB;
2336 else
2337 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2339 #endif
2341 // In the unwind destination, the incoming values for these two `invoke`s
2342 // must be compatible.
2343 if (!IncomingValuesAreCompatible(
2344 Invokes.front()->getUnwindDest(),
2345 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2346 return false;
2348 // Ignoring arguments, these `invoke`s must be identical,
2349 // including operand bundles.
2350 const InvokeInst *II0 = Invokes.front();
2351 for (auto *II : Invokes.drop_front())
2352 if (!II->isSameOperationAs(II0))
2353 return false;
2355 // Can we theoretically form the data operands for the merged `invoke`?
2356 auto IsIllegalToMergeArguments = [](auto Ops) {
2357 Type *Ty = std::get<0>(Ops)->getType();
2358 assert(Ty == std::get<1>(Ops)->getType() && "Incompatible types?");
2359 return Ty->isTokenTy() && std::get<0>(Ops) != std::get<1>(Ops);
2361 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2362 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2363 IsIllegalToMergeArguments))
2364 return false;
2366 return true;
2369 } // namespace
2371 // Merge all invokes in the provided set, all of which are compatible
2372 // as per the `CompatibleSets::shouldBelongToSameSet()`.
2373 static void MergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes,
2374 DomTreeUpdater *DTU) {
2375 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2377 SmallVector<DominatorTree::UpdateType, 8> Updates;
2378 if (DTU)
2379 Updates.reserve(2 + 3 * Invokes.size());
2381 bool HasNormalDest =
2382 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2384 // Clone one of the invokes into a new basic block.
2385 // Since they are all compatible, it doesn't matter which invoke is cloned.
2386 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2387 InvokeInst *II0 = Invokes.front();
2388 BasicBlock *II0BB = II0->getParent();
2389 BasicBlock *InsertBeforeBlock =
2390 II0->getParent()->getIterator()->getNextNode();
2391 Function *Func = II0BB->getParent();
2392 LLVMContext &Ctx = II0->getContext();
2394 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2395 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2397 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2398 // NOTE: all invokes have the same attributes, so no handling needed.
2399 MergedInvokeBB->getInstList().push_back(MergedInvoke);
2401 if (!HasNormalDest) {
2402 // This set does not have a normal destination,
2403 // so just form a new block with unreachable terminator.
2404 BasicBlock *MergedNormalDest = BasicBlock::Create(
2405 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2406 new UnreachableInst(Ctx, MergedNormalDest);
2407 MergedInvoke->setNormalDest(MergedNormalDest);
2410 // The unwind destination, however, remainds identical for all invokes here.
2412 return MergedInvoke;
2413 }();
2415 if (DTU) {
2416 // Predecessor blocks that contained these invokes will now branch to
2417 // the new block that contains the merged invoke, ...
2418 for (InvokeInst *II : Invokes)
2419 Updates.push_back(
2420 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2422 // ... which has the new `unreachable` block as normal destination,
2423 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2424 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2425 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2426 SuccBBOfMergedInvoke});
2428 // Since predecessor blocks now unconditionally branch to a new block,
2429 // they no longer branch to their original successors.
2430 for (InvokeInst *II : Invokes)
2431 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2432 Updates.push_back(
2433 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2436 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2438 // Form the merged operands for the merged invoke.
2439 for (Use &U : MergedInvoke->operands()) {
2440 // Only PHI together the indirect callees and data operands.
2441 if (MergedInvoke->isCallee(&U)) {
2442 if (!IsIndirectCall)
2443 continue;
2444 } else if (!MergedInvoke->isDataOperand(&U))
2445 continue;
2447 // Don't create trivial PHI's with all-identical incoming values.
2448 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2449 return II->getOperand(U.getOperandNo()) != U.get();
2451 if (!NeedPHI)
2452 continue;
2454 // Form a PHI out of all the data ops under this index.
2455 PHINode *PN = PHINode::Create(
2456 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke);
2457 for (InvokeInst *II : Invokes)
2458 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2460 U.set(PN);
2463 // We've ensured that each PHI node has compatible (identical) incoming values
2464 // when coming from each of the `invoke`s in the current merge set,
2465 // so update the PHI nodes accordingly.
2466 for (BasicBlock *Succ : successors(MergedInvoke))
2467 AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2468 /*ExistPred=*/Invokes.front()->getParent());
2470 // And finally, replace the original `invoke`s with an unconditional branch
2471 // to the block with the merged `invoke`. Also, give that merged `invoke`
2472 // the merged debugloc of all the original `invoke`s.
2473 const DILocation *MergedDebugLoc = nullptr;
2474 for (InvokeInst *II : Invokes) {
2475 // Compute the debug location common to all the original `invoke`s.
2476 if (!MergedDebugLoc)
2477 MergedDebugLoc = II->getDebugLoc();
2478 else
2479 MergedDebugLoc =
2480 DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2482 // And replace the old `invoke` with an unconditionally branch
2483 // to the block with the merged `invoke`.
2484 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2485 OrigSuccBB->removePredecessor(II->getParent());
2486 BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2487 II->replaceAllUsesWith(MergedInvoke);
2488 II->eraseFromParent();
2489 ++NumInvokesMerged;
2491 MergedInvoke->setDebugLoc(MergedDebugLoc);
2492 ++NumInvokeSetsFormed;
2494 if (DTU)
2495 DTU->applyUpdates(Updates);
2498 /// If this block is a `landingpad` exception handling block, categorize all
2499 /// the predecessor `invoke`s into sets, with all `invoke`s in each set
2500 /// being "mergeable" together, and then merge invokes in each set together.
2502 /// This is a weird mix of hoisting and sinking. Visually, it goes from:
2503 /// [...] [...]
2504 /// | |
2505 /// [invoke0] [invoke1]
2506 /// / \ / \
2507 /// [cont0] [landingpad] [cont1]
2508 /// to:
2509 /// [...] [...]
2510 /// \ /
2511 /// [invoke]
2512 /// / \
2513 /// [cont] [landingpad]
2515 /// But of course we can only do that if the invokes share the `landingpad`,
2516 /// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2517 /// and the invoked functions are "compatible".
2518 static bool MergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU) {
2519 if (!EnableMergeCompatibleInvokes)
2520 return false;
2522 bool Changed = false;
2524 // FIXME: generalize to all exception handling blocks?
2525 if (!BB->isLandingPad())
2526 return Changed;
2528 CompatibleSets Grouper;
2530 // Record all the predecessors of this `landingpad`. As per verifier,
2531 // the only allowed predecessor is the unwind edge of an `invoke`.
2532 // We want to group "compatible" `invokes` into the same set to be merged.
2533 for (BasicBlock *PredBB : predecessors(BB))
2534 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2536 // And now, merge `invoke`s that were grouped togeter.
2537 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2538 if (Invokes.size() < 2)
2539 continue;
2540 Changed = true;
2541 MergeCompatibleInvokesImpl(Invokes, DTU);
2544 return Changed;
2547 /// Determine if we can hoist sink a sole store instruction out of a
2548 /// conditional block.
2550 /// We are looking for code like the following:
2551 /// BrBB:
2552 /// store i32 %add, i32* %arrayidx2
2553 /// ... // No other stores or function calls (we could be calling a memory
2554 /// ... // function).
2555 /// %cmp = icmp ult %x, %y
2556 /// br i1 %cmp, label %EndBB, label %ThenBB
2557 /// ThenBB:
2558 /// store i32 %add5, i32* %arrayidx2
2559 /// br label EndBB
2560 /// EndBB:
2561 /// ...
2562 /// We are going to transform this into:
2563 /// BrBB:
2564 /// store i32 %add, i32* %arrayidx2
2565 /// ... //
2566 /// %cmp = icmp ult %x, %y
2567 /// %add.add5 = select i1 %cmp, i32 %add, %add5
2568 /// store i32 %add.add5, i32* %arrayidx2
2569 /// ...
2571 /// \return The pointer to the value of the previous store if the store can be
2572 /// hoisted into the predecessor block. 0 otherwise.
2573 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
2574 BasicBlock *StoreBB, BasicBlock *EndBB) {
2575 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2576 if (!StoreToHoist)
2577 return nullptr;
2579 // Volatile or atomic.
2580 if (!StoreToHoist->isSimple())
2581 return nullptr;
2583 Value *StorePtr = StoreToHoist->getPointerOperand();
2584 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2586 // Look for a store to the same pointer in BrBB.
2587 unsigned MaxNumInstToLookAt = 9;
2588 // Skip pseudo probe intrinsic calls which are not really killing any memory
2589 // accesses.
2590 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2591 if (!MaxNumInstToLookAt)
2592 break;
2593 --MaxNumInstToLookAt;
2595 // Could be calling an instruction that affects memory like free().
2596 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2597 return nullptr;
2599 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2600 // Found the previous store to same location and type. Make sure it is
2601 // simple, to avoid introducing a spurious non-atomic write after an
2602 // atomic write.
2603 if (SI->getPointerOperand() == StorePtr &&
2604 SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2605 // Found the previous store, return its value operand.
2606 return SI->getValueOperand();
2607 return nullptr; // Unknown store.
2610 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2611 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2612 LI->isSimple()) {
2613 // Local objects (created by an `alloca` instruction) are always
2614 // writable, so once we are past a read from a location it is valid to
2615 // also write to that same location.
2616 // If the address of the local object never escapes the function, that
2617 // means it's never concurrently read or written, hence moving the store
2618 // from under the condition will not introduce a data race.
2619 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2620 if (AI && !PointerMayBeCaptured(AI, false, true))
2621 // Found a previous load, return it.
2622 return LI;
2624 // The load didn't work out, but we may still find a store.
2628 return nullptr;
2631 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2632 /// converted to selects.
2633 static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
2634 BasicBlock *EndBB,
2635 unsigned &SpeculatedInstructions,
2636 InstructionCost &Cost,
2637 const TargetTransformInfo &TTI) {
2638 TargetTransformInfo::TargetCostKind CostKind =
2639 BB->getParent()->hasMinSize()
2640 ? TargetTransformInfo::TCK_CodeSize
2641 : TargetTransformInfo::TCK_SizeAndLatency;
2643 bool HaveRewritablePHIs = false;
2644 for (PHINode &PN : EndBB->phis()) {
2645 Value *OrigV = PN.getIncomingValueForBlock(BB);
2646 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2648 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2649 // Skip PHIs which are trivial.
2650 if (ThenV == OrigV)
2651 continue;
2653 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2654 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2656 // Don't convert to selects if we could remove undefined behavior instead.
2657 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2658 passingValueIsAlwaysUndefined(ThenV, &PN))
2659 return false;
2661 HaveRewritablePHIs = true;
2662 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2663 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2664 if (!OrigCE && !ThenCE)
2665 continue; // Known cheap (FIXME: Maybe not true for aggregates).
2667 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2668 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2669 InstructionCost MaxCost =
2670 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2671 if (OrigCost + ThenCost > MaxCost)
2672 return false;
2674 // Account for the cost of an unfolded ConstantExpr which could end up
2675 // getting expanded into Instructions.
2676 // FIXME: This doesn't account for how many operations are combined in the
2677 // constant expression.
2678 ++SpeculatedInstructions;
2679 if (SpeculatedInstructions > 1)
2680 return false;
2683 return HaveRewritablePHIs;
2686 /// Speculate a conditional basic block flattening the CFG.
2688 /// Note that this is a very risky transform currently. Speculating
2689 /// instructions like this is most often not desirable. Instead, there is an MI
2690 /// pass which can do it with full awareness of the resource constraints.
2691 /// However, some cases are "obvious" and we should do directly. An example of
2692 /// this is speculating a single, reasonably cheap instruction.
2694 /// There is only one distinct advantage to flattening the CFG at the IR level:
2695 /// it makes very common but simplistic optimizations such as are common in
2696 /// instcombine and the DAG combiner more powerful by removing CFG edges and
2697 /// modeling their effects with easier to reason about SSA value graphs.
2700 /// An illustration of this transform is turning this IR:
2701 /// \code
2702 /// BB:
2703 /// %cmp = icmp ult %x, %y
2704 /// br i1 %cmp, label %EndBB, label %ThenBB
2705 /// ThenBB:
2706 /// %sub = sub %x, %y
2707 /// br label BB2
2708 /// EndBB:
2709 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2710 /// ...
2711 /// \endcode
2713 /// Into this IR:
2714 /// \code
2715 /// BB:
2716 /// %cmp = icmp ult %x, %y
2717 /// %sub = sub %x, %y
2718 /// %cond = select i1 %cmp, 0, %sub
2719 /// ...
2720 /// \endcode
2722 /// \returns true if the conditional block is removed.
2723 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2724 const TargetTransformInfo &TTI) {
2725 // Be conservative for now. FP select instruction can often be expensive.
2726 Value *BrCond = BI->getCondition();
2727 if (isa<FCmpInst>(BrCond))
2728 return false;
2730 BasicBlock *BB = BI->getParent();
2731 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2732 InstructionCost Budget =
2733 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2735 // If ThenBB is actually on the false edge of the conditional branch, remember
2736 // to swap the select operands later.
2737 bool Invert = false;
2738 if (ThenBB != BI->getSuccessor(0)) {
2739 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2740 Invert = true;
2742 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2744 // If the branch is non-unpredictable, and is predicted to *not* branch to
2745 // the `then` block, then avoid speculating it.
2746 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2747 uint64_t TWeight, FWeight;
2748 if (extractBranchWeights(*BI, TWeight, FWeight) &&
2749 (TWeight + FWeight) != 0) {
2750 uint64_t EndWeight = Invert ? TWeight : FWeight;
2751 BranchProbability BIEndProb =
2752 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2753 BranchProbability Likely = TTI.getPredictableBranchThreshold();
2754 if (BIEndProb >= Likely)
2755 return false;
2759 // Keep a count of how many times instructions are used within ThenBB when
2760 // they are candidates for sinking into ThenBB. Specifically:
2761 // - They are defined in BB, and
2762 // - They have no side effects, and
2763 // - All of their uses are in ThenBB.
2764 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2766 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2768 unsigned SpeculatedInstructions = 0;
2769 Value *SpeculatedStoreValue = nullptr;
2770 StoreInst *SpeculatedStore = nullptr;
2771 for (BasicBlock::iterator BBI = ThenBB->begin(),
2772 BBE = std::prev(ThenBB->end());
2773 BBI != BBE; ++BBI) {
2774 Instruction *I = &*BBI;
2775 // Skip debug info.
2776 if (isa<DbgInfoIntrinsic>(I)) {
2777 SpeculatedDbgIntrinsics.push_back(I);
2778 continue;
2781 // Skip pseudo probes. The consequence is we lose track of the branch
2782 // probability for ThenBB, which is fine since the optimization here takes
2783 // place regardless of the branch probability.
2784 if (isa<PseudoProbeInst>(I)) {
2785 // The probe should be deleted so that it will not be over-counted when
2786 // the samples collected on the non-conditional path are counted towards
2787 // the conditional path. We leave it for the counts inference algorithm to
2788 // figure out a proper count for an unknown probe.
2789 SpeculatedDbgIntrinsics.push_back(I);
2790 continue;
2793 // Only speculatively execute a single instruction (not counting the
2794 // terminator) for now.
2795 ++SpeculatedInstructions;
2796 if (SpeculatedInstructions > 1)
2797 return false;
2799 // Don't hoist the instruction if it's unsafe or expensive.
2800 if (!isSafeToSpeculativelyExecute(I) &&
2801 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2802 I, BB, ThenBB, EndBB))))
2803 return false;
2804 if (!SpeculatedStoreValue &&
2805 computeSpeculationCost(I, TTI) >
2806 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2807 return false;
2809 // Store the store speculation candidate.
2810 if (SpeculatedStoreValue)
2811 SpeculatedStore = cast<StoreInst>(I);
2813 // Do not hoist the instruction if any of its operands are defined but not
2814 // used in BB. The transformation will prevent the operand from
2815 // being sunk into the use block.
2816 for (Use &Op : I->operands()) {
2817 Instruction *OpI = dyn_cast<Instruction>(Op);
2818 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2819 continue; // Not a candidate for sinking.
2821 ++SinkCandidateUseCounts[OpI];
2825 // Consider any sink candidates which are only used in ThenBB as costs for
2826 // speculation. Note, while we iterate over a DenseMap here, we are summing
2827 // and so iteration order isn't significant.
2828 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
2829 I = SinkCandidateUseCounts.begin(),
2830 E = SinkCandidateUseCounts.end();
2831 I != E; ++I)
2832 if (I->first->hasNUses(I->second)) {
2833 ++SpeculatedInstructions;
2834 if (SpeculatedInstructions > 1)
2835 return false;
2838 // Check that we can insert the selects and that it's not too expensive to do
2839 // so.
2840 bool Convert = SpeculatedStore != nullptr;
2841 InstructionCost Cost = 0;
2842 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2843 SpeculatedInstructions,
2844 Cost, TTI);
2845 if (!Convert || Cost > Budget)
2846 return false;
2848 // If we get here, we can hoist the instruction and if-convert.
2849 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2851 // Insert a select of the value of the speculated store.
2852 if (SpeculatedStoreValue) {
2853 IRBuilder<NoFolder> Builder(BI);
2854 Value *TrueV = SpeculatedStore->getValueOperand();
2855 Value *FalseV = SpeculatedStoreValue;
2856 if (Invert)
2857 std::swap(TrueV, FalseV);
2858 Value *S = Builder.CreateSelect(
2859 BrCond, TrueV, FalseV, "spec.store.select", BI);
2860 SpeculatedStore->setOperand(0, S);
2861 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2862 SpeculatedStore->getDebugLoc());
2865 // Metadata can be dependent on the condition we are hoisting above.
2866 // Conservatively strip all metadata on the instruction. Drop the debug loc
2867 // to avoid making it appear as if the condition is a constant, which would
2868 // be misleading while debugging.
2869 // Similarly strip attributes that maybe dependent on condition we are
2870 // hoisting above.
2871 for (auto &I : *ThenBB) {
2872 if (!SpeculatedStoreValue || &I != SpeculatedStore)
2873 I.setDebugLoc(DebugLoc());
2874 I.dropUndefImplyingAttrsAndUnknownMetadata();
2877 // Hoist the instructions.
2878 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2879 ThenBB->begin(), std::prev(ThenBB->end()));
2881 // Insert selects and rewrite the PHI operands.
2882 IRBuilder<NoFolder> Builder(BI);
2883 for (PHINode &PN : EndBB->phis()) {
2884 unsigned OrigI = PN.getBasicBlockIndex(BB);
2885 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2886 Value *OrigV = PN.getIncomingValue(OrigI);
2887 Value *ThenV = PN.getIncomingValue(ThenI);
2889 // Skip PHIs which are trivial.
2890 if (OrigV == ThenV)
2891 continue;
2893 // Create a select whose true value is the speculatively executed value and
2894 // false value is the pre-existing value. Swap them if the branch
2895 // destinations were inverted.
2896 Value *TrueV = ThenV, *FalseV = OrigV;
2897 if (Invert)
2898 std::swap(TrueV, FalseV);
2899 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
2900 PN.setIncomingValue(OrigI, V);
2901 PN.setIncomingValue(ThenI, V);
2904 // Remove speculated dbg intrinsics.
2905 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2906 // dbg value for the different flows and inserting it after the select.
2907 for (Instruction *I : SpeculatedDbgIntrinsics)
2908 I->eraseFromParent();
2910 ++NumSpeculations;
2911 return true;
2914 /// Return true if we can thread a branch across this block.
2915 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2916 int Size = 0;
2918 SmallPtrSet<const Value *, 32> EphValues;
2919 auto IsEphemeral = [&](const Instruction *I) {
2920 if (isa<AssumeInst>(I))
2921 return true;
2922 return !I->mayHaveSideEffects() && !I->isTerminator() &&
2923 all_of(I->users(),
2924 [&](const User *U) { return EphValues.count(U); });
2927 // Walk the loop in reverse so that we can identify ephemeral values properly
2928 // (values only feeding assumes).
2929 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
2930 // Can't fold blocks that contain noduplicate or convergent calls.
2931 if (CallInst *CI = dyn_cast<CallInst>(&I))
2932 if (CI->cannotDuplicate() || CI->isConvergent())
2933 return false;
2935 // Ignore ephemeral values which are deleted during codegen.
2936 if (IsEphemeral(&I))
2937 EphValues.insert(&I);
2938 // We will delete Phis while threading, so Phis should not be accounted in
2939 // block's size.
2940 else if (!isa<PHINode>(I)) {
2941 if (Size++ > MaxSmallBlockSize)
2942 return false; // Don't clone large BB's.
2945 // We can only support instructions that do not define values that are
2946 // live outside of the current basic block.
2947 for (User *U : I.users()) {
2948 Instruction *UI = cast<Instruction>(U);
2949 if (UI->getParent() != BB || isa<PHINode>(UI))
2950 return false;
2953 // Looks ok, continue checking.
2956 return true;
2959 static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
2960 BasicBlock *To) {
2961 // Don't look past the block defining the value, we might get the value from
2962 // a previous loop iteration.
2963 auto *I = dyn_cast<Instruction>(V);
2964 if (I && I->getParent() == To)
2965 return nullptr;
2967 // We know the value if the From block branches on it.
2968 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
2969 if (BI && BI->isConditional() && BI->getCondition() == V &&
2970 BI->getSuccessor(0) != BI->getSuccessor(1))
2971 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
2972 : ConstantInt::getFalse(BI->getContext());
2974 return nullptr;
2977 /// If we have a conditional branch on something for which we know the constant
2978 /// value in predecessors (e.g. a phi node in the current block), thread edges
2979 /// from the predecessor to their ultimate destination.
2980 static Optional<bool>
2981 FoldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU,
2982 const DataLayout &DL,
2983 AssumptionCache *AC) {
2984 SmallMapVector<ConstantInt *, SmallSetVector<BasicBlock *, 2>, 2> KnownValues;
2985 BasicBlock *BB = BI->getParent();
2986 Value *Cond = BI->getCondition();
2987 PHINode *PN = dyn_cast<PHINode>(Cond);
2988 if (PN && PN->getParent() == BB) {
2989 // Degenerate case of a single entry PHI.
2990 if (PN->getNumIncomingValues() == 1) {
2991 FoldSingleEntryPHINodes(PN->getParent());
2992 return true;
2995 for (Use &U : PN->incoming_values())
2996 if (auto *CB = dyn_cast<ConstantInt>(U))
2997 KnownValues[CB].insert(PN->getIncomingBlock(U));
2998 } else {
2999 for (BasicBlock *Pred : predecessors(BB)) {
3000 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3001 KnownValues[CB].insert(Pred);
3005 if (KnownValues.empty())
3006 return false;
3008 // Now we know that this block has multiple preds and two succs.
3009 // Check that the block is small enough and values defined in the block are
3010 // not used outside of it.
3011 if (!BlockIsSimpleEnoughToThreadThrough(BB))
3012 return false;
3014 for (const auto &Pair : KnownValues) {
3015 // Okay, we now know that all edges from PredBB should be revectored to
3016 // branch to RealDest.
3017 ConstantInt *CB = Pair.first;
3018 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3019 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3021 if (RealDest == BB)
3022 continue; // Skip self loops.
3024 // Skip if the predecessor's terminator is an indirect branch.
3025 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3026 return isa<IndirectBrInst>(PredBB->getTerminator());
3028 continue;
3030 LLVM_DEBUG({
3031 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3032 << " has value " << *Pair.first << " in predecessors:\n";
3033 for (const BasicBlock *PredBB : Pair.second)
3034 dbgs() << " " << PredBB->getName() << "\n";
3035 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3038 // Split the predecessors we are threading into a new edge block. We'll
3039 // clone the instructions into this block, and then redirect it to RealDest.
3040 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3042 // TODO: These just exist to reduce test diff, we can drop them if we like.
3043 EdgeBB->setName(RealDest->getName() + ".critedge");
3044 EdgeBB->moveBefore(RealDest);
3046 // Update PHI nodes.
3047 AddPredecessorToBlock(RealDest, EdgeBB, BB);
3049 // BB may have instructions that are being threaded over. Clone these
3050 // instructions into EdgeBB. We know that there will be no uses of the
3051 // cloned instructions outside of EdgeBB.
3052 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3053 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3054 TranslateMap[Cond] = CB;
3055 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3056 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3057 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3058 continue;
3060 // Clone the instruction.
3061 Instruction *N = BBI->clone();
3062 if (BBI->hasName())
3063 N->setName(BBI->getName() + ".c");
3065 // Update operands due to translation.
3066 for (Use &Op : N->operands()) {
3067 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3068 if (PI != TranslateMap.end())
3069 Op = PI->second;
3072 // Check for trivial simplification.
3073 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3074 if (!BBI->use_empty())
3075 TranslateMap[&*BBI] = V;
3076 if (!N->mayHaveSideEffects()) {
3077 N->deleteValue(); // Instruction folded away, don't need actual inst
3078 N = nullptr;
3080 } else {
3081 if (!BBI->use_empty())
3082 TranslateMap[&*BBI] = N;
3084 if (N) {
3085 // Insert the new instruction into its new home.
3086 EdgeBB->getInstList().insert(InsertPt, N);
3088 // Register the new instruction with the assumption cache if necessary.
3089 if (auto *Assume = dyn_cast<AssumeInst>(N))
3090 if (AC)
3091 AC->registerAssumption(Assume);
3095 BB->removePredecessor(EdgeBB);
3096 BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
3097 EdgeBI->setSuccessor(0, RealDest);
3098 EdgeBI->setDebugLoc(BI->getDebugLoc());
3100 if (DTU) {
3101 SmallVector<DominatorTree::UpdateType, 2> Updates;
3102 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3103 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3104 DTU->applyUpdates(Updates);
3107 // For simplicity, we created a separate basic block for the edge. Merge
3108 // it back into the predecessor if possible. This not only avoids
3109 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3110 // bypass the check for trivial cycles above.
3111 MergeBlockIntoPredecessor(EdgeBB, DTU);
3113 // Signal repeat, simplifying any other constants.
3114 return None;
3117 return false;
3120 static bool FoldCondBranchOnValueKnownInPredecessor(BranchInst *BI,
3121 DomTreeUpdater *DTU,
3122 const DataLayout &DL,
3123 AssumptionCache *AC) {
3124 Optional<bool> Result;
3125 bool EverChanged = false;
3126 do {
3127 // Note that None means "we changed things, but recurse further."
3128 Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3129 EverChanged |= Result == None || *Result;
3130 } while (Result == None);
3131 return EverChanged;
3134 /// Given a BB that starts with the specified two-entry PHI node,
3135 /// see if we can eliminate it.
3136 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
3137 DomTreeUpdater *DTU, const DataLayout &DL) {
3138 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3139 // statement", which has a very simple dominance structure. Basically, we
3140 // are trying to find the condition that is being branched on, which
3141 // subsequently causes this merge to happen. We really want control
3142 // dependence information for this check, but simplifycfg can't keep it up
3143 // to date, and this catches most of the cases we care about anyway.
3144 BasicBlock *BB = PN->getParent();
3146 BasicBlock *IfTrue, *IfFalse;
3147 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3148 if (!DomBI)
3149 return false;
3150 Value *IfCond = DomBI->getCondition();
3151 // Don't bother if the branch will be constant folded trivially.
3152 if (isa<ConstantInt>(IfCond))
3153 return false;
3155 BasicBlock *DomBlock = DomBI->getParent();
3156 SmallVector<BasicBlock *, 2> IfBlocks;
3157 llvm::copy_if(
3158 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3159 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3161 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3162 "Will have either one or two blocks to speculate.");
3164 // If the branch is non-unpredictable, see if we either predictably jump to
3165 // the merge bb (if we have only a single 'then' block), or if we predictably
3166 // jump to one specific 'then' block (if we have two of them).
3167 // It isn't beneficial to speculatively execute the code
3168 // from the block that we know is predictably not entered.
3169 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
3170 uint64_t TWeight, FWeight;
3171 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3172 (TWeight + FWeight) != 0) {
3173 BranchProbability BITrueProb =
3174 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3175 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3176 BranchProbability BIFalseProb = BITrueProb.getCompl();
3177 if (IfBlocks.size() == 1) {
3178 BranchProbability BIBBProb =
3179 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3180 if (BIBBProb >= Likely)
3181 return false;
3182 } else {
3183 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3184 return false;
3189 // Don't try to fold an unreachable block. For example, the phi node itself
3190 // can't be the candidate if-condition for a select that we want to form.
3191 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3192 if (IfCondPhiInst->getParent() == BB)
3193 return false;
3195 // Okay, we found that we can merge this two-entry phi node into a select.
3196 // Doing so would require us to fold *all* two entry phi nodes in this block.
3197 // At some point this becomes non-profitable (particularly if the target
3198 // doesn't support cmov's). Only do this transformation if there are two or
3199 // fewer PHI nodes in this block.
3200 unsigned NumPhis = 0;
3201 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3202 if (NumPhis > 2)
3203 return false;
3205 // Loop over the PHI's seeing if we can promote them all to select
3206 // instructions. While we are at it, keep track of the instructions
3207 // that need to be moved to the dominating block.
3208 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3209 InstructionCost Cost = 0;
3210 InstructionCost Budget =
3211 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3213 bool Changed = false;
3214 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3215 PHINode *PN = cast<PHINode>(II++);
3216 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3217 PN->replaceAllUsesWith(V);
3218 PN->eraseFromParent();
3219 Changed = true;
3220 continue;
3223 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3224 Cost, Budget, TTI) ||
3225 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3226 Cost, Budget, TTI))
3227 return Changed;
3230 // If we folded the first phi, PN dangles at this point. Refresh it. If
3231 // we ran out of PHIs then we simplified them all.
3232 PN = dyn_cast<PHINode>(BB->begin());
3233 if (!PN)
3234 return true;
3236 // Return true if at least one of these is a 'not', and another is either
3237 // a 'not' too, or a constant.
3238 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3239 if (!match(V0, m_Not(m_Value())))
3240 std::swap(V0, V1);
3241 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3242 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3245 // Don't fold i1 branches on PHIs which contain binary operators or
3246 // (possibly inverted) select form of or/ands, unless one of
3247 // the incoming values is an 'not' and another one is freely invertible.
3248 // These can often be turned into switches and other things.
3249 auto IsBinOpOrAnd = [](Value *V) {
3250 return match(
3251 V, m_CombineOr(
3252 m_BinOp(),
3253 m_CombineOr(m_Select(m_Value(), m_ImmConstant(), m_Value()),
3254 m_Select(m_Value(), m_Value(), m_ImmConstant()))));
3256 if (PN->getType()->isIntegerTy(1) &&
3257 (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3258 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3259 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3260 PN->getIncomingValue(1)))
3261 return Changed;
3263 // If all PHI nodes are promotable, check to make sure that all instructions
3264 // in the predecessor blocks can be promoted as well. If not, we won't be able
3265 // to get rid of the control flow, so it's not worth promoting to select
3266 // instructions.
3267 for (BasicBlock *IfBlock : IfBlocks)
3268 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3269 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3270 // This is not an aggressive instruction that we can promote.
3271 // Because of this, we won't be able to get rid of the control flow, so
3272 // the xform is not worth it.
3273 return Changed;
3276 // If either of the blocks has it's address taken, we can't do this fold.
3277 if (any_of(IfBlocks,
3278 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3279 return Changed;
3281 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
3282 << " T: " << IfTrue->getName()
3283 << " F: " << IfFalse->getName() << "\n");
3285 // If we can still promote the PHI nodes after this gauntlet of tests,
3286 // do all of the PHI's now.
3288 // Move all 'aggressive' instructions, which are defined in the
3289 // conditional parts of the if's up to the dominating block.
3290 for (BasicBlock *IfBlock : IfBlocks)
3291 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3293 IRBuilder<NoFolder> Builder(DomBI);
3294 // Propagate fast-math-flags from phi nodes to replacement selects.
3295 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3296 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3297 if (isa<FPMathOperator>(PN))
3298 Builder.setFastMathFlags(PN->getFastMathFlags());
3300 // Change the PHI node into a select instruction.
3301 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3302 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3304 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3305 PN->replaceAllUsesWith(Sel);
3306 Sel->takeName(PN);
3307 PN->eraseFromParent();
3310 // At this point, all IfBlocks are empty, so our if statement
3311 // has been flattened. Change DomBlock to jump directly to our new block to
3312 // avoid other simplifycfg's kicking in on the diamond.
3313 Builder.CreateBr(BB);
3315 SmallVector<DominatorTree::UpdateType, 3> Updates;
3316 if (DTU) {
3317 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3318 for (auto *Successor : successors(DomBlock))
3319 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3322 DomBI->eraseFromParent();
3323 if (DTU)
3324 DTU->applyUpdates(Updates);
3326 return true;
3329 static Value *createLogicalOp(IRBuilderBase &Builder,
3330 Instruction::BinaryOps Opc, Value *LHS,
3331 Value *RHS, const Twine &Name = "") {
3332 // Try to relax logical op to binary op.
3333 if (impliesPoison(RHS, LHS))
3334 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3335 if (Opc == Instruction::And)
3336 return Builder.CreateLogicalAnd(LHS, RHS, Name);
3337 if (Opc == Instruction::Or)
3338 return Builder.CreateLogicalOr(LHS, RHS, Name);
3339 llvm_unreachable("Invalid logical opcode");
3342 /// Return true if either PBI or BI has branch weight available, and store
3343 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3344 /// not have branch weight, use 1:1 as its weight.
3345 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
3346 uint64_t &PredTrueWeight,
3347 uint64_t &PredFalseWeight,
3348 uint64_t &SuccTrueWeight,
3349 uint64_t &SuccFalseWeight) {
3350 bool PredHasWeights =
3351 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
3352 bool SuccHasWeights =
3353 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
3354 if (PredHasWeights || SuccHasWeights) {
3355 if (!PredHasWeights)
3356 PredTrueWeight = PredFalseWeight = 1;
3357 if (!SuccHasWeights)
3358 SuccTrueWeight = SuccFalseWeight = 1;
3359 return true;
3360 } else {
3361 return false;
3365 /// Determine if the two branches share a common destination and deduce a glue
3366 /// that joins the branches' conditions to arrive at the common destination if
3367 /// that would be profitable.
3368 static Optional<std::pair<Instruction::BinaryOps, bool>>
3369 shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI,
3370 const TargetTransformInfo *TTI) {
3371 assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3372 "Both blocks must end with a conditional branches.");
3373 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&
3374 "PredBB must be a predecessor of BB.");
3376 // We have the potential to fold the conditions together, but if the
3377 // predecessor branch is predictable, we may not want to merge them.
3378 uint64_t PTWeight, PFWeight;
3379 BranchProbability PBITrueProb, Likely;
3380 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3381 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
3382 (PTWeight + PFWeight) != 0) {
3383 PBITrueProb =
3384 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3385 Likely = TTI->getPredictableBranchThreshold();
3388 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3389 // Speculate the 2nd condition unless the 1st is probably true.
3390 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3391 return {{Instruction::Or, false}};
3392 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3393 // Speculate the 2nd condition unless the 1st is probably false.
3394 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3395 return {{Instruction::And, false}};
3396 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3397 // Speculate the 2nd condition unless the 1st is probably true.
3398 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3399 return {{Instruction::And, true}};
3400 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3401 // Speculate the 2nd condition unless the 1st is probably false.
3402 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3403 return {{Instruction::Or, true}};
3405 return None;
3408 static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI,
3409 DomTreeUpdater *DTU,
3410 MemorySSAUpdater *MSSAU,
3411 const TargetTransformInfo *TTI) {
3412 BasicBlock *BB = BI->getParent();
3413 BasicBlock *PredBlock = PBI->getParent();
3415 // Determine if the two branches share a common destination.
3416 Instruction::BinaryOps Opc;
3417 bool InvertPredCond;
3418 std::tie(Opc, InvertPredCond) =
3419 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI);
3421 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3423 IRBuilder<> Builder(PBI);
3424 // The builder is used to create instructions to eliminate the branch in BB.
3425 // If BB's terminator has !annotation metadata, add it to the new
3426 // instructions.
3427 Builder.CollectMetadataToCopy(BB->getTerminator(),
3428 {LLVMContext::MD_annotation});
3430 // If we need to invert the condition in the pred block to match, do so now.
3431 if (InvertPredCond) {
3432 Value *NewCond = PBI->getCondition();
3433 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
3434 CmpInst *CI = cast<CmpInst>(NewCond);
3435 CI->setPredicate(CI->getInversePredicate());
3436 } else {
3437 NewCond =
3438 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
3441 PBI->setCondition(NewCond);
3442 PBI->swapSuccessors();
3445 BasicBlock *UniqueSucc =
3446 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3448 // Before cloning instructions, notify the successor basic block that it
3449 // is about to have a new predecessor. This will update PHI nodes,
3450 // which will allow us to update live-out uses of bonus instructions.
3451 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3453 // Try to update branch weights.
3454 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3455 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3456 SuccTrueWeight, SuccFalseWeight)) {
3457 SmallVector<uint64_t, 8> NewWeights;
3459 if (PBI->getSuccessor(0) == BB) {
3460 // PBI: br i1 %x, BB, FalseDest
3461 // BI: br i1 %y, UniqueSucc, FalseDest
3462 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3463 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3464 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3465 // TrueWeight for PBI * FalseWeight for BI.
3466 // We assume that total weights of a BranchInst can fit into 32 bits.
3467 // Therefore, we will not have overflow using 64-bit arithmetic.
3468 NewWeights.push_back(PredFalseWeight *
3469 (SuccFalseWeight + SuccTrueWeight) +
3470 PredTrueWeight * SuccFalseWeight);
3471 } else {
3472 // PBI: br i1 %x, TrueDest, BB
3473 // BI: br i1 %y, TrueDest, UniqueSucc
3474 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3475 // FalseWeight for PBI * TrueWeight for BI.
3476 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3477 PredFalseWeight * SuccTrueWeight);
3478 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3479 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3482 // Halve the weights if any of them cannot fit in an uint32_t
3483 FitWeights(NewWeights);
3485 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3486 setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3488 // TODO: If BB is reachable from all paths through PredBlock, then we
3489 // could replace PBI's branch probabilities with BI's.
3490 } else
3491 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3493 // Now, update the CFG.
3494 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3496 if (DTU)
3497 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3498 {DominatorTree::Delete, PredBlock, BB}});
3500 // If BI was a loop latch, it may have had associated loop metadata.
3501 // We need to copy it to the new latch, that is, PBI.
3502 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3503 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3505 ValueToValueMapTy VMap; // maps original values to cloned values
3506 CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap);
3508 // Now that the Cond was cloned into the predecessor basic block,
3509 // or/and the two conditions together.
3510 Value *BICond = VMap[BI->getCondition()];
3511 PBI->setCondition(
3512 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3514 // Copy any debug value intrinsics into the end of PredBlock.
3515 for (Instruction &I : *BB) {
3516 if (isa<DbgInfoIntrinsic>(I)) {
3517 Instruction *NewI = I.clone();
3518 RemapInstruction(NewI, VMap,
3519 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
3520 NewI->insertBefore(PBI);
3524 ++NumFoldBranchToCommonDest;
3525 return true;
3528 /// Return if an instruction's type or any of its operands' types are a vector
3529 /// type.
3530 static bool isVectorOp(Instruction &I) {
3531 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3532 return U->getType()->isVectorTy();
3536 /// If this basic block is simple enough, and if a predecessor branches to us
3537 /// and one of our successors, fold the block into the predecessor and use
3538 /// logical operations to pick the right destination.
3539 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU,
3540 MemorySSAUpdater *MSSAU,
3541 const TargetTransformInfo *TTI,
3542 unsigned BonusInstThreshold) {
3543 // If this block ends with an unconditional branch,
3544 // let SpeculativelyExecuteBB() deal with it.
3545 if (!BI->isConditional())
3546 return false;
3548 BasicBlock *BB = BI->getParent();
3549 TargetTransformInfo::TargetCostKind CostKind =
3550 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
3551 : TargetTransformInfo::TCK_SizeAndLatency;
3553 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3555 if (!Cond ||
3556 (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3557 !isa<SelectInst>(Cond)) ||
3558 Cond->getParent() != BB || !Cond->hasOneUse())
3559 return false;
3561 // Finally, don't infinitely unroll conditional loops.
3562 if (is_contained(successors(BB), BB))
3563 return false;
3565 // With which predecessors will we want to deal with?
3566 SmallVector<BasicBlock *, 8> Preds;
3567 for (BasicBlock *PredBlock : predecessors(BB)) {
3568 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3570 // Check that we have two conditional branches. If there is a PHI node in
3571 // the common successor, verify that the same value flows in from both
3572 // blocks.
3573 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3574 continue;
3576 // Determine if the two branches share a common destination.
3577 Instruction::BinaryOps Opc;
3578 bool InvertPredCond;
3579 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3580 std::tie(Opc, InvertPredCond) = *Recipe;
3581 else
3582 continue;
3584 // Check the cost of inserting the necessary logic before performing the
3585 // transformation.
3586 if (TTI) {
3587 Type *Ty = BI->getCondition()->getType();
3588 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
3589 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3590 !isa<CmpInst>(PBI->getCondition())))
3591 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3593 if (Cost > BranchFoldThreshold)
3594 continue;
3597 // Ok, we do want to deal with this predecessor. Record it.
3598 Preds.emplace_back(PredBlock);
3601 // If there aren't any predecessors into which we can fold,
3602 // don't bother checking the cost.
3603 if (Preds.empty())
3604 return false;
3606 // Only allow this transformation if computing the condition doesn't involve
3607 // too many instructions and these involved instructions can be executed
3608 // unconditionally. We denote all involved instructions except the condition
3609 // as "bonus instructions", and only allow this transformation when the
3610 // number of the bonus instructions we'll need to create when cloning into
3611 // each predecessor does not exceed a certain threshold.
3612 unsigned NumBonusInsts = 0;
3613 bool SawVectorOp = false;
3614 const unsigned PredCount = Preds.size();
3615 for (Instruction &I : *BB) {
3616 // Don't check the branch condition comparison itself.
3617 if (&I == Cond)
3618 continue;
3619 // Ignore dbg intrinsics, and the terminator.
3620 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3621 continue;
3622 // I must be safe to execute unconditionally.
3623 if (!isSafeToSpeculativelyExecute(&I))
3624 return false;
3625 SawVectorOp |= isVectorOp(I);
3627 // Account for the cost of duplicating this instruction into each
3628 // predecessor. Ignore free instructions.
3629 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
3630 TargetTransformInfo::TCC_Free) {
3631 NumBonusInsts += PredCount;
3633 // Early exits once we reach the limit.
3634 if (NumBonusInsts >
3635 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3636 return false;
3639 auto IsBCSSAUse = [BB, &I](Use &U) {
3640 auto *UI = cast<Instruction>(U.getUser());
3641 if (auto *PN = dyn_cast<PHINode>(UI))
3642 return PN->getIncomingBlock(U) == BB;
3643 return UI->getParent() == BB && I.comesBefore(UI);
3646 // Does this instruction require rewriting of uses?
3647 if (!all_of(I.uses(), IsBCSSAUse))
3648 return false;
3650 if (NumBonusInsts >
3651 BonusInstThreshold *
3652 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3653 return false;
3655 // Ok, we have the budget. Perform the transformation.
3656 for (BasicBlock *PredBlock : Preds) {
3657 auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3658 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3660 return false;
3663 // If there is only one store in BB1 and BB2, return it, otherwise return
3664 // nullptr.
3665 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
3666 StoreInst *S = nullptr;
3667 for (auto *BB : {BB1, BB2}) {
3668 if (!BB)
3669 continue;
3670 for (auto &I : *BB)
3671 if (auto *SI = dyn_cast<StoreInst>(&I)) {
3672 if (S)
3673 // Multiple stores seen.
3674 return nullptr;
3675 else
3676 S = SI;
3679 return S;
3682 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
3683 Value *AlternativeV = nullptr) {
3684 // PHI is going to be a PHI node that allows the value V that is defined in
3685 // BB to be referenced in BB's only successor.
3687 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3688 // doesn't matter to us what the other operand is (it'll never get used). We
3689 // could just create a new PHI with an undef incoming value, but that could
3690 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3691 // other PHI. So here we directly look for some PHI in BB's successor with V
3692 // as an incoming operand. If we find one, we use it, else we create a new
3693 // one.
3695 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3696 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3697 // where OtherBB is the single other predecessor of BB's only successor.
3698 PHINode *PHI = nullptr;
3699 BasicBlock *Succ = BB->getSingleSuccessor();
3701 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3702 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3703 PHI = cast<PHINode>(I);
3704 if (!AlternativeV)
3705 break;
3707 assert(Succ->hasNPredecessors(2));
3708 auto PredI = pred_begin(Succ);
3709 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3710 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3711 break;
3712 PHI = nullptr;
3714 if (PHI)
3715 return PHI;
3717 // If V is not an instruction defined in BB, just return it.
3718 if (!AlternativeV &&
3719 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3720 return V;
3722 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3723 PHI->addIncoming(V, BB);
3724 for (BasicBlock *PredBB : predecessors(Succ))
3725 if (PredBB != BB)
3726 PHI->addIncoming(
3727 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3728 return PHI;
3731 static bool mergeConditionalStoreToAddress(
3732 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3733 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3734 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3735 // For every pointer, there must be exactly two stores, one coming from
3736 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3737 // store (to any address) in PTB,PFB or QTB,QFB.
3738 // FIXME: We could relax this restriction with a bit more work and performance
3739 // testing.
3740 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3741 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3742 if (!PStore || !QStore)
3743 return false;
3745 // Now check the stores are compatible.
3746 if (!QStore->isUnordered() || !PStore->isUnordered() ||
3747 PStore->getValueOperand()->getType() !=
3748 QStore->getValueOperand()->getType())
3749 return false;
3751 // Check that sinking the store won't cause program behavior changes. Sinking
3752 // the store out of the Q blocks won't change any behavior as we're sinking
3753 // from a block to its unconditional successor. But we're moving a store from
3754 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3755 // So we need to check that there are no aliasing loads or stores in
3756 // QBI, QTB and QFB. We also need to check there are no conflicting memory
3757 // operations between PStore and the end of its parent block.
3759 // The ideal way to do this is to query AliasAnalysis, but we don't
3760 // preserve AA currently so that is dangerous. Be super safe and just
3761 // check there are no other memory operations at all.
3762 for (auto &I : *QFB->getSinglePredecessor())
3763 if (I.mayReadOrWriteMemory())
3764 return false;
3765 for (auto &I : *QFB)
3766 if (&I != QStore && I.mayReadOrWriteMemory())
3767 return false;
3768 if (QTB)
3769 for (auto &I : *QTB)
3770 if (&I != QStore && I.mayReadOrWriteMemory())
3771 return false;
3772 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3773 I != E; ++I)
3774 if (&*I != PStore && I->mayReadOrWriteMemory())
3775 return false;
3777 // If we're not in aggressive mode, we only optimize if we have some
3778 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3779 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3780 if (!BB)
3781 return true;
3782 // Heuristic: if the block can be if-converted/phi-folded and the
3783 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3784 // thread this store.
3785 InstructionCost Cost = 0;
3786 InstructionCost Budget =
3787 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3788 for (auto &I : BB->instructionsWithoutDebug(false)) {
3789 // Consider terminator instruction to be free.
3790 if (I.isTerminator())
3791 continue;
3792 // If this is one the stores that we want to speculate out of this BB,
3793 // then don't count it's cost, consider it to be free.
3794 if (auto *S = dyn_cast<StoreInst>(&I))
3795 if (llvm::find(FreeStores, S))
3796 continue;
3797 // Else, we have a white-list of instructions that we are ak speculating.
3798 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3799 return false; // Not in white-list - not worthwhile folding.
3800 // And finally, if this is a non-free instruction that we are okay
3801 // speculating, ensure that we consider the speculation budget.
3802 Cost +=
3803 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3804 if (Cost > Budget)
3805 return false; // Eagerly refuse to fold as soon as we're out of budget.
3807 assert(Cost <= Budget &&
3808 "When we run out of budget we will eagerly return from within the "
3809 "per-instruction loop.");
3810 return true;
3813 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3814 if (!MergeCondStoresAggressively &&
3815 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3816 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3817 return false;
3819 // If PostBB has more than two predecessors, we need to split it so we can
3820 // sink the store.
3821 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3822 // We know that QFB's only successor is PostBB. And QFB has a single
3823 // predecessor. If QTB exists, then its only successor is also PostBB.
3824 // If QTB does not exist, then QFB's only predecessor has a conditional
3825 // branch to QFB and PostBB.
3826 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3827 BasicBlock *NewBB =
3828 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3829 if (!NewBB)
3830 return false;
3831 PostBB = NewBB;
3834 // OK, we're going to sink the stores to PostBB. The store has to be
3835 // conditional though, so first create the predicate.
3836 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3837 ->getCondition();
3838 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3839 ->getCondition();
3841 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3842 PStore->getParent());
3843 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3844 QStore->getParent(), PPHI);
3846 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3848 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3849 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3851 if (InvertPCond)
3852 PPred = QB.CreateNot(PPred);
3853 if (InvertQCond)
3854 QPred = QB.CreateNot(QPred);
3855 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3857 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
3858 /*Unreachable=*/false,
3859 /*BranchWeights=*/nullptr, DTU);
3860 QB.SetInsertPoint(T);
3861 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3862 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
3863 // Choose the minimum alignment. If we could prove both stores execute, we
3864 // could use biggest one. In this case, though, we only know that one of the
3865 // stores executes. And we don't know it's safe to take the alignment from a
3866 // store that doesn't execute.
3867 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3869 QStore->eraseFromParent();
3870 PStore->eraseFromParent();
3872 return true;
3875 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3876 DomTreeUpdater *DTU, const DataLayout &DL,
3877 const TargetTransformInfo &TTI) {
3878 // The intention here is to find diamonds or triangles (see below) where each
3879 // conditional block contains a store to the same address. Both of these
3880 // stores are conditional, so they can't be unconditionally sunk. But it may
3881 // be profitable to speculatively sink the stores into one merged store at the
3882 // end, and predicate the merged store on the union of the two conditions of
3883 // PBI and QBI.
3885 // This can reduce the number of stores executed if both of the conditions are
3886 // true, and can allow the blocks to become small enough to be if-converted.
3887 // This optimization will also chain, so that ladders of test-and-set
3888 // sequences can be if-converted away.
3890 // We only deal with simple diamonds or triangles:
3892 // PBI or PBI or a combination of the two
3893 // / \ | \
3894 // PTB PFB | PFB
3895 // \ / | /
3896 // QBI QBI
3897 // / \ | \
3898 // QTB QFB | QFB
3899 // \ / | /
3900 // PostBB PostBB
3902 // We model triangles as a type of diamond with a nullptr "true" block.
3903 // Triangles are canonicalized so that the fallthrough edge is represented by
3904 // a true condition, as in the diagram above.
3905 BasicBlock *PTB = PBI->getSuccessor(0);
3906 BasicBlock *PFB = PBI->getSuccessor(1);
3907 BasicBlock *QTB = QBI->getSuccessor(0);
3908 BasicBlock *QFB = QBI->getSuccessor(1);
3909 BasicBlock *PostBB = QFB->getSingleSuccessor();
3911 // Make sure we have a good guess for PostBB. If QTB's only successor is
3912 // QFB, then QFB is a better PostBB.
3913 if (QTB->getSingleSuccessor() == QFB)
3914 PostBB = QFB;
3916 // If we couldn't find a good PostBB, stop.
3917 if (!PostBB)
3918 return false;
3920 bool InvertPCond = false, InvertQCond = false;
3921 // Canonicalize fallthroughs to the true branches.
3922 if (PFB == QBI->getParent()) {
3923 std::swap(PFB, PTB);
3924 InvertPCond = true;
3926 if (QFB == PostBB) {
3927 std::swap(QFB, QTB);
3928 InvertQCond = true;
3931 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3932 // and QFB may not. Model fallthroughs as a nullptr block.
3933 if (PTB == QBI->getParent())
3934 PTB = nullptr;
3935 if (QTB == PostBB)
3936 QTB = nullptr;
3938 // Legality bailouts. We must have at least the non-fallthrough blocks and
3939 // the post-dominating block, and the non-fallthroughs must only have one
3940 // predecessor.
3941 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3942 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3944 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3945 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3946 return false;
3947 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3948 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3949 return false;
3950 if (!QBI->getParent()->hasNUses(2))
3951 return false;
3953 // OK, this is a sequence of two diamonds or triangles.
3954 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3955 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3956 for (auto *BB : {PTB, PFB}) {
3957 if (!BB)
3958 continue;
3959 for (auto &I : *BB)
3960 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3961 PStoreAddresses.insert(SI->getPointerOperand());
3963 for (auto *BB : {QTB, QFB}) {
3964 if (!BB)
3965 continue;
3966 for (auto &I : *BB)
3967 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3968 QStoreAddresses.insert(SI->getPointerOperand());
3971 set_intersect(PStoreAddresses, QStoreAddresses);
3972 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3973 // clear what it contains.
3974 auto &CommonAddresses = PStoreAddresses;
3976 bool Changed = false;
3977 for (auto *Address : CommonAddresses)
3978 Changed |=
3979 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
3980 InvertPCond, InvertQCond, DTU, DL, TTI);
3981 return Changed;
3984 /// If the previous block ended with a widenable branch, determine if reusing
3985 /// the target block is profitable and legal. This will have the effect of
3986 /// "widening" PBI, but doesn't require us to reason about hosting safety.
3987 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3988 DomTreeUpdater *DTU) {
3989 // TODO: This can be generalized in two important ways:
3990 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3991 // values from the PBI edge.
3992 // 2) We can sink side effecting instructions into BI's fallthrough
3993 // successor provided they doesn't contribute to computation of
3994 // BI's condition.
3995 Value *CondWB, *WC;
3996 BasicBlock *IfTrueBB, *IfFalseBB;
3997 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3998 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3999 return false;
4000 if (!IfFalseBB->phis().empty())
4001 return false; // TODO
4002 // Use lambda to lazily compute expensive condition after cheap ones.
4003 auto NoSideEffects = [](BasicBlock &BB) {
4004 return llvm::none_of(BB, [](const Instruction &I) {
4005 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4008 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4009 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4010 NoSideEffects(*BI->getParent())) {
4011 auto *OldSuccessor = BI->getSuccessor(1);
4012 OldSuccessor->removePredecessor(BI->getParent());
4013 BI->setSuccessor(1, IfFalseBB);
4014 if (DTU)
4015 DTU->applyUpdates(
4016 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4017 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4018 return true;
4020 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4021 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4022 NoSideEffects(*BI->getParent())) {
4023 auto *OldSuccessor = BI->getSuccessor(0);
4024 OldSuccessor->removePredecessor(BI->getParent());
4025 BI->setSuccessor(0, IfFalseBB);
4026 if (DTU)
4027 DTU->applyUpdates(
4028 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4029 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4030 return true;
4032 return false;
4035 /// If we have a conditional branch as a predecessor of another block,
4036 /// this function tries to simplify it. We know
4037 /// that PBI and BI are both conditional branches, and BI is in one of the
4038 /// successor blocks of PBI - PBI branches to BI.
4039 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
4040 DomTreeUpdater *DTU,
4041 const DataLayout &DL,
4042 const TargetTransformInfo &TTI) {
4043 assert(PBI->isConditional() && BI->isConditional());
4044 BasicBlock *BB = BI->getParent();
4046 // If this block ends with a branch instruction, and if there is a
4047 // predecessor that ends on a branch of the same condition, make
4048 // this conditional branch redundant.
4049 if (PBI->getCondition() == BI->getCondition() &&
4050 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4051 // Okay, the outcome of this conditional branch is statically
4052 // knowable. If this block had a single pred, handle specially, otherwise
4053 // FoldCondBranchOnValueKnownInPredecessor() will handle it.
4054 if (BB->getSinglePredecessor()) {
4055 // Turn this into a branch on constant.
4056 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4057 BI->setCondition(
4058 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4059 return true; // Nuke the branch on constant.
4063 // If the previous block ended with a widenable branch, determine if reusing
4064 // the target block is profitable and legal. This will have the effect of
4065 // "widening" PBI, but doesn't require us to reason about hosting safety.
4066 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4067 return true;
4069 // If both branches are conditional and both contain stores to the same
4070 // address, remove the stores from the conditionals and create a conditional
4071 // merged store at the end.
4072 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4073 return true;
4075 // If this is a conditional branch in an empty block, and if any
4076 // predecessors are a conditional branch to one of our destinations,
4077 // fold the conditions into logical ops and one cond br.
4079 // Ignore dbg intrinsics.
4080 if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4081 return false;
4083 int PBIOp, BIOp;
4084 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4085 PBIOp = 0;
4086 BIOp = 0;
4087 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4088 PBIOp = 0;
4089 BIOp = 1;
4090 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4091 PBIOp = 1;
4092 BIOp = 0;
4093 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4094 PBIOp = 1;
4095 BIOp = 1;
4096 } else {
4097 return false;
4100 // Check to make sure that the other destination of this branch
4101 // isn't BB itself. If so, this is an infinite loop that will
4102 // keep getting unwound.
4103 if (PBI->getSuccessor(PBIOp) == BB)
4104 return false;
4106 // Do not perform this transformation if it would require
4107 // insertion of a large number of select instructions. For targets
4108 // without predication/cmovs, this is a big pessimization.
4110 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4111 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4112 unsigned NumPhis = 0;
4113 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4114 ++II, ++NumPhis) {
4115 if (NumPhis > 2) // Disable this xform.
4116 return false;
4119 // Finally, if everything is ok, fold the branches to logical ops.
4120 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4122 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4123 << "AND: " << *BI->getParent());
4125 SmallVector<DominatorTree::UpdateType, 5> Updates;
4127 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4128 // branch in it, where one edge (OtherDest) goes back to itself but the other
4129 // exits. We don't *know* that the program avoids the infinite loop
4130 // (even though that seems likely). If we do this xform naively, we'll end up
4131 // recursively unpeeling the loop. Since we know that (after the xform is
4132 // done) that the block *is* infinite if reached, we just make it an obviously
4133 // infinite loop with no cond branch.
4134 if (OtherDest == BB) {
4135 // Insert it at the end of the function, because it's either code,
4136 // or it won't matter if it's hot. :)
4137 BasicBlock *InfLoopBlock =
4138 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4139 BranchInst::Create(InfLoopBlock, InfLoopBlock);
4140 if (DTU)
4141 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4142 OtherDest = InfLoopBlock;
4145 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4147 // BI may have other predecessors. Because of this, we leave
4148 // it alone, but modify PBI.
4150 // Make sure we get to CommonDest on True&True directions.
4151 Value *PBICond = PBI->getCondition();
4152 IRBuilder<NoFolder> Builder(PBI);
4153 if (PBIOp)
4154 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4156 Value *BICond = BI->getCondition();
4157 if (BIOp)
4158 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4160 // Merge the conditions.
4161 Value *Cond =
4162 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4164 // Modify PBI to branch on the new condition to the new dests.
4165 PBI->setCondition(Cond);
4166 PBI->setSuccessor(0, CommonDest);
4167 PBI->setSuccessor(1, OtherDest);
4169 if (DTU) {
4170 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4171 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4173 DTU->applyUpdates(Updates);
4176 // Update branch weight for PBI.
4177 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4178 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4179 bool HasWeights =
4180 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4181 SuccTrueWeight, SuccFalseWeight);
4182 if (HasWeights) {
4183 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4184 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4185 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4186 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4187 // The weight to CommonDest should be PredCommon * SuccTotal +
4188 // PredOther * SuccCommon.
4189 // The weight to OtherDest should be PredOther * SuccOther.
4190 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4191 PredOther * SuccCommon,
4192 PredOther * SuccOther};
4193 // Halve the weights if any of them cannot fit in an uint32_t
4194 FitWeights(NewWeights);
4196 setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4199 // OtherDest may have phi nodes. If so, add an entry from PBI's
4200 // block that are identical to the entries for BI's block.
4201 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4203 // We know that the CommonDest already had an edge from PBI to
4204 // it. If it has PHIs though, the PHIs may have different
4205 // entries for BB and PBI's BB. If so, insert a select to make
4206 // them agree.
4207 for (PHINode &PN : CommonDest->phis()) {
4208 Value *BIV = PN.getIncomingValueForBlock(BB);
4209 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4210 Value *PBIV = PN.getIncomingValue(PBBIdx);
4211 if (BIV != PBIV) {
4212 // Insert a select in PBI to pick the right value.
4213 SelectInst *NV = cast<SelectInst>(
4214 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4215 PN.setIncomingValue(PBBIdx, NV);
4216 // Although the select has the same condition as PBI, the original branch
4217 // weights for PBI do not apply to the new select because the select's
4218 // 'logical' edges are incoming edges of the phi that is eliminated, not
4219 // the outgoing edges of PBI.
4220 if (HasWeights) {
4221 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4222 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4223 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4224 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4225 // The weight to PredCommonDest should be PredCommon * SuccTotal.
4226 // The weight to PredOtherDest should be PredOther * SuccCommon.
4227 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4228 PredOther * SuccCommon};
4230 FitWeights(NewWeights);
4232 setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4237 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4238 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4240 // This basic block is probably dead. We know it has at least
4241 // one fewer predecessor.
4242 return true;
4245 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4246 // true or to FalseBB if Cond is false.
4247 // Takes care of updating the successors and removing the old terminator.
4248 // Also makes sure not to introduce new successors by assuming that edges to
4249 // non-successor TrueBBs and FalseBBs aren't reachable.
4250 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4251 Value *Cond, BasicBlock *TrueBB,
4252 BasicBlock *FalseBB,
4253 uint32_t TrueWeight,
4254 uint32_t FalseWeight) {
4255 auto *BB = OldTerm->getParent();
4256 // Remove any superfluous successor edges from the CFG.
4257 // First, figure out which successors to preserve.
4258 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4259 // successor.
4260 BasicBlock *KeepEdge1 = TrueBB;
4261 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4263 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4265 // Then remove the rest.
4266 for (BasicBlock *Succ : successors(OldTerm)) {
4267 // Make sure only to keep exactly one copy of each edge.
4268 if (Succ == KeepEdge1)
4269 KeepEdge1 = nullptr;
4270 else if (Succ == KeepEdge2)
4271 KeepEdge2 = nullptr;
4272 else {
4273 Succ->removePredecessor(BB,
4274 /*KeepOneInputPHIs=*/true);
4276 if (Succ != TrueBB && Succ != FalseBB)
4277 RemovedSuccessors.insert(Succ);
4281 IRBuilder<> Builder(OldTerm);
4282 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4284 // Insert an appropriate new terminator.
4285 if (!KeepEdge1 && !KeepEdge2) {
4286 if (TrueBB == FalseBB) {
4287 // We were only looking for one successor, and it was present.
4288 // Create an unconditional branch to it.
4289 Builder.CreateBr(TrueBB);
4290 } else {
4291 // We found both of the successors we were looking for.
4292 // Create a conditional branch sharing the condition of the select.
4293 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4294 if (TrueWeight != FalseWeight)
4295 setBranchWeights(NewBI, TrueWeight, FalseWeight);
4297 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4298 // Neither of the selected blocks were successors, so this
4299 // terminator must be unreachable.
4300 new UnreachableInst(OldTerm->getContext(), OldTerm);
4301 } else {
4302 // One of the selected values was a successor, but the other wasn't.
4303 // Insert an unconditional branch to the one that was found;
4304 // the edge to the one that wasn't must be unreachable.
4305 if (!KeepEdge1) {
4306 // Only TrueBB was found.
4307 Builder.CreateBr(TrueBB);
4308 } else {
4309 // Only FalseBB was found.
4310 Builder.CreateBr(FalseBB);
4314 EraseTerminatorAndDCECond(OldTerm);
4316 if (DTU) {
4317 SmallVector<DominatorTree::UpdateType, 2> Updates;
4318 Updates.reserve(RemovedSuccessors.size());
4319 for (auto *RemovedSuccessor : RemovedSuccessors)
4320 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4321 DTU->applyUpdates(Updates);
4324 return true;
4327 // Replaces
4328 // (switch (select cond, X, Y)) on constant X, Y
4329 // with a branch - conditional if X and Y lead to distinct BBs,
4330 // unconditional otherwise.
4331 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4332 SelectInst *Select) {
4333 // Check for constant integer values in the select.
4334 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4335 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4336 if (!TrueVal || !FalseVal)
4337 return false;
4339 // Find the relevant condition and destinations.
4340 Value *Condition = Select->getCondition();
4341 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4342 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4344 // Get weight for TrueBB and FalseBB.
4345 uint32_t TrueWeight = 0, FalseWeight = 0;
4346 SmallVector<uint64_t, 8> Weights;
4347 bool HasWeights = hasBranchWeightMD(*SI);
4348 if (HasWeights) {
4349 GetBranchWeights(SI, Weights);
4350 if (Weights.size() == 1 + SI->getNumCases()) {
4351 TrueWeight =
4352 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4353 FalseWeight =
4354 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4358 // Perform the actual simplification.
4359 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4360 FalseWeight);
4363 // Replaces
4364 // (indirectbr (select cond, blockaddress(@fn, BlockA),
4365 // blockaddress(@fn, BlockB)))
4366 // with
4367 // (br cond, BlockA, BlockB).
4368 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4369 SelectInst *SI) {
4370 // Check that both operands of the select are block addresses.
4371 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4372 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4373 if (!TBA || !FBA)
4374 return false;
4376 // Extract the actual blocks.
4377 BasicBlock *TrueBB = TBA->getBasicBlock();
4378 BasicBlock *FalseBB = FBA->getBasicBlock();
4380 // Perform the actual simplification.
4381 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4385 /// This is called when we find an icmp instruction
4386 /// (a seteq/setne with a constant) as the only instruction in a
4387 /// block that ends with an uncond branch. We are looking for a very specific
4388 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4389 /// this case, we merge the first two "or's of icmp" into a switch, but then the
4390 /// default value goes to an uncond block with a seteq in it, we get something
4391 /// like:
4393 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4394 /// DEFAULT:
4395 /// %tmp = icmp eq i8 %A, 92
4396 /// br label %end
4397 /// end:
4398 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4400 /// We prefer to split the edge to 'end' so that there is a true/false entry to
4401 /// the PHI, merging the third icmp into the switch.
4402 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4403 ICmpInst *ICI, IRBuilder<> &Builder) {
4404 BasicBlock *BB = ICI->getParent();
4406 // If the block has any PHIs in it or the icmp has multiple uses, it is too
4407 // complex.
4408 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4409 return false;
4411 Value *V = ICI->getOperand(0);
4412 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4414 // The pattern we're looking for is where our only predecessor is a switch on
4415 // 'V' and this block is the default case for the switch. In this case we can
4416 // fold the compared value into the switch to simplify things.
4417 BasicBlock *Pred = BB->getSinglePredecessor();
4418 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4419 return false;
4421 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4422 if (SI->getCondition() != V)
4423 return false;
4425 // If BB is reachable on a non-default case, then we simply know the value of
4426 // V in this block. Substitute it and constant fold the icmp instruction
4427 // away.
4428 if (SI->getDefaultDest() != BB) {
4429 ConstantInt *VVal = SI->findCaseDest(BB);
4430 assert(VVal && "Should have a unique destination value");
4431 ICI->setOperand(0, VVal);
4433 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
4434 ICI->replaceAllUsesWith(V);
4435 ICI->eraseFromParent();
4437 // BB is now empty, so it is likely to simplify away.
4438 return requestResimplify();
4441 // Ok, the block is reachable from the default dest. If the constant we're
4442 // comparing exists in one of the other edges, then we can constant fold ICI
4443 // and zap it.
4444 if (SI->findCaseValue(Cst) != SI->case_default()) {
4445 Value *V;
4446 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4447 V = ConstantInt::getFalse(BB->getContext());
4448 else
4449 V = ConstantInt::getTrue(BB->getContext());
4451 ICI->replaceAllUsesWith(V);
4452 ICI->eraseFromParent();
4453 // BB is now empty, so it is likely to simplify away.
4454 return requestResimplify();
4457 // The use of the icmp has to be in the 'end' block, by the only PHI node in
4458 // the block.
4459 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4460 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4461 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4462 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4463 return false;
4465 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4466 // true in the PHI.
4467 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4468 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4470 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4471 std::swap(DefaultCst, NewCst);
4473 // Replace ICI (which is used by the PHI for the default value) with true or
4474 // false depending on if it is EQ or NE.
4475 ICI->replaceAllUsesWith(DefaultCst);
4476 ICI->eraseFromParent();
4478 SmallVector<DominatorTree::UpdateType, 2> Updates;
4480 // Okay, the switch goes to this block on a default value. Add an edge from
4481 // the switch to the merge point on the compared value.
4482 BasicBlock *NewBB =
4483 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4485 SwitchInstProfUpdateWrapper SIW(*SI);
4486 auto W0 = SIW.getSuccessorWeight(0);
4487 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
4488 if (W0) {
4489 NewW = ((uint64_t(*W0) + 1) >> 1);
4490 SIW.setSuccessorWeight(0, *NewW);
4492 SIW.addCase(Cst, NewBB, NewW);
4493 if (DTU)
4494 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4497 // NewBB branches to the phi block, add the uncond branch and the phi entry.
4498 Builder.SetInsertPoint(NewBB);
4499 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4500 Builder.CreateBr(SuccBlock);
4501 PHIUse->addIncoming(NewCst, NewBB);
4502 if (DTU) {
4503 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4504 DTU->applyUpdates(Updates);
4506 return true;
4509 /// The specified branch is a conditional branch.
4510 /// Check to see if it is branching on an or/and chain of icmp instructions, and
4511 /// fold it into a switch instruction if so.
4512 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4513 IRBuilder<> &Builder,
4514 const DataLayout &DL) {
4515 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4516 if (!Cond)
4517 return false;
4519 // Change br (X == 0 | X == 1), T, F into a switch instruction.
4520 // If this is a bunch of seteq's or'd together, or if it's a bunch of
4521 // 'setne's and'ed together, collect them.
4523 // Try to gather values from a chain of and/or to be turned into a switch
4524 ConstantComparesGatherer ConstantCompare(Cond, DL);
4525 // Unpack the result
4526 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4527 Value *CompVal = ConstantCompare.CompValue;
4528 unsigned UsedICmps = ConstantCompare.UsedICmps;
4529 Value *ExtraCase = ConstantCompare.Extra;
4531 // If we didn't have a multiply compared value, fail.
4532 if (!CompVal)
4533 return false;
4535 // Avoid turning single icmps into a switch.
4536 if (UsedICmps <= 1)
4537 return false;
4539 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4541 // There might be duplicate constants in the list, which the switch
4542 // instruction can't handle, remove them now.
4543 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4544 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4546 // If Extra was used, we require at least two switch values to do the
4547 // transformation. A switch with one value is just a conditional branch.
4548 if (ExtraCase && Values.size() < 2)
4549 return false;
4551 // TODO: Preserve branch weight metadata, similarly to how
4552 // FoldValueComparisonIntoPredecessors preserves it.
4554 // Figure out which block is which destination.
4555 BasicBlock *DefaultBB = BI->getSuccessor(1);
4556 BasicBlock *EdgeBB = BI->getSuccessor(0);
4557 if (!TrueWhenEqual)
4558 std::swap(DefaultBB, EdgeBB);
4560 BasicBlock *BB = BI->getParent();
4562 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4563 << " cases into SWITCH. BB is:\n"
4564 << *BB);
4566 SmallVector<DominatorTree::UpdateType, 2> Updates;
4568 // If there are any extra values that couldn't be folded into the switch
4569 // then we evaluate them with an explicit branch first. Split the block
4570 // right before the condbr to handle it.
4571 if (ExtraCase) {
4572 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4573 /*MSSAU=*/nullptr, "switch.early.test");
4575 // Remove the uncond branch added to the old block.
4576 Instruction *OldTI = BB->getTerminator();
4577 Builder.SetInsertPoint(OldTI);
4579 // There can be an unintended UB if extra values are Poison. Before the
4580 // transformation, extra values may not be evaluated according to the
4581 // condition, and it will not raise UB. But after transformation, we are
4582 // evaluating extra values before checking the condition, and it will raise
4583 // UB. It can be solved by adding freeze instruction to extra values.
4584 AssumptionCache *AC = Options.AC;
4586 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4587 ExtraCase = Builder.CreateFreeze(ExtraCase);
4589 if (TrueWhenEqual)
4590 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4591 else
4592 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4594 OldTI->eraseFromParent();
4596 if (DTU)
4597 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4599 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4600 // for the edge we just added.
4601 AddPredecessorToBlock(EdgeBB, BB, NewBB);
4603 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
4604 << "\nEXTRABB = " << *BB);
4605 BB = NewBB;
4608 Builder.SetInsertPoint(BI);
4609 // Convert pointer to int before we switch.
4610 if (CompVal->getType()->isPointerTy()) {
4611 CompVal = Builder.CreatePtrToInt(
4612 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4615 // Create the new switch instruction now.
4616 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4618 // Add all of the 'cases' to the switch instruction.
4619 for (unsigned i = 0, e = Values.size(); i != e; ++i)
4620 New->addCase(Values[i], EdgeBB);
4622 // We added edges from PI to the EdgeBB. As such, if there were any
4623 // PHI nodes in EdgeBB, they need entries to be added corresponding to
4624 // the number of edges added.
4625 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4626 PHINode *PN = cast<PHINode>(BBI);
4627 Value *InVal = PN->getIncomingValueForBlock(BB);
4628 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4629 PN->addIncoming(InVal, BB);
4632 // Erase the old branch instruction.
4633 EraseTerminatorAndDCECond(BI);
4634 if (DTU)
4635 DTU->applyUpdates(Updates);
4637 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
4638 return true;
4641 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4642 if (isa<PHINode>(RI->getValue()))
4643 return simplifyCommonResume(RI);
4644 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4645 RI->getValue() == RI->getParent()->getFirstNonPHI())
4646 // The resume must unwind the exception that caused control to branch here.
4647 return simplifySingleResume(RI);
4649 return false;
4652 // Check if cleanup block is empty
4653 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4654 for (Instruction &I : R) {
4655 auto *II = dyn_cast<IntrinsicInst>(&I);
4656 if (!II)
4657 return false;
4659 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4660 switch (IntrinsicID) {
4661 case Intrinsic::dbg_declare:
4662 case Intrinsic::dbg_value:
4663 case Intrinsic::dbg_label:
4664 case Intrinsic::lifetime_end:
4665 break;
4666 default:
4667 return false;
4670 return true;
4673 // Simplify resume that is shared by several landing pads (phi of landing pad).
4674 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4675 BasicBlock *BB = RI->getParent();
4677 // Check that there are no other instructions except for debug and lifetime
4678 // intrinsics between the phi's and resume instruction.
4679 if (!isCleanupBlockEmpty(
4680 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4681 return false;
4683 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4684 auto *PhiLPInst = cast<PHINode>(RI->getValue());
4686 // Check incoming blocks to see if any of them are trivial.
4687 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4688 Idx++) {
4689 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4690 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4692 // If the block has other successors, we can not delete it because
4693 // it has other dependents.
4694 if (IncomingBB->getUniqueSuccessor() != BB)
4695 continue;
4697 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4698 // Not the landing pad that caused the control to branch here.
4699 if (IncomingValue != LandingPad)
4700 continue;
4702 if (isCleanupBlockEmpty(
4703 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4704 TrivialUnwindBlocks.insert(IncomingBB);
4707 // If no trivial unwind blocks, don't do any simplifications.
4708 if (TrivialUnwindBlocks.empty())
4709 return false;
4711 // Turn all invokes that unwind here into calls.
4712 for (auto *TrivialBB : TrivialUnwindBlocks) {
4713 // Blocks that will be simplified should be removed from the phi node.
4714 // Note there could be multiple edges to the resume block, and we need
4715 // to remove them all.
4716 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4717 BB->removePredecessor(TrivialBB, true);
4719 for (BasicBlock *Pred :
4720 llvm::make_early_inc_range(predecessors(TrivialBB))) {
4721 removeUnwindEdge(Pred, DTU);
4722 ++NumInvokes;
4725 // In each SimplifyCFG run, only the current processed block can be erased.
4726 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4727 // of erasing TrivialBB, we only remove the branch to the common resume
4728 // block so that we can later erase the resume block since it has no
4729 // predecessors.
4730 TrivialBB->getTerminator()->eraseFromParent();
4731 new UnreachableInst(RI->getContext(), TrivialBB);
4732 if (DTU)
4733 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4736 // Delete the resume block if all its predecessors have been removed.
4737 if (pred_empty(BB))
4738 DeleteDeadBlock(BB, DTU);
4740 return !TrivialUnwindBlocks.empty();
4743 // Simplify resume that is only used by a single (non-phi) landing pad.
4744 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4745 BasicBlock *BB = RI->getParent();
4746 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4747 assert(RI->getValue() == LPInst &&
4748 "Resume must unwind the exception that caused control to here");
4750 // Check that there are no other instructions except for debug intrinsics.
4751 if (!isCleanupBlockEmpty(
4752 make_range<Instruction *>(LPInst->getNextNode(), RI)))
4753 return false;
4755 // Turn all invokes that unwind here into calls and delete the basic block.
4756 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
4757 removeUnwindEdge(Pred, DTU);
4758 ++NumInvokes;
4761 // The landingpad is now unreachable. Zap it.
4762 DeleteDeadBlock(BB, DTU);
4763 return true;
4766 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
4767 // If this is a trivial cleanup pad that executes no instructions, it can be
4768 // eliminated. If the cleanup pad continues to the caller, any predecessor
4769 // that is an EH pad will be updated to continue to the caller and any
4770 // predecessor that terminates with an invoke instruction will have its invoke
4771 // instruction converted to a call instruction. If the cleanup pad being
4772 // simplified does not continue to the caller, each predecessor will be
4773 // updated to continue to the unwind destination of the cleanup pad being
4774 // simplified.
4775 BasicBlock *BB = RI->getParent();
4776 CleanupPadInst *CPInst = RI->getCleanupPad();
4777 if (CPInst->getParent() != BB)
4778 // This isn't an empty cleanup.
4779 return false;
4781 // We cannot kill the pad if it has multiple uses. This typically arises
4782 // from unreachable basic blocks.
4783 if (!CPInst->hasOneUse())
4784 return false;
4786 // Check that there are no other instructions except for benign intrinsics.
4787 if (!isCleanupBlockEmpty(
4788 make_range<Instruction *>(CPInst->getNextNode(), RI)))
4789 return false;
4791 // If the cleanup return we are simplifying unwinds to the caller, this will
4792 // set UnwindDest to nullptr.
4793 BasicBlock *UnwindDest = RI->getUnwindDest();
4794 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4796 // We're about to remove BB from the control flow. Before we do, sink any
4797 // PHINodes into the unwind destination. Doing this before changing the
4798 // control flow avoids some potentially slow checks, since we can currently
4799 // be certain that UnwindDest and BB have no common predecessors (since they
4800 // are both EH pads).
4801 if (UnwindDest) {
4802 // First, go through the PHI nodes in UnwindDest and update any nodes that
4803 // reference the block we are removing
4804 for (PHINode &DestPN : UnwindDest->phis()) {
4805 int Idx = DestPN.getBasicBlockIndex(BB);
4806 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4807 assert(Idx != -1);
4808 // This PHI node has an incoming value that corresponds to a control
4809 // path through the cleanup pad we are removing. If the incoming
4810 // value is in the cleanup pad, it must be a PHINode (because we
4811 // verified above that the block is otherwise empty). Otherwise, the
4812 // value is either a constant or a value that dominates the cleanup
4813 // pad being removed.
4815 // Because BB and UnwindDest are both EH pads, all of their
4816 // predecessors must unwind to these blocks, and since no instruction
4817 // can have multiple unwind destinations, there will be no overlap in
4818 // incoming blocks between SrcPN and DestPN.
4819 Value *SrcVal = DestPN.getIncomingValue(Idx);
4820 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4822 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4823 for (auto *Pred : predecessors(BB)) {
4824 Value *Incoming =
4825 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4826 DestPN.addIncoming(Incoming, Pred);
4830 // Sink any remaining PHI nodes directly into UnwindDest.
4831 Instruction *InsertPt = DestEHPad;
4832 for (PHINode &PN : make_early_inc_range(BB->phis())) {
4833 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4834 // If the PHI node has no uses or all of its uses are in this basic
4835 // block (meaning they are debug or lifetime intrinsics), just leave
4836 // it. It will be erased when we erase BB below.
4837 continue;
4839 // Otherwise, sink this PHI node into UnwindDest.
4840 // Any predecessors to UnwindDest which are not already represented
4841 // must be back edges which inherit the value from the path through
4842 // BB. In this case, the PHI value must reference itself.
4843 for (auto *pred : predecessors(UnwindDest))
4844 if (pred != BB)
4845 PN.addIncoming(&PN, pred);
4846 PN.moveBefore(InsertPt);
4847 // Also, add a dummy incoming value for the original BB itself,
4848 // so that the PHI is well-formed until we drop said predecessor.
4849 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
4853 std::vector<DominatorTree::UpdateType> Updates;
4855 // We use make_early_inc_range here because we will remove all predecessors.
4856 for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) {
4857 if (UnwindDest == nullptr) {
4858 if (DTU) {
4859 DTU->applyUpdates(Updates);
4860 Updates.clear();
4862 removeUnwindEdge(PredBB, DTU);
4863 ++NumInvokes;
4864 } else {
4865 BB->removePredecessor(PredBB);
4866 Instruction *TI = PredBB->getTerminator();
4867 TI->replaceUsesOfWith(BB, UnwindDest);
4868 if (DTU) {
4869 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
4870 Updates.push_back({DominatorTree::Delete, PredBB, BB});
4875 if (DTU)
4876 DTU->applyUpdates(Updates);
4878 DeleteDeadBlock(BB, DTU);
4880 return true;
4883 // Try to merge two cleanuppads together.
4884 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4885 // Skip any cleanuprets which unwind to caller, there is nothing to merge
4886 // with.
4887 BasicBlock *UnwindDest = RI->getUnwindDest();
4888 if (!UnwindDest)
4889 return false;
4891 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4892 // be safe to merge without code duplication.
4893 if (UnwindDest->getSinglePredecessor() != RI->getParent())
4894 return false;
4896 // Verify that our cleanuppad's unwind destination is another cleanuppad.
4897 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4898 if (!SuccessorCleanupPad)
4899 return false;
4901 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4902 // Replace any uses of the successor cleanupad with the predecessor pad
4903 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4904 // funclet bundle operands.
4905 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4906 // Remove the old cleanuppad.
4907 SuccessorCleanupPad->eraseFromParent();
4908 // Now, we simply replace the cleanupret with a branch to the unwind
4909 // destination.
4910 BranchInst::Create(UnwindDest, RI->getParent());
4911 RI->eraseFromParent();
4913 return true;
4916 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4917 // It is possible to transiantly have an undef cleanuppad operand because we
4918 // have deleted some, but not all, dead blocks.
4919 // Eventually, this block will be deleted.
4920 if (isa<UndefValue>(RI->getOperand(0)))
4921 return false;
4923 if (mergeCleanupPad(RI))
4924 return true;
4926 if (removeEmptyCleanup(RI, DTU))
4927 return true;
4929 return false;
4932 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
4933 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4934 BasicBlock *BB = UI->getParent();
4936 bool Changed = false;
4938 // If there are any instructions immediately before the unreachable that can
4939 // be removed, do so.
4940 while (UI->getIterator() != BB->begin()) {
4941 BasicBlock::iterator BBI = UI->getIterator();
4942 --BBI;
4944 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
4945 break; // Can not drop any more instructions. We're done here.
4946 // Otherwise, this instruction can be freely erased,
4947 // even if it is not side-effect free.
4949 // Note that deleting EH's here is in fact okay, although it involves a bit
4950 // of subtle reasoning. If this inst is an EH, all the predecessors of this
4951 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
4952 // and we can therefore guarantee this block will be erased.
4954 // Delete this instruction (any uses are guaranteed to be dead)
4955 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
4956 BBI->eraseFromParent();
4957 Changed = true;
4960 // If the unreachable instruction is the first in the block, take a gander
4961 // at all of the predecessors of this instruction, and simplify them.
4962 if (&BB->front() != UI)
4963 return Changed;
4965 std::vector<DominatorTree::UpdateType> Updates;
4967 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4968 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4969 auto *Predecessor = Preds[i];
4970 Instruction *TI = Predecessor->getTerminator();
4971 IRBuilder<> Builder(TI);
4972 if (auto *BI = dyn_cast<BranchInst>(TI)) {
4973 // We could either have a proper unconditional branch,
4974 // or a degenerate conditional branch with matching destinations.
4975 if (all_of(BI->successors(),
4976 [BB](auto *Successor) { return Successor == BB; })) {
4977 new UnreachableInst(TI->getContext(), TI);
4978 TI->eraseFromParent();
4979 Changed = true;
4980 } else {
4981 assert(BI->isConditional() && "Can't get here with an uncond branch.");
4982 Value* Cond = BI->getCondition();
4983 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4984 "The destinations are guaranteed to be different here.");
4985 if (BI->getSuccessor(0) == BB) {
4986 Builder.CreateAssumption(Builder.CreateNot(Cond));
4987 Builder.CreateBr(BI->getSuccessor(1));
4988 } else {
4989 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
4990 Builder.CreateAssumption(Cond);
4991 Builder.CreateBr(BI->getSuccessor(0));
4993 EraseTerminatorAndDCECond(BI);
4994 Changed = true;
4996 if (DTU)
4997 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4998 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4999 SwitchInstProfUpdateWrapper SU(*SI);
5000 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5001 if (i->getCaseSuccessor() != BB) {
5002 ++i;
5003 continue;
5005 BB->removePredecessor(SU->getParent());
5006 i = SU.removeCase(i);
5007 e = SU->case_end();
5008 Changed = true;
5010 // Note that the default destination can't be removed!
5011 if (DTU && SI->getDefaultDest() != BB)
5012 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5013 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
5014 if (II->getUnwindDest() == BB) {
5015 if (DTU) {
5016 DTU->applyUpdates(Updates);
5017 Updates.clear();
5019 removeUnwindEdge(TI->getParent(), DTU);
5020 Changed = true;
5022 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5023 if (CSI->getUnwindDest() == BB) {
5024 if (DTU) {
5025 DTU->applyUpdates(Updates);
5026 Updates.clear();
5028 removeUnwindEdge(TI->getParent(), DTU);
5029 Changed = true;
5030 continue;
5033 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5034 E = CSI->handler_end();
5035 I != E; ++I) {
5036 if (*I == BB) {
5037 CSI->removeHandler(I);
5038 --I;
5039 --E;
5040 Changed = true;
5043 if (DTU)
5044 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5045 if (CSI->getNumHandlers() == 0) {
5046 if (CSI->hasUnwindDest()) {
5047 // Redirect all predecessors of the block containing CatchSwitchInst
5048 // to instead branch to the CatchSwitchInst's unwind destination.
5049 if (DTU) {
5050 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
5051 Updates.push_back({DominatorTree::Insert,
5052 PredecessorOfPredecessor,
5053 CSI->getUnwindDest()});
5054 Updates.push_back({DominatorTree::Delete,
5055 PredecessorOfPredecessor, Predecessor});
5058 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
5059 } else {
5060 // Rewrite all preds to unwind to caller (or from invoke to call).
5061 if (DTU) {
5062 DTU->applyUpdates(Updates);
5063 Updates.clear();
5065 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
5066 for (BasicBlock *EHPred : EHPreds)
5067 removeUnwindEdge(EHPred, DTU);
5069 // The catchswitch is no longer reachable.
5070 new UnreachableInst(CSI->getContext(), CSI);
5071 CSI->eraseFromParent();
5072 Changed = true;
5074 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5075 (void)CRI;
5076 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5077 "Expected to always have an unwind to BB.");
5078 if (DTU)
5079 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
5080 new UnreachableInst(TI->getContext(), TI);
5081 TI->eraseFromParent();
5082 Changed = true;
5086 if (DTU)
5087 DTU->applyUpdates(Updates);
5089 // If this block is now dead, remove it.
5090 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5091 DeleteDeadBlock(BB, DTU);
5092 return true;
5095 return Changed;
5098 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
5099 assert(Cases.size() >= 1);
5101 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
5102 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
5103 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
5104 return false;
5106 return true;
5109 static void createUnreachableSwitchDefault(SwitchInst *Switch,
5110 DomTreeUpdater *DTU) {
5111 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
5112 auto *BB = Switch->getParent();
5113 auto *OrigDefaultBlock = Switch->getDefaultDest();
5114 OrigDefaultBlock->removePredecessor(BB);
5115 BasicBlock *NewDefaultBlock = BasicBlock::Create(
5116 BB->getContext(), BB->getName() + ".unreachabledefault", BB->getParent(),
5117 OrigDefaultBlock);
5118 new UnreachableInst(Switch->getContext(), NewDefaultBlock);
5119 Switch->setDefaultDest(&*NewDefaultBlock);
5120 if (DTU) {
5121 SmallVector<DominatorTree::UpdateType, 2> Updates;
5122 Updates.push_back({DominatorTree::Insert, BB, &*NewDefaultBlock});
5123 if (!is_contained(successors(BB), OrigDefaultBlock))
5124 Updates.push_back({DominatorTree::Delete, BB, &*OrigDefaultBlock});
5125 DTU->applyUpdates(Updates);
5129 /// Turn a switch into an integer range comparison and branch.
5130 /// Switches with more than 2 destinations are ignored.
5131 /// Switches with 1 destination are also ignored.
5132 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
5133 IRBuilder<> &Builder) {
5134 assert(SI->getNumCases() > 1 && "Degenerate switch?");
5136 bool HasDefault =
5137 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5139 auto *BB = SI->getParent();
5141 // Partition the cases into two sets with different destinations.
5142 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
5143 BasicBlock *DestB = nullptr;
5144 SmallVector<ConstantInt *, 16> CasesA;
5145 SmallVector<ConstantInt *, 16> CasesB;
5147 for (auto Case : SI->cases()) {
5148 BasicBlock *Dest = Case.getCaseSuccessor();
5149 if (!DestA)
5150 DestA = Dest;
5151 if (Dest == DestA) {
5152 CasesA.push_back(Case.getCaseValue());
5153 continue;
5155 if (!DestB)
5156 DestB = Dest;
5157 if (Dest == DestB) {
5158 CasesB.push_back(Case.getCaseValue());
5159 continue;
5161 return false; // More than two destinations.
5163 if (!DestB)
5164 return false; // All destinations are the same and the default is unreachable
5166 assert(DestA && DestB &&
5167 "Single-destination switch should have been folded.");
5168 assert(DestA != DestB);
5169 assert(DestB != SI->getDefaultDest());
5170 assert(!CasesB.empty() && "There must be non-default cases.");
5171 assert(!CasesA.empty() || HasDefault);
5173 // Figure out if one of the sets of cases form a contiguous range.
5174 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
5175 BasicBlock *ContiguousDest = nullptr;
5176 BasicBlock *OtherDest = nullptr;
5177 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
5178 ContiguousCases = &CasesA;
5179 ContiguousDest = DestA;
5180 OtherDest = DestB;
5181 } else if (CasesAreContiguous(CasesB)) {
5182 ContiguousCases = &CasesB;
5183 ContiguousDest = DestB;
5184 OtherDest = DestA;
5185 } else
5186 return false;
5188 // Start building the compare and branch.
5190 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
5191 Constant *NumCases =
5192 ConstantInt::get(Offset->getType(), ContiguousCases->size());
5194 Value *Sub = SI->getCondition();
5195 if (!Offset->isNullValue())
5196 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
5198 Value *Cmp;
5199 // If NumCases overflowed, then all possible values jump to the successor.
5200 if (NumCases->isNullValue() && !ContiguousCases->empty())
5201 Cmp = ConstantInt::getTrue(SI->getContext());
5202 else
5203 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
5204 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
5206 // Update weight for the newly-created conditional branch.
5207 if (hasBranchWeightMD(*SI)) {
5208 SmallVector<uint64_t, 8> Weights;
5209 GetBranchWeights(SI, Weights);
5210 if (Weights.size() == 1 + SI->getNumCases()) {
5211 uint64_t TrueWeight = 0;
5212 uint64_t FalseWeight = 0;
5213 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
5214 if (SI->getSuccessor(I) == ContiguousDest)
5215 TrueWeight += Weights[I];
5216 else
5217 FalseWeight += Weights[I];
5219 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
5220 TrueWeight /= 2;
5221 FalseWeight /= 2;
5223 setBranchWeights(NewBI, TrueWeight, FalseWeight);
5227 // Prune obsolete incoming values off the successors' PHI nodes.
5228 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
5229 unsigned PreviousEdges = ContiguousCases->size();
5230 if (ContiguousDest == SI->getDefaultDest())
5231 ++PreviousEdges;
5232 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5233 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5235 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
5236 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
5237 if (OtherDest == SI->getDefaultDest())
5238 ++PreviousEdges;
5239 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
5240 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
5243 // Clean up the default block - it may have phis or other instructions before
5244 // the unreachable terminator.
5245 if (!HasDefault)
5246 createUnreachableSwitchDefault(SI, DTU);
5248 auto *UnreachableDefault = SI->getDefaultDest();
5250 // Drop the switch.
5251 SI->eraseFromParent();
5253 if (!HasDefault && DTU)
5254 DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}});
5256 return true;
5259 /// Compute masked bits for the condition of a switch
5260 /// and use it to remove dead cases.
5261 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
5262 AssumptionCache *AC,
5263 const DataLayout &DL) {
5264 Value *Cond = SI->getCondition();
5265 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
5267 // We can also eliminate cases by determining that their values are outside of
5268 // the limited range of the condition based on how many significant (non-sign)
5269 // bits are in the condition value.
5270 unsigned MaxSignificantBitsInCond =
5271 ComputeMaxSignificantBits(Cond, DL, 0, AC, SI);
5273 // Gather dead cases.
5274 SmallVector<ConstantInt *, 8> DeadCases;
5275 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
5276 SmallVector<BasicBlock *, 8> UniqueSuccessors;
5277 for (const auto &Case : SI->cases()) {
5278 auto *Successor = Case.getCaseSuccessor();
5279 if (DTU) {
5280 if (!NumPerSuccessorCases.count(Successor))
5281 UniqueSuccessors.push_back(Successor);
5282 ++NumPerSuccessorCases[Successor];
5284 const APInt &CaseVal = Case.getCaseValue()->getValue();
5285 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
5286 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
5287 DeadCases.push_back(Case.getCaseValue());
5288 if (DTU)
5289 --NumPerSuccessorCases[Successor];
5290 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
5291 << " is dead.\n");
5295 // If we can prove that the cases must cover all possible values, the
5296 // default destination becomes dead and we can remove it. If we know some
5297 // of the bits in the value, we can use that to more precisely compute the
5298 // number of possible unique case values.
5299 bool HasDefault =
5300 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5301 const unsigned NumUnknownBits =
5302 Known.getBitWidth() - (Known.Zero | Known.One).countPopulation();
5303 assert(NumUnknownBits <= Known.getBitWidth());
5304 if (HasDefault && DeadCases.empty() &&
5305 NumUnknownBits < 64 /* avoid overflow */ &&
5306 SI->getNumCases() == (1ULL << NumUnknownBits)) {
5307 createUnreachableSwitchDefault(SI, DTU);
5308 return true;
5311 if (DeadCases.empty())
5312 return false;
5314 SwitchInstProfUpdateWrapper SIW(*SI);
5315 for (ConstantInt *DeadCase : DeadCases) {
5316 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
5317 assert(CaseI != SI->case_default() &&
5318 "Case was not found. Probably mistake in DeadCases forming.");
5319 // Prune unused values from PHI nodes.
5320 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
5321 SIW.removeCase(CaseI);
5324 if (DTU) {
5325 std::vector<DominatorTree::UpdateType> Updates;
5326 for (auto *Successor : UniqueSuccessors)
5327 if (NumPerSuccessorCases[Successor] == 0)
5328 Updates.push_back({DominatorTree::Delete, SI->getParent(), Successor});
5329 DTU->applyUpdates(Updates);
5332 return true;
5335 /// If BB would be eligible for simplification by
5336 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
5337 /// by an unconditional branch), look at the phi node for BB in the successor
5338 /// block and see if the incoming value is equal to CaseValue. If so, return
5339 /// the phi node, and set PhiIndex to BB's index in the phi node.
5340 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
5341 BasicBlock *BB, int *PhiIndex) {
5342 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
5343 return nullptr; // BB must be empty to be a candidate for simplification.
5344 if (!BB->getSinglePredecessor())
5345 return nullptr; // BB must be dominated by the switch.
5347 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
5348 if (!Branch || !Branch->isUnconditional())
5349 return nullptr; // Terminator must be unconditional branch.
5351 BasicBlock *Succ = Branch->getSuccessor(0);
5353 for (PHINode &PHI : Succ->phis()) {
5354 int Idx = PHI.getBasicBlockIndex(BB);
5355 assert(Idx >= 0 && "PHI has no entry for predecessor?");
5357 Value *InValue = PHI.getIncomingValue(Idx);
5358 if (InValue != CaseValue)
5359 continue;
5361 *PhiIndex = Idx;
5362 return &PHI;
5365 return nullptr;
5368 /// Try to forward the condition of a switch instruction to a phi node
5369 /// dominated by the switch, if that would mean that some of the destination
5370 /// blocks of the switch can be folded away. Return true if a change is made.
5371 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
5372 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
5374 ForwardingNodesMap ForwardingNodes;
5375 BasicBlock *SwitchBlock = SI->getParent();
5376 bool Changed = false;
5377 for (const auto &Case : SI->cases()) {
5378 ConstantInt *CaseValue = Case.getCaseValue();
5379 BasicBlock *CaseDest = Case.getCaseSuccessor();
5381 // Replace phi operands in successor blocks that are using the constant case
5382 // value rather than the switch condition variable:
5383 // switchbb:
5384 // switch i32 %x, label %default [
5385 // i32 17, label %succ
5386 // ...
5387 // succ:
5388 // %r = phi i32 ... [ 17, %switchbb ] ...
5389 // -->
5390 // %r = phi i32 ... [ %x, %switchbb ] ...
5392 for (PHINode &Phi : CaseDest->phis()) {
5393 // This only works if there is exactly 1 incoming edge from the switch to
5394 // a phi. If there is >1, that means multiple cases of the switch map to 1
5395 // value in the phi, and that phi value is not the switch condition. Thus,
5396 // this transform would not make sense (the phi would be invalid because
5397 // a phi can't have different incoming values from the same block).
5398 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
5399 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
5400 count(Phi.blocks(), SwitchBlock) == 1) {
5401 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
5402 Changed = true;
5406 // Collect phi nodes that are indirectly using this switch's case constants.
5407 int PhiIdx;
5408 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
5409 ForwardingNodes[Phi].push_back(PhiIdx);
5412 for (auto &ForwardingNode : ForwardingNodes) {
5413 PHINode *Phi = ForwardingNode.first;
5414 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
5415 if (Indexes.size() < 2)
5416 continue;
5418 for (int Index : Indexes)
5419 Phi->setIncomingValue(Index, SI->getCondition());
5420 Changed = true;
5423 return Changed;
5426 /// Return true if the backend will be able to handle
5427 /// initializing an array of constants like C.
5428 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
5429 if (C->isThreadDependent())
5430 return false;
5431 if (C->isDLLImportDependent())
5432 return false;
5434 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
5435 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
5436 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
5437 return false;
5439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5440 // Pointer casts and in-bounds GEPs will not prohibit the backend from
5441 // materializing the array of constants.
5442 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets());
5443 if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI))
5444 return false;
5447 if (!TTI.shouldBuildLookupTablesForConstant(C))
5448 return false;
5450 return true;
5453 /// If V is a Constant, return it. Otherwise, try to look up
5454 /// its constant value in ConstantPool, returning 0 if it's not there.
5455 static Constant *
5456 LookupConstant(Value *V,
5457 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5458 if (Constant *C = dyn_cast<Constant>(V))
5459 return C;
5460 return ConstantPool.lookup(V);
5463 /// Try to fold instruction I into a constant. This works for
5464 /// simple instructions such as binary operations where both operands are
5465 /// constant or can be replaced by constants from the ConstantPool. Returns the
5466 /// resulting constant on success, 0 otherwise.
5467 static Constant *
5468 ConstantFold(Instruction *I, const DataLayout &DL,
5469 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5470 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
5471 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
5472 if (!A)
5473 return nullptr;
5474 if (A->isAllOnesValue())
5475 return LookupConstant(Select->getTrueValue(), ConstantPool);
5476 if (A->isNullValue())
5477 return LookupConstant(Select->getFalseValue(), ConstantPool);
5478 return nullptr;
5481 SmallVector<Constant *, 4> COps;
5482 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
5483 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
5484 COps.push_back(A);
5485 else
5486 return nullptr;
5489 return ConstantFoldInstOperands(I, COps, DL);
5492 /// Try to determine the resulting constant values in phi nodes
5493 /// at the common destination basic block, *CommonDest, for one of the case
5494 /// destionations CaseDest corresponding to value CaseVal (0 for the default
5495 /// case), of a switch instruction SI.
5496 static bool
5497 getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
5498 BasicBlock **CommonDest,
5499 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
5500 const DataLayout &DL, const TargetTransformInfo &TTI) {
5501 // The block from which we enter the common destination.
5502 BasicBlock *Pred = SI->getParent();
5504 // If CaseDest is empty except for some side-effect free instructions through
5505 // which we can constant-propagate the CaseVal, continue to its successor.
5506 SmallDenseMap<Value *, Constant *> ConstantPool;
5507 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
5508 for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) {
5509 if (I.isTerminator()) {
5510 // If the terminator is a simple branch, continue to the next block.
5511 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
5512 return false;
5513 Pred = CaseDest;
5514 CaseDest = I.getSuccessor(0);
5515 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
5516 // Instruction is side-effect free and constant.
5518 // If the instruction has uses outside this block or a phi node slot for
5519 // the block, it is not safe to bypass the instruction since it would then
5520 // no longer dominate all its uses.
5521 for (auto &Use : I.uses()) {
5522 User *User = Use.getUser();
5523 if (Instruction *I = dyn_cast<Instruction>(User))
5524 if (I->getParent() == CaseDest)
5525 continue;
5526 if (PHINode *Phi = dyn_cast<PHINode>(User))
5527 if (Phi->getIncomingBlock(Use) == CaseDest)
5528 continue;
5529 return false;
5532 ConstantPool.insert(std::make_pair(&I, C));
5533 } else {
5534 break;
5538 // If we did not have a CommonDest before, use the current one.
5539 if (!*CommonDest)
5540 *CommonDest = CaseDest;
5541 // If the destination isn't the common one, abort.
5542 if (CaseDest != *CommonDest)
5543 return false;
5545 // Get the values for this case from phi nodes in the destination block.
5546 for (PHINode &PHI : (*CommonDest)->phis()) {
5547 int Idx = PHI.getBasicBlockIndex(Pred);
5548 if (Idx == -1)
5549 continue;
5551 Constant *ConstVal =
5552 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
5553 if (!ConstVal)
5554 return false;
5556 // Be conservative about which kinds of constants we support.
5557 if (!ValidLookupTableConstant(ConstVal, TTI))
5558 return false;
5560 Res.push_back(std::make_pair(&PHI, ConstVal));
5563 return Res.size() > 0;
5566 // Helper function used to add CaseVal to the list of cases that generate
5567 // Result. Returns the updated number of cases that generate this result.
5568 static size_t mapCaseToResult(ConstantInt *CaseVal,
5569 SwitchCaseResultVectorTy &UniqueResults,
5570 Constant *Result) {
5571 for (auto &I : UniqueResults) {
5572 if (I.first == Result) {
5573 I.second.push_back(CaseVal);
5574 return I.second.size();
5577 UniqueResults.push_back(
5578 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5579 return 1;
5582 // Helper function that initializes a map containing
5583 // results for the PHI node of the common destination block for a switch
5584 // instruction. Returns false if multiple PHI nodes have been found or if
5585 // there is not a common destination block for the switch.
5586 static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
5587 BasicBlock *&CommonDest,
5588 SwitchCaseResultVectorTy &UniqueResults,
5589 Constant *&DefaultResult,
5590 const DataLayout &DL,
5591 const TargetTransformInfo &TTI,
5592 uintptr_t MaxUniqueResults) {
5593 for (const auto &I : SI->cases()) {
5594 ConstantInt *CaseVal = I.getCaseValue();
5596 // Resulting value at phi nodes for this case value.
5597 SwitchCaseResultsTy Results;
5598 if (!getCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5599 DL, TTI))
5600 return false;
5602 // Only one value per case is permitted.
5603 if (Results.size() > 1)
5604 return false;
5606 // Add the case->result mapping to UniqueResults.
5607 const size_t NumCasesForResult =
5608 mapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5610 // Early out if there are too many cases for this result.
5611 if (NumCasesForResult > MaxSwitchCasesPerResult)
5612 return false;
5614 // Early out if there are too many unique results.
5615 if (UniqueResults.size() > MaxUniqueResults)
5616 return false;
5618 // Check the PHI consistency.
5619 if (!PHI)
5620 PHI = Results[0].first;
5621 else if (PHI != Results[0].first)
5622 return false;
5624 // Find the default result value.
5625 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5626 BasicBlock *DefaultDest = SI->getDefaultDest();
5627 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5628 DL, TTI);
5629 // If the default value is not found abort unless the default destination
5630 // is unreachable.
5631 DefaultResult =
5632 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5633 if ((!DefaultResult &&
5634 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5635 return false;
5637 return true;
5640 // Helper function that checks if it is possible to transform a switch with only
5641 // two cases (or two cases + default) that produces a result into a select.
5642 // TODO: Handle switches with more than 2 cases that map to the same result.
5643 static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
5644 Constant *DefaultResult, Value *Condition,
5645 IRBuilder<> &Builder) {
5646 // If we are selecting between only two cases transform into a simple
5647 // select or a two-way select if default is possible.
5648 // Example:
5649 // switch (a) { %0 = icmp eq i32 %a, 10
5650 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
5651 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
5652 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
5653 // }
5654 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
5655 ResultVector[1].second.size() == 1) {
5656 ConstantInt *FirstCase = ResultVector[0].second[0];
5657 ConstantInt *SecondCase = ResultVector[1].second[0];
5658 Value *SelectValue = ResultVector[1].first;
5659 if (DefaultResult) {
5660 Value *ValueCompare =
5661 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5662 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5663 DefaultResult, "switch.select");
5665 Value *ValueCompare =
5666 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5667 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5668 SelectValue, "switch.select");
5671 // Handle the degenerate case where two cases have the same result value.
5672 if (ResultVector.size() == 1 && DefaultResult) {
5673 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
5674 unsigned CaseCount = CaseValues.size();
5675 // n bits group cases map to the same result:
5676 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
5677 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
5678 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
5679 if (isPowerOf2_32(CaseCount)) {
5680 ConstantInt *MinCaseVal = CaseValues[0];
5681 // Find mininal value.
5682 for (auto Case : CaseValues)
5683 if (Case->getValue().slt(MinCaseVal->getValue()))
5684 MinCaseVal = Case;
5686 // Mark the bits case number touched.
5687 APInt BitMask = APInt::getZero(MinCaseVal->getBitWidth());
5688 for (auto Case : CaseValues)
5689 BitMask |= (Case->getValue() - MinCaseVal->getValue());
5691 // Check if cases with the same result can cover all number
5692 // in touched bits.
5693 if (BitMask.countPopulation() == Log2_32(CaseCount)) {
5694 if (!MinCaseVal->isNullValue())
5695 Condition = Builder.CreateSub(Condition, MinCaseVal);
5696 Value *And = Builder.CreateAnd(Condition, ~BitMask, "switch.and");
5697 Value *Cmp = Builder.CreateICmpEQ(
5698 And, Constant::getNullValue(And->getType()), "switch.selectcmp");
5699 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5703 // Handle the degenerate case where two cases have the same value.
5704 if (CaseValues.size() == 2) {
5705 Value *Cmp1 = Builder.CreateICmpEQ(Condition, CaseValues[0],
5706 "switch.selectcmp.case1");
5707 Value *Cmp2 = Builder.CreateICmpEQ(Condition, CaseValues[1],
5708 "switch.selectcmp.case2");
5709 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
5710 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5714 return nullptr;
5717 // Helper function to cleanup a switch instruction that has been converted into
5718 // a select, fixing up PHI nodes and basic blocks.
5719 static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI,
5720 Value *SelectValue,
5721 IRBuilder<> &Builder,
5722 DomTreeUpdater *DTU) {
5723 std::vector<DominatorTree::UpdateType> Updates;
5725 BasicBlock *SelectBB = SI->getParent();
5726 BasicBlock *DestBB = PHI->getParent();
5728 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
5729 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
5730 Builder.CreateBr(DestBB);
5732 // Remove the switch.
5734 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5735 PHI->removeIncomingValue(SelectBB);
5736 PHI->addIncoming(SelectValue, SelectBB);
5738 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
5739 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5740 BasicBlock *Succ = SI->getSuccessor(i);
5742 if (Succ == DestBB)
5743 continue;
5744 Succ->removePredecessor(SelectBB);
5745 if (DTU && RemovedSuccessors.insert(Succ).second)
5746 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
5748 SI->eraseFromParent();
5749 if (DTU)
5750 DTU->applyUpdates(Updates);
5753 /// If a switch is only used to initialize one or more phi nodes in a common
5754 /// successor block with only two different constant values, try to replace the
5755 /// switch with a select. Returns true if the fold was made.
5756 static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5757 DomTreeUpdater *DTU, const DataLayout &DL,
5758 const TargetTransformInfo &TTI) {
5759 Value *const Cond = SI->getCondition();
5760 PHINode *PHI = nullptr;
5761 BasicBlock *CommonDest = nullptr;
5762 Constant *DefaultResult;
5763 SwitchCaseResultVectorTy UniqueResults;
5764 // Collect all the cases that will deliver the same value from the switch.
5765 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5766 DL, TTI, /*MaxUniqueResults*/ 2))
5767 return false;
5769 assert(PHI != nullptr && "PHI for value select not found");
5770 Builder.SetInsertPoint(SI);
5771 Value *SelectValue =
5772 foldSwitchToSelect(UniqueResults, DefaultResult, Cond, Builder);
5773 if (!SelectValue)
5774 return false;
5776 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
5777 return true;
5780 namespace {
5782 /// This class represents a lookup table that can be used to replace a switch.
5783 class SwitchLookupTable {
5784 public:
5785 /// Create a lookup table to use as a switch replacement with the contents
5786 /// of Values, using DefaultValue to fill any holes in the table.
5787 SwitchLookupTable(
5788 Module &M, uint64_t TableSize, ConstantInt *Offset,
5789 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5790 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5792 /// Build instructions with Builder to retrieve the value at
5793 /// the position given by Index in the lookup table.
5794 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5796 /// Return true if a table with TableSize elements of
5797 /// type ElementType would fit in a target-legal register.
5798 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5799 Type *ElementType);
5801 private:
5802 // Depending on the contents of the table, it can be represented in
5803 // different ways.
5804 enum {
5805 // For tables where each element contains the same value, we just have to
5806 // store that single value and return it for each lookup.
5807 SingleValueKind,
5809 // For tables where there is a linear relationship between table index
5810 // and values. We calculate the result with a simple multiplication
5811 // and addition instead of a table lookup.
5812 LinearMapKind,
5814 // For small tables with integer elements, we can pack them into a bitmap
5815 // that fits into a target-legal register. Values are retrieved by
5816 // shift and mask operations.
5817 BitMapKind,
5819 // The table is stored as an array of values. Values are retrieved by load
5820 // instructions from the table.
5821 ArrayKind
5822 } Kind;
5824 // For SingleValueKind, this is the single value.
5825 Constant *SingleValue = nullptr;
5827 // For BitMapKind, this is the bitmap.
5828 ConstantInt *BitMap = nullptr;
5829 IntegerType *BitMapElementTy = nullptr;
5831 // For LinearMapKind, these are the constants used to derive the value.
5832 ConstantInt *LinearOffset = nullptr;
5833 ConstantInt *LinearMultiplier = nullptr;
5835 // For ArrayKind, this is the array.
5836 GlobalVariable *Array = nullptr;
5839 } // end anonymous namespace
5841 SwitchLookupTable::SwitchLookupTable(
5842 Module &M, uint64_t TableSize, ConstantInt *Offset,
5843 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5844 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5845 assert(Values.size() && "Can't build lookup table without values!");
5846 assert(TableSize >= Values.size() && "Can't fit values in table!");
5848 // If all values in the table are equal, this is that value.
5849 SingleValue = Values.begin()->second;
5851 Type *ValueType = Values.begin()->second->getType();
5853 // Build up the table contents.
5854 SmallVector<Constant *, 64> TableContents(TableSize);
5855 for (size_t I = 0, E = Values.size(); I != E; ++I) {
5856 ConstantInt *CaseVal = Values[I].first;
5857 Constant *CaseRes = Values[I].second;
5858 assert(CaseRes->getType() == ValueType);
5860 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5861 TableContents[Idx] = CaseRes;
5863 if (CaseRes != SingleValue)
5864 SingleValue = nullptr;
5867 // Fill in any holes in the table with the default result.
5868 if (Values.size() < TableSize) {
5869 assert(DefaultValue &&
5870 "Need a default value to fill the lookup table holes.");
5871 assert(DefaultValue->getType() == ValueType);
5872 for (uint64_t I = 0; I < TableSize; ++I) {
5873 if (!TableContents[I])
5874 TableContents[I] = DefaultValue;
5877 if (DefaultValue != SingleValue)
5878 SingleValue = nullptr;
5881 // If each element in the table contains the same value, we only need to store
5882 // that single value.
5883 if (SingleValue) {
5884 Kind = SingleValueKind;
5885 return;
5888 // Check if we can derive the value with a linear transformation from the
5889 // table index.
5890 if (isa<IntegerType>(ValueType)) {
5891 bool LinearMappingPossible = true;
5892 APInt PrevVal;
5893 APInt DistToPrev;
5894 assert(TableSize >= 2 && "Should be a SingleValue table.");
5895 // Check if there is the same distance between two consecutive values.
5896 for (uint64_t I = 0; I < TableSize; ++I) {
5897 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5898 if (!ConstVal) {
5899 // This is an undef. We could deal with it, but undefs in lookup tables
5900 // are very seldom. It's probably not worth the additional complexity.
5901 LinearMappingPossible = false;
5902 break;
5904 const APInt &Val = ConstVal->getValue();
5905 if (I != 0) {
5906 APInt Dist = Val - PrevVal;
5907 if (I == 1) {
5908 DistToPrev = Dist;
5909 } else if (Dist != DistToPrev) {
5910 LinearMappingPossible = false;
5911 break;
5914 PrevVal = Val;
5916 if (LinearMappingPossible) {
5917 LinearOffset = cast<ConstantInt>(TableContents[0]);
5918 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5919 Kind = LinearMapKind;
5920 ++NumLinearMaps;
5921 return;
5925 // If the type is integer and the table fits in a register, build a bitmap.
5926 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5927 IntegerType *IT = cast<IntegerType>(ValueType);
5928 APInt TableInt(TableSize * IT->getBitWidth(), 0);
5929 for (uint64_t I = TableSize; I > 0; --I) {
5930 TableInt <<= IT->getBitWidth();
5931 // Insert values into the bitmap. Undef values are set to zero.
5932 if (!isa<UndefValue>(TableContents[I - 1])) {
5933 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5934 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5937 BitMap = ConstantInt::get(M.getContext(), TableInt);
5938 BitMapElementTy = IT;
5939 Kind = BitMapKind;
5940 ++NumBitMaps;
5941 return;
5944 // Store the table in an array.
5945 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5946 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5948 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5949 GlobalVariable::PrivateLinkage, Initializer,
5950 "switch.table." + FuncName);
5951 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5952 // Set the alignment to that of an array items. We will be only loading one
5953 // value out of it.
5954 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5955 Kind = ArrayKind;
5958 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5959 switch (Kind) {
5960 case SingleValueKind:
5961 return SingleValue;
5962 case LinearMapKind: {
5963 // Derive the result value from the input value.
5964 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5965 false, "switch.idx.cast");
5966 if (!LinearMultiplier->isOne())
5967 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5968 if (!LinearOffset->isZero())
5969 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5970 return Result;
5972 case BitMapKind: {
5973 // Type of the bitmap (e.g. i59).
5974 IntegerType *MapTy = BitMap->getType();
5976 // Cast Index to the same type as the bitmap.
5977 // Note: The Index is <= the number of elements in the table, so
5978 // truncating it to the width of the bitmask is safe.
5979 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5981 // Multiply the shift amount by the element width.
5982 ShiftAmt = Builder.CreateMul(
5983 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5984 "switch.shiftamt");
5986 // Shift down.
5987 Value *DownShifted =
5988 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5989 // Mask off.
5990 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5992 case ArrayKind: {
5993 // Make sure the table index will not overflow when treated as signed.
5994 IntegerType *IT = cast<IntegerType>(Index->getType());
5995 uint64_t TableSize =
5996 Array->getInitializer()->getType()->getArrayNumElements();
5997 if (TableSize > (1ULL << std::min(IT->getBitWidth() - 1, 63u)))
5998 Index = Builder.CreateZExt(
5999 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
6000 "switch.tableidx.zext");
6002 Value *GEPIndices[] = {Builder.getInt32(0), Index};
6003 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
6004 GEPIndices, "switch.gep");
6005 return Builder.CreateLoad(
6006 cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
6007 "switch.load");
6010 llvm_unreachable("Unknown lookup table kind!");
6013 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
6014 uint64_t TableSize,
6015 Type *ElementType) {
6016 auto *IT = dyn_cast<IntegerType>(ElementType);
6017 if (!IT)
6018 return false;
6019 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
6020 // are <= 15, we could try to narrow the type.
6022 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
6023 if (TableSize >= UINT_MAX / IT->getBitWidth())
6024 return false;
6025 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
6028 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI,
6029 const DataLayout &DL) {
6030 // Allow any legal type.
6031 if (TTI.isTypeLegal(Ty))
6032 return true;
6034 auto *IT = dyn_cast<IntegerType>(Ty);
6035 if (!IT)
6036 return false;
6038 // Also allow power of 2 integer types that have at least 8 bits and fit in
6039 // a register. These types are common in frontend languages and targets
6040 // usually support loads of these types.
6041 // TODO: We could relax this to any integer that fits in a register and rely
6042 // on ABI alignment and padding in the table to allow the load to be widened.
6043 // Or we could widen the constants and truncate the load.
6044 unsigned BitWidth = IT->getBitWidth();
6045 return BitWidth >= 8 && isPowerOf2_32(BitWidth) &&
6046 DL.fitsInLegalInteger(IT->getBitWidth());
6049 static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange) {
6050 // 40% is the default density for building a jump table in optsize/minsize
6051 // mode. See also TargetLoweringBase::isSuitableForJumpTable(), which this
6052 // function was based on.
6053 const uint64_t MinDensity = 40;
6055 if (CaseRange >= UINT64_MAX / 100)
6056 return false; // Avoid multiplication overflows below.
6058 return NumCases * 100 >= CaseRange * MinDensity;
6061 static bool isSwitchDense(ArrayRef<int64_t> Values) {
6062 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
6063 uint64_t Range = Diff + 1;
6064 if (Range < Diff)
6065 return false; // Overflow.
6067 return isSwitchDense(Values.size(), Range);
6070 /// Determine whether a lookup table should be built for this switch, based on
6071 /// the number of cases, size of the table, and the types of the results.
6072 // TODO: We could support larger than legal types by limiting based on the
6073 // number of loads required and/or table size. If the constants are small we
6074 // could use smaller table entries and extend after the load.
6075 static bool
6076 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
6077 const TargetTransformInfo &TTI, const DataLayout &DL,
6078 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
6079 if (SI->getNumCases() > TableSize)
6080 return false; // TableSize overflowed.
6082 bool AllTablesFitInRegister = true;
6083 bool HasIllegalType = false;
6084 for (const auto &I : ResultTypes) {
6085 Type *Ty = I.second;
6087 // Saturate this flag to true.
6088 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
6090 // Saturate this flag to false.
6091 AllTablesFitInRegister =
6092 AllTablesFitInRegister &&
6093 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
6095 // If both flags saturate, we're done. NOTE: This *only* works with
6096 // saturating flags, and all flags have to saturate first due to the
6097 // non-deterministic behavior of iterating over a dense map.
6098 if (HasIllegalType && !AllTablesFitInRegister)
6099 break;
6102 // If each table would fit in a register, we should build it anyway.
6103 if (AllTablesFitInRegister)
6104 return true;
6106 // Don't build a table that doesn't fit in-register if it has illegal types.
6107 if (HasIllegalType)
6108 return false;
6110 return isSwitchDense(SI->getNumCases(), TableSize);
6113 static bool ShouldUseSwitchConditionAsTableIndex(
6114 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
6115 bool HasDefaultResults, const SmallDenseMap<PHINode *, Type *> &ResultTypes,
6116 const DataLayout &DL, const TargetTransformInfo &TTI) {
6117 if (MinCaseVal.isNullValue())
6118 return true;
6119 if (MinCaseVal.isNegative() ||
6120 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
6121 !HasDefaultResults)
6122 return false;
6123 return all_of(ResultTypes, [&](const auto &KV) {
6124 return SwitchLookupTable::WouldFitInRegister(
6125 DL, MaxCaseVal.getLimitedValue() + 1 /* TableSize */,
6126 KV.second /* ResultType */);
6130 /// Try to reuse the switch table index compare. Following pattern:
6131 /// \code
6132 /// if (idx < tablesize)
6133 /// r = table[idx]; // table does not contain default_value
6134 /// else
6135 /// r = default_value;
6136 /// if (r != default_value)
6137 /// ...
6138 /// \endcode
6139 /// Is optimized to:
6140 /// \code
6141 /// cond = idx < tablesize;
6142 /// if (cond)
6143 /// r = table[idx];
6144 /// else
6145 /// r = default_value;
6146 /// if (cond)
6147 /// ...
6148 /// \endcode
6149 /// Jump threading will then eliminate the second if(cond).
6150 static void reuseTableCompare(
6151 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
6152 Constant *DefaultValue,
6153 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
6154 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
6155 if (!CmpInst)
6156 return;
6158 // We require that the compare is in the same block as the phi so that jump
6159 // threading can do its work afterwards.
6160 if (CmpInst->getParent() != PhiBlock)
6161 return;
6163 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
6164 if (!CmpOp1)
6165 return;
6167 Value *RangeCmp = RangeCheckBranch->getCondition();
6168 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
6169 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
6171 // Check if the compare with the default value is constant true or false.
6172 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6173 DefaultValue, CmpOp1, true);
6174 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
6175 return;
6177 // Check if the compare with the case values is distinct from the default
6178 // compare result.
6179 for (auto ValuePair : Values) {
6180 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
6181 ValuePair.second, CmpOp1, true);
6182 if (!CaseConst || CaseConst == DefaultConst ||
6183 (CaseConst != TrueConst && CaseConst != FalseConst))
6184 return;
6187 // Check if the branch instruction dominates the phi node. It's a simple
6188 // dominance check, but sufficient for our needs.
6189 // Although this check is invariant in the calling loops, it's better to do it
6190 // at this late stage. Practically we do it at most once for a switch.
6191 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
6192 for (BasicBlock *Pred : predecessors(PhiBlock)) {
6193 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
6194 return;
6197 if (DefaultConst == FalseConst) {
6198 // The compare yields the same result. We can replace it.
6199 CmpInst->replaceAllUsesWith(RangeCmp);
6200 ++NumTableCmpReuses;
6201 } else {
6202 // The compare yields the same result, just inverted. We can replace it.
6203 Value *InvertedTableCmp = BinaryOperator::CreateXor(
6204 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
6205 RangeCheckBranch);
6206 CmpInst->replaceAllUsesWith(InvertedTableCmp);
6207 ++NumTableCmpReuses;
6211 /// If the switch is only used to initialize one or more phi nodes in a common
6212 /// successor block with different constant values, replace the switch with
6213 /// lookup tables.
6214 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
6215 DomTreeUpdater *DTU, const DataLayout &DL,
6216 const TargetTransformInfo &TTI) {
6217 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6219 BasicBlock *BB = SI->getParent();
6220 Function *Fn = BB->getParent();
6221 // Only build lookup table when we have a target that supports it or the
6222 // attribute is not set.
6223 if (!TTI.shouldBuildLookupTables() ||
6224 (Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
6225 return false;
6227 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
6228 // split off a dense part and build a lookup table for that.
6230 // FIXME: This creates arrays of GEPs to constant strings, which means each
6231 // GEP needs a runtime relocation in PIC code. We should just build one big
6232 // string and lookup indices into that.
6234 // Ignore switches with less than three cases. Lookup tables will not make
6235 // them faster, so we don't analyze them.
6236 if (SI->getNumCases() < 3)
6237 return false;
6239 // Figure out the corresponding result for each case value and phi node in the
6240 // common destination, as well as the min and max case values.
6241 assert(!SI->cases().empty());
6242 SwitchInst::CaseIt CI = SI->case_begin();
6243 ConstantInt *MinCaseVal = CI->getCaseValue();
6244 ConstantInt *MaxCaseVal = CI->getCaseValue();
6246 BasicBlock *CommonDest = nullptr;
6248 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
6249 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
6251 SmallDenseMap<PHINode *, Constant *> DefaultResults;
6252 SmallDenseMap<PHINode *, Type *> ResultTypes;
6253 SmallVector<PHINode *, 4> PHIs;
6255 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
6256 ConstantInt *CaseVal = CI->getCaseValue();
6257 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
6258 MinCaseVal = CaseVal;
6259 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
6260 MaxCaseVal = CaseVal;
6262 // Resulting value at phi nodes for this case value.
6263 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
6264 ResultsTy Results;
6265 if (!getCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
6266 Results, DL, TTI))
6267 return false;
6269 // Append the result from this case to the list for each phi.
6270 for (const auto &I : Results) {
6271 PHINode *PHI = I.first;
6272 Constant *Value = I.second;
6273 if (!ResultLists.count(PHI))
6274 PHIs.push_back(PHI);
6275 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
6279 // Keep track of the result types.
6280 for (PHINode *PHI : PHIs) {
6281 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
6284 uint64_t NumResults = ResultLists[PHIs[0]].size();
6286 // If the table has holes, we need a constant result for the default case
6287 // or a bitmask that fits in a register.
6288 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
6289 bool HasDefaultResults =
6290 getCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
6291 DefaultResultsList, DL, TTI);
6293 for (const auto &I : DefaultResultsList) {
6294 PHINode *PHI = I.first;
6295 Constant *Result = I.second;
6296 DefaultResults[PHI] = Result;
6299 bool UseSwitchConditionAsTableIndex = ShouldUseSwitchConditionAsTableIndex(
6300 *MinCaseVal, *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
6301 uint64_t TableSize;
6302 if (UseSwitchConditionAsTableIndex)
6303 TableSize = MaxCaseVal->getLimitedValue() + 1;
6304 else
6305 TableSize =
6306 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
6308 bool TableHasHoles = (NumResults < TableSize);
6309 bool NeedMask = (TableHasHoles && !HasDefaultResults);
6310 if (NeedMask) {
6311 // As an extra penalty for the validity test we require more cases.
6312 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
6313 return false;
6314 if (!DL.fitsInLegalInteger(TableSize))
6315 return false;
6318 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
6319 return false;
6321 std::vector<DominatorTree::UpdateType> Updates;
6323 // Create the BB that does the lookups.
6324 Module &Mod = *CommonDest->getParent()->getParent();
6325 BasicBlock *LookupBB = BasicBlock::Create(
6326 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
6328 // Compute the table index value.
6329 Builder.SetInsertPoint(SI);
6330 Value *TableIndex;
6331 ConstantInt *TableIndexOffset;
6332 if (UseSwitchConditionAsTableIndex) {
6333 TableIndexOffset = ConstantInt::get(MaxCaseVal->getType(), 0);
6334 TableIndex = SI->getCondition();
6335 } else {
6336 TableIndexOffset = MinCaseVal;
6337 TableIndex =
6338 Builder.CreateSub(SI->getCondition(), TableIndexOffset, "switch.tableidx");
6341 // Compute the maximum table size representable by the integer type we are
6342 // switching upon.
6343 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
6344 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
6345 assert(MaxTableSize >= TableSize &&
6346 "It is impossible for a switch to have more entries than the max "
6347 "representable value of its input integer type's size.");
6349 // If the default destination is unreachable, or if the lookup table covers
6350 // all values of the conditional variable, branch directly to the lookup table
6351 // BB. Otherwise, check that the condition is within the case range.
6352 const bool DefaultIsReachable =
6353 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
6354 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
6355 BranchInst *RangeCheckBranch = nullptr;
6357 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6358 Builder.CreateBr(LookupBB);
6359 if (DTU)
6360 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6361 // Note: We call removeProdecessor later since we need to be able to get the
6362 // PHI value for the default case in case we're using a bit mask.
6363 } else {
6364 Value *Cmp = Builder.CreateICmpULT(
6365 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
6366 RangeCheckBranch =
6367 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
6368 if (DTU)
6369 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6372 // Populate the BB that does the lookups.
6373 Builder.SetInsertPoint(LookupBB);
6375 if (NeedMask) {
6376 // Before doing the lookup, we do the hole check. The LookupBB is therefore
6377 // re-purposed to do the hole check, and we create a new LookupBB.
6378 BasicBlock *MaskBB = LookupBB;
6379 MaskBB->setName("switch.hole_check");
6380 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
6381 CommonDest->getParent(), CommonDest);
6383 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
6384 // unnecessary illegal types.
6385 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
6386 APInt MaskInt(TableSizePowOf2, 0);
6387 APInt One(TableSizePowOf2, 1);
6388 // Build bitmask; fill in a 1 bit for every case.
6389 const ResultListTy &ResultList = ResultLists[PHIs[0]];
6390 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
6391 uint64_t Idx = (ResultList[I].first->getValue() - TableIndexOffset->getValue())
6392 .getLimitedValue();
6393 MaskInt |= One << Idx;
6395 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
6397 // Get the TableIndex'th bit of the bitmask.
6398 // If this bit is 0 (meaning hole) jump to the default destination,
6399 // else continue with table lookup.
6400 IntegerType *MapTy = TableMask->getType();
6401 Value *MaskIndex =
6402 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
6403 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
6404 Value *LoBit = Builder.CreateTrunc(
6405 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
6406 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
6407 if (DTU) {
6408 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
6409 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
6411 Builder.SetInsertPoint(LookupBB);
6412 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
6415 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6416 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
6417 // do not delete PHINodes here.
6418 SI->getDefaultDest()->removePredecessor(BB,
6419 /*KeepOneInputPHIs=*/true);
6420 if (DTU)
6421 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
6424 for (PHINode *PHI : PHIs) {
6425 const ResultListTy &ResultList = ResultLists[PHI];
6427 // If using a bitmask, use any value to fill the lookup table holes.
6428 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
6429 StringRef FuncName = Fn->getName();
6430 SwitchLookupTable Table(Mod, TableSize, TableIndexOffset, ResultList, DV,
6431 DL, FuncName);
6433 Value *Result = Table.BuildLookup(TableIndex, Builder);
6435 // Do a small peephole optimization: re-use the switch table compare if
6436 // possible.
6437 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
6438 BasicBlock *PhiBlock = PHI->getParent();
6439 // Search for compare instructions which use the phi.
6440 for (auto *User : PHI->users()) {
6441 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
6445 PHI->addIncoming(Result, LookupBB);
6448 Builder.CreateBr(CommonDest);
6449 if (DTU)
6450 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
6452 // Remove the switch.
6453 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
6454 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6455 BasicBlock *Succ = SI->getSuccessor(i);
6457 if (Succ == SI->getDefaultDest())
6458 continue;
6459 Succ->removePredecessor(BB);
6460 if (DTU && RemovedSuccessors.insert(Succ).second)
6461 Updates.push_back({DominatorTree::Delete, BB, Succ});
6463 SI->eraseFromParent();
6465 if (DTU)
6466 DTU->applyUpdates(Updates);
6468 ++NumLookupTables;
6469 if (NeedMask)
6470 ++NumLookupTablesHoles;
6471 return true;
6474 /// Try to transform a switch that has "holes" in it to a contiguous sequence
6475 /// of cases.
6477 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
6478 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
6480 /// This converts a sparse switch into a dense switch which allows better
6481 /// lowering and could also allow transforming into a lookup table.
6482 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
6483 const DataLayout &DL,
6484 const TargetTransformInfo &TTI) {
6485 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
6486 if (CondTy->getIntegerBitWidth() > 64 ||
6487 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6488 return false;
6489 // Only bother with this optimization if there are more than 3 switch cases;
6490 // SDAG will only bother creating jump tables for 4 or more cases.
6491 if (SI->getNumCases() < 4)
6492 return false;
6494 // This transform is agnostic to the signedness of the input or case values. We
6495 // can treat the case values as signed or unsigned. We can optimize more common
6496 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
6497 // as signed.
6498 SmallVector<int64_t,4> Values;
6499 for (const auto &C : SI->cases())
6500 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
6501 llvm::sort(Values);
6503 // If the switch is already dense, there's nothing useful to do here.
6504 if (isSwitchDense(Values))
6505 return false;
6507 // First, transform the values such that they start at zero and ascend.
6508 int64_t Base = Values[0];
6509 for (auto &V : Values)
6510 V -= (uint64_t)(Base);
6512 // Now we have signed numbers that have been shifted so that, given enough
6513 // precision, there are no negative values. Since the rest of the transform
6514 // is bitwise only, we switch now to an unsigned representation.
6516 // This transform can be done speculatively because it is so cheap - it
6517 // results in a single rotate operation being inserted.
6518 // FIXME: It's possible that optimizing a switch on powers of two might also
6519 // be beneficial - flag values are often powers of two and we could use a CLZ
6520 // as the key function.
6522 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
6523 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
6524 // less than 64.
6525 unsigned Shift = 64;
6526 for (auto &V : Values)
6527 Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
6528 assert(Shift < 64);
6529 if (Shift > 0)
6530 for (auto &V : Values)
6531 V = (int64_t)((uint64_t)V >> Shift);
6533 if (!isSwitchDense(Values))
6534 // Transform didn't create a dense switch.
6535 return false;
6537 // The obvious transform is to shift the switch condition right and emit a
6538 // check that the condition actually cleanly divided by GCD, i.e.
6539 // C & (1 << Shift - 1) == 0
6540 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
6542 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
6543 // shift and puts the shifted-off bits in the uppermost bits. If any of these
6544 // are nonzero then the switch condition will be very large and will hit the
6545 // default case.
6547 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
6548 Builder.SetInsertPoint(SI);
6549 auto *ShiftC = ConstantInt::get(Ty, Shift);
6550 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
6551 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
6552 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
6553 auto *Rot = Builder.CreateOr(LShr, Shl);
6554 SI->replaceUsesOfWith(SI->getCondition(), Rot);
6556 for (auto Case : SI->cases()) {
6557 auto *Orig = Case.getCaseValue();
6558 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
6559 Case.setValue(
6560 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
6562 return true;
6565 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
6566 BasicBlock *BB = SI->getParent();
6568 if (isValueEqualityComparison(SI)) {
6569 // If we only have one predecessor, and if it is a branch on this value,
6570 // see if that predecessor totally determines the outcome of this switch.
6571 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6572 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
6573 return requestResimplify();
6575 Value *Cond = SI->getCondition();
6576 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
6577 if (SimplifySwitchOnSelect(SI, Select))
6578 return requestResimplify();
6580 // If the block only contains the switch, see if we can fold the block
6581 // away into any preds.
6582 if (SI == &*BB->instructionsWithoutDebug(false).begin())
6583 if (FoldValueComparisonIntoPredecessors(SI, Builder))
6584 return requestResimplify();
6587 // Try to transform the switch into an icmp and a branch.
6588 // The conversion from switch to comparison may lose information on
6589 // impossible switch values, so disable it early in the pipeline.
6590 if (Options.ConvertSwitchRangeToICmp && TurnSwitchRangeIntoICmp(SI, Builder))
6591 return requestResimplify();
6593 // Remove unreachable cases.
6594 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
6595 return requestResimplify();
6597 if (trySwitchToSelect(SI, Builder, DTU, DL, TTI))
6598 return requestResimplify();
6600 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
6601 return requestResimplify();
6603 // The conversion from switch to lookup tables results in difficult-to-analyze
6604 // code and makes pruning branches much harder. This is a problem if the
6605 // switch expression itself can still be restricted as a result of inlining or
6606 // CVP. Therefore, only apply this transformation during late stages of the
6607 // optimisation pipeline.
6608 if (Options.ConvertSwitchToLookupTable &&
6609 SwitchToLookupTable(SI, Builder, DTU, DL, TTI))
6610 return requestResimplify();
6612 if (ReduceSwitchRange(SI, Builder, DL, TTI))
6613 return requestResimplify();
6615 return false;
6618 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
6619 BasicBlock *BB = IBI->getParent();
6620 bool Changed = false;
6622 // Eliminate redundant destinations.
6623 SmallPtrSet<Value *, 8> Succs;
6624 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
6625 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
6626 BasicBlock *Dest = IBI->getDestination(i);
6627 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
6628 if (!Dest->hasAddressTaken())
6629 RemovedSuccs.insert(Dest);
6630 Dest->removePredecessor(BB);
6631 IBI->removeDestination(i);
6632 --i;
6633 --e;
6634 Changed = true;
6638 if (DTU) {
6639 std::vector<DominatorTree::UpdateType> Updates;
6640 Updates.reserve(RemovedSuccs.size());
6641 for (auto *RemovedSucc : RemovedSuccs)
6642 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
6643 DTU->applyUpdates(Updates);
6646 if (IBI->getNumDestinations() == 0) {
6647 // If the indirectbr has no successors, change it to unreachable.
6648 new UnreachableInst(IBI->getContext(), IBI);
6649 EraseTerminatorAndDCECond(IBI);
6650 return true;
6653 if (IBI->getNumDestinations() == 1) {
6654 // If the indirectbr has one successor, change it to a direct branch.
6655 BranchInst::Create(IBI->getDestination(0), IBI);
6656 EraseTerminatorAndDCECond(IBI);
6657 return true;
6660 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
6661 if (SimplifyIndirectBrOnSelect(IBI, SI))
6662 return requestResimplify();
6664 return Changed;
6667 /// Given an block with only a single landing pad and a unconditional branch
6668 /// try to find another basic block which this one can be merged with. This
6669 /// handles cases where we have multiple invokes with unique landing pads, but
6670 /// a shared handler.
6672 /// We specifically choose to not worry about merging non-empty blocks
6673 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
6674 /// practice, the optimizer produces empty landing pad blocks quite frequently
6675 /// when dealing with exception dense code. (see: instcombine, gvn, if-else
6676 /// sinking in this file)
6678 /// This is primarily a code size optimization. We need to avoid performing
6679 /// any transform which might inhibit optimization (such as our ability to
6680 /// specialize a particular handler via tail commoning). We do this by not
6681 /// merging any blocks which require us to introduce a phi. Since the same
6682 /// values are flowing through both blocks, we don't lose any ability to
6683 /// specialize. If anything, we make such specialization more likely.
6685 /// TODO - This transformation could remove entries from a phi in the target
6686 /// block when the inputs in the phi are the same for the two blocks being
6687 /// merged. In some cases, this could result in removal of the PHI entirely.
6688 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
6689 BasicBlock *BB, DomTreeUpdater *DTU) {
6690 auto Succ = BB->getUniqueSuccessor();
6691 assert(Succ);
6692 // If there's a phi in the successor block, we'd likely have to introduce
6693 // a phi into the merged landing pad block.
6694 if (isa<PHINode>(*Succ->begin()))
6695 return false;
6697 for (BasicBlock *OtherPred : predecessors(Succ)) {
6698 if (BB == OtherPred)
6699 continue;
6700 BasicBlock::iterator I = OtherPred->begin();
6701 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6702 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6703 continue;
6704 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6706 BranchInst *BI2 = dyn_cast<BranchInst>(I);
6707 if (!BI2 || !BI2->isIdenticalTo(BI))
6708 continue;
6710 std::vector<DominatorTree::UpdateType> Updates;
6712 // We've found an identical block. Update our predecessors to take that
6713 // path instead and make ourselves dead.
6714 SmallSetVector<BasicBlock *, 16> UniquePreds(pred_begin(BB), pred_end(BB));
6715 for (BasicBlock *Pred : UniquePreds) {
6716 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6717 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
6718 "unexpected successor");
6719 II->setUnwindDest(OtherPred);
6720 if (DTU) {
6721 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
6722 Updates.push_back({DominatorTree::Delete, Pred, BB});
6726 // The debug info in OtherPred doesn't cover the merged control flow that
6727 // used to go through BB. We need to delete it or update it.
6728 for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred))
6729 if (isa<DbgInfoIntrinsic>(Inst))
6730 Inst.eraseFromParent();
6732 SmallSetVector<BasicBlock *, 16> UniqueSuccs(succ_begin(BB), succ_end(BB));
6733 for (BasicBlock *Succ : UniqueSuccs) {
6734 Succ->removePredecessor(BB);
6735 if (DTU)
6736 Updates.push_back({DominatorTree::Delete, BB, Succ});
6739 IRBuilder<> Builder(BI);
6740 Builder.CreateUnreachable();
6741 BI->eraseFromParent();
6742 if (DTU)
6743 DTU->applyUpdates(Updates);
6744 return true;
6746 return false;
6749 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6750 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6751 : simplifyCondBranch(Branch, Builder);
6754 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6755 IRBuilder<> &Builder) {
6756 BasicBlock *BB = BI->getParent();
6757 BasicBlock *Succ = BI->getSuccessor(0);
6759 // If the Terminator is the only non-phi instruction, simplify the block.
6760 // If LoopHeader is provided, check if the block or its successor is a loop
6761 // header. (This is for early invocations before loop simplify and
6762 // vectorization to keep canonical loop forms for nested loops. These blocks
6763 // can be eliminated when the pass is invoked later in the back-end.)
6764 // Note that if BB has only one predecessor then we do not introduce new
6765 // backedge, so we can eliminate BB.
6766 bool NeedCanonicalLoop =
6767 Options.NeedCanonicalLoop &&
6768 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
6769 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
6770 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator();
6771 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6772 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
6773 return true;
6775 // If the only instruction in the block is a seteq/setne comparison against a
6776 // constant, try to simplify the block.
6777 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6778 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6779 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6781 if (I->isTerminator() &&
6782 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6783 return true;
6786 // See if we can merge an empty landing pad block with another which is
6787 // equivalent.
6788 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6789 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6791 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU))
6792 return true;
6795 // If this basic block is ONLY a compare and a branch, and if a predecessor
6796 // branches to us and our successor, fold the comparison into the
6797 // predecessor and use logical operations to update the incoming value
6798 // for PHI nodes in common successor.
6799 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6800 Options.BonusInstThreshold))
6801 return requestResimplify();
6802 return false;
6805 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6806 BasicBlock *PredPred = nullptr;
6807 for (auto *P : predecessors(BB)) {
6808 BasicBlock *PPred = P->getSinglePredecessor();
6809 if (!PPred || (PredPred && PredPred != PPred))
6810 return nullptr;
6811 PredPred = PPred;
6813 return PredPred;
6816 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6817 assert(
6818 !isa<ConstantInt>(BI->getCondition()) &&
6819 BI->getSuccessor(0) != BI->getSuccessor(1) &&
6820 "Tautological conditional branch should have been eliminated already.");
6822 BasicBlock *BB = BI->getParent();
6823 if (!Options.SimplifyCondBranch)
6824 return false;
6826 // Conditional branch
6827 if (isValueEqualityComparison(BI)) {
6828 // If we only have one predecessor, and if it is a branch on this value,
6829 // see if that predecessor totally determines the outcome of this
6830 // switch.
6831 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6832 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6833 return requestResimplify();
6835 // This block must be empty, except for the setcond inst, if it exists.
6836 // Ignore dbg and pseudo intrinsics.
6837 auto I = BB->instructionsWithoutDebug(true).begin();
6838 if (&*I == BI) {
6839 if (FoldValueComparisonIntoPredecessors(BI, Builder))
6840 return requestResimplify();
6841 } else if (&*I == cast<Instruction>(BI->getCondition())) {
6842 ++I;
6843 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6844 return requestResimplify();
6848 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6849 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6850 return true;
6852 // If this basic block has dominating predecessor blocks and the dominating
6853 // blocks' conditions imply BI's condition, we know the direction of BI.
6854 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6855 if (Imp) {
6856 // Turn this into a branch on constant.
6857 auto *OldCond = BI->getCondition();
6858 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6859 : ConstantInt::getFalse(BB->getContext());
6860 BI->setCondition(TorF);
6861 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6862 return requestResimplify();
6865 // If this basic block is ONLY a compare and a branch, and if a predecessor
6866 // branches to us and one of our successors, fold the comparison into the
6867 // predecessor and use logical operations to pick the right destination.
6868 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6869 Options.BonusInstThreshold))
6870 return requestResimplify();
6872 // We have a conditional branch to two blocks that are only reachable
6873 // from BI. We know that the condbr dominates the two blocks, so see if
6874 // there is any identical code in the "then" and "else" blocks. If so, we
6875 // can hoist it up to the branching block.
6876 if (BI->getSuccessor(0)->getSinglePredecessor()) {
6877 if (BI->getSuccessor(1)->getSinglePredecessor()) {
6878 if (HoistCommon &&
6879 HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts))
6880 return requestResimplify();
6881 } else {
6882 // If Successor #1 has multiple preds, we may be able to conditionally
6883 // execute Successor #0 if it branches to Successor #1.
6884 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6885 if (Succ0TI->getNumSuccessors() == 1 &&
6886 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6887 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6888 return requestResimplify();
6890 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6891 // If Successor #0 has multiple preds, we may be able to conditionally
6892 // execute Successor #1 if it branches to Successor #0.
6893 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6894 if (Succ1TI->getNumSuccessors() == 1 &&
6895 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6896 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6897 return requestResimplify();
6900 // If this is a branch on something for which we know the constant value in
6901 // predecessors (e.g. a phi node in the current block), thread control
6902 // through this block.
6903 if (FoldCondBranchOnValueKnownInPredecessor(BI, DTU, DL, Options.AC))
6904 return requestResimplify();
6906 // Scan predecessor blocks for conditional branches.
6907 for (BasicBlock *Pred : predecessors(BB))
6908 if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
6909 if (PBI != BI && PBI->isConditional())
6910 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
6911 return requestResimplify();
6913 // Look for diamond patterns.
6914 if (MergeCondStores)
6915 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6916 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6917 if (PBI != BI && PBI->isConditional())
6918 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
6919 return requestResimplify();
6921 return false;
6924 /// Check if passing a value to an instruction will cause undefined behavior.
6925 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
6926 Constant *C = dyn_cast<Constant>(V);
6927 if (!C)
6928 return false;
6930 if (I->use_empty())
6931 return false;
6933 if (C->isNullValue() || isa<UndefValue>(C)) {
6934 // Only look at the first use, avoid hurting compile time with long uselists
6935 auto *Use = cast<Instruction>(*I->user_begin());
6936 // Bail out if Use is not in the same BB as I or Use == I or Use comes
6937 // before I in the block. The latter two can be the case if Use is a PHI
6938 // node.
6939 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
6940 return false;
6942 // Now make sure that there are no instructions in between that can alter
6943 // control flow (eg. calls)
6944 auto InstrRange =
6945 make_range(std::next(I->getIterator()), Use->getIterator());
6946 if (any_of(InstrRange, [](Instruction &I) {
6947 return !isGuaranteedToTransferExecutionToSuccessor(&I);
6949 return false;
6951 // Look through GEPs. A load from a GEP derived from NULL is still undefined
6952 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6953 if (GEP->getPointerOperand() == I) {
6954 if (!GEP->isInBounds() || !GEP->hasAllZeroIndices())
6955 PtrValueMayBeModified = true;
6956 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
6959 // Look through bitcasts.
6960 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6961 return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified);
6963 // Load from null is undefined.
6964 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6965 if (!LI->isVolatile())
6966 return !NullPointerIsDefined(LI->getFunction(),
6967 LI->getPointerAddressSpace());
6969 // Store to null is undefined.
6970 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6971 if (!SI->isVolatile())
6972 return (!NullPointerIsDefined(SI->getFunction(),
6973 SI->getPointerAddressSpace())) &&
6974 SI->getPointerOperand() == I;
6976 if (auto *CB = dyn_cast<CallBase>(Use)) {
6977 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
6978 return false;
6979 // A call to null is undefined.
6980 if (CB->getCalledOperand() == I)
6981 return true;
6983 if (C->isNullValue()) {
6984 for (const llvm::Use &Arg : CB->args())
6985 if (Arg == I) {
6986 unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6987 if (CB->isPassingUndefUB(ArgIdx) &&
6988 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) {
6989 // Passing null to a nonnnull+noundef argument is undefined.
6990 return !PtrValueMayBeModified;
6993 } else if (isa<UndefValue>(C)) {
6994 // Passing undef to a noundef argument is undefined.
6995 for (const llvm::Use &Arg : CB->args())
6996 if (Arg == I) {
6997 unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6998 if (CB->isPassingUndefUB(ArgIdx)) {
6999 // Passing undef to a noundef argument is undefined.
7000 return true;
7006 return false;
7009 /// If BB has an incoming value that will always trigger undefined behavior
7010 /// (eg. null pointer dereference), remove the branch leading here.
7011 static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
7012 DomTreeUpdater *DTU) {
7013 for (PHINode &PHI : BB->phis())
7014 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
7015 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
7016 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
7017 Instruction *T = Predecessor->getTerminator();
7018 IRBuilder<> Builder(T);
7019 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
7020 BB->removePredecessor(Predecessor);
7021 // Turn unconditional branches into unreachables and remove the dead
7022 // destination from conditional branches.
7023 if (BI->isUnconditional())
7024 Builder.CreateUnreachable();
7025 else {
7026 // Preserve guarding condition in assume, because it might not be
7027 // inferrable from any dominating condition.
7028 Value *Cond = BI->getCondition();
7029 if (BI->getSuccessor(0) == BB)
7030 Builder.CreateAssumption(Builder.CreateNot(Cond));
7031 else
7032 Builder.CreateAssumption(Cond);
7033 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
7034 : BI->getSuccessor(0));
7036 BI->eraseFromParent();
7037 if (DTU)
7038 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
7039 return true;
7040 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
7041 // Redirect all branches leading to UB into
7042 // a newly created unreachable block.
7043 BasicBlock *Unreachable = BasicBlock::Create(
7044 Predecessor->getContext(), "unreachable", BB->getParent(), BB);
7045 Builder.SetInsertPoint(Unreachable);
7046 // The new block contains only one instruction: Unreachable
7047 Builder.CreateUnreachable();
7048 for (const auto &Case : SI->cases())
7049 if (Case.getCaseSuccessor() == BB) {
7050 BB->removePredecessor(Predecessor);
7051 Case.setSuccessor(Unreachable);
7053 if (SI->getDefaultDest() == BB) {
7054 BB->removePredecessor(Predecessor);
7055 SI->setDefaultDest(Unreachable);
7058 if (DTU)
7059 DTU->applyUpdates(
7060 { { DominatorTree::Insert, Predecessor, Unreachable },
7061 { DominatorTree::Delete, Predecessor, BB } });
7062 return true;
7066 return false;
7069 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
7070 bool Changed = false;
7072 assert(BB && BB->getParent() && "Block not embedded in function!");
7073 assert(BB->getTerminator() && "Degenerate basic block encountered!");
7075 // Remove basic blocks that have no predecessors (except the entry block)...
7076 // or that just have themself as a predecessor. These are unreachable.
7077 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
7078 BB->getSinglePredecessor() == BB) {
7079 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
7080 DeleteDeadBlock(BB, DTU);
7081 return true;
7084 // Check to see if we can constant propagate this terminator instruction
7085 // away...
7086 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
7087 /*TLI=*/nullptr, DTU);
7089 // Check for and eliminate duplicate PHI nodes in this block.
7090 Changed |= EliminateDuplicatePHINodes(BB);
7092 // Check for and remove branches that will always cause undefined behavior.
7093 if (removeUndefIntroducingPredecessor(BB, DTU))
7094 return requestResimplify();
7096 // Merge basic blocks into their predecessor if there is only one distinct
7097 // pred, and if there is only one distinct successor of the predecessor, and
7098 // if there are no PHI nodes.
7099 if (MergeBlockIntoPredecessor(BB, DTU))
7100 return true;
7102 if (SinkCommon && Options.SinkCommonInsts)
7103 if (SinkCommonCodeFromPredecessors(BB, DTU) ||
7104 MergeCompatibleInvokes(BB, DTU)) {
7105 // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
7106 // so we may now how duplicate PHI's.
7107 // Let's rerun EliminateDuplicatePHINodes() first,
7108 // before FoldTwoEntryPHINode() potentially converts them into select's,
7109 // after which we'd need a whole EarlyCSE pass run to cleanup them.
7110 return true;
7113 IRBuilder<> Builder(BB);
7115 if (Options.FoldTwoEntryPHINode) {
7116 // If there is a trivial two-entry PHI node in this basic block, and we can
7117 // eliminate it, do so now.
7118 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
7119 if (PN->getNumIncomingValues() == 2)
7120 if (FoldTwoEntryPHINode(PN, TTI, DTU, DL))
7121 return true;
7124 Instruction *Terminator = BB->getTerminator();
7125 Builder.SetInsertPoint(Terminator);
7126 switch (Terminator->getOpcode()) {
7127 case Instruction::Br:
7128 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
7129 break;
7130 case Instruction::Resume:
7131 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
7132 break;
7133 case Instruction::CleanupRet:
7134 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
7135 break;
7136 case Instruction::Switch:
7137 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
7138 break;
7139 case Instruction::Unreachable:
7140 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
7141 break;
7142 case Instruction::IndirectBr:
7143 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
7144 break;
7147 return Changed;
7150 bool SimplifyCFGOpt::run(BasicBlock *BB) {
7151 bool Changed = false;
7153 // Repeated simplify BB as long as resimplification is requested.
7154 do {
7155 Resimplify = false;
7157 // Perform one round of simplifcation. Resimplify flag will be set if
7158 // another iteration is requested.
7159 Changed |= simplifyOnce(BB);
7160 } while (Resimplify);
7162 return Changed;
7165 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
7166 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
7167 ArrayRef<WeakVH> LoopHeaders) {
7168 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
7169 Options)
7170 .run(BB);