Bug Summary

File:llvm/lib/Transforms/Utils/SimplifyCFG.cpp
Warning:line 4406, column 24
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SimplifyCFG.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Transforms/Utils -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Transforms/Utils -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Transforms/Utils -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/Sequence.h"
21#include "llvm/ADT/SetOperations.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Analysis/AssumptionCache.h"
28#include "llvm/Analysis/ConstantFolding.h"
29#include "llvm/Analysis/EHPersonalities.h"
30#include "llvm/Analysis/GuardUtils.h"
31#include "llvm/Analysis/InstructionSimplify.h"
32#include "llvm/Analysis/MemorySSA.h"
33#include "llvm/Analysis/MemorySSAUpdater.h"
34#include "llvm/Analysis/TargetTransformInfo.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/ConstantRange.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/GlobalVariable.h"
47#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
50#include "llvm/IR/Instructions.h"
51#include "llvm/IR/IntrinsicInst.h"
52#include "llvm/IR/Intrinsics.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/PseudoProbe.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/SSAUpdater.h"
77#include "llvm/Transforms/Utils/ValueMapper.h"
78#include <algorithm>
79#include <cassert>
80#include <climits>
81#include <cstddef>
82#include <cstdint>
83#include <iterator>
84#include <map>
85#include <set>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace PatternMatch;
92
93#define DEBUG_TYPE"simplifycfg" "simplifycfg"
94
95cl::opt<bool> llvm::RequireAndPreserveDomTree(
96 "simplifycfg-require-and-preserve-domtree", cl::Hidden, cl::ZeroOrMore,
97 cl::init(false),
98 cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
99 "into preserving DomTree,"));
100
101// Chosen as 2 so as to be cheap, but still to have enough power to fold
102// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
103// To catch this, we need to fold a compare and a select, hence '2' being the
104// minimum reasonable default.
105static cl::opt<unsigned> PHINodeFoldingThreshold(
106 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
107 cl::desc(
108 "Control the amount of phi node folding to perform (default = 2)"));
109
110static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
111 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
112 cl::desc("Control the maximal total instruction cost that we are willing "
113 "to speculatively execute to fold a 2-entry PHI node into a "
114 "select (default = 4)"));
115
116static cl::opt<bool> DupRet(
117 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
118 cl::desc("Duplicate return instructions into unconditional branches"));
119
120static cl::opt<bool>
121 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
122 cl::desc("Hoist common instructions up to the parent block"));
123
124static cl::opt<bool>
125 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
126 cl::desc("Sink common instructions down to the end block"));
127
128static cl::opt<bool> HoistCondStores(
129 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
130 cl::desc("Hoist conditional stores if an unconditional store precedes"));
131
132static cl::opt<bool> MergeCondStores(
133 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
134 cl::desc("Hoist conditional stores even if an unconditional store does not "
135 "precede - hoist multiple conditional stores into a single "
136 "predicated store"));
137
138static cl::opt<bool> MergeCondStoresAggressively(
139 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
140 cl::desc("When merging conditional stores, do so even if the resultant "
141 "basic blocks are unlikely to be if-converted as a result"));
142
143static cl::opt<bool> SpeculateOneExpensiveInst(
144 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
145 cl::desc("Allow exactly one expensive instruction to be speculatively "
146 "executed"));
147
148static cl::opt<unsigned> MaxSpeculationDepth(
149 "max-speculation-depth", cl::Hidden, cl::init(10),
150 cl::desc("Limit maximum recursion depth when calculating costs of "
151 "speculatively executed instructions"));
152
153static cl::opt<int>
154 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
155 cl::init(10),
156 cl::desc("Max size of a block which is still considered "
157 "small enough to thread through"));
158
159// Two is chosen to allow one negation and a logical combine.
160static cl::opt<unsigned>
161 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
162 cl::init(2),
163 cl::desc("Maximum cost of combining conditions when "
164 "folding branches"));
165
166STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps")static llvm::Statistic NumBitMaps = {"simplifycfg", "NumBitMaps"
, "Number of switch instructions turned into bitmaps"}
;
167STATISTIC(NumLinearMaps,static llvm::Statistic NumLinearMaps = {"simplifycfg", "NumLinearMaps"
, "Number of switch instructions turned into linear mapping"}
168 "Number of switch instructions turned into linear mapping")static llvm::Statistic NumLinearMaps = {"simplifycfg", "NumLinearMaps"
, "Number of switch instructions turned into linear mapping"}
;
169STATISTIC(NumLookupTables,static llvm::Statistic NumLookupTables = {"simplifycfg", "NumLookupTables"
, "Number of switch instructions turned into lookup tables"}
170 "Number of switch instructions turned into lookup tables")static llvm::Statistic NumLookupTables = {"simplifycfg", "NumLookupTables"
, "Number of switch instructions turned into lookup tables"}
;
171STATISTIC(static llvm::Statistic NumLookupTablesHoles = {"simplifycfg",
"NumLookupTablesHoles", "Number of switch instructions turned into lookup tables (holes checked)"
}
172 NumLookupTablesHoles,static llvm::Statistic NumLookupTablesHoles = {"simplifycfg",
"NumLookupTablesHoles", "Number of switch instructions turned into lookup tables (holes checked)"
}
173 "Number of switch instructions turned into lookup tables (holes checked)")static llvm::Statistic NumLookupTablesHoles = {"simplifycfg",
"NumLookupTablesHoles", "Number of switch instructions turned into lookup tables (holes checked)"
}
;
174STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares")static llvm::Statistic NumTableCmpReuses = {"simplifycfg", "NumTableCmpReuses"
, "Number of reused switch table lookup compares"}
;
175STATISTIC(NumFoldValueComparisonIntoPredecessors,static llvm::Statistic NumFoldValueComparisonIntoPredecessors
= {"simplifycfg", "NumFoldValueComparisonIntoPredecessors", "Number of value comparisons folded into predecessor basic blocks"
}
176 "Number of value comparisons folded into predecessor basic blocks")static llvm::Statistic NumFoldValueComparisonIntoPredecessors
= {"simplifycfg", "NumFoldValueComparisonIntoPredecessors", "Number of value comparisons folded into predecessor basic blocks"
}
;
177STATISTIC(NumFoldBranchToCommonDest,static llvm::Statistic NumFoldBranchToCommonDest = {"simplifycfg"
, "NumFoldBranchToCommonDest", "Number of branches folded into predecessor basic block"
}
178 "Number of branches folded into predecessor basic block")static llvm::Statistic NumFoldBranchToCommonDest = {"simplifycfg"
, "NumFoldBranchToCommonDest", "Number of branches folded into predecessor basic block"
}
;
179STATISTIC(static llvm::Statistic NumHoistCommonCode = {"simplifycfg", "NumHoistCommonCode"
, "Number of common instruction 'blocks' hoisted up to the begin block"
}
180 NumHoistCommonCode,static llvm::Statistic NumHoistCommonCode = {"simplifycfg", "NumHoistCommonCode"
, "Number of common instruction 'blocks' hoisted up to the begin block"
}
181 "Number of common instruction 'blocks' hoisted up to the begin block")static llvm::Statistic NumHoistCommonCode = {"simplifycfg", "NumHoistCommonCode"
, "Number of common instruction 'blocks' hoisted up to the begin block"
}
;
182STATISTIC(NumHoistCommonInstrs,static llvm::Statistic NumHoistCommonInstrs = {"simplifycfg",
"NumHoistCommonInstrs", "Number of common instructions hoisted up to the begin block"
}
183 "Number of common instructions hoisted up to the begin block")static llvm::Statistic NumHoistCommonInstrs = {"simplifycfg",
"NumHoistCommonInstrs", "Number of common instructions hoisted up to the begin block"
}
;
184STATISTIC(NumSinkCommonCode,static llvm::Statistic NumSinkCommonCode = {"simplifycfg", "NumSinkCommonCode"
, "Number of common instruction 'blocks' sunk down to the end block"
}
185 "Number of common instruction 'blocks' sunk down to the end block")static llvm::Statistic NumSinkCommonCode = {"simplifycfg", "NumSinkCommonCode"
, "Number of common instruction 'blocks' sunk down to the end block"
}
;
186STATISTIC(NumSinkCommonInstrs,static llvm::Statistic NumSinkCommonInstrs = {"simplifycfg", "NumSinkCommonInstrs"
, "Number of common instructions sunk down to the end block"}
187 "Number of common instructions sunk down to the end block")static llvm::Statistic NumSinkCommonInstrs = {"simplifycfg", "NumSinkCommonInstrs"
, "Number of common instructions sunk down to the end block"}
;
188STATISTIC(NumSpeculations, "Number of speculative executed instructions")static llvm::Statistic NumSpeculations = {"simplifycfg", "NumSpeculations"
, "Number of speculative executed instructions"}
;
189STATISTIC(NumInvokes,static llvm::Statistic NumInvokes = {"simplifycfg", "NumInvokes"
, "Number of invokes with empty resume blocks simplified into calls"
}
190 "Number of invokes with empty resume blocks simplified into calls")static llvm::Statistic NumInvokes = {"simplifycfg", "NumInvokes"
, "Number of invokes with empty resume blocks simplified into calls"
}
;
191
192namespace {
193
194// The first field contains the value that the switch produces when a certain
195// case group is selected, and the second field is a vector containing the
196// cases composing the case group.
197using SwitchCaseResultVectorTy =
198 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
199
200// The first field contains the phi node that generates a result of the switch
201// and the second field contains the value generated for a certain case in the
202// switch for that PHI.
203using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
204
205/// ValueEqualityComparisonCase - Represents a case of a switch.
206struct ValueEqualityComparisonCase {
207 ConstantInt *Value;
208 BasicBlock *Dest;
209
210 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
211 : Value(Value), Dest(Dest) {}
212
213 bool operator<(ValueEqualityComparisonCase RHS) const {
214 // Comparing pointers is ok as we only rely on the order for uniquing.
215 return Value < RHS.Value;
216 }
217
218 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
219};
220
221class SimplifyCFGOpt {
222 const TargetTransformInfo &TTI;
223 DomTreeUpdater *DTU;
224 const DataLayout &DL;
225 ArrayRef<WeakVH> LoopHeaders;
226 const SimplifyCFGOptions &Options;
227 bool Resimplify;
228
229 Value *isValueEqualityComparison(Instruction *TI);
230 BasicBlock *GetValueEqualityComparisonCases(
231 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
232 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
233 BasicBlock *Pred,
234 IRBuilder<> &Builder);
235 bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
236 Instruction *PTI,
237 IRBuilder<> &Builder);
238 bool FoldValueComparisonIntoPredecessors(Instruction *TI,
239 IRBuilder<> &Builder);
240
241 bool simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
242 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
243 bool simplifySingleResume(ResumeInst *RI);
244 bool simplifyCommonResume(ResumeInst *RI);
245 bool simplifyCleanupReturn(CleanupReturnInst *RI);
246 bool simplifyUnreachable(UnreachableInst *UI);
247 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
248 bool simplifyIndirectBr(IndirectBrInst *IBI);
249 bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
250 bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
251 bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
252 bool SimplifyCondBranchToTwoReturns(BranchInst *BI, IRBuilder<> &Builder);
253
254 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
255 IRBuilder<> &Builder);
256
257 bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI,
258 bool EqTermsOnly);
259 bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
260 const TargetTransformInfo &TTI);
261 bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
262 BasicBlock *TrueBB, BasicBlock *FalseBB,
263 uint32_t TrueWeight, uint32_t FalseWeight);
264 bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
265 const DataLayout &DL);
266 bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
267 bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
268 bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
269
270public:
271 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
272 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
273 const SimplifyCFGOptions &Opts)
274 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
275 assert((!DTU || !DTU->hasPostDomTree()) &&(static_cast <bool> ((!DTU || !DTU->hasPostDomTree()
) && "SimplifyCFG is not yet capable of maintaining validity of a "
"PostDomTree, so don't ask for it.") ? void (0) : __assert_fail
("(!DTU || !DTU->hasPostDomTree()) && \"SimplifyCFG is not yet capable of maintaining validity of a \" \"PostDomTree, so don't ask for it.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 277, __extension__ __PRETTY_FUNCTION__))
276 "SimplifyCFG is not yet capable of maintaining validity of a "(static_cast <bool> ((!DTU || !DTU->hasPostDomTree()
) && "SimplifyCFG is not yet capable of maintaining validity of a "
"PostDomTree, so don't ask for it.") ? void (0) : __assert_fail
("(!DTU || !DTU->hasPostDomTree()) && \"SimplifyCFG is not yet capable of maintaining validity of a \" \"PostDomTree, so don't ask for it.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 277, __extension__ __PRETTY_FUNCTION__))
277 "PostDomTree, so don't ask for it.")(static_cast <bool> ((!DTU || !DTU->hasPostDomTree()
) && "SimplifyCFG is not yet capable of maintaining validity of a "
"PostDomTree, so don't ask for it.") ? void (0) : __assert_fail
("(!DTU || !DTU->hasPostDomTree()) && \"SimplifyCFG is not yet capable of maintaining validity of a \" \"PostDomTree, so don't ask for it.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 277, __extension__ __PRETTY_FUNCTION__))
;
278 }
279
280 bool simplifyOnce(BasicBlock *BB);
281 bool simplifyOnceImpl(BasicBlock *BB);
282 bool run(BasicBlock *BB);
283
284 // Helper to set Resimplify and return change indication.
285 bool requestResimplify() {
286 Resimplify = true;
287 return true;
288 }
289};
290
291} // end anonymous namespace
292
293/// Return true if it is safe to merge these two
294/// terminator instructions together.
295static bool
296SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
297 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
298 if (SI1 == SI2)
299 return false; // Can't merge with self!
300
301 // It is not safe to merge these two switch instructions if they have a common
302 // successor, and if that successor has a PHI node, and if *that* PHI node has
303 // conflicting incoming values from the two switch blocks.
304 BasicBlock *SI1BB = SI1->getParent();
305 BasicBlock *SI2BB = SI2->getParent();
306
307 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
308 bool Fail = false;
309 for (BasicBlock *Succ : successors(SI2BB))
310 if (SI1Succs.count(Succ))
311 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
312 PHINode *PN = cast<PHINode>(BBI);
313 if (PN->getIncomingValueForBlock(SI1BB) !=
314 PN->getIncomingValueForBlock(SI2BB)) {
315 if (FailBlocks)
316 FailBlocks->insert(Succ);
317 Fail = true;
318 }
319 }
320
321 return !Fail;
322}
323
324/// Update PHI nodes in Succ to indicate that there will now be entries in it
325/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
326/// will be the same as those coming in from ExistPred, an existing predecessor
327/// of Succ.
328static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
329 BasicBlock *ExistPred,
330 MemorySSAUpdater *MSSAU = nullptr) {
331 for (PHINode &PN : Succ->phis())
332 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
333 if (MSSAU)
334 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
335 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
336}
337
338/// Compute an abstract "cost" of speculating the given instruction,
339/// which is assumed to be safe to speculate. TCC_Free means cheap,
340/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
341/// expensive.
342static InstructionCost computeSpeculationCost(const User *I,
343 const TargetTransformInfo &TTI) {
344 assert(isSafeToSpeculativelyExecute(I) &&(static_cast <bool> (isSafeToSpeculativelyExecute(I) &&
"Instruction is not safe to speculatively execute!") ? void (
0) : __assert_fail ("isSafeToSpeculativelyExecute(I) && \"Instruction is not safe to speculatively execute!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 345, __extension__ __PRETTY_FUNCTION__))
345 "Instruction is not safe to speculatively execute!")(static_cast <bool> (isSafeToSpeculativelyExecute(I) &&
"Instruction is not safe to speculatively execute!") ? void (
0) : __assert_fail ("isSafeToSpeculativelyExecute(I) && \"Instruction is not safe to speculatively execute!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 345, __extension__ __PRETTY_FUNCTION__))
;
346 return TTI.getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency);
347}
348
349/// If we have a merge point of an "if condition" as accepted above,
350/// return true if the specified value dominates the block. We
351/// don't handle the true generality of domination here, just a special case
352/// which works well enough for us.
353///
354/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
355/// see if V (which must be an instruction) and its recursive operands
356/// that do not dominate BB have a combined cost lower than Budget and
357/// are non-trapping. If both are true, the instruction is inserted into the
358/// set and true is returned.
359///
360/// The cost for most non-trapping instructions is defined as 1 except for
361/// Select whose cost is 2.
362///
363/// After this function returns, Cost is increased by the cost of
364/// V plus its non-dominating operands. If that cost is greater than
365/// Budget, false is returned and Cost is undefined.
366static bool dominatesMergePoint(Value *V, BasicBlock *BB,
367 SmallPtrSetImpl<Instruction *> &AggressiveInsts,
368 InstructionCost &Cost,
369 InstructionCost Budget,
370 const TargetTransformInfo &TTI,
371 unsigned Depth = 0) {
372 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
373 // so limit the recursion depth.
374 // TODO: While this recursion limit does prevent pathological behavior, it
375 // would be better to track visited instructions to avoid cycles.
376 if (Depth == MaxSpeculationDepth)
377 return false;
378
379 Instruction *I = dyn_cast<Instruction>(V);
380 if (!I) {
381 // Non-instructions all dominate instructions, but not all constantexprs
382 // can be executed unconditionally.
383 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
384 if (C->canTrap())
385 return false;
386 return true;
387 }
388 BasicBlock *PBB = I->getParent();
389
390 // We don't want to allow weird loops that might have the "if condition" in
391 // the bottom of this block.
392 if (PBB == BB)
393 return false;
394
395 // If this instruction is defined in a block that contains an unconditional
396 // branch to BB, then it must be in the 'conditional' part of the "if
397 // statement". If not, it definitely dominates the region.
398 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
399 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
400 return true;
401
402 // If we have seen this instruction before, don't count it again.
403 if (AggressiveInsts.count(I))
404 return true;
405
406 // Okay, it looks like the instruction IS in the "condition". Check to
407 // see if it's a cheap instruction to unconditionally compute, and if it
408 // only uses stuff defined outside of the condition. If so, hoist it out.
409 if (!isSafeToSpeculativelyExecute(I))
410 return false;
411
412 Cost += computeSpeculationCost(I, TTI);
413
414 // Allow exactly one instruction to be speculated regardless of its cost
415 // (as long as it is safe to do so).
416 // This is intended to flatten the CFG even if the instruction is a division
417 // or other expensive operation. The speculation of an expensive instruction
418 // is expected to be undone in CodeGenPrepare if the speculation has not
419 // enabled further IR optimizations.
420 if (Cost > Budget &&
421 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
422 !Cost.isValid()))
423 return false;
424
425 // Okay, we can only really hoist these out if their operands do
426 // not take us over the cost threshold.
427 for (Use &Op : I->operands())
428 if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
429 Depth + 1))
430 return false;
431 // Okay, it's safe to do this! Remember this instruction.
432 AggressiveInsts.insert(I);
433 return true;
434}
435
436/// Extract ConstantInt from value, looking through IntToPtr
437/// and PointerNullValue. Return NULL if value is not a constant int.
438static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
439 // Normal constant int.
440 ConstantInt *CI = dyn_cast<ConstantInt>(V);
441 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
442 return CI;
443
444 // This is some kind of pointer constant. Turn it into a pointer-sized
445 // ConstantInt if possible.
446 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
447
448 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
449 if (isa<ConstantPointerNull>(V))
450 return ConstantInt::get(PtrTy, 0);
451
452 // IntToPtr const int.
453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
454 if (CE->getOpcode() == Instruction::IntToPtr)
455 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
456 // The constant is very likely to have the right type already.
457 if (CI->getType() == PtrTy)
458 return CI;
459 else
460 return cast<ConstantInt>(
461 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
462 }
463 return nullptr;
464}
465
466namespace {
467
468/// Given a chain of or (||) or and (&&) comparison of a value against a
469/// constant, this will try to recover the information required for a switch
470/// structure.
471/// It will depth-first traverse the chain of comparison, seeking for patterns
472/// like %a == 12 or %a < 4 and combine them to produce a set of integer
473/// representing the different cases for the switch.
474/// Note that if the chain is composed of '||' it will build the set of elements
475/// that matches the comparisons (i.e. any of this value validate the chain)
476/// while for a chain of '&&' it will build the set elements that make the test
477/// fail.
478struct ConstantComparesGatherer {
479 const DataLayout &DL;
480
481 /// Value found for the switch comparison
482 Value *CompValue = nullptr;
483
484 /// Extra clause to be checked before the switch
485 Value *Extra = nullptr;
486
487 /// Set of integers to match in switch
488 SmallVector<ConstantInt *, 8> Vals;
489
490 /// Number of comparisons matched in the and/or chain
491 unsigned UsedICmps = 0;
492
493 /// Construct and compute the result for the comparison instruction Cond
494 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
495 gather(Cond);
496 }
497
498 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
499 ConstantComparesGatherer &
500 operator=(const ConstantComparesGatherer &) = delete;
501
502private:
503 /// Try to set the current value used for the comparison, it succeeds only if
504 /// it wasn't set before or if the new value is the same as the old one
505 bool setValueOnce(Value *NewVal) {
506 if (CompValue && CompValue != NewVal)
507 return false;
508 CompValue = NewVal;
509 return (CompValue != nullptr);
510 }
511
512 /// Try to match Instruction "I" as a comparison against a constant and
513 /// populates the array Vals with the set of values that match (or do not
514 /// match depending on isEQ).
515 /// Return false on failure. On success, the Value the comparison matched
516 /// against is placed in CompValue.
517 /// If CompValue is already set, the function is expected to fail if a match
518 /// is found but the value compared to is different.
519 bool matchInstruction(Instruction *I, bool isEQ) {
520 // If this is an icmp against a constant, handle this as one of the cases.
521 ICmpInst *ICI;
522 ConstantInt *C;
523 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
524 (C = GetConstantInt(I->getOperand(1), DL)))) {
525 return false;
526 }
527
528 Value *RHSVal;
529 const APInt *RHSC;
530
531 // Pattern match a special case
532 // (x & ~2^z) == y --> x == y || x == y|2^z
533 // This undoes a transformation done by instcombine to fuse 2 compares.
534 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
535 // It's a little bit hard to see why the following transformations are
536 // correct. Here is a CVC3 program to verify them for 64-bit values:
537
538 /*
539 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
540 x : BITVECTOR(64);
541 y : BITVECTOR(64);
542 z : BITVECTOR(64);
543 mask : BITVECTOR(64) = BVSHL(ONE, z);
544 QUERY( (y & ~mask = y) =>
545 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
546 );
547 QUERY( (y | mask = y) =>
548 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
549 );
550 */
551
552 // Please note that each pattern must be a dual implication (<--> or
553 // iff). One directional implication can create spurious matches. If the
554 // implication is only one-way, an unsatisfiable condition on the left
555 // side can imply a satisfiable condition on the right side. Dual
556 // implication ensures that satisfiable conditions are transformed to
557 // other satisfiable conditions and unsatisfiable conditions are
558 // transformed to other unsatisfiable conditions.
559
560 // Here is a concrete example of a unsatisfiable condition on the left
561 // implying a satisfiable condition on the right:
562 //
563 // mask = (1 << z)
564 // (x & ~mask) == y --> (x == y || x == (y | mask))
565 //
566 // Substituting y = 3, z = 0 yields:
567 // (x & -2) == 3 --> (x == 3 || x == 2)
568
569 // Pattern match a special case:
570 /*
571 QUERY( (y & ~mask = y) =>
572 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
573 );
574 */
575 if (match(ICI->getOperand(0),
576 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
577 APInt Mask = ~*RHSC;
578 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
579 // If we already have a value for the switch, it has to match!
580 if (!setValueOnce(RHSVal))
581 return false;
582
583 Vals.push_back(C);
584 Vals.push_back(
585 ConstantInt::get(C->getContext(),
586 C->getValue() | Mask));
587 UsedICmps++;
588 return true;
589 }
590 }
591
592 // Pattern match a special case:
593 /*
594 QUERY( (y | mask = y) =>
595 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
596 );
597 */
598 if (match(ICI->getOperand(0),
599 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
600 APInt Mask = *RHSC;
601 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
602 // If we already have a value for the switch, it has to match!
603 if (!setValueOnce(RHSVal))
604 return false;
605
606 Vals.push_back(C);
607 Vals.push_back(ConstantInt::get(C->getContext(),
608 C->getValue() & ~Mask));
609 UsedICmps++;
610 return true;
611 }
612 }
613
614 // If we already have a value for the switch, it has to match!
615 if (!setValueOnce(ICI->getOperand(0)))
616 return false;
617
618 UsedICmps++;
619 Vals.push_back(C);
620 return ICI->getOperand(0);
621 }
622
623 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
624 ConstantRange Span =
625 ConstantRange::makeExactICmpRegion(ICI->getPredicate(), C->getValue());
626
627 // Shift the range if the compare is fed by an add. This is the range
628 // compare idiom as emitted by instcombine.
629 Value *CandidateVal = I->getOperand(0);
630 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
631 Span = Span.subtract(*RHSC);
632 CandidateVal = RHSVal;
633 }
634
635 // If this is an and/!= check, then we are looking to build the set of
636 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
637 // x != 0 && x != 1.
638 if (!isEQ)
639 Span = Span.inverse();
640
641 // If there are a ton of values, we don't want to make a ginormous switch.
642 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
643 return false;
644 }
645
646 // If we already have a value for the switch, it has to match!
647 if (!setValueOnce(CandidateVal))
648 return false;
649
650 // Add all values from the range to the set
651 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
652 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
653
654 UsedICmps++;
655 return true;
656 }
657
658 /// Given a potentially 'or'd or 'and'd together collection of icmp
659 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
660 /// the value being compared, and stick the list constants into the Vals
661 /// vector.
662 /// One "Extra" case is allowed to differ from the other.
663 void gather(Value *V) {
664 bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
665
666 // Keep a stack (SmallVector for efficiency) for depth-first traversal
667 SmallVector<Value *, 8> DFT;
668 SmallPtrSet<Value *, 8> Visited;
669
670 // Initialize
671 Visited.insert(V);
672 DFT.push_back(V);
673
674 while (!DFT.empty()) {
675 V = DFT.pop_back_val();
676
677 if (Instruction *I = dyn_cast<Instruction>(V)) {
678 // If it is a || (or && depending on isEQ), process the operands.
679 Value *Op0, *Op1;
680 if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
681 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
682 if (Visited.insert(Op1).second)
683 DFT.push_back(Op1);
684 if (Visited.insert(Op0).second)
685 DFT.push_back(Op0);
686
687 continue;
688 }
689
690 // Try to match the current instruction
691 if (matchInstruction(I, isEQ))
692 // Match succeed, continue the loop
693 continue;
694 }
695
696 // One element of the sequence of || (or &&) could not be match as a
697 // comparison against the same value as the others.
698 // We allow only one "Extra" case to be checked before the switch
699 if (!Extra) {
700 Extra = V;
701 continue;
702 }
703 // Failed to parse a proper sequence, abort now
704 CompValue = nullptr;
705 break;
706 }
707 }
708};
709
710} // end anonymous namespace
711
712static void EraseTerminatorAndDCECond(Instruction *TI,
713 MemorySSAUpdater *MSSAU = nullptr) {
714 Instruction *Cond = nullptr;
715 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
716 Cond = dyn_cast<Instruction>(SI->getCondition());
717 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
718 if (BI->isConditional())
719 Cond = dyn_cast<Instruction>(BI->getCondition());
720 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
721 Cond = dyn_cast<Instruction>(IBI->getAddress());
722 }
723
724 TI->eraseFromParent();
725 if (Cond)
726 RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
727}
728
729/// Return true if the specified terminator checks
730/// to see if a value is equal to constant integer value.
731Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
732 Value *CV = nullptr;
733 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
734 // Do not permit merging of large switch instructions into their
735 // predecessors unless there is only one predecessor.
736 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
737 CV = SI->getCondition();
738 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
739 if (BI->isConditional() && BI->getCondition()->hasOneUse())
740 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
741 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
742 CV = ICI->getOperand(0);
743 }
744
745 // Unwrap any lossless ptrtoint cast.
746 if (CV) {
747 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
748 Value *Ptr = PTII->getPointerOperand();
749 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
750 CV = Ptr;
751 }
752 }
753 return CV;
754}
755
756/// Given a value comparison instruction,
757/// decode all of the 'cases' that it represents and return the 'default' block.
758BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
759 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
760 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
761 Cases.reserve(SI->getNumCases());
762 for (auto Case : SI->cases())
763 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
764 Case.getCaseSuccessor()));
765 return SI->getDefaultDest();
766 }
767
768 BranchInst *BI = cast<BranchInst>(TI);
769 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
770 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
771 Cases.push_back(ValueEqualityComparisonCase(
772 GetConstantInt(ICI->getOperand(1), DL), Succ));
773 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
774}
775
776/// Given a vector of bb/value pairs, remove any entries
777/// in the list that match the specified block.
778static void
779EliminateBlockCases(BasicBlock *BB,
780 std::vector<ValueEqualityComparisonCase> &Cases) {
781 llvm::erase_value(Cases, BB);
782}
783
784/// Return true if there are any keys in C1 that exist in C2 as well.
785static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
786 std::vector<ValueEqualityComparisonCase> &C2) {
787 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
788
789 // Make V1 be smaller than V2.
790 if (V1->size() > V2->size())
791 std::swap(V1, V2);
792
793 if (V1->empty())
794 return false;
795 if (V1->size() == 1) {
796 // Just scan V2.
797 ConstantInt *TheVal = (*V1)[0].Value;
798 for (unsigned i = 0, e = V2->size(); i != e; ++i)
799 if (TheVal == (*V2)[i].Value)
800 return true;
801 }
802
803 // Otherwise, just sort both lists and compare element by element.
804 array_pod_sort(V1->begin(), V1->end());
805 array_pod_sort(V2->begin(), V2->end());
806 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
807 while (i1 != e1 && i2 != e2) {
808 if ((*V1)[i1].Value == (*V2)[i2].Value)
809 return true;
810 if ((*V1)[i1].Value < (*V2)[i2].Value)
811 ++i1;
812 else
813 ++i2;
814 }
815 return false;
816}
817
818// Set branch weights on SwitchInst. This sets the metadata if there is at
819// least one non-zero weight.
820static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
821 // Check that there is at least one non-zero weight. Otherwise, pass
822 // nullptr to setMetadata which will erase the existing metadata.
823 MDNode *N = nullptr;
824 if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
825 N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
826 SI->setMetadata(LLVMContext::MD_prof, N);
827}
828
829// Similar to the above, but for branch and select instructions that take
830// exactly 2 weights.
831static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
832 uint32_t FalseWeight) {
833 assert(isa<BranchInst>(I) || isa<SelectInst>(I))(static_cast <bool> (isa<BranchInst>(I) || isa<
SelectInst>(I)) ? void (0) : __assert_fail ("isa<BranchInst>(I) || isa<SelectInst>(I)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 833, __extension__ __PRETTY_FUNCTION__))
;
834 // Check that there is at least one non-zero weight. Otherwise, pass
835 // nullptr to setMetadata which will erase the existing metadata.
836 MDNode *N = nullptr;
837 if (TrueWeight || FalseWeight)
838 N = MDBuilder(I->getParent()->getContext())
839 .createBranchWeights(TrueWeight, FalseWeight);
840 I->setMetadata(LLVMContext::MD_prof, N);
841}
842
843/// If TI is known to be a terminator instruction and its block is known to
844/// only have a single predecessor block, check to see if that predecessor is
845/// also a value comparison with the same value, and if that comparison
846/// determines the outcome of this comparison. If so, simplify TI. This does a
847/// very limited form of jump threading.
848bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
849 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
850 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
851 if (!PredVal)
852 return false; // Not a value comparison in predecessor.
853
854 Value *ThisVal = isValueEqualityComparison(TI);
855 assert(ThisVal && "This isn't a value comparison!!")(static_cast <bool> (ThisVal && "This isn't a value comparison!!"
) ? void (0) : __assert_fail ("ThisVal && \"This isn't a value comparison!!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 855, __extension__ __PRETTY_FUNCTION__))
;
856 if (ThisVal != PredVal)
857 return false; // Different predicates.
858
859 // TODO: Preserve branch weight metadata, similarly to how
860 // FoldValueComparisonIntoPredecessors preserves it.
861
862 // Find out information about when control will move from Pred to TI's block.
863 std::vector<ValueEqualityComparisonCase> PredCases;
864 BasicBlock *PredDef =
865 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
866 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
867
868 // Find information about how control leaves this block.
869 std::vector<ValueEqualityComparisonCase> ThisCases;
870 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
871 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
872
873 // If TI's block is the default block from Pred's comparison, potentially
874 // simplify TI based on this knowledge.
875 if (PredDef == TI->getParent()) {
876 // If we are here, we know that the value is none of those cases listed in
877 // PredCases. If there are any cases in ThisCases that are in PredCases, we
878 // can simplify TI.
879 if (!ValuesOverlap(PredCases, ThisCases))
880 return false;
881
882 if (isa<BranchInst>(TI)) {
883 // Okay, one of the successors of this condbr is dead. Convert it to a
884 // uncond br.
885 assert(ThisCases.size() == 1 && "Branch can only have one case!")(static_cast <bool> (ThisCases.size() == 1 && "Branch can only have one case!"
) ? void (0) : __assert_fail ("ThisCases.size() == 1 && \"Branch can only have one case!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 885, __extension__ __PRETTY_FUNCTION__))
;
886 // Insert the new branch.
887 Instruction *NI = Builder.CreateBr(ThisDef);
888 (void)NI;
889
890 // Remove PHI node entries for the dead edge.
891 ThisCases[0].Dest->removePredecessor(PredDef);
892
893 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
894 << "Through successor TI: " << *TI << "Leaving: " << *NIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
895 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
;
896
897 EraseTerminatorAndDCECond(TI);
898
899 if (DTU)
900 DTU->applyUpdates(
901 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
902
903 return true;
904 }
905
906 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
907 // Okay, TI has cases that are statically dead, prune them away.
908 SmallPtrSet<Constant *, 16> DeadCases;
909 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
910 DeadCases.insert(PredCases[i].Value);
911
912 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI; } } while (false)
913 << "Through successor TI: " << *TI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI; } } while (false)
;
914
915 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
916 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
917 --i;
918 auto *Successor = i->getCaseSuccessor();
919 if (DTU)
920 ++NumPerSuccessorCases[Successor];
921 if (DeadCases.count(i->getCaseValue())) {
922 Successor->removePredecessor(PredDef);
923 SI.removeCase(i);
924 if (DTU)
925 --NumPerSuccessorCases[Successor];
926 }
927 }
928
929 if (DTU) {
930 std::vector<DominatorTree::UpdateType> Updates;
931 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
932 if (I.second == 0)
933 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
934 DTU->applyUpdates(Updates);
935 }
936
937 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Leaving: " << *TI <<
"\n"; } } while (false)
;
938 return true;
939 }
940
941 // Otherwise, TI's block must correspond to some matched value. Find out
942 // which value (or set of values) this is.
943 ConstantInt *TIV = nullptr;
944 BasicBlock *TIBB = TI->getParent();
945 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946 if (PredCases[i].Dest == TIBB) {
947 if (TIV)
948 return false; // Cannot handle multiple values coming to this block.
949 TIV = PredCases[i].Value;
950 }
951 assert(TIV && "No edge from pred to succ?")(static_cast <bool> (TIV && "No edge from pred to succ?"
) ? void (0) : __assert_fail ("TIV && \"No edge from pred to succ?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 951, __extension__ __PRETTY_FUNCTION__))
;
952
953 // Okay, we found the one constant that our value can be if we get into TI's
954 // BB. Find out which successor will unconditionally be branched to.
955 BasicBlock *TheRealDest = nullptr;
956 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
957 if (ThisCases[i].Value == TIV) {
958 TheRealDest = ThisCases[i].Dest;
959 break;
960 }
961
962 // If not handled by any explicit cases, it is handled by the default case.
963 if (!TheRealDest)
964 TheRealDest = ThisDef;
965
966 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
967
968 // Remove PHI node entries for dead edges.
969 BasicBlock *CheckEdge = TheRealDest;
970 for (BasicBlock *Succ : successors(TIBB))
971 if (Succ != CheckEdge) {
972 if (Succ != TheRealDest)
973 RemovedSuccs.insert(Succ);
974 Succ->removePredecessor(TIBB);
975 } else
976 CheckEdge = nullptr;
977
978 // Insert the new branch.
979 Instruction *NI = Builder.CreateBr(TheRealDest);
980 (void)NI;
981
982 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
983 << "Through successor TI: " << *TI << "Leaving: " << *NIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
984 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Threading pred instr: " <<
*Pred->getTerminator() << "Through successor TI: " <<
*TI << "Leaving: " << *NI << "\n"; } } while
(false)
;
985
986 EraseTerminatorAndDCECond(TI);
987 if (DTU) {
988 SmallVector<DominatorTree::UpdateType, 2> Updates;
989 Updates.reserve(RemovedSuccs.size());
990 for (auto *RemovedSucc : RemovedSuccs)
991 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
992 DTU->applyUpdates(Updates);
993 }
994 return true;
995}
996
997namespace {
998
999/// This class implements a stable ordering of constant
1000/// integers that does not depend on their address. This is important for
1001/// applications that sort ConstantInt's to ensure uniqueness.
1002struct ConstantIntOrdering {
1003 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1004 return LHS->getValue().ult(RHS->getValue());
1005 }
1006};
1007
1008} // end anonymous namespace
1009
1010static int ConstantIntSortPredicate(ConstantInt *const *P1,
1011 ConstantInt *const *P2) {
1012 const ConstantInt *LHS = *P1;
1013 const ConstantInt *RHS = *P2;
1014 if (LHS == RHS)
1015 return 0;
1016 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1017}
1018
1019static inline bool HasBranchWeights(const Instruction *I) {
1020 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
1021 if (ProfMD && ProfMD->getOperand(0))
1022 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
1023 return MDS->getString().equals("branch_weights");
1024
1025 return false;
1026}
1027
1028/// Get Weights of a given terminator, the default weight is at the front
1029/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1030/// metadata.
1031static void GetBranchWeights(Instruction *TI,
1032 SmallVectorImpl<uint64_t> &Weights) {
1033 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1034 assert(MD)(static_cast <bool> (MD) ? void (0) : __assert_fail ("MD"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1034, __extension__ __PRETTY_FUNCTION__))
;
1035 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
1036 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
1037 Weights.push_back(CI->getValue().getZExtValue());
1038 }
1039
1040 // If TI is a conditional eq, the default case is the false case,
1041 // and the corresponding branch-weight data is at index 2. We swap the
1042 // default weight to be the first entry.
1043 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1044 assert(Weights.size() == 2)(static_cast <bool> (Weights.size() == 2) ? void (0) : __assert_fail
("Weights.size() == 2", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1044, __extension__ __PRETTY_FUNCTION__))
;
1045 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
1046 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1047 std::swap(Weights.front(), Weights.back());
1048 }
1049}
1050
1051/// Keep halving the weights until all can fit in uint32_t.
1052static void FitWeights(MutableArrayRef<uint64_t> Weights) {
1053 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
1054 if (Max > UINT_MAX(2147483647 *2U +1U)) {
1055 unsigned Offset = 32 - countLeadingZeros(Max);
1056 for (uint64_t &I : Weights)
1057 I >>= Offset;
1058 }
1059}
1060
1061static void CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
1062 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1063 Instruction *PTI = PredBlock->getTerminator();
1064
1065 // If we have bonus instructions, clone them into the predecessor block.
1066 // Note that there may be multiple predecessor blocks, so we cannot move
1067 // bonus instructions to a predecessor block.
1068 for (Instruction &BonusInst : *BB) {
1069 if (isa<DbgInfoIntrinsic>(BonusInst) || BonusInst.isTerminator())
1070 continue;
1071
1072 Instruction *NewBonusInst = BonusInst.clone();
1073
1074 if (PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1075 // Unless the instruction has the same !dbg location as the original
1076 // branch, drop it. When we fold the bonus instructions we want to make
1077 // sure we reset their debug locations in order to avoid stepping on
1078 // dead code caused by folding dead branches.
1079 NewBonusInst->setDebugLoc(DebugLoc());
1080 }
1081
1082 RemapInstruction(NewBonusInst, VMap,
1083 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1084 VMap[&BonusInst] = NewBonusInst;
1085
1086 // If we moved a load, we cannot any longer claim any knowledge about
1087 // its potential value. The previous information might have been valid
1088 // only given the branch precondition.
1089 // For an analogous reason, we must also drop all the metadata whose
1090 // semantics we don't understand. We *can* preserve !annotation, because
1091 // it is tied to the instruction itself, not the value or position.
1092 NewBonusInst->dropUnknownNonDebugMetadata(LLVMContext::MD_annotation);
1093
1094 PredBlock->getInstList().insert(PTI->getIterator(), NewBonusInst);
1095 NewBonusInst->takeName(&BonusInst);
1096 BonusInst.setName(NewBonusInst->getName() + ".old");
1097
1098 // Update (liveout) uses of bonus instructions,
1099 // now that the bonus instruction has been cloned into predecessor.
1100 SSAUpdater SSAUpdate;
1101 SSAUpdate.Initialize(BonusInst.getType(),
1102 (NewBonusInst->getName() + ".merge").str());
1103 SSAUpdate.AddAvailableValue(BB, &BonusInst);
1104 SSAUpdate.AddAvailableValue(PredBlock, NewBonusInst);
1105 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1106 auto *UI = cast<Instruction>(U.getUser());
1107 if (UI->getParent() != PredBlock)
1108 SSAUpdate.RewriteUseAfterInsertions(U);
1109 else // Use is in the same block as, and comes before, NewBonusInst.
1110 SSAUpdate.RewriteUse(U);
1111 }
1112 }
1113}
1114
1115bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1116 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1117 BasicBlock *BB = TI->getParent();
1118 BasicBlock *Pred = PTI->getParent();
1119
1120 SmallVector<DominatorTree::UpdateType, 32> Updates;
1121
1122 // Figure out which 'cases' to copy from SI to PSI.
1123 std::vector<ValueEqualityComparisonCase> BBCases;
1124 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1125
1126 std::vector<ValueEqualityComparisonCase> PredCases;
1127 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1128
1129 // Based on whether the default edge from PTI goes to BB or not, fill in
1130 // PredCases and PredDefault with the new switch cases we would like to
1131 // build.
1132 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1133
1134 // Update the branch weight metadata along the way
1135 SmallVector<uint64_t, 8> Weights;
1136 bool PredHasWeights = HasBranchWeights(PTI);
1137 bool SuccHasWeights = HasBranchWeights(TI);
1138
1139 if (PredHasWeights) {
1140 GetBranchWeights(PTI, Weights);
1141 // branch-weight metadata is inconsistent here.
1142 if (Weights.size() != 1 + PredCases.size())
1143 PredHasWeights = SuccHasWeights = false;
1144 } else if (SuccHasWeights)
1145 // If there are no predecessor weights but there are successor weights,
1146 // populate Weights with 1, which will later be scaled to the sum of
1147 // successor's weights
1148 Weights.assign(1 + PredCases.size(), 1);
1149
1150 SmallVector<uint64_t, 8> SuccWeights;
1151 if (SuccHasWeights) {
1152 GetBranchWeights(TI, SuccWeights);
1153 // branch-weight metadata is inconsistent here.
1154 if (SuccWeights.size() != 1 + BBCases.size())
1155 PredHasWeights = SuccHasWeights = false;
1156 } else if (PredHasWeights)
1157 SuccWeights.assign(1 + BBCases.size(), 1);
1158
1159 if (PredDefault == BB) {
1160 // If this is the default destination from PTI, only the edges in TI
1161 // that don't occur in PTI, or that branch to BB will be activated.
1162 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1163 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1164 if (PredCases[i].Dest != BB)
1165 PTIHandled.insert(PredCases[i].Value);
1166 else {
1167 // The default destination is BB, we don't need explicit targets.
1168 std::swap(PredCases[i], PredCases.back());
1169
1170 if (PredHasWeights || SuccHasWeights) {
1171 // Increase weight for the default case.
1172 Weights[0] += Weights[i + 1];
1173 std::swap(Weights[i + 1], Weights.back());
1174 Weights.pop_back();
1175 }
1176
1177 PredCases.pop_back();
1178 --i;
1179 --e;
1180 }
1181
1182 // Reconstruct the new switch statement we will be building.
1183 if (PredDefault != BBDefault) {
1184 PredDefault->removePredecessor(Pred);
1185 if (DTU && PredDefault != BB)
1186 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1187 PredDefault = BBDefault;
1188 ++NewSuccessors[BBDefault];
1189 }
1190
1191 unsigned CasesFromPred = Weights.size();
1192 uint64_t ValidTotalSuccWeight = 0;
1193 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1194 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1195 PredCases.push_back(BBCases[i]);
1196 ++NewSuccessors[BBCases[i].Dest];
1197 if (SuccHasWeights || PredHasWeights) {
1198 // The default weight is at index 0, so weight for the ith case
1199 // should be at index i+1. Scale the cases from successor by
1200 // PredDefaultWeight (Weights[0]).
1201 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1202 ValidTotalSuccWeight += SuccWeights[i + 1];
1203 }
1204 }
1205
1206 if (SuccHasWeights || PredHasWeights) {
1207 ValidTotalSuccWeight += SuccWeights[0];
1208 // Scale the cases from predecessor by ValidTotalSuccWeight.
1209 for (unsigned i = 1; i < CasesFromPred; ++i)
1210 Weights[i] *= ValidTotalSuccWeight;
1211 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1212 Weights[0] *= SuccWeights[0];
1213 }
1214 } else {
1215 // If this is not the default destination from PSI, only the edges
1216 // in SI that occur in PSI with a destination of BB will be
1217 // activated.
1218 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1219 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1220 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1221 if (PredCases[i].Dest == BB) {
1222 PTIHandled.insert(PredCases[i].Value);
1223
1224 if (PredHasWeights || SuccHasWeights) {
1225 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1226 std::swap(Weights[i + 1], Weights.back());
1227 Weights.pop_back();
1228 }
1229
1230 std::swap(PredCases[i], PredCases.back());
1231 PredCases.pop_back();
1232 --i;
1233 --e;
1234 }
1235
1236 // Okay, now we know which constants were sent to BB from the
1237 // predecessor. Figure out where they will all go now.
1238 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1239 if (PTIHandled.count(BBCases[i].Value)) {
1240 // If this is one we are capable of getting...
1241 if (PredHasWeights || SuccHasWeights)
1242 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1243 PredCases.push_back(BBCases[i]);
1244 ++NewSuccessors[BBCases[i].Dest];
1245 PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1246 }
1247
1248 // If there are any constants vectored to BB that TI doesn't handle,
1249 // they must go to the default destination of TI.
1250 for (ConstantInt *I : PTIHandled) {
1251 if (PredHasWeights || SuccHasWeights)
1252 Weights.push_back(WeightsForHandled[I]);
1253 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1254 ++NewSuccessors[BBDefault];
1255 }
1256 }
1257
1258 // Okay, at this point, we know which new successor Pred will get. Make
1259 // sure we update the number of entries in the PHI nodes for these
1260 // successors.
1261 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1262 if (DTU) {
1263 SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1264 Updates.reserve(Updates.size() + NewSuccessors.size());
1265 }
1266 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1267 NewSuccessors) {
1268 for (auto I : seq(0, NewSuccessor.second)) {
1269 (void)I;
1270 AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1271 }
1272 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1273 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1274 }
1275
1276 Builder.SetInsertPoint(PTI);
1277 // Convert pointer to int before we switch.
1278 if (CV->getType()->isPointerTy()) {
1279 CV =
1280 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1281 }
1282
1283 // Now that the successors are updated, create the new Switch instruction.
1284 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1285 NewSI->setDebugLoc(PTI->getDebugLoc());
1286 for (ValueEqualityComparisonCase &V : PredCases)
1287 NewSI->addCase(V.Value, V.Dest);
1288
1289 if (PredHasWeights || SuccHasWeights) {
1290 // Halve the weights if any of them cannot fit in an uint32_t
1291 FitWeights(Weights);
1292
1293 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1294
1295 setBranchWeights(NewSI, MDWeights);
1296 }
1297
1298 EraseTerminatorAndDCECond(PTI);
1299
1300 // Okay, last check. If BB is still a successor of PSI, then we must
1301 // have an infinite loop case. If so, add an infinitely looping block
1302 // to handle the case to preserve the behavior of the code.
1303 BasicBlock *InfLoopBlock = nullptr;
1304 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1305 if (NewSI->getSuccessor(i) == BB) {
1306 if (!InfLoopBlock) {
1307 // Insert it at the end of the function, because it's either code,
1308 // or it won't matter if it's hot. :)
1309 InfLoopBlock =
1310 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1311 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1312 if (DTU)
1313 Updates.push_back(
1314 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1315 }
1316 NewSI->setSuccessor(i, InfLoopBlock);
1317 }
1318
1319 if (DTU) {
1320 if (InfLoopBlock)
1321 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1322
1323 Updates.push_back({DominatorTree::Delete, Pred, BB});
1324
1325 DTU->applyUpdates(Updates);
1326 }
1327
1328 ++NumFoldValueComparisonIntoPredecessors;
1329 return true;
1330}
1331
1332/// The specified terminator is a value equality comparison instruction
1333/// (either a switch or a branch on "X == c").
1334/// See if any of the predecessors of the terminator block are value comparisons
1335/// on the same value. If so, and if safe to do so, fold them together.
1336bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1337 IRBuilder<> &Builder) {
1338 BasicBlock *BB = TI->getParent();
1339 Value *CV = isValueEqualityComparison(TI); // CondVal
1340 assert(CV && "Not a comparison?")(static_cast <bool> (CV && "Not a comparison?")
? void (0) : __assert_fail ("CV && \"Not a comparison?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1340, __extension__ __PRETTY_FUNCTION__))
;
1341
1342 bool Changed = false;
1343
1344 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1345 while (!Preds.empty()) {
1346 BasicBlock *Pred = Preds.pop_back_val();
1347 Instruction *PTI = Pred->getTerminator();
1348
1349 // Don't try to fold into itself.
1350 if (Pred == BB)
1351 continue;
1352
1353 // See if the predecessor is a comparison with the same value.
1354 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1355 if (PCV != CV)
1356 continue;
1357
1358 SmallSetVector<BasicBlock *, 4> FailBlocks;
1359 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1360 for (auto *Succ : FailBlocks) {
1361 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1362 return false;
1363 }
1364 }
1365
1366 PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1367 Changed = true;
1368 }
1369 return Changed;
1370}
1371
1372// If we would need to insert a select that uses the value of this invoke
1373// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1374// can't hoist the invoke, as there is nowhere to put the select in this case.
1375static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1376 Instruction *I1, Instruction *I2) {
1377 for (BasicBlock *Succ : successors(BB1)) {
1378 for (const PHINode &PN : Succ->phis()) {
1379 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1380 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1381 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1382 return false;
1383 }
1384 }
1385 }
1386 return true;
1387}
1388
1389static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1390
1391/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1392/// in the two blocks up into the branch block. The caller of this function
1393/// guarantees that BI's block dominates BB1 and BB2. If EqTermsOnly is given,
1394/// only perform hoisting in case both blocks only contain a terminator. In that
1395/// case, only the original BI will be replaced and selects for PHIs are added.
1396bool SimplifyCFGOpt::HoistThenElseCodeToIf(BranchInst *BI,
1397 const TargetTransformInfo &TTI,
1398 bool EqTermsOnly) {
1399 // This does very trivial matching, with limited scanning, to find identical
1400 // instructions in the two blocks. In particular, we don't want to get into
1401 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1402 // such, we currently just scan for obviously identical instructions in an
1403 // identical order.
1404 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1405 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1406
1407 // If either of the blocks has it's address taken, then we can't do this fold,
1408 // because the code we'd hoist would no longer run when we jump into the block
1409 // by it's address.
1410 if (BB1->hasAddressTaken() || BB2->hasAddressTaken())
1411 return false;
1412
1413 BasicBlock::iterator BB1_Itr = BB1->begin();
1414 BasicBlock::iterator BB2_Itr = BB2->begin();
1415
1416 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1417 // Skip debug info if it is not identical.
1418 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1419 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1420 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1421 while (isa<DbgInfoIntrinsic>(I1))
1422 I1 = &*BB1_Itr++;
1423 while (isa<DbgInfoIntrinsic>(I2))
1424 I2 = &*BB2_Itr++;
1425 }
1426 // FIXME: Can we define a safety predicate for CallBr?
1427 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1428 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
1429 isa<CallBrInst>(I1))
1430 return false;
1431
1432 BasicBlock *BIParent = BI->getParent();
1433
1434 bool Changed = false;
1435
1436 auto _ = make_scope_exit([&]() {
1437 if (Changed)
1438 ++NumHoistCommonCode;
1439 });
1440
1441 // Check if only hoisting terminators is allowed. This does not add new
1442 // instructions to the hoist location.
1443 if (EqTermsOnly) {
1444 // Skip any debug intrinsics, as they are free to hoist.
1445 auto *I1NonDbg = &*skipDebugIntrinsics(I1->getIterator());
1446 auto *I2NonDbg = &*skipDebugIntrinsics(I2->getIterator());
1447 if (!I1NonDbg->isIdenticalToWhenDefined(I2NonDbg))
1448 return false;
1449 if (!I1NonDbg->isTerminator())
1450 return false;
1451 // Now we know that we only need to hoist debug instrinsics and the
1452 // terminator. Let the loop below handle those 2 cases.
1453 }
1454
1455 do {
1456 // If we are hoisting the terminator instruction, don't move one (making a
1457 // broken BB), instead clone it, and remove BI.
1458 if (I1->isTerminator())
1459 goto HoistTerminator;
1460
1461 // If we're going to hoist a call, make sure that the two instructions we're
1462 // commoning/hoisting are both marked with musttail, or neither of them is
1463 // marked as such. Otherwise, we might end up in a situation where we hoist
1464 // from a block where the terminator is a `ret` to a block where the terminator
1465 // is a `br`, and `musttail` calls expect to be followed by a return.
1466 auto *C1 = dyn_cast<CallInst>(I1);
1467 auto *C2 = dyn_cast<CallInst>(I2);
1468 if (C1 && C2)
1469 if (C1->isMustTailCall() != C2->isMustTailCall())
1470 return Changed;
1471
1472 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1473 return Changed;
1474
1475 // If any of the two call sites has nomerge attribute, stop hoisting.
1476 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1477 if (CB1->cannotMerge())
1478 return Changed;
1479 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1480 if (CB2->cannotMerge())
1481 return Changed;
1482
1483 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1484 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2))(static_cast <bool> (isa<DbgInfoIntrinsic>(I1) &&
isa<DbgInfoIntrinsic>(I2)) ? void (0) : __assert_fail (
"isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1484, __extension__ __PRETTY_FUNCTION__))
;
1485 // The debug location is an integral part of a debug info intrinsic
1486 // and can't be separated from it or replaced. Instead of attempting
1487 // to merge locations, simply hoist both copies of the intrinsic.
1488 BIParent->getInstList().splice(BI->getIterator(),
1489 BB1->getInstList(), I1);
1490 BIParent->getInstList().splice(BI->getIterator(),
1491 BB2->getInstList(), I2);
1492 Changed = true;
1493 } else {
1494 // For a normal instruction, we just move one to right before the branch,
1495 // then replace all uses of the other with the first. Finally, we remove
1496 // the now redundant second instruction.
1497 BIParent->getInstList().splice(BI->getIterator(),
1498 BB1->getInstList(), I1);
1499 if (!I2->use_empty())
1500 I2->replaceAllUsesWith(I1);
1501 I1->andIRFlags(I2);
1502 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1503 LLVMContext::MD_range,
1504 LLVMContext::MD_fpmath,
1505 LLVMContext::MD_invariant_load,
1506 LLVMContext::MD_nonnull,
1507 LLVMContext::MD_invariant_group,
1508 LLVMContext::MD_align,
1509 LLVMContext::MD_dereferenceable,
1510 LLVMContext::MD_dereferenceable_or_null,
1511 LLVMContext::MD_mem_parallel_loop_access,
1512 LLVMContext::MD_access_group,
1513 LLVMContext::MD_preserve_access_index};
1514 combineMetadata(I1, I2, KnownIDs, true);
1515
1516 // I1 and I2 are being combined into a single instruction. Its debug
1517 // location is the merged locations of the original instructions.
1518 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1519
1520 I2->eraseFromParent();
1521 Changed = true;
1522 }
1523 ++NumHoistCommonInstrs;
1524
1525 I1 = &*BB1_Itr++;
1526 I2 = &*BB2_Itr++;
1527 // Skip debug info if it is not identical.
1528 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1529 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1530 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1531 while (isa<DbgInfoIntrinsic>(I1))
1532 I1 = &*BB1_Itr++;
1533 while (isa<DbgInfoIntrinsic>(I2))
1534 I2 = &*BB2_Itr++;
1535 }
1536 } while (I1->isIdenticalToWhenDefined(I2));
1537
1538 return true;
1539
1540HoistTerminator:
1541 // It may not be possible to hoist an invoke.
1542 // FIXME: Can we define a safety predicate for CallBr?
1543 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1544 return Changed;
1545
1546 // TODO: callbr hoisting currently disabled pending further study.
1547 if (isa<CallBrInst>(I1))
1548 return Changed;
1549
1550 for (BasicBlock *Succ : successors(BB1)) {
1551 for (PHINode &PN : Succ->phis()) {
1552 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1553 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1554 if (BB1V == BB2V)
1555 continue;
1556
1557 // Check for passingValueIsAlwaysUndefined here because we would rather
1558 // eliminate undefined control flow then converting it to a select.
1559 if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1560 passingValueIsAlwaysUndefined(BB2V, &PN))
1561 return Changed;
1562
1563 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1564 return Changed;
1565 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1566 return Changed;
1567 }
1568 }
1569
1570 // Okay, it is safe to hoist the terminator.
1571 Instruction *NT = I1->clone();
1572 BIParent->getInstList().insert(BI->getIterator(), NT);
1573 if (!NT->getType()->isVoidTy()) {
1574 I1->replaceAllUsesWith(NT);
1575 I2->replaceAllUsesWith(NT);
1576 NT->takeName(I1);
1577 }
1578 Changed = true;
1579 ++NumHoistCommonInstrs;
1580
1581 // Ensure terminator gets a debug location, even an unknown one, in case
1582 // it involves inlinable calls.
1583 NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1584
1585 // PHIs created below will adopt NT's merged DebugLoc.
1586 IRBuilder<NoFolder> Builder(NT);
1587
1588 // Hoisting one of the terminators from our successor is a great thing.
1589 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1590 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1591 // nodes, so we insert select instruction to compute the final result.
1592 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1593 for (BasicBlock *Succ : successors(BB1)) {
1594 for (PHINode &PN : Succ->phis()) {
1595 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1596 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1597 if (BB1V == BB2V)
1598 continue;
1599
1600 // These values do not agree. Insert a select instruction before NT
1601 // that determines the right value.
1602 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1603 if (!SI) {
1604 // Propagate fast-math-flags from phi node to its replacement select.
1605 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1606 if (isa<FPMathOperator>(PN))
1607 Builder.setFastMathFlags(PN.getFastMathFlags());
1608
1609 SI = cast<SelectInst>(
1610 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1611 BB1V->getName() + "." + BB2V->getName(), BI));
1612 }
1613
1614 // Make the PHI node use the select for all incoming values for BB1/BB2
1615 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1616 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1617 PN.setIncomingValue(i, SI);
1618 }
1619 }
1620
1621 SmallVector<DominatorTree::UpdateType, 4> Updates;
1622
1623 // Update any PHI nodes in our new successors.
1624 for (BasicBlock *Succ : successors(BB1)) {
1625 AddPredecessorToBlock(Succ, BIParent, BB1);
1626 if (DTU)
1627 Updates.push_back({DominatorTree::Insert, BIParent, Succ});
1628 }
1629
1630 if (DTU)
1631 for (BasicBlock *Succ : successors(BI))
1632 Updates.push_back({DominatorTree::Delete, BIParent, Succ});
1633
1634 EraseTerminatorAndDCECond(BI);
1635 if (DTU)
1636 DTU->applyUpdates(Updates);
1637 return Changed;
1638}
1639
1640// Check lifetime markers.
1641static bool isLifeTimeMarker(const Instruction *I) {
1642 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1643 switch (II->getIntrinsicID()) {
1644 default:
1645 break;
1646 case Intrinsic::lifetime_start:
1647 case Intrinsic::lifetime_end:
1648 return true;
1649 }
1650 }
1651 return false;
1652}
1653
1654// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1655// into variables.
1656static bool replacingOperandWithVariableIsCheap(const Instruction *I,
1657 int OpIdx) {
1658 return !isa<IntrinsicInst>(I);
1659}
1660
1661// All instructions in Insts belong to different blocks that all unconditionally
1662// branch to a common successor. Analyze each instruction and return true if it
1663// would be possible to sink them into their successor, creating one common
1664// instruction instead. For every value that would be required to be provided by
1665// PHI node (because an operand varies in each input block), add to PHIOperands.
1666static bool canSinkInstructions(
1667 ArrayRef<Instruction *> Insts,
1668 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1669 // Prune out obviously bad instructions to move. Each instruction must have
1670 // exactly zero or one use, and we check later that use is by a single, common
1671 // PHI instruction in the successor.
1672 bool HasUse = !Insts.front()->user_empty();
1673 for (auto *I : Insts) {
1674 // These instructions may change or break semantics if moved.
1675 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1676 I->getType()->isTokenTy())
1677 return false;
1678
1679 // Do not try to sink an instruction in an infinite loop - it can cause
1680 // this algorithm to infinite loop.
1681 if (I->getParent()->getSingleSuccessor() == I->getParent())
1682 return false;
1683
1684 // Conservatively return false if I is an inline-asm instruction. Sinking
1685 // and merging inline-asm instructions can potentially create arguments
1686 // that cannot satisfy the inline-asm constraints.
1687 // If the instruction has nomerge attribute, return false.
1688 if (const auto *C = dyn_cast<CallBase>(I))
1689 if (C->isInlineAsm() || C->cannotMerge())
1690 return false;
1691
1692 // Each instruction must have zero or one use.
1693 if (HasUse && !I->hasOneUse())
1694 return false;
1695 if (!HasUse && !I->user_empty())
1696 return false;
1697 }
1698
1699 const Instruction *I0 = Insts.front();
1700 for (auto *I : Insts)
1701 if (!I->isSameOperationAs(I0))
1702 return false;
1703
1704 // All instructions in Insts are known to be the same opcode. If they have a
1705 // use, check that the only user is a PHI or in the same block as the
1706 // instruction, because if a user is in the same block as an instruction we're
1707 // contemplating sinking, it must already be determined to be sinkable.
1708 if (HasUse) {
1709 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1710 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1711 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1712 auto *U = cast<Instruction>(*I->user_begin());
1713 return (PNUse &&
1714 PNUse->getParent() == Succ &&
1715 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1716 U->getParent() == I->getParent();
1717 }))
1718 return false;
1719 }
1720
1721 // Because SROA can't handle speculating stores of selects, try not to sink
1722 // loads, stores or lifetime markers of allocas when we'd have to create a
1723 // PHI for the address operand. Also, because it is likely that loads or
1724 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1725 // them.
1726 // This can cause code churn which can have unintended consequences down
1727 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1728 // FIXME: This is a workaround for a deficiency in SROA - see
1729 // https://llvm.org/bugs/show_bug.cgi?id=30188
1730 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1731 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1732 }))
1733 return false;
1734 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1735 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1736 }))
1737 return false;
1738 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1739 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1740 }))
1741 return false;
1742
1743 // For calls to be sinkable, they must all be indirect, or have same callee.
1744 // I.e. if we have two direct calls to different callees, we don't want to
1745 // turn that into an indirect call. Likewise, if we have an indirect call,
1746 // and a direct call, we don't actually want to have a single indirect call.
1747 if (isa<CallBase>(I0)) {
1748 auto IsIndirectCall = [](const Instruction *I) {
1749 return cast<CallBase>(I)->isIndirectCall();
1750 };
1751 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1752 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1753 if (HaveIndirectCalls) {
1754 if (!AllCallsAreIndirect)
1755 return false;
1756 } else {
1757 // All callees must be identical.
1758 Value *Callee = nullptr;
1759 for (const Instruction *I : Insts) {
1760 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1761 if (!Callee)
1762 Callee = CurrCallee;
1763 else if (Callee != CurrCallee)
1764 return false;
1765 }
1766 }
1767 }
1768
1769 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1770 Value *Op = I0->getOperand(OI);
1771 if (Op->getType()->isTokenTy())
1772 // Don't touch any operand of token type.
1773 return false;
1774
1775 auto SameAsI0 = [&I0, OI](const Instruction *I) {
1776 assert(I->getNumOperands() == I0->getNumOperands())(static_cast <bool> (I->getNumOperands() == I0->getNumOperands
()) ? void (0) : __assert_fail ("I->getNumOperands() == I0->getNumOperands()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1776, __extension__ __PRETTY_FUNCTION__))
;
1777 return I->getOperand(OI) == I0->getOperand(OI);
1778 };
1779 if (!all_of(Insts, SameAsI0)) {
1780 if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1781 !canReplaceOperandWithVariable(I0, OI))
1782 // We can't create a PHI from this GEP.
1783 return false;
1784 for (auto *I : Insts)
1785 PHIOperands[I].push_back(I->getOperand(OI));
1786 }
1787 }
1788 return true;
1789}
1790
1791// Assuming canSinkInstructions(Blocks) has returned true, sink the last
1792// instruction of every block in Blocks to their common successor, commoning
1793// into one instruction.
1794static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
1795 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1796
1797 // canSinkInstructions returning true guarantees that every block has at
1798 // least one non-terminator instruction.
1799 SmallVector<Instruction*,4> Insts;
1800 for (auto *BB : Blocks) {
1801 Instruction *I = BB->getTerminator();
1802 do {
1803 I = I->getPrevNode();
1804 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1805 if (!isa<DbgInfoIntrinsic>(I))
1806 Insts.push_back(I);
1807 }
1808
1809 // The only checking we need to do now is that all users of all instructions
1810 // are the same PHI node. canSinkInstructions should have checked this but
1811 // it is slightly over-aggressive - it gets confused by commutative
1812 // instructions so double-check it here.
1813 Instruction *I0 = Insts.front();
1814 if (!I0->user_empty()) {
1815 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1816 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1817 auto *U = cast<Instruction>(*I->user_begin());
1818 return U == PNUse;
1819 }))
1820 return false;
1821 }
1822
1823 // We don't need to do any more checking here; canSinkInstructions should
1824 // have done it all for us.
1825 SmallVector<Value*, 4> NewOperands;
1826 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1827 // This check is different to that in canSinkInstructions. There, we
1828 // cared about the global view once simplifycfg (and instcombine) have
1829 // completed - it takes into account PHIs that become trivially
1830 // simplifiable. However here we need a more local view; if an operand
1831 // differs we create a PHI and rely on instcombine to clean up the very
1832 // small mess we may make.
1833 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1834 return I->getOperand(O) != I0->getOperand(O);
1835 });
1836 if (!NeedPHI) {
1837 NewOperands.push_back(I0->getOperand(O));
1838 continue;
1839 }
1840
1841 // Create a new PHI in the successor block and populate it.
1842 auto *Op = I0->getOperand(O);
1843 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!")(static_cast <bool> (!Op->getType()->isTokenTy() &&
"Can't PHI tokens!") ? void (0) : __assert_fail ("!Op->getType()->isTokenTy() && \"Can't PHI tokens!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 1843, __extension__ __PRETTY_FUNCTION__))
;
1844 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1845 Op->getName() + ".sink", &BBEnd->front());
1846 for (auto *I : Insts)
1847 PN->addIncoming(I->getOperand(O), I->getParent());
1848 NewOperands.push_back(PN);
1849 }
1850
1851 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1852 // and move it to the start of the successor block.
1853 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1854 I0->getOperandUse(O).set(NewOperands[O]);
1855 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1856
1857 // Update metadata and IR flags, and merge debug locations.
1858 for (auto *I : Insts)
1859 if (I != I0) {
1860 // The debug location for the "common" instruction is the merged locations
1861 // of all the commoned instructions. We start with the original location
1862 // of the "common" instruction and iteratively merge each location in the
1863 // loop below.
1864 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1865 // However, as N-way merge for CallInst is rare, so we use simplified API
1866 // instead of using complex API for N-way merge.
1867 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1868 combineMetadataForCSE(I0, I, true);
1869 I0->andIRFlags(I);
1870 }
1871
1872 if (!I0->user_empty()) {
1873 // canSinkLastInstruction checked that all instructions were used by
1874 // one and only one PHI node. Find that now, RAUW it to our common
1875 // instruction and nuke it.
1876 auto *PN = cast<PHINode>(*I0->user_begin());
1877 PN->replaceAllUsesWith(I0);
1878 PN->eraseFromParent();
1879 }
1880
1881 // Finally nuke all instructions apart from the common instruction.
1882 for (auto *I : Insts)
1883 if (I != I0)
1884 I->eraseFromParent();
1885
1886 return true;
1887}
1888
1889namespace {
1890
1891 // LockstepReverseIterator - Iterates through instructions
1892 // in a set of blocks in reverse order from the first non-terminator.
1893 // For example (assume all blocks have size n):
1894 // LockstepReverseIterator I([B1, B2, B3]);
1895 // *I-- = [B1[n], B2[n], B3[n]];
1896 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1897 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1898 // ...
1899 class LockstepReverseIterator {
1900 ArrayRef<BasicBlock*> Blocks;
1901 SmallVector<Instruction*,4> Insts;
1902 bool Fail;
1903
1904 public:
1905 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
1906 reset();
1907 }
1908
1909 void reset() {
1910 Fail = false;
1911 Insts.clear();
1912 for (auto *BB : Blocks) {
1913 Instruction *Inst = BB->getTerminator();
1914 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1915 Inst = Inst->getPrevNode();
1916 if (!Inst) {
1917 // Block wasn't big enough.
1918 Fail = true;
1919 return;
1920 }
1921 Insts.push_back(Inst);
1922 }
1923 }
1924
1925 bool isValid() const {
1926 return !Fail;
1927 }
1928
1929 void operator--() {
1930 if (Fail)
1931 return;
1932 for (auto *&Inst : Insts) {
1933 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1934 Inst = Inst->getPrevNode();
1935 // Already at beginning of block.
1936 if (!Inst) {
1937 Fail = true;
1938 return;
1939 }
1940 }
1941 }
1942
1943 void operator++() {
1944 if (Fail)
1945 return;
1946 for (auto *&Inst : Insts) {
1947 for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1948 Inst = Inst->getNextNode();
1949 // Already at end of block.
1950 if (!Inst) {
1951 Fail = true;
1952 return;
1953 }
1954 }
1955 }
1956
1957 ArrayRef<Instruction*> operator * () const {
1958 return Insts;
1959 }
1960 };
1961
1962} // end anonymous namespace
1963
1964/// Check whether BB's predecessors end with unconditional branches. If it is
1965/// true, sink any common code from the predecessors to BB.
1966static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
1967 DomTreeUpdater *DTU) {
1968 // We support two situations:
1969 // (1) all incoming arcs are unconditional
1970 // (2) there are non-unconditional incoming arcs
1971 //
1972 // (2) is very common in switch defaults and
1973 // else-if patterns;
1974 //
1975 // if (a) f(1);
1976 // else if (b) f(2);
1977 //
1978 // produces:
1979 //
1980 // [if]
1981 // / \
1982 // [f(1)] [if]
1983 // | | \
1984 // | | |
1985 // | [f(2)]|
1986 // \ | /
1987 // [ end ]
1988 //
1989 // [end] has two unconditional predecessor arcs and one conditional. The
1990 // conditional refers to the implicit empty 'else' arc. This conditional
1991 // arc can also be caused by an empty default block in a switch.
1992 //
1993 // In this case, we attempt to sink code from all *unconditional* arcs.
1994 // If we can sink instructions from these arcs (determined during the scan
1995 // phase below) we insert a common successor for all unconditional arcs and
1996 // connect that to [end], to enable sinking:
1997 //
1998 // [if]
1999 // / \
2000 // [x(1)] [if]
2001 // | | \
2002 // | | \
2003 // | [x(2)] |
2004 // \ / |
2005 // [sink.split] |
2006 // \ /
2007 // [ end ]
2008 //
2009 SmallVector<BasicBlock*,4> UnconditionalPreds;
2010 bool HaveNonUnconditionalPredecessors = false;
2011 for (auto *PredBB : predecessors(BB)) {
2012 auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2013 if (PredBr && PredBr->isUnconditional())
2014 UnconditionalPreds.push_back(PredBB);
2015 else
2016 HaveNonUnconditionalPredecessors = true;
2017 }
2018 if (UnconditionalPreds.size() < 2)
2019 return false;
2020
2021 // We take a two-step approach to tail sinking. First we scan from the end of
2022 // each block upwards in lockstep. If the n'th instruction from the end of each
2023 // block can be sunk, those instructions are added to ValuesToSink and we
2024 // carry on. If we can sink an instruction but need to PHI-merge some operands
2025 // (because they're not identical in each instruction) we add these to
2026 // PHIOperands.
2027 int ScanIdx = 0;
2028 SmallPtrSet<Value*,4> InstructionsToSink;
2029 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
2030 LockstepReverseIterator LRI(UnconditionalPreds);
2031 while (LRI.isValid() &&
2032 canSinkInstructions(*LRI, PHIOperands)) {
2033 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: instruction can be sunk: "
<< *(*LRI)[0] << "\n"; } } while (false)
2034 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: instruction can be sunk: "
<< *(*LRI)[0] << "\n"; } } while (false)
;
2035 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2036 ++ScanIdx;
2037 --LRI;
2038 }
2039
2040 // If no instructions can be sunk, early-return.
2041 if (ScanIdx == 0)
2042 return false;
2043
2044 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2045 // actually sink before encountering instruction that is unprofitable to sink?
2046 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2047 unsigned NumPHIdValues = 0;
2048 for (auto *I : *LRI)
2049 for (auto *V : PHIOperands[I]) {
2050 if (InstructionsToSink.count(V) == 0)
2051 ++NumPHIdValues;
2052 // FIXME: this check is overly optimistic. We may end up not sinking
2053 // said instruction, due to the very same profitability check.
2054 // See @creating_too_many_phis in sink-common-code.ll.
2055 }
2056 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: #phid values: " <<
NumPHIdValues << "\n"; } } while (false)
;
2057 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2058 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2059 NumPHIInsts++;
2060
2061 return NumPHIInsts <= 1;
2062 };
2063
2064 // We've determined that we are going to sink last ScanIdx instructions,
2065 // and recorded them in InstructionsToSink. Now, some instructions may be
2066 // unprofitable to sink. But that determination depends on the instructions
2067 // that we are going to sink.
2068
2069 // First, forward scan: find the first instruction unprofitable to sink,
2070 // recording all the ones that are profitable to sink.
2071 // FIXME: would it be better, after we detect that not all are profitable.
2072 // to either record the profitable ones, or erase the unprofitable ones?
2073 // Maybe we need to choose (at runtime) the one that will touch least instrs?
2074 LRI.reset();
2075 int Idx = 0;
2076 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2077 while (Idx < ScanIdx) {
2078 if (!ProfitableToSinkInstruction(LRI)) {
2079 // Too many PHIs would be created.
2080 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: stopping here, too many PHIs would be created!\n"
; } } while (false)
2081 dbgs() << "SINK: stopping here, too many PHIs would be created!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: stopping here, too many PHIs would be created!\n"
; } } while (false)
;
2082 break;
2083 }
2084 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2085 --LRI;
2086 ++Idx;
2087 }
2088
2089 // If no instructions can be sunk, early-return.
2090 if (Idx == 0)
2091 return false;
2092
2093 // Did we determine that (only) some instructions are unprofitable to sink?
2094 if (Idx < ScanIdx) {
2095 // Okay, some instructions are unprofitable.
2096 ScanIdx = Idx;
2097 InstructionsToSink = InstructionsProfitableToSink;
2098
2099 // But, that may make other instructions unprofitable, too.
2100 // So, do a backward scan, do any earlier instructions become unprofitable?
2101 assert(!ProfitableToSinkInstruction(LRI) &&(static_cast <bool> (!ProfitableToSinkInstruction(LRI) &&
"We already know that the last instruction is unprofitable to sink"
) ? void (0) : __assert_fail ("!ProfitableToSinkInstruction(LRI) && \"We already know that the last instruction is unprofitable to sink\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
2102 "We already know that the last instruction is unprofitable to sink")(static_cast <bool> (!ProfitableToSinkInstruction(LRI) &&
"We already know that the last instruction is unprofitable to sink"
) ? void (0) : __assert_fail ("!ProfitableToSinkInstruction(LRI) && \"We already know that the last instruction is unprofitable to sink\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
;
2103 ++LRI;
2104 --Idx;
2105 while (Idx >= 0) {
2106 // If we detect that an instruction becomes unprofitable to sink,
2107 // all earlier instructions won't be sunk either,
2108 // so preemptively keep InstructionsProfitableToSink in sync.
2109 // FIXME: is this the most performant approach?
2110 for (auto *I : *LRI)
2111 InstructionsProfitableToSink.erase(I);
2112 if (!ProfitableToSinkInstruction(LRI)) {
2113 // Everything starting with this instruction won't be sunk.
2114 ScanIdx = Idx;
2115 InstructionsToSink = InstructionsProfitableToSink;
2116 }
2117 ++LRI;
2118 --Idx;
2119 }
2120 }
2121
2122 // If no instructions can be sunk, early-return.
2123 if (ScanIdx == 0)
2124 return false;
2125
2126 bool Changed = false;
2127
2128 if (HaveNonUnconditionalPredecessors) {
2129 // It is always legal to sink common instructions from unconditional
2130 // predecessors. However, if not all predecessors are unconditional,
2131 // this transformation might be pessimizing. So as a rule of thumb,
2132 // don't do it unless we'd sink at least one non-speculatable instruction.
2133 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2134 LRI.reset();
2135 int Idx = 0;
2136 bool Profitable = false;
2137 while (Idx < ScanIdx) {
2138 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2139 Profitable = true;
2140 break;
2141 }
2142 --LRI;
2143 ++Idx;
2144 }
2145 if (!Profitable)
2146 return false;
2147
2148 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: Splitting edge\n"; }
} while (false)
;
2149 // We have a conditional edge and we're going to sink some instructions.
2150 // Insert a new block postdominating all blocks we're going to sink from.
2151 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2152 // Edges couldn't be split.
2153 return false;
2154 Changed = true;
2155 }
2156
2157 // Now that we've analyzed all potential sinking candidates, perform the
2158 // actual sink. We iteratively sink the last non-terminator of the source
2159 // blocks into their common successor unless doing so would require too
2160 // many PHI instructions to be generated (currently only one PHI is allowed
2161 // per sunk instruction).
2162 //
2163 // We can use InstructionsToSink to discount values needing PHI-merging that will
2164 // actually be sunk in a later iteration. This allows us to be more
2165 // aggressive in what we sink. This does allow a false positive where we
2166 // sink presuming a later value will also be sunk, but stop half way through
2167 // and never actually sink it which means we produce more PHIs than intended.
2168 // This is unlikely in practice though.
2169 int SinkIdx = 0;
2170 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2171 LLVM_DEBUG(dbgs() << "SINK: Sink: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: Sink: " << *UnconditionalPreds
[0]->getTerminator()->getPrevNode() << "\n"; } } while
(false)
2172 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: Sink: " << *UnconditionalPreds
[0]->getTerminator()->getPrevNode() << "\n"; } } while
(false)
2173 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: Sink: " << *UnconditionalPreds
[0]->getTerminator()->getPrevNode() << "\n"; } } while
(false)
;
2174
2175 // Because we've sunk every instruction in turn, the current instruction to
2176 // sink is always at index 0.
2177 LRI.reset();
2178
2179 if (!sinkLastInstruction(UnconditionalPreds)) {
2180 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: stopping here, failed to actually sink instruction!\n"
; } } while (false)
2181 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: stopping here, failed to actually sink instruction!\n"
; } } while (false)
2182 << "SINK: stopping here, failed to actually sink instruction!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SINK: stopping here, failed to actually sink instruction!\n"
; } } while (false)
;
2183 break;
2184 }
2185
2186 NumSinkCommonInstrs++;
2187 Changed = true;
2188 }
2189 if (SinkIdx != 0)
2190 ++NumSinkCommonCode;
2191 return Changed;
2192}
2193
2194/// Determine if we can hoist sink a sole store instruction out of a
2195/// conditional block.
2196///
2197/// We are looking for code like the following:
2198/// BrBB:
2199/// store i32 %add, i32* %arrayidx2
2200/// ... // No other stores or function calls (we could be calling a memory
2201/// ... // function).
2202/// %cmp = icmp ult %x, %y
2203/// br i1 %cmp, label %EndBB, label %ThenBB
2204/// ThenBB:
2205/// store i32 %add5, i32* %arrayidx2
2206/// br label EndBB
2207/// EndBB:
2208/// ...
2209/// We are going to transform this into:
2210/// BrBB:
2211/// store i32 %add, i32* %arrayidx2
2212/// ... //
2213/// %cmp = icmp ult %x, %y
2214/// %add.add5 = select i1 %cmp, i32 %add, %add5
2215/// store i32 %add.add5, i32* %arrayidx2
2216/// ...
2217///
2218/// \return The pointer to the value of the previous store if the store can be
2219/// hoisted into the predecessor block. 0 otherwise.
2220static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
2221 BasicBlock *StoreBB, BasicBlock *EndBB) {
2222 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2223 if (!StoreToHoist)
2224 return nullptr;
2225
2226 // Volatile or atomic.
2227 if (!StoreToHoist->isSimple())
2228 return nullptr;
2229
2230 Value *StorePtr = StoreToHoist->getPointerOperand();
2231 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2232
2233 // Look for a store to the same pointer in BrBB.
2234 unsigned MaxNumInstToLookAt = 9;
2235 // Skip pseudo probe intrinsic calls which are not really killing any memory
2236 // accesses.
2237 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2238 if (!MaxNumInstToLookAt)
2239 break;
2240 --MaxNumInstToLookAt;
2241
2242 // Could be calling an instruction that affects memory like free().
2243 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2244 return nullptr;
2245
2246 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2247 // Found the previous store to same location and type. Make sure it is
2248 // simple, to avoid introducing a spurious non-atomic write after an
2249 // atomic write.
2250 if (SI->getPointerOperand() == StorePtr &&
2251 SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2252 // Found the previous store, return its value operand.
2253 return SI->getValueOperand();
2254 return nullptr; // Unknown store.
2255 }
2256 }
2257
2258 return nullptr;
2259}
2260
2261/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2262/// converted to selects.
2263static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
2264 BasicBlock *EndBB,
2265 unsigned &SpeculatedInstructions,
2266 InstructionCost &Cost,
2267 const TargetTransformInfo &TTI) {
2268 TargetTransformInfo::TargetCostKind CostKind =
2269 BB->getParent()->hasMinSize()
2270 ? TargetTransformInfo::TCK_CodeSize
2271 : TargetTransformInfo::TCK_SizeAndLatency;
2272
2273 bool HaveRewritablePHIs = false;
2274 for (PHINode &PN : EndBB->phis()) {
2275 Value *OrigV = PN.getIncomingValueForBlock(BB);
2276 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2277
2278 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2279 // Skip PHIs which are trivial.
2280 if (ThenV == OrigV)
2281 continue;
2282
2283 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2284 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2285
2286 // Don't convert to selects if we could remove undefined behavior instead.
2287 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2288 passingValueIsAlwaysUndefined(ThenV, &PN))
2289 return false;
2290
2291 HaveRewritablePHIs = true;
2292 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2293 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2294 if (!OrigCE && !ThenCE)
2295 continue; // Known safe and cheap.
2296
2297 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2298 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
2299 return false;
2300 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2301 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2302 InstructionCost MaxCost =
2303 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2304 if (OrigCost + ThenCost > MaxCost)
2305 return false;
2306
2307 // Account for the cost of an unfolded ConstantExpr which could end up
2308 // getting expanded into Instructions.
2309 // FIXME: This doesn't account for how many operations are combined in the
2310 // constant expression.
2311 ++SpeculatedInstructions;
2312 if (SpeculatedInstructions > 1)
2313 return false;
2314 }
2315
2316 return HaveRewritablePHIs;
2317}
2318
2319/// Speculate a conditional basic block flattening the CFG.
2320///
2321/// Note that this is a very risky transform currently. Speculating
2322/// instructions like this is most often not desirable. Instead, there is an MI
2323/// pass which can do it with full awareness of the resource constraints.
2324/// However, some cases are "obvious" and we should do directly. An example of
2325/// this is speculating a single, reasonably cheap instruction.
2326///
2327/// There is only one distinct advantage to flattening the CFG at the IR level:
2328/// it makes very common but simplistic optimizations such as are common in
2329/// instcombine and the DAG combiner more powerful by removing CFG edges and
2330/// modeling their effects with easier to reason about SSA value graphs.
2331///
2332///
2333/// An illustration of this transform is turning this IR:
2334/// \code
2335/// BB:
2336/// %cmp = icmp ult %x, %y
2337/// br i1 %cmp, label %EndBB, label %ThenBB
2338/// ThenBB:
2339/// %sub = sub %x, %y
2340/// br label BB2
2341/// EndBB:
2342/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2343/// ...
2344/// \endcode
2345///
2346/// Into this IR:
2347/// \code
2348/// BB:
2349/// %cmp = icmp ult %x, %y
2350/// %sub = sub %x, %y
2351/// %cond = select i1 %cmp, 0, %sub
2352/// ...
2353/// \endcode
2354///
2355/// \returns true if the conditional block is removed.
2356bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2357 const TargetTransformInfo &TTI) {
2358 // Be conservative for now. FP select instruction can often be expensive.
2359 Value *BrCond = BI->getCondition();
2360 if (isa<FCmpInst>(BrCond))
2361 return false;
2362
2363 BasicBlock *BB = BI->getParent();
2364 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2365 InstructionCost Budget =
2366 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2367
2368 // If ThenBB is actually on the false edge of the conditional branch, remember
2369 // to swap the select operands later.
2370 bool Invert = false;
2371 if (ThenBB != BI->getSuccessor(0)) {
2372 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?")(static_cast <bool> (ThenBB == BI->getSuccessor(1) &&
"No edge from 'if' block?") ? void (0) : __assert_fail ("ThenBB == BI->getSuccessor(1) && \"No edge from 'if' block?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2372, __extension__ __PRETTY_FUNCTION__))
;
2373 Invert = true;
2374 }
2375 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block")(static_cast <bool> (EndBB == BI->getSuccessor(!Invert
) && "No edge from to end block") ? void (0) : __assert_fail
("EndBB == BI->getSuccessor(!Invert) && \"No edge from to end block\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2375, __extension__ __PRETTY_FUNCTION__))
;
2376
2377 // If the branch is non-unpredictable, and is predicted to *not* branch to
2378 // the `then` block, then avoid speculating it.
2379 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2380 uint64_t TWeight, FWeight;
2381 if (BI->extractProfMetadata(TWeight, FWeight) && (TWeight + FWeight) != 0) {
2382 uint64_t EndWeight = Invert ? TWeight : FWeight;
2383 BranchProbability BIEndProb =
2384 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2385 BranchProbability Likely = TTI.getPredictableBranchThreshold();
2386 if (BIEndProb >= Likely)
2387 return false;
2388 }
2389 }
2390
2391 // Keep a count of how many times instructions are used within ThenBB when
2392 // they are candidates for sinking into ThenBB. Specifically:
2393 // - They are defined in BB, and
2394 // - They have no side effects, and
2395 // - All of their uses are in ThenBB.
2396 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2397
2398 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2399
2400 unsigned SpeculatedInstructions = 0;
2401 Value *SpeculatedStoreValue = nullptr;
2402 StoreInst *SpeculatedStore = nullptr;
2403 for (BasicBlock::iterator BBI = ThenBB->begin(),
2404 BBE = std::prev(ThenBB->end());
2405 BBI != BBE; ++BBI) {
2406 Instruction *I = &*BBI;
2407 // Skip debug info.
2408 if (isa<DbgInfoIntrinsic>(I)) {
2409 SpeculatedDbgIntrinsics.push_back(I);
2410 continue;
2411 }
2412
2413 // Skip pseudo probes. The consequence is we lose track of the branch
2414 // probability for ThenBB, which is fine since the optimization here takes
2415 // place regardless of the branch probability.
2416 if (isa<PseudoProbeInst>(I)) {
2417 // The probe should be deleted so that it will not be over-counted when
2418 // the samples collected on the non-conditional path are counted towards
2419 // the conditional path. We leave it for the counts inference algorithm to
2420 // figure out a proper count for an unknown probe.
2421 SpeculatedDbgIntrinsics.push_back(I);
2422 continue;
2423 }
2424
2425 // Only speculatively execute a single instruction (not counting the
2426 // terminator) for now.
2427 ++SpeculatedInstructions;
2428 if (SpeculatedInstructions > 1)
2429 return false;
2430
2431 // Don't hoist the instruction if it's unsafe or expensive.
2432 if (!isSafeToSpeculativelyExecute(I) &&
2433 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2434 I, BB, ThenBB, EndBB))))
2435 return false;
2436 if (!SpeculatedStoreValue &&
2437 computeSpeculationCost(I, TTI) >
2438 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2439 return false;
2440
2441 // Store the store speculation candidate.
2442 if (SpeculatedStoreValue)
2443 SpeculatedStore = cast<StoreInst>(I);
2444
2445 // Do not hoist the instruction if any of its operands are defined but not
2446 // used in BB. The transformation will prevent the operand from
2447 // being sunk into the use block.
2448 for (Use &Op : I->operands()) {
2449 Instruction *OpI = dyn_cast<Instruction>(Op);
2450 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2451 continue; // Not a candidate for sinking.
2452
2453 ++SinkCandidateUseCounts[OpI];
2454 }
2455 }
2456
2457 // Consider any sink candidates which are only used in ThenBB as costs for
2458 // speculation. Note, while we iterate over a DenseMap here, we are summing
2459 // and so iteration order isn't significant.
2460 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
2461 I = SinkCandidateUseCounts.begin(),
2462 E = SinkCandidateUseCounts.end();
2463 I != E; ++I)
2464 if (I->first->hasNUses(I->second)) {
2465 ++SpeculatedInstructions;
2466 if (SpeculatedInstructions > 1)
2467 return false;
2468 }
2469
2470 // Check that we can insert the selects and that it's not too expensive to do
2471 // so.
2472 bool Convert = SpeculatedStore != nullptr;
2473 InstructionCost Cost = 0;
2474 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2475 SpeculatedInstructions,
2476 Cost, TTI);
2477 if (!Convert || Cost > Budget)
2478 return false;
2479
2480 // If we get here, we can hoist the instruction and if-convert.
2481 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SPECULATIVELY EXECUTING BB"
<< *ThenBB << "\n";; } } while (false)
;
2482
2483 // Insert a select of the value of the speculated store.
2484 if (SpeculatedStoreValue) {
2485 IRBuilder<NoFolder> Builder(BI);
2486 Value *TrueV = SpeculatedStore->getValueOperand();
2487 Value *FalseV = SpeculatedStoreValue;
2488 if (Invert)
2489 std::swap(TrueV, FalseV);
2490 Value *S = Builder.CreateSelect(
2491 BrCond, TrueV, FalseV, "spec.store.select", BI);
2492 SpeculatedStore->setOperand(0, S);
2493 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2494 SpeculatedStore->getDebugLoc());
2495 }
2496
2497 // Metadata can be dependent on the condition we are hoisting above.
2498 // Conservatively strip all metadata on the instruction. Drop the debug loc
2499 // to avoid making it appear as if the condition is a constant, which would
2500 // be misleading while debugging.
2501 for (auto &I : *ThenBB) {
2502 if (!SpeculatedStoreValue || &I != SpeculatedStore)
2503 I.setDebugLoc(DebugLoc());
2504 I.dropUnknownNonDebugMetadata();
2505 }
2506
2507 // Hoist the instructions.
2508 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2509 ThenBB->begin(), std::prev(ThenBB->end()));
2510
2511 // Insert selects and rewrite the PHI operands.
2512 IRBuilder<NoFolder> Builder(BI);
2513 for (PHINode &PN : EndBB->phis()) {
2514 unsigned OrigI = PN.getBasicBlockIndex(BB);
2515 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2516 Value *OrigV = PN.getIncomingValue(OrigI);
2517 Value *ThenV = PN.getIncomingValue(ThenI);
2518
2519 // Skip PHIs which are trivial.
2520 if (OrigV == ThenV)
2521 continue;
2522
2523 // Create a select whose true value is the speculatively executed value and
2524 // false value is the pre-existing value. Swap them if the branch
2525 // destinations were inverted.
2526 Value *TrueV = ThenV, *FalseV = OrigV;
2527 if (Invert)
2528 std::swap(TrueV, FalseV);
2529 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
2530 PN.setIncomingValue(OrigI, V);
2531 PN.setIncomingValue(ThenI, V);
2532 }
2533
2534 // Remove speculated dbg intrinsics.
2535 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2536 // dbg value for the different flows and inserting it after the select.
2537 for (Instruction *I : SpeculatedDbgIntrinsics)
2538 I->eraseFromParent();
2539
2540 ++NumSpeculations;
2541 return true;
2542}
2543
2544/// Return true if we can thread a branch across this block.
2545static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2546 int Size = 0;
2547
2548 SmallPtrSet<const Value *, 32> EphValues;
2549 auto IsEphemeral = [&](const Value *V) {
2550 if (isa<AssumeInst>(V))
2551 return true;
2552 return isSafeToSpeculativelyExecute(V) &&
2553 all_of(V->users(),
2554 [&](const User *U) { return EphValues.count(U); });
2555 };
2556
2557 // Walk the loop in reverse so that we can identify ephemeral values properly
2558 // (values only feeding assumes).
2559 for (Instruction &I : reverse(BB->instructionsWithoutDebug())) {
2560 // Can't fold blocks that contain noduplicate or convergent calls.
2561 if (CallInst *CI = dyn_cast<CallInst>(&I))
2562 if (CI->cannotDuplicate() || CI->isConvergent())
2563 return false;
2564
2565 // Ignore ephemeral values which are deleted during codegen.
2566 if (IsEphemeral(&I))
2567 EphValues.insert(&I);
2568 // We will delete Phis while threading, so Phis should not be accounted in
2569 // block's size.
2570 else if (!isa<PHINode>(I)) {
2571 if (Size++ > MaxSmallBlockSize)
2572 return false; // Don't clone large BB's.
2573 }
2574
2575 // We can only support instructions that do not define values that are
2576 // live outside of the current basic block.
2577 for (User *U : I.users()) {
2578 Instruction *UI = cast<Instruction>(U);
2579 if (UI->getParent() != BB || isa<PHINode>(UI))
2580 return false;
2581 }
2582
2583 // Looks ok, continue checking.
2584 }
2585
2586 return true;
2587}
2588
2589/// If we have a conditional branch on a PHI node value that is defined in the
2590/// same block as the branch and if any PHI entries are constants, thread edges
2591/// corresponding to that entry to be branches to their ultimate destination.
2592static bool FoldCondBranchOnPHI(BranchInst *BI, DomTreeUpdater *DTU,
2593 const DataLayout &DL, AssumptionCache *AC) {
2594 BasicBlock *BB = BI->getParent();
2595 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
2596 // NOTE: we currently cannot transform this case if the PHI node is used
2597 // outside of the block.
2598 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2599 return false;
2600
2601 // Degenerate case of a single entry PHI.
2602 if (PN->getNumIncomingValues() == 1) {
2603 FoldSingleEntryPHINodes(PN->getParent());
2604 return true;
2605 }
2606
2607 // Now we know that this block has multiple preds and two succs.
2608 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2609 return false;
2610
2611 // Okay, this is a simple enough basic block. See if any phi values are
2612 // constants.
2613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2614 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
2615 if (!CB || !CB->getType()->isIntegerTy(1))
2616 continue;
2617
2618 // Okay, we now know that all edges from PredBB should be revectored to
2619 // branch to RealDest.
2620 BasicBlock *PredBB = PN->getIncomingBlock(i);
2621 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
2622
2623 if (RealDest == BB)
2624 continue; // Skip self loops.
2625 // Skip if the predecessor's terminator is an indirect branch.
2626 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2627 continue;
2628
2629 SmallVector<DominatorTree::UpdateType, 3> Updates;
2630
2631 // The dest block might have PHI nodes, other predecessors and other
2632 // difficult cases. Instead of being smart about this, just insert a new
2633 // block that jumps to the destination block, effectively splitting
2634 // the edge we are about to create.
2635 BasicBlock *EdgeBB =
2636 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2637 RealDest->getParent(), RealDest);
2638 BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
2639 if (DTU)
2640 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
2641 CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
2642
2643 // Update PHI nodes.
2644 AddPredecessorToBlock(RealDest, EdgeBB, BB);
2645
2646 // BB may have instructions that are being threaded over. Clone these
2647 // instructions into EdgeBB. We know that there will be no uses of the
2648 // cloned instructions outside of EdgeBB.
2649 BasicBlock::iterator InsertPt = EdgeBB->begin();
2650 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
2651 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2652 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2653 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2654 continue;
2655 }
2656 // Clone the instruction.
2657 Instruction *N = BBI->clone();
2658 if (BBI->hasName())
2659 N->setName(BBI->getName() + ".c");
2660
2661 // Update operands due to translation.
2662 for (Use &Op : N->operands()) {
2663 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
2664 if (PI != TranslateMap.end())
2665 Op = PI->second;
2666 }
2667
2668 // Check for trivial simplification.
2669 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
2670 if (!BBI->use_empty())
2671 TranslateMap[&*BBI] = V;
2672 if (!N->mayHaveSideEffects()) {
2673 N->deleteValue(); // Instruction folded away, don't need actual inst
2674 N = nullptr;
2675 }
2676 } else {
2677 if (!BBI->use_empty())
2678 TranslateMap[&*BBI] = N;
2679 }
2680 if (N) {
2681 // Insert the new instruction into its new home.
2682 EdgeBB->getInstList().insert(InsertPt, N);
2683
2684 // Register the new instruction with the assumption cache if necessary.
2685 if (auto *Assume = dyn_cast<AssumeInst>(N))
2686 if (AC)
2687 AC->registerAssumption(Assume);
2688 }
2689 }
2690
2691 // Loop over all of the edges from PredBB to BB, changing them to branch
2692 // to EdgeBB instead.
2693 Instruction *PredBBTI = PredBB->getTerminator();
2694 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2695 if (PredBBTI->getSuccessor(i) == BB) {
2696 BB->removePredecessor(PredBB);
2697 PredBBTI->setSuccessor(i, EdgeBB);
2698 }
2699
2700 if (DTU) {
2701 Updates.push_back({DominatorTree::Insert, PredBB, EdgeBB});
2702 Updates.push_back({DominatorTree::Delete, PredBB, BB});
2703
2704 DTU->applyUpdates(Updates);
2705 }
2706
2707 // Recurse, simplifying any other constants.
2708 return FoldCondBranchOnPHI(BI, DTU, DL, AC) || true;
2709 }
2710
2711 return false;
2712}
2713
2714/// Given a BB that starts with the specified two-entry PHI node,
2715/// see if we can eliminate it.
2716static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2717 DomTreeUpdater *DTU, const DataLayout &DL) {
2718 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2719 // statement", which has a very simple dominance structure. Basically, we
2720 // are trying to find the condition that is being branched on, which
2721 // subsequently causes this merge to happen. We really want control
2722 // dependence information for this check, but simplifycfg can't keep it up
2723 // to date, and this catches most of the cases we care about anyway.
2724 BasicBlock *BB = PN->getParent();
2725
2726 BasicBlock *IfTrue, *IfFalse;
2727 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
2728 if (!DomBI)
2729 return false;
2730 Value *IfCond = DomBI->getCondition();
2731 // Don't bother if the branch will be constant folded trivially.
2732 if (isa<ConstantInt>(IfCond))
2733 return false;
2734
2735 BasicBlock *DomBlock = DomBI->getParent();
2736 SmallVector<BasicBlock *, 2> IfBlocks;
2737 llvm::copy_if(
2738 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
2739 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
2740 });
2741 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&(static_cast <bool> ((IfBlocks.size() == 1 || IfBlocks.
size() == 2) && "Will have either one or two blocks to speculate."
) ? void (0) : __assert_fail ("(IfBlocks.size() == 1 || IfBlocks.size() == 2) && \"Will have either one or two blocks to speculate.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2742, __extension__ __PRETTY_FUNCTION__))
2742 "Will have either one or two blocks to speculate.")(static_cast <bool> ((IfBlocks.size() == 1 || IfBlocks.
size() == 2) && "Will have either one or two blocks to speculate."
) ? void (0) : __assert_fail ("(IfBlocks.size() == 1 || IfBlocks.size() == 2) && \"Will have either one or two blocks to speculate.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2742, __extension__ __PRETTY_FUNCTION__))
;
2743
2744 // If the branch is non-unpredictable, see if we either predictably jump to
2745 // the merge bb (if we have only a single 'then' block), or if we predictably
2746 // jump to one specific 'then' block (if we have two of them).
2747 // It isn't beneficial to speculatively execute the code
2748 // from the block that we know is predictably not entered.
2749 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
2750 uint64_t TWeight, FWeight;
2751 if (DomBI->extractProfMetadata(TWeight, FWeight) &&
2752 (TWeight + FWeight) != 0) {
2753 BranchProbability BITrueProb =
2754 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
2755 BranchProbability Likely = TTI.getPredictableBranchThreshold();
2756 BranchProbability BIFalseProb = BITrueProb.getCompl();
2757 if (IfBlocks.size() == 1) {
2758 BranchProbability BIBBProb =
2759 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
2760 if (BIBBProb >= Likely)
2761 return false;
2762 } else {
2763 if (BITrueProb >= Likely || BIFalseProb >= Likely)
2764 return false;
2765 }
2766 }
2767 }
2768
2769 // Don't try to fold an unreachable block. For example, the phi node itself
2770 // can't be the candidate if-condition for a select that we want to form.
2771 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
2772 if (IfCondPhiInst->getParent() == BB)
2773 return false;
2774
2775 // Okay, we found that we can merge this two-entry phi node into a select.
2776 // Doing so would require us to fold *all* two entry phi nodes in this block.
2777 // At some point this becomes non-profitable (particularly if the target
2778 // doesn't support cmov's). Only do this transformation if there are two or
2779 // fewer PHI nodes in this block.
2780 unsigned NumPhis = 0;
2781 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2782 if (NumPhis > 2)
2783 return false;
2784
2785 // Loop over the PHI's seeing if we can promote them all to select
2786 // instructions. While we are at it, keep track of the instructions
2787 // that need to be moved to the dominating block.
2788 SmallPtrSet<Instruction *, 4> AggressiveInsts;
2789 InstructionCost Cost = 0;
2790 InstructionCost Budget =
2791 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2792
2793 bool Changed = false;
2794 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2795 PHINode *PN = cast<PHINode>(II++);
2796 if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
2797 PN->replaceAllUsesWith(V);
2798 PN->eraseFromParent();
2799 Changed = true;
2800 continue;
2801 }
2802
2803 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
2804 Cost, Budget, TTI) ||
2805 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
2806 Cost, Budget, TTI))
2807 return Changed;
2808 }
2809
2810 // If we folded the first phi, PN dangles at this point. Refresh it. If
2811 // we ran out of PHIs then we simplified them all.
2812 PN = dyn_cast<PHINode>(BB->begin());
2813 if (!PN)
2814 return true;
2815
2816 // Return true if at least one of these is a 'not', and another is either
2817 // a 'not' too, or a constant.
2818 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
2819 if (!match(V0, m_Not(m_Value())))
2820 std::swap(V0, V1);
2821 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
2822 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
2823 };
2824
2825 // Don't fold i1 branches on PHIs which contain binary operators or
2826 // (possibly inverted) select form of or/ands, unless one of
2827 // the incoming values is an 'not' and another one is freely invertible.
2828 // These can often be turned into switches and other things.
2829 auto IsBinOpOrAnd = [](Value *V) {
2830 return match(
2831 V, m_CombineOr(
2832 m_BinOp(),
2833 m_CombineOr(m_Select(m_Value(), m_ImmConstant(), m_Value()),
2834 m_Select(m_Value(), m_Value(), m_ImmConstant()))));
2835 };
2836 if (PN->getType()->isIntegerTy(1) &&
2837 (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
2838 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
2839 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
2840 PN->getIncomingValue(1)))
2841 return Changed;
2842
2843 // If all PHI nodes are promotable, check to make sure that all instructions
2844 // in the predecessor blocks can be promoted as well. If not, we won't be able
2845 // to get rid of the control flow, so it's not worth promoting to select
2846 // instructions.
2847 for (BasicBlock *IfBlock : IfBlocks)
2848 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
2849 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I) &&
2850 !isa<PseudoProbeInst>(I)) {
2851 // This is not an aggressive instruction that we can promote.
2852 // Because of this, we won't be able to get rid of the control flow, so
2853 // the xform is not worth it.
2854 return Changed;
2855 }
2856
2857 // If either of the blocks has it's address taken, we can't do this fold.
2858 if (any_of(IfBlocks,
2859 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
2860 return Changed;
2861
2862 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfConddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOUND IF CONDITION! " <<
*IfCond << " T: " << IfTrue->getName() <<
" F: " << IfFalse->getName() << "\n"; } } while
(false)
2863 << " T: " << IfTrue->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOUND IF CONDITION! " <<
*IfCond << " T: " << IfTrue->getName() <<
" F: " << IfFalse->getName() << "\n"; } } while
(false)
2864 << " F: " << IfFalse->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOUND IF CONDITION! " <<
*IfCond << " T: " << IfTrue->getName() <<
" F: " << IfFalse->getName() << "\n"; } } while
(false)
;
2865
2866 // If we can still promote the PHI nodes after this gauntlet of tests,
2867 // do all of the PHI's now.
2868
2869 // Move all 'aggressive' instructions, which are defined in the
2870 // conditional parts of the if's up to the dominating block.
2871 for (BasicBlock *IfBlock : IfBlocks)
2872 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
2873
2874 IRBuilder<NoFolder> Builder(DomBI);
2875 // Propagate fast-math-flags from phi nodes to replacement selects.
2876 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2877 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2878 if (isa<FPMathOperator>(PN))
2879 Builder.setFastMathFlags(PN->getFastMathFlags());
2880
2881 // Change the PHI node into a select instruction.
2882 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
2883 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
2884
2885 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
2886 PN->replaceAllUsesWith(Sel);
2887 Sel->takeName(PN);
2888 PN->eraseFromParent();
2889 }
2890
2891 // At this point, all IfBlocks are empty, so our if statement
2892 // has been flattened. Change DomBlock to jump directly to our new block to
2893 // avoid other simplifycfg's kicking in on the diamond.
2894 Builder.CreateBr(BB);
2895
2896 SmallVector<DominatorTree::UpdateType, 3> Updates;
2897 if (DTU) {
2898 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
2899 for (auto *Successor : successors(DomBlock))
2900 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
2901 }
2902
2903 DomBI->eraseFromParent();
2904 if (DTU)
2905 DTU->applyUpdates(Updates);
2906
2907 return true;
2908}
2909
2910/// If we found a conditional branch that goes to two returning blocks,
2911/// try to merge them together into one return,
2912/// introducing a select if the return values disagree.
2913bool SimplifyCFGOpt::SimplifyCondBranchToTwoReturns(BranchInst *BI,
2914 IRBuilder<> &Builder) {
2915 auto *BB = BI->getParent();
2916 assert(BI->isConditional() && "Must be a conditional branch")(static_cast <bool> (BI->isConditional() && "Must be a conditional branch"
) ? void (0) : __assert_fail ("BI->isConditional() && \"Must be a conditional branch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 2916, __extension__ __PRETTY_FUNCTION__))
;
2917 BasicBlock *TrueSucc = BI->getSuccessor(0);
2918 BasicBlock *FalseSucc = BI->getSuccessor(1);
2919 if (TrueSucc == FalseSucc)
2920 return false;
2921 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2922 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
2923
2924 // Check to ensure both blocks are empty (just a return) or optionally empty
2925 // with PHI nodes. If there are other instructions, merging would cause extra
2926 // computation on one path or the other.
2927 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2928 return false;
2929 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
2930 return false;
2931
2932 Builder.SetInsertPoint(BI);
2933 // Okay, we found a branch that is going to two return nodes. If
2934 // there is no return value for this function, just change the
2935 // branch into a return.
2936 if (FalseRet->getNumOperands() == 0) {
2937 TrueSucc->removePredecessor(BB);
2938 FalseSucc->removePredecessor(BB);
2939 Builder.CreateRetVoid();
2940 EraseTerminatorAndDCECond(BI);
2941 if (DTU)
2942 DTU->applyUpdates({{DominatorTree::Delete, BB, TrueSucc},
2943 {DominatorTree::Delete, BB, FalseSucc}});
2944 return true;
2945 }
2946
2947 // Otherwise, figure out what the true and false return values are
2948 // so we can insert a new select instruction.
2949 Value *TrueValue = TrueRet->getReturnValue();
2950 Value *FalseValue = FalseRet->getReturnValue();
2951
2952 // Unwrap any PHI nodes in the return blocks.
2953 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2954 if (TVPN->getParent() == TrueSucc)
2955 TrueValue = TVPN->getIncomingValueForBlock(BB);
2956 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2957 if (FVPN->getParent() == FalseSucc)
2958 FalseValue = FVPN->getIncomingValueForBlock(BB);
2959
2960 // In order for this transformation to be safe, we must be able to
2961 // unconditionally execute both operands to the return. This is
2962 // normally the case, but we could have a potentially-trapping
2963 // constant expression that prevents this transformation from being
2964 // safe.
2965 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2966 if (TCV->canTrap())
2967 return false;
2968 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2969 if (FCV->canTrap())
2970 return false;
2971
2972 // Okay, we collected all the mapped values and checked them for sanity, and
2973 // defined to really do this transformation. First, update the CFG.
2974 TrueSucc->removePredecessor(BB);
2975 FalseSucc->removePredecessor(BB);
2976
2977 // Insert select instructions where needed.
2978 Value *BrCond = BI->getCondition();
2979 if (TrueValue) {
2980 // Insert a select if the results differ.
2981 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2982 } else if (isa<UndefValue>(TrueValue)) {
2983 TrueValue = FalseValue;
2984 } else {
2985 TrueValue =
2986 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
2987 }
2988 }
2989
2990 Value *RI =
2991 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2992
2993 (void)RI;
2994
2995 LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
<< "\n " << *BI << "\nNewRet = " <<
*RI << "\nTRUEBLOCK: " << *TrueSucc << "\nFALSEBLOCK: "
<< *FalseSucc; } } while (false)
2996 << "\n " << *BI << "\nNewRet = " << *RI << "\nTRUEBLOCK: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
<< "\n " << *BI << "\nNewRet = " <<
*RI << "\nTRUEBLOCK: " << *TrueSucc << "\nFALSEBLOCK: "
<< *FalseSucc; } } while (false)
2997 << *TrueSucc << "\nFALSEBLOCK: " << *FalseSucc)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
<< "\n " << *BI << "\nNewRet = " <<
*RI << "\nTRUEBLOCK: " << *TrueSucc << "\nFALSEBLOCK: "
<< *FalseSucc; } } while (false)
;
2998
2999 EraseTerminatorAndDCECond(BI);
3000 if (DTU)
3001 DTU->applyUpdates({{DominatorTree::Delete, BB, TrueSucc},
3002 {DominatorTree::Delete, BB, FalseSucc}});
3003
3004 return true;
3005}
3006
3007static Value *createLogicalOp(IRBuilderBase &Builder,
3008 Instruction::BinaryOps Opc, Value *LHS,
3009 Value *RHS, const Twine &Name = "") {
3010 // Try to relax logical op to binary op.
3011 if (impliesPoison(RHS, LHS))
3012 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3013 if (Opc == Instruction::And)
3014 return Builder.CreateLogicalAnd(LHS, RHS, Name);
3015 if (Opc == Instruction::Or)
3016 return Builder.CreateLogicalOr(LHS, RHS, Name);
3017 llvm_unreachable("Invalid logical opcode")::llvm::llvm_unreachable_internal("Invalid logical opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3017)
;
3018}
3019
3020/// Return true if either PBI or BI has branch weight available, and store
3021/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3022/// not have branch weight, use 1:1 as its weight.
3023static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
3024 uint64_t &PredTrueWeight,
3025 uint64_t &PredFalseWeight,
3026 uint64_t &SuccTrueWeight,
3027 uint64_t &SuccFalseWeight) {
3028 bool PredHasWeights =
3029 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
3030 bool SuccHasWeights =
3031 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
3032 if (PredHasWeights || SuccHasWeights) {
3033 if (!PredHasWeights)
3034 PredTrueWeight = PredFalseWeight = 1;
3035 if (!SuccHasWeights)
3036 SuccTrueWeight = SuccFalseWeight = 1;
3037 return true;
3038 } else {
3039 return false;
3040 }
3041}
3042
3043/// Determine if the two branches share a common destination and deduce a glue
3044/// that joins the branches' conditions to arrive at the common destination if
3045/// that would be profitable.
3046static Optional<std::pair<Instruction::BinaryOps, bool>>
3047shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI,
3048 const TargetTransformInfo *TTI) {
3049 assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&(static_cast <bool> (BI && PBI && BI->
isConditional() && PBI->isConditional() &&
"Both blocks must end with a conditional branches.") ? void (
0) : __assert_fail ("BI && PBI && BI->isConditional() && PBI->isConditional() && \"Both blocks must end with a conditional branches.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3050, __extension__ __PRETTY_FUNCTION__))
3050 "Both blocks must end with a conditional branches.")(static_cast <bool> (BI && PBI && BI->
isConditional() && PBI->isConditional() &&
"Both blocks must end with a conditional branches.") ? void (
0) : __assert_fail ("BI && PBI && BI->isConditional() && PBI->isConditional() && \"Both blocks must end with a conditional branches.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3050, __extension__ __PRETTY_FUNCTION__))
;
3051 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&(static_cast <bool> (is_contained(predecessors(BI->getParent
()), PBI->getParent()) && "PredBB must be a predecessor of BB."
) ? void (0) : __assert_fail ("is_contained(predecessors(BI->getParent()), PBI->getParent()) && \"PredBB must be a predecessor of BB.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3052, __extension__ __PRETTY_FUNCTION__))
3052 "PredBB must be a predecessor of BB.")(static_cast <bool> (is_contained(predecessors(BI->getParent
()), PBI->getParent()) && "PredBB must be a predecessor of BB."
) ? void (0) : __assert_fail ("is_contained(predecessors(BI->getParent()), PBI->getParent()) && \"PredBB must be a predecessor of BB.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3052, __extension__ __PRETTY_FUNCTION__))
;
3053
3054 // We have the potential to fold the conditions together, but if the
3055 // predecessor branch is predictable, we may not want to merge them.
3056 uint64_t PTWeight, PFWeight;
3057 BranchProbability PBITrueProb, Likely;
3058 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3059 PBI->extractProfMetadata(PTWeight, PFWeight) &&
3060 (PTWeight + PFWeight) != 0) {
3061 PBITrueProb =
3062 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3063 Likely = TTI->getPredictableBranchThreshold();
3064 }
3065
3066 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3067 // Speculate the 2nd condition unless the 1st is probably true.
3068 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3069 return {{Instruction::Or, false}};
3070 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3071 // Speculate the 2nd condition unless the 1st is probably false.
3072 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3073 return {{Instruction::And, false}};
3074 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3075 // Speculate the 2nd condition unless the 1st is probably true.
3076 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3077 return {{Instruction::And, true}};
3078 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3079 // Speculate the 2nd condition unless the 1st is probably false.
3080 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3081 return {{Instruction::Or, true}};
3082 }
3083 return None;
3084}
3085
3086static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI,
3087 DomTreeUpdater *DTU,
3088 MemorySSAUpdater *MSSAU,
3089 const TargetTransformInfo *TTI) {
3090 BasicBlock *BB = BI->getParent();
3091 BasicBlock *PredBlock = PBI->getParent();
3092
3093 // Determine if the two branches share a common destination.
3094 Instruction::BinaryOps Opc;
3095 bool InvertPredCond;
3096 std::tie(Opc, InvertPredCond) =
3097 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI);
3098
3099 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOLDING BRANCH TO COMMON DEST:\n"
<< *PBI << *BB; } } while (false)
;
3100
3101 IRBuilder<> Builder(PBI);
3102 // The builder is used to create instructions to eliminate the branch in BB.
3103 // If BB's terminator has !annotation metadata, add it to the new
3104 // instructions.
3105 Builder.CollectMetadataToCopy(BB->getTerminator(),
3106 {LLVMContext::MD_annotation});
3107
3108 // If we need to invert the condition in the pred block to match, do so now.
3109 if (InvertPredCond) {
3110 Value *NewCond = PBI->getCondition();
3111 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
3112 CmpInst *CI = cast<CmpInst>(NewCond);
3113 CI->setPredicate(CI->getInversePredicate());
3114 } else {
3115 NewCond =
3116 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
3117 }
3118
3119 PBI->setCondition(NewCond);
3120 PBI->swapSuccessors();
3121 }
3122
3123 BasicBlock *UniqueSucc =
3124 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3125
3126 // Before cloning instructions, notify the successor basic block that it
3127 // is about to have a new predecessor. This will update PHI nodes,
3128 // which will allow us to update live-out uses of bonus instructions.
3129 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3130
3131 // Try to update branch weights.
3132 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3133 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3134 SuccTrueWeight, SuccFalseWeight)) {
3135 SmallVector<uint64_t, 8> NewWeights;
3136
3137 if (PBI->getSuccessor(0) == BB) {
3138 // PBI: br i1 %x, BB, FalseDest
3139 // BI: br i1 %y, UniqueSucc, FalseDest
3140 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3141 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3142 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3143 // TrueWeight for PBI * FalseWeight for BI.
3144 // We assume that total weights of a BranchInst can fit into 32 bits.
3145 // Therefore, we will not have overflow using 64-bit arithmetic.
3146 NewWeights.push_back(PredFalseWeight *
3147 (SuccFalseWeight + SuccTrueWeight) +
3148 PredTrueWeight * SuccFalseWeight);
3149 } else {
3150 // PBI: br i1 %x, TrueDest, BB
3151 // BI: br i1 %y, TrueDest, UniqueSucc
3152 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3153 // FalseWeight for PBI * TrueWeight for BI.
3154 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3155 PredFalseWeight * SuccTrueWeight);
3156 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3157 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3158 }
3159
3160 // Halve the weights if any of them cannot fit in an uint32_t
3161 FitWeights(NewWeights);
3162
3163 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3164 setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3165
3166 // TODO: If BB is reachable from all paths through PredBlock, then we
3167 // could replace PBI's branch probabilities with BI's.
3168 } else
3169 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3170
3171 // Now, update the CFG.
3172 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3173
3174 if (DTU)
3175 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3176 {DominatorTree::Delete, PredBlock, BB}});
3177
3178 // If BI was a loop latch, it may have had associated loop metadata.
3179 // We need to copy it to the new latch, that is, PBI.
3180 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3181 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3182
3183 ValueToValueMapTy VMap; // maps original values to cloned values
3184 CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap);
3185
3186 // Now that the Cond was cloned into the predecessor basic block,
3187 // or/and the two conditions together.
3188 Value *BICond = VMap[BI->getCondition()];
3189 PBI->setCondition(
3190 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3191
3192 // Copy any debug value intrinsics into the end of PredBlock.
3193 for (Instruction &I : *BB) {
3194 if (isa<DbgInfoIntrinsic>(I)) {
3195 Instruction *NewI = I.clone();
3196 RemapInstruction(NewI, VMap,
3197 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
3198 NewI->insertBefore(PBI);
3199 }
3200 }
3201
3202 ++NumFoldBranchToCommonDest;
3203 return true;
3204}
3205
3206/// If this basic block is simple enough, and if a predecessor branches to us
3207/// and one of our successors, fold the block into the predecessor and use
3208/// logical operations to pick the right destination.
3209bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU,
3210 MemorySSAUpdater *MSSAU,
3211 const TargetTransformInfo *TTI,
3212 unsigned BonusInstThreshold) {
3213 // If this block ends with an unconditional branch,
3214 // let SpeculativelyExecuteBB() deal with it.
3215 if (!BI->isConditional())
3216 return false;
3217
3218 BasicBlock *BB = BI->getParent();
3219 TargetTransformInfo::TargetCostKind CostKind =
3220 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
3221 : TargetTransformInfo::TCK_SizeAndLatency;
3222
3223 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3224
3225 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
3226 Cond->getParent() != BB || !Cond->hasOneUse())
3227 return false;
3228
3229 // Cond is known to be a compare or binary operator. Check to make sure that
3230 // neither operand is a potentially-trapping constant expression.
3231 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
3232 if (CE->canTrap())
3233 return false;
3234 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
3235 if (CE->canTrap())
3236 return false;
3237
3238 // Finally, don't infinitely unroll conditional loops.
3239 if (is_contained(successors(BB), BB))
3240 return false;
3241
3242 // With which predecessors will we want to deal with?
3243 SmallVector<BasicBlock *, 8> Preds;
3244 for (BasicBlock *PredBlock : predecessors(BB)) {
3245 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3246
3247 // Check that we have two conditional branches. If there is a PHI node in
3248 // the common successor, verify that the same value flows in from both
3249 // blocks.
3250 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3251 continue;
3252
3253 // Determine if the two branches share a common destination.
3254 Instruction::BinaryOps Opc;
3255 bool InvertPredCond;
3256 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3257 std::tie(Opc, InvertPredCond) = *Recipe;
3258 else
3259 continue;
3260
3261 // Check the cost of inserting the necessary logic before performing the
3262 // transformation.
3263 if (TTI) {
3264 Type *Ty = BI->getCondition()->getType();
3265 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind);
3266 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3267 !isa<CmpInst>(PBI->getCondition())))
3268 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3269
3270 if (Cost > BranchFoldThreshold)
3271 continue;
3272 }
3273
3274 // Ok, we do want to deal with this predecessor. Record it.
3275 Preds.emplace_back(PredBlock);
3276 }
3277
3278 // If there aren't any predecessors into which we can fold,
3279 // don't bother checking the cost.
3280 if (Preds.empty())
3281 return false;
3282
3283 // Only allow this transformation if computing the condition doesn't involve
3284 // too many instructions and these involved instructions can be executed
3285 // unconditionally. We denote all involved instructions except the condition
3286 // as "bonus instructions", and only allow this transformation when the
3287 // number of the bonus instructions we'll need to create when cloning into
3288 // each predecessor does not exceed a certain threshold.
3289 unsigned NumBonusInsts = 0;
3290 const unsigned PredCount = Preds.size();
3291 for (Instruction &I : *BB) {
3292 // Don't check the branch condition comparison itself.
3293 if (&I == Cond)
3294 continue;
3295 // Ignore dbg intrinsics, and the terminator.
3296 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3297 continue;
3298 // I must be safe to execute unconditionally.
3299 if (!isSafeToSpeculativelyExecute(&I))
3300 return false;
3301
3302 // Account for the cost of duplicating this instruction into each
3303 // predecessor.
3304 NumBonusInsts += PredCount;
3305 // Early exits once we reach the limit.
3306 if (NumBonusInsts > BonusInstThreshold)
3307 return false;
3308 }
3309
3310 // Ok, we have the budget. Perform the transformation.
3311 for (BasicBlock *PredBlock : Preds) {
3312 auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3313 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3314 }
3315 return false;
3316}
3317
3318// If there is only one store in BB1 and BB2, return it, otherwise return
3319// nullptr.
3320static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
3321 StoreInst *S = nullptr;
3322 for (auto *BB : {BB1, BB2}) {
3323 if (!BB)
3324 continue;
3325 for (auto &I : *BB)
3326 if (auto *SI = dyn_cast<StoreInst>(&I)) {
3327 if (S)
3328 // Multiple stores seen.
3329 return nullptr;
3330 else
3331 S = SI;
3332 }
3333 }
3334 return S;
3335}
3336
3337static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
3338 Value *AlternativeV = nullptr) {
3339 // PHI is going to be a PHI node that allows the value V that is defined in
3340 // BB to be referenced in BB's only successor.
3341 //
3342 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3343 // doesn't matter to us what the other operand is (it'll never get used). We
3344 // could just create a new PHI with an undef incoming value, but that could
3345 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3346 // other PHI. So here we directly look for some PHI in BB's successor with V
3347 // as an incoming operand. If we find one, we use it, else we create a new
3348 // one.
3349 //
3350 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3351 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3352 // where OtherBB is the single other predecessor of BB's only successor.
3353 PHINode *PHI = nullptr;
3354 BasicBlock *Succ = BB->getSingleSuccessor();
3355
3356 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3357 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3358 PHI = cast<PHINode>(I);
3359 if (!AlternativeV)
3360 break;
3361
3362 assert(Succ->hasNPredecessors(2))(static_cast <bool> (Succ->hasNPredecessors(2)) ? void
(0) : __assert_fail ("Succ->hasNPredecessors(2)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3362, __extension__ __PRETTY_FUNCTION__))
;
3363 auto PredI = pred_begin(Succ);
3364 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3365 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3366 break;
3367 PHI = nullptr;
3368 }
3369 if (PHI)
3370 return PHI;
3371
3372 // If V is not an instruction defined in BB, just return it.
3373 if (!AlternativeV &&
3374 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3375 return V;
3376
3377 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3378 PHI->addIncoming(V, BB);
3379 for (BasicBlock *PredBB : predecessors(Succ))
3380 if (PredBB != BB)
3381 PHI->addIncoming(
3382 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3383 return PHI;
3384}
3385
3386static bool mergeConditionalStoreToAddress(
3387 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3388 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3389 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3390 // For every pointer, there must be exactly two stores, one coming from
3391 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3392 // store (to any address) in PTB,PFB or QTB,QFB.
3393 // FIXME: We could relax this restriction with a bit more work and performance
3394 // testing.
3395 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3396 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3397 if (!PStore || !QStore)
3398 return false;
3399
3400 // Now check the stores are compatible.
3401 if (!QStore->isUnordered() || !PStore->isUnordered())
3402 return false;
3403
3404 // Check that sinking the store won't cause program behavior changes. Sinking
3405 // the store out of the Q blocks won't change any behavior as we're sinking
3406 // from a block to its unconditional successor. But we're moving a store from
3407 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3408 // So we need to check that there are no aliasing loads or stores in
3409 // QBI, QTB and QFB. We also need to check there are no conflicting memory
3410 // operations between PStore and the end of its parent block.
3411 //
3412 // The ideal way to do this is to query AliasAnalysis, but we don't
3413 // preserve AA currently so that is dangerous. Be super safe and just
3414 // check there are no other memory operations at all.
3415 for (auto &I : *QFB->getSinglePredecessor())
3416 if (I.mayReadOrWriteMemory())
3417 return false;
3418 for (auto &I : *QFB)
3419 if (&I != QStore && I.mayReadOrWriteMemory())
3420 return false;
3421 if (QTB)
3422 for (auto &I : *QTB)
3423 if (&I != QStore && I.mayReadOrWriteMemory())
3424 return false;
3425 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3426 I != E; ++I)
3427 if (&*I != PStore && I->mayReadOrWriteMemory())
3428 return false;
3429
3430 // If we're not in aggressive mode, we only optimize if we have some
3431 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3432 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3433 if (!BB)
3434 return true;
3435 // Heuristic: if the block can be if-converted/phi-folded and the
3436 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3437 // thread this store.
3438 InstructionCost Cost = 0;
3439 InstructionCost Budget =
3440 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3441 for (auto &I : BB->instructionsWithoutDebug()) {
3442 // Consider terminator instruction to be free.
3443 if (I.isTerminator())
3444 continue;
3445 // If this is one the stores that we want to speculate out of this BB,
3446 // then don't count it's cost, consider it to be free.
3447 if (auto *S = dyn_cast<StoreInst>(&I))
3448 if (llvm::find(FreeStores, S))
3449 continue;
3450 // Else, we have a white-list of instructions that we are ak speculating.
3451 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3452 return false; // Not in white-list - not worthwhile folding.
3453 // And finally, if this is a non-free instruction that we are okay
3454 // speculating, ensure that we consider the speculation budget.
3455 Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
3456 if (Cost > Budget)
3457 return false; // Eagerly refuse to fold as soon as we're out of budget.
3458 }
3459 assert(Cost <= Budget &&(static_cast <bool> (Cost <= Budget && "When we run out of budget we will eagerly return from within the "
"per-instruction loop.") ? void (0) : __assert_fail ("Cost <= Budget && \"When we run out of budget we will eagerly return from within the \" \"per-instruction loop.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3461, __extension__ __PRETTY_FUNCTION__))
3460 "When we run out of budget we will eagerly return from within the "(static_cast <bool> (Cost <= Budget && "When we run out of budget we will eagerly return from within the "
"per-instruction loop.") ? void (0) : __assert_fail ("Cost <= Budget && \"When we run out of budget we will eagerly return from within the \" \"per-instruction loop.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3461, __extension__ __PRETTY_FUNCTION__))
3461 "per-instruction loop.")(static_cast <bool> (Cost <= Budget && "When we run out of budget we will eagerly return from within the "
"per-instruction loop.") ? void (0) : __assert_fail ("Cost <= Budget && \"When we run out of budget we will eagerly return from within the \" \"per-instruction loop.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3461, __extension__ __PRETTY_FUNCTION__))
;
3462 return true;
3463 };
3464
3465 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3466 if (!MergeCondStoresAggressively &&
3467 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3468 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3469 return false;
3470
3471 // If PostBB has more than two predecessors, we need to split it so we can
3472 // sink the store.
3473 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3474 // We know that QFB's only successor is PostBB. And QFB has a single
3475 // predecessor. If QTB exists, then its only successor is also PostBB.
3476 // If QTB does not exist, then QFB's only predecessor has a conditional
3477 // branch to QFB and PostBB.
3478 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3479 BasicBlock *NewBB =
3480 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3481 if (!NewBB)
3482 return false;
3483 PostBB = NewBB;
3484 }
3485
3486 // OK, we're going to sink the stores to PostBB. The store has to be
3487 // conditional though, so first create the predicate.
3488 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3489 ->getCondition();
3490 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3491 ->getCondition();
3492
3493 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3494 PStore->getParent());
3495 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3496 QStore->getParent(), PPHI);
3497
3498 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3499
3500 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3501 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3502
3503 if (InvertPCond)
3504 PPred = QB.CreateNot(PPred);
3505 if (InvertQCond)
3506 QPred = QB.CreateNot(QPred);
3507 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3508
3509 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
3510 /*Unreachable=*/false,
3511 /*BranchWeights=*/nullptr, DTU);
3512 QB.SetInsertPoint(T);
3513 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3514 AAMDNodes AAMD;
3515 PStore->getAAMetadata(AAMD, /*Merge=*/false);
3516 PStore->getAAMetadata(AAMD, /*Merge=*/true);
3517 SI->setAAMetadata(AAMD);
3518 // Choose the minimum alignment. If we could prove both stores execute, we
3519 // could use biggest one. In this case, though, we only know that one of the
3520 // stores executes. And we don't know it's safe to take the alignment from a
3521 // store that doesn't execute.
3522 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
3523
3524 QStore->eraseFromParent();
3525 PStore->eraseFromParent();
3526
3527 return true;
3528}
3529
3530static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3531 DomTreeUpdater *DTU, const DataLayout &DL,
3532 const TargetTransformInfo &TTI) {
3533 // The intention here is to find diamonds or triangles (see below) where each
3534 // conditional block contains a store to the same address. Both of these
3535 // stores are conditional, so they can't be unconditionally sunk. But it may
3536 // be profitable to speculatively sink the stores into one merged store at the
3537 // end, and predicate the merged store on the union of the two conditions of
3538 // PBI and QBI.
3539 //
3540 // This can reduce the number of stores executed if both of the conditions are
3541 // true, and can allow the blocks to become small enough to be if-converted.
3542 // This optimization will also chain, so that ladders of test-and-set
3543 // sequences can be if-converted away.
3544 //
3545 // We only deal with simple diamonds or triangles:
3546 //
3547 // PBI or PBI or a combination of the two
3548 // / \ | \
3549 // PTB PFB | PFB
3550 // \ / | /
3551 // QBI QBI
3552 // / \ | \
3553 // QTB QFB | QFB
3554 // \ / | /
3555 // PostBB PostBB
3556 //
3557 // We model triangles as a type of diamond with a nullptr "true" block.
3558 // Triangles are canonicalized so that the fallthrough edge is represented by
3559 // a true condition, as in the diagram above.
3560 BasicBlock *PTB = PBI->getSuccessor(0);
3561 BasicBlock *PFB = PBI->getSuccessor(1);
3562 BasicBlock *QTB = QBI->getSuccessor(0);
3563 BasicBlock *QFB = QBI->getSuccessor(1);
3564 BasicBlock *PostBB = QFB->getSingleSuccessor();
3565
3566 // Make sure we have a good guess for PostBB. If QTB's only successor is
3567 // QFB, then QFB is a better PostBB.
3568 if (QTB->getSingleSuccessor() == QFB)
3569 PostBB = QFB;
3570
3571 // If we couldn't find a good PostBB, stop.
3572 if (!PostBB)
3573 return false;
3574
3575 bool InvertPCond = false, InvertQCond = false;
3576 // Canonicalize fallthroughs to the true branches.
3577 if (PFB == QBI->getParent()) {
3578 std::swap(PFB, PTB);
3579 InvertPCond = true;
3580 }
3581 if (QFB == PostBB) {
3582 std::swap(QFB, QTB);
3583 InvertQCond = true;
3584 }
3585
3586 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3587 // and QFB may not. Model fallthroughs as a nullptr block.
3588 if (PTB == QBI->getParent())
3589 PTB = nullptr;
3590 if (QTB == PostBB)
3591 QTB = nullptr;
3592
3593 // Legality bailouts. We must have at least the non-fallthrough blocks and
3594 // the post-dominating block, and the non-fallthroughs must only have one
3595 // predecessor.
3596 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3597 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3598 };
3599 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3600 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3601 return false;
3602 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3603 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3604 return false;
3605 if (!QBI->getParent()->hasNUses(2))
3606 return false;
3607
3608 // OK, this is a sequence of two diamonds or triangles.
3609 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3610 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3611 for (auto *BB : {PTB, PFB}) {
3612 if (!BB)
3613 continue;
3614 for (auto &I : *BB)
3615 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3616 PStoreAddresses.insert(SI->getPointerOperand());
3617 }
3618 for (auto *BB : {QTB, QFB}) {
3619 if (!BB)
3620 continue;
3621 for (auto &I : *BB)
3622 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3623 QStoreAddresses.insert(SI->getPointerOperand());
3624 }
3625
3626 set_intersect(PStoreAddresses, QStoreAddresses);
3627 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3628 // clear what it contains.
3629 auto &CommonAddresses = PStoreAddresses;
3630
3631 bool Changed = false;
3632 for (auto *Address : CommonAddresses)
3633 Changed |=
3634 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
3635 InvertPCond, InvertQCond, DTU, DL, TTI);
3636 return Changed;
3637}
3638
3639/// If the previous block ended with a widenable branch, determine if reusing
3640/// the target block is profitable and legal. This will have the effect of
3641/// "widening" PBI, but doesn't require us to reason about hosting safety.
3642static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3643 DomTreeUpdater *DTU) {
3644 // TODO: This can be generalized in two important ways:
3645 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3646 // values from the PBI edge.
3647 // 2) We can sink side effecting instructions into BI's fallthrough
3648 // successor provided they doesn't contribute to computation of
3649 // BI's condition.
3650 Value *CondWB, *WC;
3651 BasicBlock *IfTrueBB, *IfFalseBB;
3652 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3653 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3654 return false;
3655 if (!IfFalseBB->phis().empty())
3656 return false; // TODO
3657 // Use lambda to lazily compute expensive condition after cheap ones.
3658 auto NoSideEffects = [](BasicBlock &BB) {
3659 return !llvm::any_of(BB, [](const Instruction &I) {
3660 return I.mayWriteToMemory() || I.mayHaveSideEffects();
3661 });
3662 };
3663 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
3664 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
3665 NoSideEffects(*BI->getParent())) {
3666 auto *OldSuccessor = BI->getSuccessor(1);
3667 OldSuccessor->removePredecessor(BI->getParent());
3668 BI->setSuccessor(1, IfFalseBB);
3669 if (DTU)
3670 DTU->applyUpdates(
3671 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
3672 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
3673 return true;
3674 }
3675 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
3676 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
3677 NoSideEffects(*BI->getParent())) {
3678 auto *OldSuccessor = BI->getSuccessor(0);
3679 OldSuccessor->removePredecessor(BI->getParent());
3680 BI->setSuccessor(0, IfFalseBB);
3681 if (DTU)
3682 DTU->applyUpdates(
3683 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
3684 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
3685 return true;
3686 }
3687 return false;
3688}
3689
3690/// If we have a conditional branch as a predecessor of another block,
3691/// this function tries to simplify it. We know
3692/// that PBI and BI are both conditional branches, and BI is in one of the
3693/// successor blocks of PBI - PBI branches to BI.
3694static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3695 DomTreeUpdater *DTU,
3696 const DataLayout &DL,
3697 const TargetTransformInfo &TTI) {
3698 assert(PBI->isConditional() && BI->isConditional())(static_cast <bool> (PBI->isConditional() &&
BI->isConditional()) ? void (0) : __assert_fail ("PBI->isConditional() && BI->isConditional()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 3698, __extension__ __PRETTY_FUNCTION__))
;
3699 BasicBlock *BB = BI->getParent();
3700
3701 // If this block ends with a branch instruction, and if there is a
3702 // predecessor that ends on a branch of the same condition, make
3703 // this conditional branch redundant.
3704 if (PBI->getCondition() == BI->getCondition() &&
3705 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3706 // Okay, the outcome of this conditional branch is statically
3707 // knowable. If this block had a single pred, handle specially.
3708 if (BB->getSinglePredecessor()) {
3709 // Turn this into a branch on constant.
3710 bool CondIsTrue = PBI->getSuccessor(0) == BB;
3711 BI->setCondition(
3712 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3713 return true; // Nuke the branch on constant.
3714 }
3715
3716 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3717 // in the constant and simplify the block result. Subsequent passes of
3718 // simplifycfg will thread the block.
3719 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3720 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3721 PHINode *NewPN = PHINode::Create(
3722 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3723 BI->getCondition()->getName() + ".pr", &BB->front());
3724 // Okay, we're going to insert the PHI node. Since PBI is not the only
3725 // predecessor, compute the PHI'd conditional value for all of the preds.
3726 // Any predecessor where the condition is not computable we keep symbolic.
3727 for (pred_iterator PI = PB; PI != PE; ++PI) {
3728 BasicBlock *P = *PI;
3729 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3730 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3731 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3732 bool CondIsTrue = PBI->getSuccessor(0) == BB;
3733 NewPN->addIncoming(
3734 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3735 P);
3736 } else {
3737 NewPN->addIncoming(BI->getCondition(), P);
3738 }
3739 }
3740
3741 BI->setCondition(NewPN);
3742 return true;
3743 }
3744 }
3745
3746 // If the previous block ended with a widenable branch, determine if reusing
3747 // the target block is profitable and legal. This will have the effect of
3748 // "widening" PBI, but doesn't require us to reason about hosting safety.
3749 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
3750 return true;
3751
3752 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3753 if (CE->canTrap())
3754 return false;
3755
3756 // If both branches are conditional and both contain stores to the same
3757 // address, remove the stores from the conditionals and create a conditional
3758 // merged store at the end.
3759 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
3760 return true;
3761
3762 // If this is a conditional branch in an empty block, and if any
3763 // predecessors are a conditional branch to one of our destinations,
3764 // fold the conditions into logical ops and one cond br.
3765
3766 // Ignore dbg intrinsics.
3767 if (&*BB->instructionsWithoutDebug().begin() != BI)
3768 return false;
3769
3770 int PBIOp, BIOp;
3771 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3772 PBIOp = 0;
3773 BIOp = 0;
3774 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3775 PBIOp = 0;
3776 BIOp = 1;
3777 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3778 PBIOp = 1;
3779 BIOp = 0;
3780 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3781 PBIOp = 1;
3782 BIOp = 1;
3783 } else {
3784 return false;
3785 }
3786
3787 // Check to make sure that the other destination of this branch
3788 // isn't BB itself. If so, this is an infinite loop that will
3789 // keep getting unwound.
3790 if (PBI->getSuccessor(PBIOp) == BB)
3791 return false;
3792
3793 // Do not perform this transformation if it would require
3794 // insertion of a large number of select instructions. For targets
3795 // without predication/cmovs, this is a big pessimization.
3796
3797 // Also do not perform this transformation if any phi node in the common
3798 // destination block can trap when reached by BB or PBB (PR17073). In that
3799 // case, it would be unsafe to hoist the operation into a select instruction.
3800
3801 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3802 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
3803 unsigned NumPhis = 0;
3804 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3805 ++II, ++NumPhis) {
3806 if (NumPhis > 2) // Disable this xform.
3807 return false;
3808
3809 PHINode *PN = cast<PHINode>(II);
3810 Value *BIV = PN->getIncomingValueForBlock(BB);
3811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3812 if (CE->canTrap())
3813 return false;
3814
3815 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3816 Value *PBIV = PN->getIncomingValue(PBBIdx);
3817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3818 if (CE->canTrap())
3819 return false;
3820 }
3821
3822 // Finally, if everything is ok, fold the branches to logical ops.
3823 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3824
3825 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOLDING BRs:" << *PBI
->getParent() << "AND: " << *BI->getParent(
); } } while (false)
3826 << "AND: " << *BI->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOLDING BRs:" << *PBI
->getParent() << "AND: " << *BI->getParent(
); } } while (false)
;
3827
3828 SmallVector<DominatorTree::UpdateType, 5> Updates;
3829
3830 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3831 // branch in it, where one edge (OtherDest) goes back to itself but the other
3832 // exits. We don't *know* that the program avoids the infinite loop
3833 // (even though that seems likely). If we do this xform naively, we'll end up
3834 // recursively unpeeling the loop. Since we know that (after the xform is
3835 // done) that the block *is* infinite if reached, we just make it an obviously
3836 // infinite loop with no cond branch.
3837 if (OtherDest == BB) {
3838 // Insert it at the end of the function, because it's either code,
3839 // or it won't matter if it's hot. :)
3840 BasicBlock *InfLoopBlock =
3841 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3842 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3843 if (DTU)
3844 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
3845 OtherDest = InfLoopBlock;
3846 }
3847
3848 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << *PBI->getParent()->getParent
(); } } while (false)
;
3849
3850 // BI may have other predecessors. Because of this, we leave
3851 // it alone, but modify PBI.
3852
3853 // Make sure we get to CommonDest on True&True directions.
3854 Value *PBICond = PBI->getCondition();
3855 IRBuilder<NoFolder> Builder(PBI);
3856 if (PBIOp)
3857 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3858
3859 Value *BICond = BI->getCondition();
3860 if (BIOp)
3861 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3862
3863 // Merge the conditions.
3864 Value *Cond =
3865 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
3866
3867 // Modify PBI to branch on the new condition to the new dests.
3868 PBI->setCondition(Cond);
3869 PBI->setSuccessor(0, CommonDest);
3870 PBI->setSuccessor(1, OtherDest);
3871
3872 if (DTU) {
3873 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
3874 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
3875
3876 DTU->applyUpdates(Updates);
3877 }
3878
3879 // Update branch weight for PBI.
3880 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3881 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3882 bool HasWeights =
3883 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3884 SuccTrueWeight, SuccFalseWeight);
3885 if (HasWeights) {
3886 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3887 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3888 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3889 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3890 // The weight to CommonDest should be PredCommon * SuccTotal +
3891 // PredOther * SuccCommon.
3892 // The weight to OtherDest should be PredOther * SuccOther.
3893 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3894 PredOther * SuccCommon,
3895 PredOther * SuccOther};
3896 // Halve the weights if any of them cannot fit in an uint32_t
3897 FitWeights(NewWeights);
3898
3899 setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
3900 }
3901
3902 // OtherDest may have phi nodes. If so, add an entry from PBI's
3903 // block that are identical to the entries for BI's block.
3904 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3905
3906 // We know that the CommonDest already had an edge from PBI to
3907 // it. If it has PHIs though, the PHIs may have different
3908 // entries for BB and PBI's BB. If so, insert a select to make
3909 // them agree.
3910 for (PHINode &PN : CommonDest->phis()) {
3911 Value *BIV = PN.getIncomingValueForBlock(BB);
3912 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
3913 Value *PBIV = PN.getIncomingValue(PBBIdx);
3914 if (BIV != PBIV) {
3915 // Insert a select in PBI to pick the right value.
3916 SelectInst *NV = cast<SelectInst>(
3917 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3918 PN.setIncomingValue(PBBIdx, NV);
3919 // Although the select has the same condition as PBI, the original branch
3920 // weights for PBI do not apply to the new select because the select's
3921 // 'logical' edges are incoming edges of the phi that is eliminated, not
3922 // the outgoing edges of PBI.
3923 if (HasWeights) {
3924 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3925 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3926 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3927 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3928 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3929 // The weight to PredOtherDest should be PredOther * SuccCommon.
3930 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3931 PredOther * SuccCommon};
3932
3933 FitWeights(NewWeights);
3934
3935 setBranchWeights(NV, NewWeights[0], NewWeights[1]);
3936 }
3937 }
3938 }
3939
3940 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "INTO: " << *PBI->
getParent(); } } while (false)
;
3941 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << *PBI->getParent()->getParent
(); } } while (false)
;
3942
3943 // This basic block is probably dead. We know it has at least
3944 // one fewer predecessor.
3945 return true;
3946}
3947
3948// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3949// true or to FalseBB if Cond is false.
3950// Takes care of updating the successors and removing the old terminator.
3951// Also makes sure not to introduce new successors by assuming that edges to
3952// non-successor TrueBBs and FalseBBs aren't reachable.
3953bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
3954 Value *Cond, BasicBlock *TrueBB,
3955 BasicBlock *FalseBB,
3956 uint32_t TrueWeight,
3957 uint32_t FalseWeight) {
3958 auto *BB = OldTerm->getParent();
3959 // Remove any superfluous successor edges from the CFG.
3960 // First, figure out which successors to preserve.
3961 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3962 // successor.
3963 BasicBlock *KeepEdge1 = TrueBB;
3964 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3965
3966 SmallPtrSet<BasicBlock *, 2> RemovedSuccessors;
3967
3968 // Then remove the rest.
3969 for (BasicBlock *Succ : successors(OldTerm)) {
3970 // Make sure only to keep exactly one copy of each edge.
3971 if (Succ == KeepEdge1)
3972 KeepEdge1 = nullptr;
3973 else if (Succ == KeepEdge2)
3974 KeepEdge2 = nullptr;
3975 else {
3976 Succ->removePredecessor(BB,
3977 /*KeepOneInputPHIs=*/true);
3978
3979 if (Succ != TrueBB && Succ != FalseBB)
3980 RemovedSuccessors.insert(Succ);
3981 }
3982 }
3983
3984 IRBuilder<> Builder(OldTerm);
3985 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3986
3987 // Insert an appropriate new terminator.
3988 if (!KeepEdge1 && !KeepEdge2) {
3989 if (TrueBB == FalseBB) {
3990 // We were only looking for one successor, and it was present.
3991 // Create an unconditional branch to it.
3992 Builder.CreateBr(TrueBB);
3993 } else {
3994 // We found both of the successors we were looking for.
3995 // Create a conditional branch sharing the condition of the select.
3996 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3997 if (TrueWeight != FalseWeight)
3998 setBranchWeights(NewBI, TrueWeight, FalseWeight);
3999 }
4000 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4001 // Neither of the selected blocks were successors, so this
4002 // terminator must be unreachable.
4003 new UnreachableInst(OldTerm->getContext(), OldTerm);
4004 } else {
4005 // One of the selected values was a successor, but the other wasn't.
4006 // Insert an unconditional branch to the one that was found;
4007 // the edge to the one that wasn't must be unreachable.
4008 if (!KeepEdge1) {
4009 // Only TrueBB was found.
4010 Builder.CreateBr(TrueBB);
4011 } else {
4012 // Only FalseBB was found.
4013 Builder.CreateBr(FalseBB);
4014 }
4015 }
4016
4017 EraseTerminatorAndDCECond(OldTerm);
4018
4019 if (DTU) {
4020 SmallVector<DominatorTree::UpdateType, 2> Updates;
4021 Updates.reserve(RemovedSuccessors.size());
4022 for (auto *RemovedSuccessor : RemovedSuccessors)
4023 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4024 DTU->applyUpdates(Updates);
4025 }
4026
4027 return true;
4028}
4029
4030// Replaces
4031// (switch (select cond, X, Y)) on constant X, Y
4032// with a branch - conditional if X and Y lead to distinct BBs,
4033// unconditional otherwise.
4034bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4035 SelectInst *Select) {
4036 // Check for constant integer values in the select.
4037 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4038 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4039 if (!TrueVal || !FalseVal)
4040 return false;
4041
4042 // Find the relevant condition and destinations.
4043 Value *Condition = Select->getCondition();
4044 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4045 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4046
4047 // Get weight for TrueBB and FalseBB.
4048 uint32_t TrueWeight = 0, FalseWeight = 0;
4049 SmallVector<uint64_t, 8> Weights;
4050 bool HasWeights = HasBranchWeights(SI);
4051 if (HasWeights) {
4052 GetBranchWeights(SI, Weights);
4053 if (Weights.size() == 1 + SI->getNumCases()) {
4054 TrueWeight =
4055 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4056 FalseWeight =
4057 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4058 }
4059 }
4060
4061 // Perform the actual simplification.
4062 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4063 FalseWeight);
4064}
4065
4066// Replaces
4067// (indirectbr (select cond, blockaddress(@fn, BlockA),
4068// blockaddress(@fn, BlockB)))
4069// with
4070// (br cond, BlockA, BlockB).
4071bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4072 SelectInst *SI) {
4073 // Check that both operands of the select are block addresses.
4074 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4075 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4076 if (!TBA || !FBA)
4077 return false;
4078
4079 // Extract the actual blocks.
4080 BasicBlock *TrueBB = TBA->getBasicBlock();
4081 BasicBlock *FalseBB = FBA->getBasicBlock();
4082
4083 // Perform the actual simplification.
4084 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4085 0);
4086}
4087
4088/// This is called when we find an icmp instruction
4089/// (a seteq/setne with a constant) as the only instruction in a
4090/// block that ends with an uncond branch. We are looking for a very specific
4091/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4092/// this case, we merge the first two "or's of icmp" into a switch, but then the
4093/// default value goes to an uncond block with a seteq in it, we get something
4094/// like:
4095///
4096/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4097/// DEFAULT:
4098/// %tmp = icmp eq i8 %A, 92
4099/// br label %end
4100/// end:
4101/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4102///
4103/// We prefer to split the edge to 'end' so that there is a true/false entry to
4104/// the PHI, merging the third icmp into the switch.
4105bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4106 ICmpInst *ICI, IRBuilder<> &Builder) {
4107 BasicBlock *BB = ICI->getParent();
4108
4109 // If the block has any PHIs in it or the icmp has multiple uses, it is too
4110 // complex.
4111 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4112 return false;
4113
4114 Value *V = ICI->getOperand(0);
4115 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4116
4117 // The pattern we're looking for is where our only predecessor is a switch on
4118 // 'V' and this block is the default case for the switch. In this case we can
4119 // fold the compared value into the switch to simplify things.
4120 BasicBlock *Pred = BB->getSinglePredecessor();
4121 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4122 return false;
4123
4124 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4125 if (SI->getCondition() != V)
4126 return false;
4127
4128 // If BB is reachable on a non-default case, then we simply know the value of
4129 // V in this block. Substitute it and constant fold the icmp instruction
4130 // away.
4131 if (SI->getDefaultDest() != BB) {
4132 ConstantInt *VVal = SI->findCaseDest(BB);
4133 assert(VVal && "Should have a unique destination value")(static_cast <bool> (VVal && "Should have a unique destination value"
) ? void (0) : __assert_fail ("VVal && \"Should have a unique destination value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4133, __extension__ __PRETTY_FUNCTION__))
;
4134 ICI->setOperand(0, VVal);
4135
4136 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
4137 ICI->replaceAllUsesWith(V);
4138 ICI->eraseFromParent();
4139 }
4140 // BB is now empty, so it is likely to simplify away.
4141 return requestResimplify();
4142 }
4143
4144 // Ok, the block is reachable from the default dest. If the constant we're
4145 // comparing exists in one of the other edges, then we can constant fold ICI
4146 // and zap it.
4147 if (SI->findCaseValue(Cst) != SI->case_default()) {
4148 Value *V;
4149 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4150 V = ConstantInt::getFalse(BB->getContext());
4151 else
4152 V = ConstantInt::getTrue(BB->getContext());
4153
4154 ICI->replaceAllUsesWith(V);
4155 ICI->eraseFromParent();
4156 // BB is now empty, so it is likely to simplify away.
4157 return requestResimplify();
4158 }
4159
4160 // The use of the icmp has to be in the 'end' block, by the only PHI node in
4161 // the block.
4162 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4163 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4164 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4165 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4166 return false;
4167
4168 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4169 // true in the PHI.
4170 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4171 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4172
4173 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4174 std::swap(DefaultCst, NewCst);
4175
4176 // Replace ICI (which is used by the PHI for the default value) with true or
4177 // false depending on if it is EQ or NE.
4178 ICI->replaceAllUsesWith(DefaultCst);
4179 ICI->eraseFromParent();
4180
4181 SmallVector<DominatorTree::UpdateType, 2> Updates;
4182
4183 // Okay, the switch goes to this block on a default value. Add an edge from
4184 // the switch to the merge point on the compared value.
4185 BasicBlock *NewBB =
4186 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4187 {
4188 SwitchInstProfUpdateWrapper SIW(*SI);
4189 auto W0 = SIW.getSuccessorWeight(0);
4190 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
4191 if (W0) {
4192 NewW = ((uint64_t(*W0) + 1) >> 1);
4193 SIW.setSuccessorWeight(0, *NewW);
4194 }
4195 SIW.addCase(Cst, NewBB, NewW);
4196 if (DTU)
4197 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4198 }
4199
4200 // NewBB branches to the phi block, add the uncond branch and the phi entry.
4201 Builder.SetInsertPoint(NewBB);
4202 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4203 Builder.CreateBr(SuccBlock);
4204 PHIUse->addIncoming(NewCst, NewBB);
4205 if (DTU) {
4206 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4207 DTU->applyUpdates(Updates);
4208 }
4209 return true;
4210}
4211
4212/// The specified branch is a conditional branch.
4213/// Check to see if it is branching on an or/and chain of icmp instructions, and
4214/// fold it into a switch instruction if so.
4215bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4216 IRBuilder<> &Builder,
4217 const DataLayout &DL) {
4218 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4219 if (!Cond)
4220 return false;
4221
4222 // Change br (X == 0 | X == 1), T, F into a switch instruction.
4223 // If this is a bunch of seteq's or'd together, or if it's a bunch of
4224 // 'setne's and'ed together, collect them.
4225
4226 // Try to gather values from a chain of and/or to be turned into a switch
4227 ConstantComparesGatherer ConstantCompare(Cond, DL);
4228 // Unpack the result
4229 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4230 Value *CompVal = ConstantCompare.CompValue;
4231 unsigned UsedICmps = ConstantCompare.UsedICmps;
4232 Value *ExtraCase = ConstantCompare.Extra;
4233
4234 // If we didn't have a multiply compared value, fail.
4235 if (!CompVal)
4236 return false;
4237
4238 // Avoid turning single icmps into a switch.
4239 if (UsedICmps <= 1)
4240 return false;
4241
4242 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4243
4244 // There might be duplicate constants in the list, which the switch
4245 // instruction can't handle, remove them now.
4246 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4247 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4248
4249 // If Extra was used, we require at least two switch values to do the
4250 // transformation. A switch with one value is just a conditional branch.
4251 if (ExtraCase && Values.size() < 2)
4252 return false;
4253
4254 // TODO: Preserve branch weight metadata, similarly to how
4255 // FoldValueComparisonIntoPredecessors preserves it.
4256
4257 // Figure out which block is which destination.
4258 BasicBlock *DefaultBB = BI->getSuccessor(1);
4259 BasicBlock *EdgeBB = BI->getSuccessor(0);
4260 if (!TrueWhenEqual)
4261 std::swap(DefaultBB, EdgeBB);
4262
4263 BasicBlock *BB = BI->getParent();
4264
4265 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Converting 'icmp' chain with "
<< Values.size() << " cases into SWITCH. BB is:\n"
<< *BB; } } while (false)
4266 << " cases into SWITCH. BB is:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Converting 'icmp' chain with "
<< Values.size() << " cases into SWITCH. BB is:\n"
<< *BB; } } while (false)
4267 << *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Converting 'icmp' chain with "
<< Values.size() << " cases into SWITCH. BB is:\n"
<< *BB; } } while (false)
;
4268
4269 SmallVector<DominatorTree::UpdateType, 2> Updates;
4270
4271 // If there are any extra values that couldn't be folded into the switch
4272 // then we evaluate them with an explicit branch first. Split the block
4273 // right before the condbr to handle it.
4274 if (ExtraCase) {
4275 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4276 /*MSSAU=*/nullptr, "switch.early.test");
4277
4278 // Remove the uncond branch added to the old block.
4279 Instruction *OldTI = BB->getTerminator();
4280 Builder.SetInsertPoint(OldTI);
4281
4282 // There can be an unintended UB if extra values are Poison. Before the
4283 // transformation, extra values may not be evaluated according to the
4284 // condition, and it will not raise UB. But after transformation, we are
4285 // evaluating extra values before checking the condition, and it will raise
4286 // UB. It can be solved by adding freeze instruction to extra values.
4287 AssumptionCache *AC = Options.AC;
4288
4289 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4290 ExtraCase = Builder.CreateFreeze(ExtraCase);
4291
4292 if (TrueWhenEqual)
4293 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4294 else
4295 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4296
4297 OldTI->eraseFromParent();
4298
4299 if (DTU)
4300 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4301
4302 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4303 // for the edge we just added.
4304 AddPredecessorToBlock(EdgeBB, BB, NewBB);
4305
4306 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCasedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << " ** 'icmp' chain unhandled condition: "
<< *ExtraCase << "\nEXTRABB = " << *BB; } }
while (false)
4307 << "\nEXTRABB = " << *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << " ** 'icmp' chain unhandled condition: "
<< *ExtraCase << "\nEXTRABB = " << *BB; } }
while (false)
;
4308 BB = NewBB;
4309 }
4310
4311 Builder.SetInsertPoint(BI);
4312 // Convert pointer to int before we switch.
4313 if (CompVal->getType()->isPointerTy()) {
4314 CompVal = Builder.CreatePtrToInt(
4315 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4316 }
4317
4318 // Create the new switch instruction now.
4319 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4320
4321 // Add all of the 'cases' to the switch instruction.
4322 for (unsigned i = 0, e = Values.size(); i != e; ++i)
4323 New->addCase(Values[i], EdgeBB);
4324
4325 // We added edges from PI to the EdgeBB. As such, if there were any
4326 // PHI nodes in EdgeBB, they need entries to be added corresponding to
4327 // the number of edges added.
4328 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4329 PHINode *PN = cast<PHINode>(BBI);
4330 Value *InVal = PN->getIncomingValueForBlock(BB);
4331 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4332 PN->addIncoming(InVal, BB);
4333 }
4334
4335 // Erase the old branch instruction.
4336 EraseTerminatorAndDCECond(BI);
4337 if (DTU)
4338 DTU->applyUpdates(Updates);
4339
4340 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << " ** 'icmp' chain result is:\n"
<< *BB << '\n'; } } while (false)
;
4341 return true;
4342}
4343
4344bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4345 if (isa<PHINode>(RI->getValue()))
19
Assuming the object is a 'PHINode'
20
Taking true branch
4346 return simplifyCommonResume(RI);
21
Calling 'SimplifyCFGOpt::simplifyCommonResume'
4347 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4348 RI->getValue() == RI->getParent()->getFirstNonPHI())
4349 // The resume must unwind the exception that caused control to branch here.
4350 return simplifySingleResume(RI);
4351
4352 return false;
4353}
4354
4355// Check if cleanup block is empty
4356static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
4357 for (Instruction &I : R) {
4358 auto *II = dyn_cast<IntrinsicInst>(&I);
4359 if (!II)
4360 return false;
4361
4362 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4363 switch (IntrinsicID) {
4364 case Intrinsic::dbg_declare:
4365 case Intrinsic::dbg_value:
4366 case Intrinsic::dbg_label:
4367 case Intrinsic::lifetime_end:
4368 break;
4369 default:
4370 return false;
4371 }
4372 }
4373 return true;
23
Returning the value 1, which participates in a condition later
4374}
4375
4376// Simplify resume that is shared by several landing pads (phi of landing pad).
4377bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4378 BasicBlock *BB = RI->getParent();
4379
4380 // Check that there are no other instructions except for debug and lifetime
4381 // intrinsics between the phi's and resume instruction.
4382 if (!isCleanupBlockEmpty(
22
Calling 'isCleanupBlockEmpty'
24
Returning from 'isCleanupBlockEmpty'
25
Taking false branch
4383 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
4384 return false;
4385
4386 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4387 auto *PhiLPInst = cast<PHINode>(RI->getValue());
26
The object is a 'PHINode'
4388
4389 // Check incoming blocks to see if any of them are trivial.
4390 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
27
Assuming 'Idx' is not equal to 'End'
28
Loop condition is true. Entering loop body
4391 Idx++) {
4392 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4393 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4394
4395 // If the block has other successors, we can not delete it because
4396 // it has other dependents.
4397 if (IncomingBB->getUniqueSuccessor() != BB)
29
Assuming the condition is false
30
Taking false branch
4398 continue;
4399
4400 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
31
Assuming the object is not a 'LandingPadInst'
32
'LandingPad' initialized to a null pointer value
4401 // Not the landing pad that caused the control to branch here.
4402 if (IncomingValue
32.1
'IncomingValue' is equal to 'LandingPad'
!= LandingPad)
33
Taking false branch
4403 continue;
4404
4405 if (isCleanupBlockEmpty(
4406 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
34
Called C++ object pointer is null
4407 TrivialUnwindBlocks.insert(IncomingBB);
4408 }
4409
4410 // If no trivial unwind blocks, don't do any simplifications.
4411 if (TrivialUnwindBlocks.empty())
4412 return false;
4413
4414 // Turn all invokes that unwind here into calls.
4415 for (auto *TrivialBB : TrivialUnwindBlocks) {
4416 // Blocks that will be simplified should be removed from the phi node.
4417 // Note there could be multiple edges to the resume block, and we need
4418 // to remove them all.
4419 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4420 BB->removePredecessor(TrivialBB, true);
4421
4422 for (BasicBlock *Pred :
4423 llvm::make_early_inc_range(predecessors(TrivialBB))) {
4424 removeUnwindEdge(Pred, DTU);
4425 ++NumInvokes;
4426 }
4427
4428 // In each SimplifyCFG run, only the current processed block can be erased.
4429 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4430 // of erasing TrivialBB, we only remove the branch to the common resume
4431 // block so that we can later erase the resume block since it has no
4432 // predecessors.
4433 TrivialBB->getTerminator()->eraseFromParent();
4434 new UnreachableInst(RI->getContext(), TrivialBB);
4435 if (DTU)
4436 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4437 }
4438
4439 // Delete the resume block if all its predecessors have been removed.
4440 if (pred_empty(BB))
4441 DeleteDeadBlock(BB, DTU);
4442
4443 return !TrivialUnwindBlocks.empty();
4444}
4445
4446// Simplify resume that is only used by a single (non-phi) landing pad.
4447bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4448 BasicBlock *BB = RI->getParent();
4449 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4450 assert(RI->getValue() == LPInst &&(static_cast <bool> (RI->getValue() == LPInst &&
"Resume must unwind the exception that caused control to here"
) ? void (0) : __assert_fail ("RI->getValue() == LPInst && \"Resume must unwind the exception that caused control to here\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4451, __extension__ __PRETTY_FUNCTION__))
4451 "Resume must unwind the exception that caused control to here")(static_cast <bool> (RI->getValue() == LPInst &&
"Resume must unwind the exception that caused control to here"
) ? void (0) : __assert_fail ("RI->getValue() == LPInst && \"Resume must unwind the exception that caused control to here\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4451, __extension__ __PRETTY_FUNCTION__))
;
4452
4453 // Check that there are no other instructions except for debug intrinsics.
4454 if (!isCleanupBlockEmpty(
4455 make_range<Instruction *>(LPInst->getNextNode(), RI)))
4456 return false;
4457
4458 // Turn all invokes that unwind here into calls and delete the basic block.
4459 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) {
4460 removeUnwindEdge(Pred, DTU);
4461 ++NumInvokes;
4462 }
4463
4464 // The landingpad is now unreachable. Zap it.
4465 DeleteDeadBlock(BB, DTU);
4466 return true;
4467}
4468
4469static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
4470 // If this is a trivial cleanup pad that executes no instructions, it can be
4471 // eliminated. If the cleanup pad continues to the caller, any predecessor
4472 // that is an EH pad will be updated to continue to the caller and any
4473 // predecessor that terminates with an invoke instruction will have its invoke
4474 // instruction converted to a call instruction. If the cleanup pad being
4475 // simplified does not continue to the caller, each predecessor will be
4476 // updated to continue to the unwind destination of the cleanup pad being
4477 // simplified.
4478 BasicBlock *BB = RI->getParent();
4479 CleanupPadInst *CPInst = RI->getCleanupPad();
4480 if (CPInst->getParent() != BB)
4481 // This isn't an empty cleanup.
4482 return false;
4483
4484 // We cannot kill the pad if it has multiple uses. This typically arises
4485 // from unreachable basic blocks.
4486 if (!CPInst->hasOneUse())
4487 return false;
4488
4489 // Check that there are no other instructions except for benign intrinsics.
4490 if (!isCleanupBlockEmpty(
4491 make_range<Instruction *>(CPInst->getNextNode(), RI)))
4492 return false;
4493
4494 // If the cleanup return we are simplifying unwinds to the caller, this will
4495 // set UnwindDest to nullptr.
4496 BasicBlock *UnwindDest = RI->getUnwindDest();
4497 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4498
4499 // We're about to remove BB from the control flow. Before we do, sink any
4500 // PHINodes into the unwind destination. Doing this before changing the
4501 // control flow avoids some potentially slow checks, since we can currently
4502 // be certain that UnwindDest and BB have no common predecessors (since they
4503 // are both EH pads).
4504 if (UnwindDest) {
4505 // First, go through the PHI nodes in UnwindDest and update any nodes that
4506 // reference the block we are removing
4507 for (PHINode &DestPN : UnwindDest->phis()) {
4508 int Idx = DestPN.getBasicBlockIndex(BB);
4509 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4510 assert(Idx != -1)(static_cast <bool> (Idx != -1) ? void (0) : __assert_fail
("Idx != -1", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4510, __extension__ __PRETTY_FUNCTION__))
;
4511 // This PHI node has an incoming value that corresponds to a control
4512 // path through the cleanup pad we are removing. If the incoming
4513 // value is in the cleanup pad, it must be a PHINode (because we
4514 // verified above that the block is otherwise empty). Otherwise, the
4515 // value is either a constant or a value that dominates the cleanup
4516 // pad being removed.
4517 //
4518 // Because BB and UnwindDest are both EH pads, all of their
4519 // predecessors must unwind to these blocks, and since no instruction
4520 // can have multiple unwind destinations, there will be no overlap in
4521 // incoming blocks between SrcPN and DestPN.
4522 Value *SrcVal = DestPN.getIncomingValue(Idx);
4523 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4524
4525 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4526 for (auto *Pred : predecessors(BB)) {
4527 Value *Incoming =
4528 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4529 DestPN.addIncoming(Incoming, Pred);
4530 }
4531 }
4532
4533 // Sink any remaining PHI nodes directly into UnwindDest.
4534 Instruction *InsertPt = DestEHPad;
4535 for (PHINode &PN : make_early_inc_range(BB->phis())) {
4536 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4537 // If the PHI node has no uses or all of its uses are in this basic
4538 // block (meaning they are debug or lifetime intrinsics), just leave
4539 // it. It will be erased when we erase BB below.
4540 continue;
4541
4542 // Otherwise, sink this PHI node into UnwindDest.
4543 // Any predecessors to UnwindDest which are not already represented
4544 // must be back edges which inherit the value from the path through
4545 // BB. In this case, the PHI value must reference itself.
4546 for (auto *pred : predecessors(UnwindDest))
4547 if (pred != BB)
4548 PN.addIncoming(&PN, pred);
4549 PN.moveBefore(InsertPt);
4550 // Also, add a dummy incoming value for the original BB itself,
4551 // so that the PHI is well-formed until we drop said predecessor.
4552 PN.addIncoming(UndefValue::get(PN.getType()), BB);
4553 }
4554 }
4555
4556 std::vector<DominatorTree::UpdateType> Updates;
4557
4558 // We use make_early_inc_range here because we will remove all predecessors.
4559 for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) {
4560 if (UnwindDest == nullptr) {
4561 if (DTU) {
4562 DTU->applyUpdates(Updates);
4563 Updates.clear();
4564 }
4565 removeUnwindEdge(PredBB, DTU);
4566 ++NumInvokes;
4567 } else {
4568 BB->removePredecessor(PredBB);
4569 Instruction *TI = PredBB->getTerminator();
4570 TI->replaceUsesOfWith(BB, UnwindDest);
4571 if (DTU) {
4572 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
4573 Updates.push_back({DominatorTree::Delete, PredBB, BB});
4574 }
4575 }
4576 }
4577
4578 if (DTU)
4579 DTU->applyUpdates(Updates);
4580
4581 DeleteDeadBlock(BB, DTU);
4582
4583 return true;
4584}
4585
4586// Try to merge two cleanuppads together.
4587static bool mergeCleanupPad(CleanupReturnInst *RI) {
4588 // Skip any cleanuprets which unwind to caller, there is nothing to merge
4589 // with.
4590 BasicBlock *UnwindDest = RI->getUnwindDest();
4591 if (!UnwindDest)
4592 return false;
4593
4594 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4595 // be safe to merge without code duplication.
4596 if (UnwindDest->getSinglePredecessor() != RI->getParent())
4597 return false;
4598
4599 // Verify that our cleanuppad's unwind destination is another cleanuppad.
4600 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4601 if (!SuccessorCleanupPad)
4602 return false;
4603
4604 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4605 // Replace any uses of the successor cleanupad with the predecessor pad
4606 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4607 // funclet bundle operands.
4608 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4609 // Remove the old cleanuppad.
4610 SuccessorCleanupPad->eraseFromParent();
4611 // Now, we simply replace the cleanupret with a branch to the unwind
4612 // destination.
4613 BranchInst::Create(UnwindDest, RI->getParent());
4614 RI->eraseFromParent();
4615
4616 return true;
4617}
4618
4619bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
4620 // It is possible to transiantly have an undef cleanuppad operand because we
4621 // have deleted some, but not all, dead blocks.
4622 // Eventually, this block will be deleted.
4623 if (isa<UndefValue>(RI->getOperand(0)))
4624 return false;
4625
4626 if (mergeCleanupPad(RI))
4627 return true;
4628
4629 if (removeEmptyCleanup(RI, DTU))
4630 return true;
4631
4632 return false;
4633}
4634
4635bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4636 BasicBlock *BB = RI->getParent();
4637 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4638 return false;
4639
4640 // Find predecessors that end with branches.
4641 SmallVector<BasicBlock *, 8> UncondBranchPreds;
4642 SmallVector<BranchInst *, 8> CondBranchPreds;
4643 for (BasicBlock *P : predecessors(BB)) {
4644 Instruction *PTI = P->getTerminator();
4645 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4646 if (BI->isUnconditional())
4647 UncondBranchPreds.push_back(P);
4648 else
4649 CondBranchPreds.push_back(BI);
4650 }
4651 }
4652
4653 // If we found some, do the transformation!
4654 if (!UncondBranchPreds.empty() && DupRet) {
4655 while (!UncondBranchPreds.empty()) {
4656 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4657 LLVM_DEBUG(dbgs() << "FOLDING: " << *BBdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOLDING: " << *BB <<
"INTO UNCOND BRANCH PRED: " << *Pred; } } while (false
)
4658 << "INTO UNCOND BRANCH PRED: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "FOLDING: " << *BB <<
"INTO UNCOND BRANCH PRED: " << *Pred; } } while (false
)
;
4659 (void)FoldReturnIntoUncondBranch(RI, BB, Pred, DTU);
4660 }
4661
4662 // If we eliminated all predecessors of the block, delete the block now.
4663 if (pred_empty(BB))
4664 DeleteDeadBlock(BB, DTU);
4665
4666 return true;
4667 }
4668
4669 // Check out all of the conditional branches going to this return
4670 // instruction. If any of them just select between returns, change the
4671 // branch itself into a select/return pair.
4672 while (!CondBranchPreds.empty()) {
4673 BranchInst *BI = CondBranchPreds.pop_back_val();
4674
4675 // Check to see if the non-BB successor is also a return block.
4676 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4677 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4678 SimplifyCondBranchToTwoReturns(BI, Builder))
4679 return true;
4680 }
4681 return false;
4682}
4683
4684// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
4685bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
4686 BasicBlock *BB = UI->getParent();
4687
4688 bool Changed = false;
4689
4690 // If there are any instructions immediately before the unreachable that can
4691 // be removed, do so.
4692 while (UI->getIterator() != BB->begin()) {
4693 BasicBlock::iterator BBI = UI->getIterator();
4694 --BBI;
4695
4696 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
4697 break; // Can not drop any more instructions. We're done here.
4698 // Otherwise, this instruction can be freely erased,
4699 // even if it is not side-effect free.
4700
4701 // Note that deleting EH's here is in fact okay, although it involves a bit
4702 // of subtle reasoning. If this inst is an EH, all the predecessors of this
4703 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
4704 // and we can therefore guarantee this block will be erased.
4705
4706 // Delete this instruction (any uses are guaranteed to be dead)
4707 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
4708 BBI->eraseFromParent();
4709 Changed = true;
4710 }
4711
4712 // If the unreachable instruction is the first in the block, take a gander
4713 // at all of the predecessors of this instruction, and simplify them.
4714 if (&BB->front() != UI)
4715 return Changed;
4716
4717 std::vector<DominatorTree::UpdateType> Updates;
4718
4719 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4720 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4721 auto *Predecessor = Preds[i];
4722 Instruction *TI = Predecessor->getTerminator();
4723 IRBuilder<> Builder(TI);
4724 if (auto *BI = dyn_cast<BranchInst>(TI)) {
4725 // We could either have a proper unconditional branch,
4726 // or a degenerate conditional branch with matching destinations.
4727 if (all_of(BI->successors(),
4728 [BB](auto *Successor) { return Successor == BB; })) {
4729 new UnreachableInst(TI->getContext(), TI);
4730 TI->eraseFromParent();
4731 Changed = true;
4732 } else {
4733 assert(BI->isConditional() && "Can't get here with an uncond branch.")(static_cast <bool> (BI->isConditional() && "Can't get here with an uncond branch."
) ? void (0) : __assert_fail ("BI->isConditional() && \"Can't get here with an uncond branch.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4733, __extension__ __PRETTY_FUNCTION__))
;
4734 Value* Cond = BI->getCondition();
4735 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "The destinations are guaranteed to be different here."
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"The destinations are guaranteed to be different here.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4736, __extension__ __PRETTY_FUNCTION__))
4736 "The destinations are guaranteed to be different here.")(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "The destinations are guaranteed to be different here."
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"The destinations are guaranteed to be different here.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4736, __extension__ __PRETTY_FUNCTION__))
;
4737 if (BI->getSuccessor(0) == BB) {
4738 Builder.CreateAssumption(Builder.CreateNot(Cond));
4739 Builder.CreateBr(BI->getSuccessor(1));
4740 } else {
4741 assert(BI->getSuccessor(1) == BB && "Incorrect CFG")(static_cast <bool> (BI->getSuccessor(1) == BB &&
"Incorrect CFG") ? void (0) : __assert_fail ("BI->getSuccessor(1) == BB && \"Incorrect CFG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4741, __extension__ __PRETTY_FUNCTION__))
;
4742 Builder.CreateAssumption(Cond);
4743 Builder.CreateBr(BI->getSuccessor(0));
4744 }
4745 EraseTerminatorAndDCECond(BI);
4746 Changed = true;
4747 }
4748 if (DTU)
4749 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4750 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4751 SwitchInstProfUpdateWrapper SU(*SI);
4752 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
4753 if (i->getCaseSuccessor() != BB) {
4754 ++i;
4755 continue;
4756 }
4757 BB->removePredecessor(SU->getParent());
4758 i = SU.removeCase(i);
4759 e = SU->case_end();
4760 Changed = true;
4761 }
4762 // Note that the default destination can't be removed!
4763 if (DTU && SI->getDefaultDest() != BB)
4764 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4765 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4766 if (II->getUnwindDest() == BB) {
4767 if (DTU) {
4768 DTU->applyUpdates(Updates);
4769 Updates.clear();
4770 }
4771 removeUnwindEdge(TI->getParent(), DTU);
4772 Changed = true;
4773 }
4774 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4775 if (CSI->getUnwindDest() == BB) {
4776 if (DTU) {
4777 DTU->applyUpdates(Updates);
4778 Updates.clear();
4779 }
4780 removeUnwindEdge(TI->getParent(), DTU);
4781 Changed = true;
4782 continue;
4783 }
4784
4785 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4786 E = CSI->handler_end();
4787 I != E; ++I) {
4788 if (*I == BB) {
4789 CSI->removeHandler(I);
4790 --I;
4791 --E;
4792 Changed = true;
4793 }
4794 }
4795 if (DTU)
4796 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4797 if (CSI->getNumHandlers() == 0) {
4798 if (CSI->hasUnwindDest()) {
4799 // Redirect all predecessors of the block containing CatchSwitchInst
4800 // to instead branch to the CatchSwitchInst's unwind destination.
4801 if (DTU) {
4802 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) {
4803 Updates.push_back({DominatorTree::Insert,
4804 PredecessorOfPredecessor,
4805 CSI->getUnwindDest()});
4806 Updates.push_back({DominatorTree::Delete,
4807 PredecessorOfPredecessor, Predecessor});
4808 }
4809 }
4810 Predecessor->replaceAllUsesWith(CSI->getUnwindDest());
4811 } else {
4812 // Rewrite all preds to unwind to caller (or from invoke to call).
4813 if (DTU) {
4814 DTU->applyUpdates(Updates);
4815 Updates.clear();
4816 }
4817 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor));
4818 for (BasicBlock *EHPred : EHPreds)
4819 removeUnwindEdge(EHPred, DTU);
4820 }
4821 // The catchswitch is no longer reachable.
4822 new UnreachableInst(CSI->getContext(), CSI);
4823 CSI->eraseFromParent();
4824 Changed = true;
4825 }
4826 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4827 (void)CRI;
4828 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&(static_cast <bool> (CRI->hasUnwindDest() &&
CRI->getUnwindDest() == BB && "Expected to always have an unwind to BB."
) ? void (0) : __assert_fail ("CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && \"Expected to always have an unwind to BB.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4829, __extension__ __PRETTY_FUNCTION__))
4829 "Expected to always have an unwind to BB.")(static_cast <bool> (CRI->hasUnwindDest() &&
CRI->getUnwindDest() == BB && "Expected to always have an unwind to BB."
) ? void (0) : __assert_fail ("CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && \"Expected to always have an unwind to BB.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4829, __extension__ __PRETTY_FUNCTION__))
;
4830 if (DTU)
4831 Updates.push_back({DominatorTree::Delete, Predecessor, BB});
4832 new UnreachableInst(TI->getContext(), TI);
4833 TI->eraseFromParent();
4834 Changed = true;
4835 }
4836 }
4837
4838 if (DTU)
4839 DTU->applyUpdates(Updates);
4840
4841 // If this block is now dead, remove it.
4842 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4843 DeleteDeadBlock(BB, DTU);
4844 return true;
4845 }
4846
4847 return Changed;
4848}
4849
4850static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4851 assert(Cases.size() >= 1)(static_cast <bool> (Cases.size() >= 1) ? void (0) :
__assert_fail ("Cases.size() >= 1", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4851, __extension__ __PRETTY_FUNCTION__))
;
4852
4853 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4854 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4855 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4856 return false;
4857 }
4858 return true;
4859}
4860
4861static void createUnreachableSwitchDefault(SwitchInst *Switch,
4862 DomTreeUpdater *DTU) {
4863 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SimplifyCFG: switch default is dead.\n"
; } } while (false)
;
4864 auto *BB = Switch->getParent();
4865 BasicBlock *NewDefaultBlock = SplitBlockPredecessors(
4866 Switch->getDefaultDest(), Switch->getParent(), "", DTU);
4867 auto *OrigDefaultBlock = Switch->getDefaultDest();
4868 Switch->setDefaultDest(&*NewDefaultBlock);
4869 if (DTU)
4870 DTU->applyUpdates({{DominatorTree::Insert, BB, &*NewDefaultBlock},
4871 {DominatorTree::Delete, BB, OrigDefaultBlock}});
4872 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front(), DTU);
4873 SmallVector<DominatorTree::UpdateType, 2> Updates;
4874 if (DTU)
4875 for (auto *Successor : successors(NewDefaultBlock))
4876 Updates.push_back({DominatorTree::Delete, NewDefaultBlock, Successor});
4877 auto *NewTerminator = NewDefaultBlock->getTerminator();
4878 new UnreachableInst(Switch->getContext(), NewTerminator);
4879 EraseTerminatorAndDCECond(NewTerminator);
4880 if (DTU)
4881 DTU->applyUpdates(Updates);
4882}
4883
4884/// Turn a switch with two reachable destinations into an integer range
4885/// comparison and branch.
4886bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI,
4887 IRBuilder<> &Builder) {
4888 assert(SI->getNumCases() > 1 && "Degenerate switch?")(static_cast <bool> (SI->getNumCases() > 1 &&
"Degenerate switch?") ? void (0) : __assert_fail ("SI->getNumCases() > 1 && \"Degenerate switch?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4888, __extension__ __PRETTY_FUNCTION__))
;
4889
4890 bool HasDefault =
4891 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4892
4893 auto *BB = SI->getParent();
4894
4895 // Partition the cases into two sets with different destinations.
4896 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4897 BasicBlock *DestB = nullptr;
4898 SmallVector<ConstantInt *, 16> CasesA;
4899 SmallVector<ConstantInt *, 16> CasesB;
4900
4901 for (auto Case : SI->cases()) {
4902 BasicBlock *Dest = Case.getCaseSuccessor();
4903 if (!DestA)
4904 DestA = Dest;
4905 if (Dest == DestA) {
4906 CasesA.push_back(Case.getCaseValue());
4907 continue;
4908 }
4909 if (!DestB)
4910 DestB = Dest;
4911 if (Dest == DestB) {
4912 CasesB.push_back(Case.getCaseValue());
4913 continue;
4914 }
4915 return false; // More than two destinations.
4916 }
4917
4918 assert(DestA && DestB &&(static_cast <bool> (DestA && DestB && "Single-destination switch should have been folded."
) ? void (0) : __assert_fail ("DestA && DestB && \"Single-destination switch should have been folded.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4919, __extension__ __PRETTY_FUNCTION__))
4919 "Single-destination switch should have been folded.")(static_cast <bool> (DestA && DestB && "Single-destination switch should have been folded."
) ? void (0) : __assert_fail ("DestA && DestB && \"Single-destination switch should have been folded.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4919, __extension__ __PRETTY_FUNCTION__))
;
4920 assert(DestA != DestB)(static_cast <bool> (DestA != DestB) ? void (0) : __assert_fail
("DestA != DestB", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
;
4921 assert(DestB != SI->getDefaultDest())(static_cast <bool> (DestB != SI->getDefaultDest()) ?
void (0) : __assert_fail ("DestB != SI->getDefaultDest()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4921, __extension__ __PRETTY_FUNCTION__))
;
4922 assert(!CasesB.empty() && "There must be non-default cases.")(static_cast <bool> (!CasesB.empty() && "There must be non-default cases."
) ? void (0) : __assert_fail ("!CasesB.empty() && \"There must be non-default cases.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4922, __extension__ __PRETTY_FUNCTION__))
;
4923 assert(!CasesA.empty() || HasDefault)(static_cast <bool> (!CasesA.empty() || HasDefault) ? void
(0) : __assert_fail ("!CasesA.empty() || HasDefault", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
;
4924
4925 // Figure out if one of the sets of cases form a contiguous range.
4926 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4927 BasicBlock *ContiguousDest = nullptr;
4928 BasicBlock *OtherDest = nullptr;
4929 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4930 ContiguousCases = &CasesA;
4931 ContiguousDest = DestA;
4932 OtherDest = DestB;
4933 } else if (CasesAreContiguous(CasesB)) {
4934 ContiguousCases = &CasesB;
4935 ContiguousDest = DestB;
4936 OtherDest = DestA;
4937 } else
4938 return false;
4939
4940 // Start building the compare and branch.
4941
4942 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4943 Constant *NumCases =
4944 ConstantInt::get(Offset->getType(), ContiguousCases->size());
4945
4946 Value *Sub = SI->getCondition();
4947 if (!Offset->isNullValue())
4948 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4949
4950 Value *Cmp;
4951 // If NumCases overflowed, then all possible values jump to the successor.
4952 if (NumCases->isNullValue() && !ContiguousCases->empty())
4953 Cmp = ConstantInt::getTrue(SI->getContext());
4954 else
4955 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4956 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4957
4958 // Update weight for the newly-created conditional branch.
4959 if (HasBranchWeights(SI)) {
4960 SmallVector<uint64_t, 8> Weights;
4961 GetBranchWeights(SI, Weights);
4962 if (Weights.size() == 1 + SI->getNumCases()) {
4963 uint64_t TrueWeight = 0;
4964 uint64_t FalseWeight = 0;
4965 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4966 if (SI->getSuccessor(I) == ContiguousDest)
4967 TrueWeight += Weights[I];
4968 else
4969 FalseWeight += Weights[I];
4970 }
4971 while (TrueWeight > UINT32_MAX(4294967295U) || FalseWeight > UINT32_MAX(4294967295U)) {
4972 TrueWeight /= 2;
4973 FalseWeight /= 2;
4974 }
4975 setBranchWeights(NewBI, TrueWeight, FalseWeight);
4976 }
4977 }
4978
4979 // Prune obsolete incoming values off the successors' PHI nodes.
4980 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4981 unsigned PreviousEdges = ContiguousCases->size();
4982 if (ContiguousDest == SI->getDefaultDest())
4983 ++PreviousEdges;
4984 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4985 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4986 }
4987 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4988 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4989 if (OtherDest == SI->getDefaultDest())
4990 ++PreviousEdges;
4991 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4992 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4993 }
4994
4995 // Clean up the default block - it may have phis or other instructions before
4996 // the unreachable terminator.
4997 if (!HasDefault)
4998 createUnreachableSwitchDefault(SI, DTU);
4999
5000 auto *UnreachableDefault = SI->getDefaultDest();
5001
5002 // Drop the switch.
5003 SI->eraseFromParent();
5004
5005 if (!HasDefault && DTU)
5006 DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}});
5007
5008 return true;
5009}
5010
5011/// Compute masked bits for the condition of a switch
5012/// and use it to remove dead cases.
5013static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
5014 AssumptionCache *AC,
5015 const DataLayout &DL) {
5016 Value *Cond = SI->getCondition();
5017 unsigned Bits = Cond->getType()->getIntegerBitWidth();
5018 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
5019
5020 // We can also eliminate cases by determining that their values are outside of
5021 // the limited range of the condition based on how many significant (non-sign)
5022 // bits are in the condition value.
5023 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
5024 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
5025
5026 // Gather dead cases.
5027 SmallVector<ConstantInt *, 8> DeadCases;
5028 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
5029 for (auto &Case : SI->cases()) {
5030 auto *Successor = Case.getCaseSuccessor();
5031 if (DTU)
5032 ++NumPerSuccessorCases[Successor];
5033 const APInt &CaseVal = Case.getCaseValue()->getValue();
5034 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
5035 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
5036 DeadCases.push_back(Case.getCaseValue());
5037 if (DTU)
5038 --NumPerSuccessorCases[Successor];
5039 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseValdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SimplifyCFG: switch case "
<< CaseVal << " is dead.\n"; } } while (false)
5040 << " is dead.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "SimplifyCFG: switch case "
<< CaseVal << " is dead.\n"; } } while (false)
;
5041 }
5042 }
5043
5044 // If we can prove that the cases must cover all possible values, the
5045 // default destination becomes dead and we can remove it. If we know some
5046 // of the bits in the value, we can use that to more precisely compute the
5047 // number of possible unique case values.
5048 bool HasDefault =
5049 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5050 const unsigned NumUnknownBits =
5051 Bits - (Known.Zero | Known.One).countPopulation();
5052 assert(NumUnknownBits <= Bits)(static_cast <bool> (NumUnknownBits <= Bits) ? void (
0) : __assert_fail ("NumUnknownBits <= Bits", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5052, __extension__ __PRETTY_FUNCTION__))
;
5053 if (HasDefault && DeadCases.empty() &&
5054 NumUnknownBits < 64 /* avoid overflow */ &&
5055 SI->getNumCases() == (1ULL << NumUnknownBits)) {
5056 createUnreachableSwitchDefault(SI, DTU);
5057 return true;
5058 }
5059
5060 if (DeadCases.empty())
5061 return false;
5062
5063 SwitchInstProfUpdateWrapper SIW(*SI);
5064 for (ConstantInt *DeadCase : DeadCases) {
5065 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
5066 assert(CaseI != SI->case_default() &&(static_cast <bool> (CaseI != SI->case_default() &&
"Case was not found. Probably mistake in DeadCases forming."
) ? void (0) : __assert_fail ("CaseI != SI->case_default() && \"Case was not found. Probably mistake in DeadCases forming.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5067, __extension__ __PRETTY_FUNCTION__))
5067 "Case was not found. Probably mistake in DeadCases forming.")(static_cast <bool> (CaseI != SI->case_default() &&
"Case was not found. Probably mistake in DeadCases forming."
) ? void (0) : __assert_fail ("CaseI != SI->case_default() && \"Case was not found. Probably mistake in DeadCases forming.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5067, __extension__ __PRETTY_FUNCTION__))
;
5068 // Prune unused values from PHI nodes.
5069 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
5070 SIW.removeCase(CaseI);
5071 }
5072
5073 if (DTU) {
5074 std::vector<DominatorTree::UpdateType> Updates;
5075 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
5076 if (I.second == 0)
5077 Updates.push_back({DominatorTree::Delete, SI->getParent(), I.first});
5078 DTU->applyUpdates(Updates);
5079 }
5080
5081 return true;
5082}
5083
5084/// If BB would be eligible for simplification by
5085/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
5086/// by an unconditional branch), look at the phi node for BB in the successor
5087/// block and see if the incoming value is equal to CaseValue. If so, return
5088/// the phi node, and set PhiIndex to BB's index in the phi node.
5089static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
5090 BasicBlock *BB, int *PhiIndex) {
5091 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
5092 return nullptr; // BB must be empty to be a candidate for simplification.
5093 if (!BB->getSinglePredecessor())
5094 return nullptr; // BB must be dominated by the switch.
5095
5096 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
5097 if (!Branch || !Branch->isUnconditional())
5098 return nullptr; // Terminator must be unconditional branch.
5099
5100 BasicBlock *Succ = Branch->getSuccessor(0);
5101
5102 for (PHINode &PHI : Succ->phis()) {
5103 int Idx = PHI.getBasicBlockIndex(BB);
5104 assert(Idx >= 0 && "PHI has no entry for predecessor?")(static_cast <bool> (Idx >= 0 && "PHI has no entry for predecessor?"
) ? void (0) : __assert_fail ("Idx >= 0 && \"PHI has no entry for predecessor?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5104, __extension__ __PRETTY_FUNCTION__))
;
5105
5106 Value *InValue = PHI.getIncomingValue(Idx);
5107 if (InValue != CaseValue)
5108 continue;
5109
5110 *PhiIndex = Idx;
5111 return &PHI;
5112 }
5113
5114 return nullptr;
5115}
5116
5117/// Try to forward the condition of a switch instruction to a phi node
5118/// dominated by the switch, if that would mean that some of the destination
5119/// blocks of the switch can be folded away. Return true if a change is made.
5120static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
5121 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
5122
5123 ForwardingNodesMap ForwardingNodes;
5124 BasicBlock *SwitchBlock = SI->getParent();
5125 bool Changed = false;
5126 for (auto &Case : SI->cases()) {
5127 ConstantInt *CaseValue = Case.getCaseValue();
5128 BasicBlock *CaseDest = Case.getCaseSuccessor();
5129
5130 // Replace phi operands in successor blocks that are using the constant case
5131 // value rather than the switch condition variable:
5132 // switchbb:
5133 // switch i32 %x, label %default [
5134 // i32 17, label %succ
5135 // ...
5136 // succ:
5137 // %r = phi i32 ... [ 17, %switchbb ] ...
5138 // -->
5139 // %r = phi i32 ... [ %x, %switchbb ] ...
5140
5141 for (PHINode &Phi : CaseDest->phis()) {
5142 // This only works if there is exactly 1 incoming edge from the switch to
5143 // a phi. If there is >1, that means multiple cases of the switch map to 1
5144 // value in the phi, and that phi value is not the switch condition. Thus,
5145 // this transform would not make sense (the phi would be invalid because
5146 // a phi can't have different incoming values from the same block).
5147 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
5148 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
5149 count(Phi.blocks(), SwitchBlock) == 1) {
5150 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
5151 Changed = true;
5152 }
5153 }
5154
5155 // Collect phi nodes that are indirectly using this switch's case constants.
5156 int PhiIdx;
5157 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
5158 ForwardingNodes[Phi].push_back(PhiIdx);
5159 }
5160
5161 for (auto &ForwardingNode : ForwardingNodes) {
5162 PHINode *Phi = ForwardingNode.first;
5163 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
5164 if (Indexes.size() < 2)
5165 continue;
5166
5167 for (int Index : Indexes)
5168 Phi->setIncomingValue(Index, SI->getCondition());
5169 Changed = true;
5170 }
5171
5172 return Changed;
5173}
5174
5175/// Return true if the backend will be able to handle
5176/// initializing an array of constants like C.
5177static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
5178 if (C->isThreadDependent())
5179 return false;
5180 if (C->isDLLImportDependent())
5181 return false;
5182
5183 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
5184 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
5185 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
5186 return false;
5187
5188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5189 if (!CE->isGEPWithNoNotionalOverIndexing())
5190 return false;
5191 if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
5192 return false;
5193 }
5194
5195 if (!TTI.shouldBuildLookupTablesForConstant(C))
5196 return false;
5197
5198 return true;
5199}
5200
5201/// If V is a Constant, return it. Otherwise, try to look up
5202/// its constant value in ConstantPool, returning 0 if it's not there.
5203static Constant *
5204LookupConstant(Value *V,
5205 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5206 if (Constant *C = dyn_cast<Constant>(V))
5207 return C;
5208 return ConstantPool.lookup(V);
5209}
5210
5211/// Try to fold instruction I into a constant. This works for
5212/// simple instructions such as binary operations where both operands are
5213/// constant or can be replaced by constants from the ConstantPool. Returns the
5214/// resulting constant on success, 0 otherwise.
5215static Constant *
5216ConstantFold(Instruction *I, const DataLayout &DL,
5217 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
5218 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
5219 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
5220 if (!A)
5221 return nullptr;
5222 if (A->isAllOnesValue())
5223 return LookupConstant(Select->getTrueValue(), ConstantPool);
5224 if (A->isNullValue())
5225 return LookupConstant(Select->getFalseValue(), ConstantPool);
5226 return nullptr;
5227 }
5228
5229 SmallVector<Constant *, 4> COps;
5230 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
5231 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
5232 COps.push_back(A);
5233 else
5234 return nullptr;
5235 }
5236
5237 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
5238 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
5239 COps[1], DL);
5240 }
5241
5242 return ConstantFoldInstOperands(I, COps, DL);
5243}
5244
5245/// Try to determine the resulting constant values in phi nodes
5246/// at the common destination basic block, *CommonDest, for one of the case
5247/// destionations CaseDest corresponding to value CaseVal (0 for the default
5248/// case), of a switch instruction SI.
5249static bool
5250GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
5251 BasicBlock **CommonDest,
5252 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
5253 const DataLayout &DL, const TargetTransformInfo &TTI) {
5254 // The block from which we enter the common destination.
5255 BasicBlock *Pred = SI->getParent();
5256
5257 // If CaseDest is empty except for some side-effect free instructions through
5258 // which we can constant-propagate the CaseVal, continue to its successor.
5259 SmallDenseMap<Value *, Constant *> ConstantPool;
5260 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
5261 for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
5262 if (I.isTerminator()) {
5263 // If the terminator is a simple branch, continue to the next block.
5264 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
5265 return false;
5266 Pred = CaseDest;
5267 CaseDest = I.getSuccessor(0);
5268 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
5269 // Instruction is side-effect free and constant.
5270
5271 // If the instruction has uses outside this block or a phi node slot for
5272 // the block, it is not safe to bypass the instruction since it would then
5273 // no longer dominate all its uses.
5274 for (auto &Use : I.uses()) {
5275 User *User = Use.getUser();
5276 if (Instruction *I = dyn_cast<Instruction>(User))
5277 if (I->getParent() == CaseDest)
5278 continue;
5279 if (PHINode *Phi = dyn_cast<PHINode>(User))
5280 if (Phi->getIncomingBlock(Use) == CaseDest)
5281 continue;
5282 return false;
5283 }
5284
5285 ConstantPool.insert(std::make_pair(&I, C));
5286 } else {
5287 break;
5288 }
5289 }
5290
5291 // If we did not have a CommonDest before, use the current one.
5292 if (!*CommonDest)
5293 *CommonDest = CaseDest;
5294 // If the destination isn't the common one, abort.
5295 if (CaseDest != *CommonDest)
5296 return false;
5297
5298 // Get the values for this case from phi nodes in the destination block.
5299 for (PHINode &PHI : (*CommonDest)->phis()) {
5300 int Idx = PHI.getBasicBlockIndex(Pred);
5301 if (Idx == -1)
5302 continue;
5303
5304 Constant *ConstVal =
5305 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
5306 if (!ConstVal)
5307 return false;
5308
5309 // Be conservative about which kinds of constants we support.
5310 if (!ValidLookupTableConstant(ConstVal, TTI))
5311 return false;
5312
5313 Res.push_back(std::make_pair(&PHI, ConstVal));
5314 }
5315
5316 return Res.size() > 0;
5317}
5318
5319// Helper function used to add CaseVal to the list of cases that generate
5320// Result. Returns the updated number of cases that generate this result.
5321static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
5322 SwitchCaseResultVectorTy &UniqueResults,
5323 Constant *Result) {
5324 for (auto &I : UniqueResults) {
5325 if (I.first == Result) {
5326 I.second.push_back(CaseVal);
5327 return I.second.size();
5328 }
5329 }
5330 UniqueResults.push_back(
5331 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
5332 return 1;
5333}
5334
5335// Helper function that initializes a map containing
5336// results for the PHI node of the common destination block for a switch
5337// instruction. Returns false if multiple PHI nodes have been found or if
5338// there is not a common destination block for the switch.
5339static bool
5340InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
5341 SwitchCaseResultVectorTy &UniqueResults,
5342 Constant *&DefaultResult, const DataLayout &DL,
5343 const TargetTransformInfo &TTI,
5344 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
5345 for (auto &I : SI->cases()) {
5346 ConstantInt *CaseVal = I.getCaseValue();
5347
5348 // Resulting value at phi nodes for this case value.
5349 SwitchCaseResultsTy Results;
5350 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
5351 DL, TTI))
5352 return false;
5353
5354 // Only one value per case is permitted.
5355 if (Results.size() > 1)
5356 return false;
5357
5358 // Add the case->result mapping to UniqueResults.
5359 const uintptr_t NumCasesForResult =
5360 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
5361
5362 // Early out if there are too many cases for this result.
5363 if (NumCasesForResult > MaxCasesPerResult)
5364 return false;
5365
5366 // Early out if there are too many unique results.
5367 if (UniqueResults.size() > MaxUniqueResults)
5368 return false;
5369
5370 // Check the PHI consistency.
5371 if (!PHI)
5372 PHI = Results[0].first;
5373 else if (PHI != Results[0].first)
5374 return false;
5375 }
5376 // Find the default result value.
5377 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
5378 BasicBlock *DefaultDest = SI->getDefaultDest();
5379 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
5380 DL, TTI);
5381 // If the default value is not found abort unless the default destination
5382 // is unreachable.
5383 DefaultResult =
5384 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
5385 if ((!DefaultResult &&
5386 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
5387 return false;
5388
5389 return true;
5390}
5391
5392// Helper function that checks if it is possible to transform a switch with only
5393// two cases (or two cases + default) that produces a result into a select.
5394// Example:
5395// switch (a) {
5396// case 10: %0 = icmp eq i32 %a, 10
5397// return 10; %1 = select i1 %0, i32 10, i32 4
5398// case 20: ----> %2 = icmp eq i32 %a, 20
5399// return 2; %3 = select i1 %2, i32 2, i32 %1
5400// default:
5401// return 4;
5402// }
5403static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
5404 Constant *DefaultResult, Value *Condition,
5405 IRBuilder<> &Builder) {
5406 // If we are selecting between only two cases transform into a simple
5407 // select or a two-way select if default is possible.
5408 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
5409 ResultVector[1].second.size() == 1) {
5410 ConstantInt *const FirstCase = ResultVector[0].second[0];
5411 ConstantInt *const SecondCase = ResultVector[1].second[0];
5412
5413 bool DefaultCanTrigger = DefaultResult;
5414 Value *SelectValue = ResultVector[1].first;
5415 if (DefaultCanTrigger) {
5416 Value *const ValueCompare =
5417 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
5418 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
5419 DefaultResult, "switch.select");
5420 }
5421 Value *const ValueCompare =
5422 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
5423 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
5424 SelectValue, "switch.select");
5425 }
5426
5427 // Handle the degenerate case where two cases have the same value.
5428 if (ResultVector.size() == 1 && ResultVector[0].second.size() == 2 &&
5429 DefaultResult) {
5430 Value *Cmp1 = Builder.CreateICmpEQ(
5431 Condition, ResultVector[0].second[0], "switch.selectcmp.case1");
5432 Value *Cmp2 = Builder.CreateICmpEQ(
5433 Condition, ResultVector[0].second[1], "switch.selectcmp.case2");
5434 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp");
5435 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult);
5436 }
5437
5438 return nullptr;
5439}
5440
5441// Helper function to cleanup a switch instruction that has been converted into
5442// a select, fixing up PHI nodes and basic blocks.
5443static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
5444 Value *SelectValue,
5445 IRBuilder<> &Builder,
5446 DomTreeUpdater *DTU) {
5447 std::vector<DominatorTree::UpdateType> Updates;
5448
5449 BasicBlock *SelectBB = SI->getParent();
5450 BasicBlock *DestBB = PHI->getParent();
5451
5452 if (DTU && !is_contained(predecessors(DestBB), SelectBB))
5453 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB});
5454 Builder.CreateBr(DestBB);
5455
5456 // Remove the switch.
5457
5458 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
5459 PHI->removeIncomingValue(SelectBB);
5460 PHI->addIncoming(SelectValue, SelectBB);
5461
5462 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
5463 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5464 BasicBlock *Succ = SI->getSuccessor(i);
5465
5466 if (Succ == DestBB)
5467 continue;
5468 Succ->removePredecessor(SelectBB);
5469 if (DTU && RemovedSuccessors.insert(Succ).second)
5470 Updates.push_back({DominatorTree::Delete, SelectBB, Succ});
5471 }
5472 SI->eraseFromParent();
5473 if (DTU)
5474 DTU->applyUpdates(Updates);
5475}
5476
5477/// If the switch is only used to initialize one or more
5478/// phi nodes in a common successor block with only two different
5479/// constant values, replace the switch with select.
5480static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
5481 DomTreeUpdater *DTU, const DataLayout &DL,
5482 const TargetTransformInfo &TTI) {
5483 Value *const Cond = SI->getCondition();
5484 PHINode *PHI = nullptr;
5485 BasicBlock *CommonDest = nullptr;
5486 Constant *DefaultResult;
5487 SwitchCaseResultVectorTy UniqueResults;
5488 // Collect all the cases that will deliver the same value from the switch.
5489 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
5490 DL, TTI, /*MaxUniqueResults*/2,
5491 /*MaxCasesPerResult*/2))
5492 return false;
5493 assert(PHI != nullptr && "PHI for value select not found")(static_cast <bool> (PHI != nullptr && "PHI for value select not found"
) ? void (0) : __assert_fail ("PHI != nullptr && \"PHI for value select not found\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5493, __extension__ __PRETTY_FUNCTION__))
;
5494
5495 Builder.SetInsertPoint(SI);
5496 Value *SelectValue =
5497 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
5498 if (SelectValue) {
5499 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder, DTU);
5500 return true;
5501 }
5502 // The switch couldn't be converted into a select.
5503 return false;
5504}
5505
5506namespace {
5507
5508/// This class represents a lookup table that can be used to replace a switch.
5509class SwitchLookupTable {
5510public:
5511 /// Create a lookup table to use as a switch replacement with the contents
5512 /// of Values, using DefaultValue to fill any holes in the table.
5513 SwitchLookupTable(
5514 Module &M, uint64_t TableSize, ConstantInt *Offset,
5515 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5516 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
5517
5518 /// Build instructions with Builder to retrieve the value at
5519 /// the position given by Index in the lookup table.
5520 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
5521
5522 /// Return true if a table with TableSize elements of
5523 /// type ElementType would fit in a target-legal register.
5524 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
5525 Type *ElementType);
5526
5527private:
5528 // Depending on the contents of the table, it can be represented in
5529 // different ways.
5530 enum {
5531 // For tables where each element contains the same value, we just have to
5532 // store that single value and return it for each lookup.
5533 SingleValueKind,
5534
5535 // For tables where there is a linear relationship between table index
5536 // and values. We calculate the result with a simple multiplication
5537 // and addition instead of a table lookup.
5538 LinearMapKind,
5539
5540 // For small tables with integer elements, we can pack them into a bitmap
5541 // that fits into a target-legal register. Values are retrieved by
5542 // shift and mask operations.
5543 BitMapKind,
5544
5545 // The table is stored as an array of values. Values are retrieved by load
5546 // instructions from the table.
5547 ArrayKind
5548 } Kind;
5549
5550 // For SingleValueKind, this is the single value.
5551 Constant *SingleValue = nullptr;
5552
5553 // For BitMapKind, this is the bitmap.
5554 ConstantInt *BitMap = nullptr;
5555 IntegerType *BitMapElementTy = nullptr;
5556
5557 // For LinearMapKind, these are the constants used to derive the value.
5558 ConstantInt *LinearOffset = nullptr;
5559 ConstantInt *LinearMultiplier = nullptr;
5560
5561 // For ArrayKind, this is the array.
5562 GlobalVariable *Array = nullptr;
5563};
5564
5565} // end anonymous namespace
5566
5567SwitchLookupTable::SwitchLookupTable(
5568 Module &M, uint64_t TableSize, ConstantInt *Offset,
5569 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5570 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5571 assert(Values.size() && "Can't build lookup table without values!")(static_cast <bool> (Values.size() && "Can't build lookup table without values!"
) ? void (0) : __assert_fail ("Values.size() && \"Can't build lookup table without values!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5571, __extension__ __PRETTY_FUNCTION__))
;
5572 assert(TableSize >= Values.size() && "Can't fit values in table!")(static_cast <bool> (TableSize >= Values.size() &&
"Can't fit values in table!") ? void (0) : __assert_fail ("TableSize >= Values.size() && \"Can't fit values in table!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5572, __extension__ __PRETTY_FUNCTION__))
;
5573
5574 // If all values in the table are equal, this is that value.
5575 SingleValue = Values.begin()->second;
5576
5577 Type *ValueType = Values.begin()->second->getType();
5578
5579 // Build up the table contents.
5580 SmallVector<Constant *, 64> TableContents(TableSize);
5581 for (size_t I = 0, E = Values.size(); I != E; ++I) {
5582 ConstantInt *CaseVal = Values[I].first;
5583 Constant *CaseRes = Values[I].second;
5584 assert(CaseRes->getType() == ValueType)(static_cast <bool> (CaseRes->getType() == ValueType
) ? void (0) : __assert_fail ("CaseRes->getType() == ValueType"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5584, __extension__ __PRETTY_FUNCTION__))
;
5585
5586 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5587 TableContents[Idx] = CaseRes;
5588
5589 if (CaseRes != SingleValue)
5590 SingleValue = nullptr;
5591 }
5592
5593 // Fill in any holes in the table with the default result.
5594 if (Values.size() < TableSize) {
5595 assert(DefaultValue &&(static_cast <bool> (DefaultValue && "Need a default value to fill the lookup table holes."
) ? void (0) : __assert_fail ("DefaultValue && \"Need a default value to fill the lookup table holes.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5596, __extension__ __PRETTY_FUNCTION__))
5596 "Need a default value to fill the lookup table holes.")(static_cast <bool> (DefaultValue && "Need a default value to fill the lookup table holes."
) ? void (0) : __assert_fail ("DefaultValue && \"Need a default value to fill the lookup table holes.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5596, __extension__ __PRETTY_FUNCTION__))
;
5597 assert(DefaultValue->getType() == ValueType)(static_cast <bool> (DefaultValue->getType() == ValueType
) ? void (0) : __assert_fail ("DefaultValue->getType() == ValueType"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5597, __extension__ __PRETTY_FUNCTION__))
;
5598 for (uint64_t I = 0; I < TableSize; ++I) {
5599 if (!TableContents[I])
5600 TableContents[I] = DefaultValue;
5601 }
5602
5603 if (DefaultValue != SingleValue)
5604 SingleValue = nullptr;
5605 }
5606
5607 // If each element in the table contains the same value, we only need to store
5608 // that single value.
5609 if (SingleValue) {
5610 Kind = SingleValueKind;
5611 return;
5612 }
5613
5614 // Check if we can derive the value with a linear transformation from the
5615 // table index.
5616 if (isa<IntegerType>(ValueType)) {
5617 bool LinearMappingPossible = true;
5618 APInt PrevVal;
5619 APInt DistToPrev;
5620 assert(TableSize >= 2 && "Should be a SingleValue table.")(static_cast <bool> (TableSize >= 2 && "Should be a SingleValue table."
) ? void (0) : __assert_fail ("TableSize >= 2 && \"Should be a SingleValue table.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5620, __extension__ __PRETTY_FUNCTION__))
;
5621 // Check if there is the same distance between two consecutive values.
5622 for (uint64_t I = 0; I < TableSize; ++I) {
5623 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5624 if (!ConstVal) {
5625 // This is an undef. We could deal with it, but undefs in lookup tables
5626 // are very seldom. It's probably not worth the additional complexity.
5627 LinearMappingPossible = false;
5628 break;
5629 }
5630 const APInt &Val = ConstVal->getValue();
5631 if (I != 0) {
5632 APInt Dist = Val - PrevVal;
5633 if (I == 1) {
5634 DistToPrev = Dist;
5635 } else if (Dist != DistToPrev) {
5636 LinearMappingPossible = false;
5637 break;
5638 }
5639 }
5640 PrevVal = Val;
5641 }
5642 if (LinearMappingPossible) {
5643 LinearOffset = cast<ConstantInt>(TableContents[0]);
5644 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5645 Kind = LinearMapKind;
5646 ++NumLinearMaps;
5647 return;
5648 }
5649 }
5650
5651 // If the type is integer and the table fits in a register, build a bitmap.
5652 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5653 IntegerType *IT = cast<IntegerType>(ValueType);
5654 APInt TableInt(TableSize * IT->getBitWidth(), 0);
5655 for (uint64_t I = TableSize; I > 0; --I) {
5656 TableInt <<= IT->getBitWidth();
5657 // Insert values into the bitmap. Undef values are set to zero.
5658 if (!isa<UndefValue>(TableContents[I - 1])) {
5659 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5660 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5661 }
5662 }
5663 BitMap = ConstantInt::get(M.getContext(), TableInt);
5664 BitMapElementTy = IT;
5665 Kind = BitMapKind;
5666 ++NumBitMaps;
5667 return;
5668 }
5669
5670 // Store the table in an array.
5671 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5672 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5673
5674 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5675 GlobalVariable::PrivateLinkage, Initializer,
5676 "switch.table." + FuncName);
5677 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5678 // Set the alignment to that of an array items. We will be only loading one
5679 // value out of it.
5680 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5681 Kind = ArrayKind;
5682}
5683
5684Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5685 switch (Kind) {
5686 case SingleValueKind:
5687 return SingleValue;
5688 case LinearMapKind: {
5689 // Derive the result value from the input value.
5690 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5691 false, "switch.idx.cast");
5692 if (!LinearMultiplier->isOne())
5693 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5694 if (!LinearOffset->isZero())
5695 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5696 return Result;
5697 }
5698 case BitMapKind: {
5699 // Type of the bitmap (e.g. i59).
5700 IntegerType *MapTy = BitMap->getType();
5701
5702 // Cast Index to the same type as the bitmap.
5703 // Note: The Index is <= the number of elements in the table, so
5704 // truncating it to the width of the bitmask is safe.
5705 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5706
5707 // Multiply the shift amount by the element width.
5708 ShiftAmt = Builder.CreateMul(
5709 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5710 "switch.shiftamt");
5711
5712 // Shift down.
5713 Value *DownShifted =
5714 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5715 // Mask off.
5716 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5717 }
5718 case ArrayKind: {
5719 // Make sure the table index will not overflow when treated as signed.
5720 IntegerType *IT = cast<IntegerType>(Index->getType());
5721 uint64_t TableSize =
5722 Array->getInitializer()->getType()->getArrayNumElements();
5723 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5724 Index = Builder.CreateZExt(
5725 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5726 "switch.tableidx.zext");
5727
5728 Value *GEPIndices[] = {Builder.getInt32(0), Index};
5729 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5730 GEPIndices, "switch.gep");
5731 return Builder.CreateLoad(
5732 cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
5733 "switch.load");
5734 }
5735 }
5736 llvm_unreachable("Unknown lookup table kind!")::llvm::llvm_unreachable_internal("Unknown lookup table kind!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5736)
;
5737}
5738
5739bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5740 uint64_t TableSize,
5741 Type *ElementType) {
5742 auto *IT = dyn_cast<IntegerType>(ElementType);
5743 if (!IT)
5744 return false;
5745 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5746 // are <= 15, we could try to narrow the type.
5747
5748 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5749 if (TableSize >= UINT_MAX(2147483647 *2U +1U) / IT->getBitWidth())
5750 return false;
5751 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5752}
5753
5754/// Determine whether a lookup table should be built for this switch, based on
5755/// the number of cases, size of the table, and the types of the results.
5756static bool
5757ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5758 const TargetTransformInfo &TTI, const DataLayout &DL,
5759 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5760 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX(18446744073709551615UL) / 10)
5761 return false; // TableSize overflowed, or mul below might overflow.
5762
5763 bool AllTablesFitInRegister = true;
5764 bool HasIllegalType = false;
5765 for (const auto &I : ResultTypes) {
5766 Type *Ty = I.second;
5767
5768 // Saturate this flag to true.
5769 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5770
5771 // Saturate this flag to false.
5772 AllTablesFitInRegister =
5773 AllTablesFitInRegister &&
5774 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5775
5776 // If both flags saturate, we're done. NOTE: This *only* works with
5777 // saturating flags, and all flags have to saturate first due to the
5778 // non-deterministic behavior of iterating over a dense map.
5779 if (HasIllegalType && !AllTablesFitInRegister)
5780 break;
5781 }
5782
5783 // If each table would fit in a register, we should build it anyway.
5784 if (AllTablesFitInRegister)
5785 return true;
5786
5787 // Don't build a table that doesn't fit in-register if it has illegal types.
5788 if (HasIllegalType)
5789 return false;
5790
5791 // The table density should be at least 40%. This is the same criterion as for
5792 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5793 // FIXME: Find the best cut-off.
5794 return SI->getNumCases() * 10 >= TableSize * 4;
5795}
5796
5797/// Try to reuse the switch table index compare. Following pattern:
5798/// \code
5799/// if (idx < tablesize)
5800/// r = table[idx]; // table does not contain default_value
5801/// else
5802/// r = default_value;
5803/// if (r != default_value)
5804/// ...
5805/// \endcode
5806/// Is optimized to:
5807/// \code
5808/// cond = idx < tablesize;
5809/// if (cond)
5810/// r = table[idx];
5811/// else
5812/// r = default_value;
5813/// if (cond)
5814/// ...
5815/// \endcode
5816/// Jump threading will then eliminate the second if(cond).
5817static void reuseTableCompare(
5818 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5819 Constant *DefaultValue,
5820 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5821 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5822 if (!CmpInst)
5823 return;
5824
5825 // We require that the compare is in the same block as the phi so that jump
5826 // threading can do its work afterwards.
5827 if (CmpInst->getParent() != PhiBlock)
5828 return;
5829
5830 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5831 if (!CmpOp1)
5832 return;
5833
5834 Value *RangeCmp = RangeCheckBranch->getCondition();
5835 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5836 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5837
5838 // Check if the compare with the default value is constant true or false.
5839 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5840 DefaultValue, CmpOp1, true);
5841 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5842 return;
5843
5844 // Check if the compare with the case values is distinct from the default
5845 // compare result.
5846 for (auto ValuePair : Values) {
5847 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5848 ValuePair.second, CmpOp1, true);
5849 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5850 return;
5851 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&(static_cast <bool> ((CaseConst == TrueConst || CaseConst
== FalseConst) && "Expect true or false as compare result."
) ? void (0) : __assert_fail ("(CaseConst == TrueConst || CaseConst == FalseConst) && \"Expect true or false as compare result.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5852, __extension__ __PRETTY_FUNCTION__))
5852 "Expect true or false as compare result.")(static_cast <bool> ((CaseConst == TrueConst || CaseConst
== FalseConst) && "Expect true or false as compare result."
) ? void (0) : __assert_fail ("(CaseConst == TrueConst || CaseConst == FalseConst) && \"Expect true or false as compare result.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5852, __extension__ __PRETTY_FUNCTION__))
;
5853 }
5854
5855 // Check if the branch instruction dominates the phi node. It's a simple
5856 // dominance check, but sufficient for our needs.
5857 // Although this check is invariant in the calling loops, it's better to do it
5858 // at this late stage. Practically we do it at most once for a switch.
5859 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5860 for (BasicBlock *Pred : predecessors(PhiBlock)) {
5861 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5862 return;
5863 }
5864
5865 if (DefaultConst == FalseConst) {
5866 // The compare yields the same result. We can replace it.
5867 CmpInst->replaceAllUsesWith(RangeCmp);
5868 ++NumTableCmpReuses;
5869 } else {
5870 // The compare yields the same result, just inverted. We can replace it.
5871 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5872 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5873 RangeCheckBranch);
5874 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5875 ++NumTableCmpReuses;
5876 }
5877}
5878
5879/// If the switch is only used to initialize one or more phi nodes in a common
5880/// successor block with different constant values, replace the switch with
5881/// lookup tables.
5882static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5883 DomTreeUpdater *DTU, const DataLayout &DL,
5884 const TargetTransformInfo &TTI) {
5885 assert(SI->getNumCases() > 1 && "Degenerate switch?")(static_cast <bool> (SI->getNumCases() > 1 &&
"Degenerate switch?") ? void (0) : __assert_fail ("SI->getNumCases() > 1 && \"Degenerate switch?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5885, __extension__ __PRETTY_FUNCTION__))
;
5886
5887 BasicBlock *BB = SI->getParent();
5888 Function *Fn = BB->getParent();
5889 // Only build lookup table when we have a target that supports it or the
5890 // attribute is not set.
5891 if (!TTI.shouldBuildLookupTables() ||
5892 (Fn->getFnAttribute("no-jump-tables").getValueAsBool()))
5893 return false;
5894
5895 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5896 // split off a dense part and build a lookup table for that.
5897
5898 // FIXME: This creates arrays of GEPs to constant strings, which means each
5899 // GEP needs a runtime relocation in PIC code. We should just build one big
5900 // string and lookup indices into that.
5901
5902 // Ignore switches with less than three cases. Lookup tables will not make
5903 // them faster, so we don't analyze them.
5904 if (SI->getNumCases() < 3)
5905 return false;
5906
5907 // Figure out the corresponding result for each case value and phi node in the
5908 // common destination, as well as the min and max case values.
5909 assert(!SI->cases().empty())(static_cast <bool> (!SI->cases().empty()) ? void (0
) : __assert_fail ("!SI->cases().empty()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 5909, __extension__ __PRETTY_FUNCTION__))
;
5910 SwitchInst::CaseIt CI = SI->case_begin();
5911 ConstantInt *MinCaseVal = CI->getCaseValue();
5912 ConstantInt *MaxCaseVal = CI->getCaseValue();
5913
5914 BasicBlock *CommonDest = nullptr;
5915
5916 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5917 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5918
5919 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5920 SmallDenseMap<PHINode *, Type *> ResultTypes;
5921 SmallVector<PHINode *, 4> PHIs;
5922
5923 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5924 ConstantInt *CaseVal = CI->getCaseValue();
5925 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5926 MinCaseVal = CaseVal;
5927 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5928 MaxCaseVal = CaseVal;
5929
5930 // Resulting value at phi nodes for this case value.
5931 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5932 ResultsTy Results;
5933 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5934 Results, DL, TTI))
5935 return false;
5936
5937 // Append the result from this case to the list for each phi.
5938 for (const auto &I : Results) {
5939 PHINode *PHI = I.first;
5940 Constant *Value = I.second;
5941 if (!ResultLists.count(PHI))
5942 PHIs.push_back(PHI);
5943 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5944 }
5945 }
5946
5947 // Keep track of the result types.
5948 for (PHINode *PHI : PHIs) {
5949 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5950 }
5951
5952 uint64_t NumResults = ResultLists[PHIs[0]].size();
5953 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5954 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5955 bool TableHasHoles = (NumResults < TableSize);
5956
5957 // If the table has holes, we need a constant result for the default case
5958 // or a bitmask that fits in a register.
5959 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5960 bool HasDefaultResults =
5961 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5962 DefaultResultsList, DL, TTI);
5963
5964 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5965 if (NeedMask) {
5966 // As an extra penalty for the validity test we require more cases.
5967 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5968 return false;
5969 if (!DL.fitsInLegalInteger(TableSize))
5970 return false;
5971 }
5972
5973 for (const auto &I : DefaultResultsList) {
5974 PHINode *PHI = I.first;
5975 Constant *Result = I.second;
5976 DefaultResults[PHI] = Result;
5977 }
5978
5979 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5980 return false;
5981
5982 std::vector<DominatorTree::UpdateType> Updates;
5983
5984 // Create the BB that does the lookups.
5985 Module &Mod = *CommonDest->getParent()->getParent();
5986 BasicBlock *LookupBB = BasicBlock::Create(
5987 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5988
5989 // Compute the table index value.
5990 Builder.SetInsertPoint(SI);
5991 Value *TableIndex;
5992 if (MinCaseVal->isNullValue())
5993 TableIndex = SI->getCondition();
5994 else
5995 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5996 "switch.tableidx");
5997
5998 // Compute the maximum table size representable by the integer type we are
5999 // switching upon.
6000 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
6001 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX(18446744073709551615UL) : 1ULL << CaseSize;
6002 assert(MaxTableSize >= TableSize &&(static_cast <bool> (MaxTableSize >= TableSize &&
"It is impossible for a switch to have more entries than the max "
"representable value of its input integer type's size.") ? void
(0) : __assert_fail ("MaxTableSize >= TableSize && \"It is impossible for a switch to have more entries than the max \" \"representable value of its input integer type's size.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6004, __extension__ __PRETTY_FUNCTION__))
6003 "It is impossible for a switch to have more entries than the max "(static_cast <bool> (MaxTableSize >= TableSize &&
"It is impossible for a switch to have more entries than the max "
"representable value of its input integer type's size.") ? void
(0) : __assert_fail ("MaxTableSize >= TableSize && \"It is impossible for a switch to have more entries than the max \" \"representable value of its input integer type's size.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6004, __extension__ __PRETTY_FUNCTION__))
6004 "representable value of its input integer type's size.")(static_cast <bool> (MaxTableSize >= TableSize &&
"It is impossible for a switch to have more entries than the max "
"representable value of its input integer type's size.") ? void
(0) : __assert_fail ("MaxTableSize >= TableSize && \"It is impossible for a switch to have more entries than the max \" \"representable value of its input integer type's size.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6004, __extension__ __PRETTY_FUNCTION__))
;
6005
6006 // If the default destination is unreachable, or if the lookup table covers
6007 // all values of the conditional variable, branch directly to the lookup table
6008 // BB. Otherwise, check that the condition is within the case range.
6009 const bool DefaultIsReachable =
6010 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
6011 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
6012 BranchInst *RangeCheckBranch = nullptr;
6013
6014 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6015 Builder.CreateBr(LookupBB);
6016 if (DTU)
6017 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6018 // Note: We call removeProdecessor later since we need to be able to get the
6019 // PHI value for the default case in case we're using a bit mask.
6020 } else {
6021 Value *Cmp = Builder.CreateICmpULT(
6022 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
6023 RangeCheckBranch =
6024 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
6025 if (DTU)
6026 Updates.push_back({DominatorTree::Insert, BB, LookupBB});
6027 }
6028
6029 // Populate the BB that does the lookups.
6030 Builder.SetInsertPoint(LookupBB);
6031
6032 if (NeedMask) {
6033 // Before doing the lookup, we do the hole check. The LookupBB is therefore
6034 // re-purposed to do the hole check, and we create a new LookupBB.
6035 BasicBlock *MaskBB = LookupBB;
6036 MaskBB->setName("switch.hole_check");
6037 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
6038 CommonDest->getParent(), CommonDest);
6039
6040 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
6041 // unnecessary illegal types.
6042 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
6043 APInt MaskInt(TableSizePowOf2, 0);
6044 APInt One(TableSizePowOf2, 1);
6045 // Build bitmask; fill in a 1 bit for every case.
6046 const ResultListTy &ResultList = ResultLists[PHIs[0]];
6047 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
6048 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
6049 .getLimitedValue();
6050 MaskInt |= One << Idx;
6051 }
6052 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
6053
6054 // Get the TableIndex'th bit of the bitmask.
6055 // If this bit is 0 (meaning hole) jump to the default destination,
6056 // else continue with table lookup.
6057 IntegerType *MapTy = TableMask->getType();
6058 Value *MaskIndex =
6059 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
6060 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
6061 Value *LoBit = Builder.CreateTrunc(
6062 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
6063 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
6064 if (DTU) {
6065 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB});
6066 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
6067 }
6068 Builder.SetInsertPoint(LookupBB);
6069 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB);
6070 }
6071
6072 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
6073 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
6074 // do not delete PHINodes here.
6075 SI->getDefaultDest()->removePredecessor(BB,
6076 /*KeepOneInputPHIs=*/true);
6077 if (DTU)
6078 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()});
6079 }
6080
6081 bool ReturnedEarly = false;
6082 for (PHINode *PHI : PHIs) {
6083 const ResultListTy &ResultList = ResultLists[PHI];
6084
6085 // If using a bitmask, use any value to fill the lookup table holes.
6086 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
6087 StringRef FuncName = Fn->getName();
6088 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
6089 FuncName);
6090
6091 Value *Result = Table.BuildLookup(TableIndex, Builder);
6092
6093 // If the result is used to return immediately from the function, we want to
6094 // do that right here.
6095 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
6096 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
6097 Builder.CreateRet(Result);
6098 ReturnedEarly = true;
6099 break;
6100 }
6101
6102 // Do a small peephole optimization: re-use the switch table compare if
6103 // possible.
6104 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
6105 BasicBlock *PhiBlock = PHI->getParent();
6106 // Search for compare instructions which use the phi.
6107 for (auto *User : PHI->users()) {
6108 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
6109 }
6110 }
6111
6112 PHI->addIncoming(Result, LookupBB);
6113 }
6114
6115 if (!ReturnedEarly) {
6116 Builder.CreateBr(CommonDest);
6117 if (DTU)
6118 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest});
6119 }
6120
6121 // Remove the switch.
6122 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
6123 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6124 BasicBlock *Succ = SI->getSuccessor(i);
6125
6126 if (Succ == SI->getDefaultDest())
6127 continue;
6128 Succ->removePredecessor(BB);
6129 RemovedSuccessors.insert(Succ);
6130 }
6131 SI->eraseFromParent();
6132
6133 if (DTU) {
6134 for (BasicBlock *RemovedSuccessor : RemovedSuccessors)
6135 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
6136 DTU->applyUpdates(Updates);
6137 }
6138
6139 ++NumLookupTables;
6140 if (NeedMask)
6141 ++NumLookupTablesHoles;
6142 return true;
6143}
6144
6145static bool isSwitchDense(ArrayRef<int64_t> Values) {
6146 // See also SelectionDAGBuilder::isDense(), which this function was based on.
6147 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
6148 uint64_t Range = Diff + 1;
6149 uint64_t NumCases = Values.size();
6150 // 40% is the default density for building a jump table in optsize/minsize mode.
6151 uint64_t MinDensity = 40;
6152
6153 return NumCases * 100 >= Range * MinDensity;
6154}
6155
6156/// Try to transform a switch that has "holes" in it to a contiguous sequence
6157/// of cases.
6158///
6159/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
6160/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
6161///
6162/// This converts a sparse switch into a dense switch which allows better
6163/// lowering and could also allow transforming into a lookup table.
6164static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
6165 const DataLayout &DL,
6166 const TargetTransformInfo &TTI) {
6167 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
6168 if (CondTy->getIntegerBitWidth() > 64 ||
6169 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
6170 return false;
6171 // Only bother with this optimization if there are more than 3 switch cases;
6172 // SDAG will only bother creating jump tables for 4 or more cases.
6173 if (SI->getNumCases() < 4)
6174 return false;
6175
6176 // This transform is agnostic to the signedness of the input or case values. We
6177 // can treat the case values as signed or unsigned. We can optimize more common
6178 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
6179 // as signed.
6180 SmallVector<int64_t,4> Values;
6181 for (auto &C : SI->cases())
6182 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
6183 llvm::sort(Values);
6184
6185 // If the switch is already dense, there's nothing useful to do here.
6186 if (isSwitchDense(Values))
6187 return false;
6188
6189 // First, transform the values such that they start at zero and ascend.
6190 int64_t Base = Values[0];
6191 for (auto &V : Values)
6192 V -= (uint64_t)(Base);
6193
6194 // Now we have signed numbers that have been shifted so that, given enough
6195 // precision, there are no negative values. Since the rest of the transform
6196 // is bitwise only, we switch now to an unsigned representation.
6197
6198 // This transform can be done speculatively because it is so cheap - it
6199 // results in a single rotate operation being inserted.
6200 // FIXME: It's possible that optimizing a switch on powers of two might also
6201 // be beneficial - flag values are often powers of two and we could use a CLZ
6202 // as the key function.
6203
6204 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
6205 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
6206 // less than 64.
6207 unsigned Shift = 64;
6208 for (auto &V : Values)
6209 Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
6210 assert(Shift < 64)(static_cast <bool> (Shift < 64) ? void (0) : __assert_fail
("Shift < 64", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6210, __extension__ __PRETTY_FUNCTION__))
;
6211 if (Shift > 0)
6212 for (auto &V : Values)
6213 V = (int64_t)((uint64_t)V >> Shift);
6214
6215 if (!isSwitchDense(Values))
6216 // Transform didn't create a dense switch.
6217 return false;
6218
6219 // The obvious transform is to shift the switch condition right and emit a
6220 // check that the condition actually cleanly divided by GCD, i.e.
6221 // C & (1 << Shift - 1) == 0
6222 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
6223 //
6224 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
6225 // shift and puts the shifted-off bits in the uppermost bits. If any of these
6226 // are nonzero then the switch condition will be very large and will hit the
6227 // default case.
6228
6229 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
6230 Builder.SetInsertPoint(SI);
6231 auto *ShiftC = ConstantInt::get(Ty, Shift);
6232 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
6233 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
6234 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
6235 auto *Rot = Builder.CreateOr(LShr, Shl);
6236 SI->replaceUsesOfWith(SI->getCondition(), Rot);
6237
6238 for (auto Case : SI->cases()) {
6239 auto *Orig = Case.getCaseValue();
6240 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
6241 Case.setValue(
6242 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
6243 }
6244 return true;
6245}
6246
6247bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
6248 BasicBlock *BB = SI->getParent();
6249
6250 if (isValueEqualityComparison(SI)) {
6251 // If we only have one predecessor, and if it is a branch on this value,
6252 // see if that predecessor totally determines the outcome of this switch.
6253 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6254 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
6255 return requestResimplify();
6256
6257 Value *Cond = SI->getCondition();
6258 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
6259 if (SimplifySwitchOnSelect(SI, Select))
6260 return requestResimplify();
6261
6262 // If the block only contains the switch, see if we can fold the block
6263 // away into any preds.
6264 if (SI == &*BB->instructionsWithoutDebug().begin())
6265 if (FoldValueComparisonIntoPredecessors(SI, Builder))
6266 return requestResimplify();
6267 }
6268
6269 // Try to transform the switch into an icmp and a branch.
6270 if (TurnSwitchRangeIntoICmp(SI, Builder))
6271 return requestResimplify();
6272
6273 // Remove unreachable cases.
6274 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL))
6275 return requestResimplify();
6276
6277 if (switchToSelect(SI, Builder, DTU, DL, TTI))
6278 return requestResimplify();
6279
6280 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
6281 return requestResimplify();
6282
6283 // The conversion from switch to lookup tables results in difficult-to-analyze
6284 // code and makes pruning branches much harder. This is a problem if the
6285 // switch expression itself can still be restricted as a result of inlining or
6286 // CVP. Therefore, only apply this transformation during late stages of the
6287 // optimisation pipeline.
6288 if (Options.ConvertSwitchToLookupTable &&
6289 SwitchToLookupTable(SI, Builder, DTU, DL, TTI))
6290 return requestResimplify();
6291
6292 if (ReduceSwitchRange(SI, Builder, DL, TTI))
6293 return requestResimplify();
6294
6295 return false;
6296}
6297
6298bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
6299 BasicBlock *BB = IBI->getParent();
6300 bool Changed = false;
6301
6302 // Eliminate redundant destinations.
6303 SmallPtrSet<Value *, 8> Succs;
6304 SmallPtrSet<BasicBlock *, 8> RemovedSuccs;
6305 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
6306 BasicBlock *Dest = IBI->getDestination(i);
6307 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
6308 if (!Dest->hasAddressTaken())
6309 RemovedSuccs.insert(Dest);
6310 Dest->removePredecessor(BB);
6311 IBI->removeDestination(i);
6312 --i;
6313 --e;
6314 Changed = true;
6315 }
6316 }
6317
6318 if (DTU) {
6319 std::vector<DominatorTree::UpdateType> Updates;
6320 Updates.reserve(RemovedSuccs.size());
6321 for (auto *RemovedSucc : RemovedSuccs)
6322 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc});
6323 DTU->applyUpdates(Updates);
6324 }
6325
6326 if (IBI->getNumDestinations() == 0) {
6327 // If the indirectbr has no successors, change it to unreachable.
6328 new UnreachableInst(IBI->getContext(), IBI);
6329 EraseTerminatorAndDCECond(IBI);
6330 return true;
6331 }
6332
6333 if (IBI->getNumDestinations() == 1) {
6334 // If the indirectbr has one successor, change it to a direct branch.
6335 BranchInst::Create(IBI->getDestination(0), IBI);
6336 EraseTerminatorAndDCECond(IBI);
6337 return true;
6338 }
6339
6340 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
6341 if (SimplifyIndirectBrOnSelect(IBI, SI))
6342 return requestResimplify();
6343 }
6344 return Changed;
6345}
6346
6347/// Given an block with only a single landing pad and a unconditional branch
6348/// try to find another basic block which this one can be merged with. This
6349/// handles cases where we have multiple invokes with unique landing pads, but
6350/// a shared handler.
6351///
6352/// We specifically choose to not worry about merging non-empty blocks
6353/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
6354/// practice, the optimizer produces empty landing pad blocks quite frequently
6355/// when dealing with exception dense code. (see: instcombine, gvn, if-else
6356/// sinking in this file)
6357///
6358/// This is primarily a code size optimization. We need to avoid performing
6359/// any transform which might inhibit optimization (such as our ability to
6360/// specialize a particular handler via tail commoning). We do this by not
6361/// merging any blocks which require us to introduce a phi. Since the same
6362/// values are flowing through both blocks, we don't lose any ability to
6363/// specialize. If anything, we make such specialization more likely.
6364///
6365/// TODO - This transformation could remove entries from a phi in the target
6366/// block when the inputs in the phi are the same for the two blocks being
6367/// merged. In some cases, this could result in removal of the PHI entirely.
6368static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
6369 BasicBlock *BB, DomTreeUpdater *DTU) {
6370 auto Succ = BB->getUniqueSuccessor();
6371 assert(Succ)(static_cast <bool> (Succ) ? void (0) : __assert_fail (
"Succ", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6371, __extension__ __PRETTY_FUNCTION__))
;
6372 // If there's a phi in the successor block, we'd likely have to introduce
6373 // a phi into the merged landing pad block.
6374 if (isa<PHINode>(*Succ->begin()))
6375 return false;
6376
6377 for (BasicBlock *OtherPred : predecessors(Succ)) {
6378 if (BB == OtherPred)
6379 continue;
6380 BasicBlock::iterator I = OtherPred->begin();
6381 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
6382 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
6383 continue;
6384 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6385 ;
6386 BranchInst *BI2 = dyn_cast<BranchInst>(I);
6387 if (!BI2 || !BI2->isIdenticalTo(BI))
6388 continue;
6389
6390 std::vector<DominatorTree::UpdateType> Updates;
6391
6392 // We've found an identical block. Update our predecessors to take that
6393 // path instead and make ourselves dead.
6394 SmallPtrSet<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
6395 for (BasicBlock *Pred : Preds) {
6396 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
6397 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&(static_cast <bool> (II->getNormalDest() != BB &&
II->getUnwindDest() == BB && "unexpected successor"
) ? void (0) : __assert_fail ("II->getNormalDest() != BB && II->getUnwindDest() == BB && \"unexpected successor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6398, __extension__ __PRETTY_FUNCTION__))
6398 "unexpected successor")(static_cast <bool> (II->getNormalDest() != BB &&
II->getUnwindDest() == BB && "unexpected successor"
) ? void (0) : __assert_fail ("II->getNormalDest() != BB && II->getUnwindDest() == BB && \"unexpected successor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6398, __extension__ __PRETTY_FUNCTION__))
;
6399 II->setUnwindDest(OtherPred);
6400 if (DTU) {
6401 Updates.push_back({DominatorTree::Insert, Pred, OtherPred});
6402 Updates.push_back({DominatorTree::Delete, Pred, BB});
6403 }
6404 }
6405
6406 // The debug info in OtherPred doesn't cover the merged control flow that
6407 // used to go through BB. We need to delete it or update it.
6408 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
6409 Instruction &Inst = *I;
6410 I++;
6411 if (isa<DbgInfoIntrinsic>(Inst))
6412 Inst.eraseFromParent();
6413 }
6414
6415 SmallPtrSet<BasicBlock *, 16> Succs(succ_begin(BB), succ_end(BB));
6416 for (BasicBlock *Succ : Succs) {
6417 Succ->removePredecessor(BB);
6418 if (DTU)
6419 Updates.push_back({DominatorTree::Delete, BB, Succ});
6420 }
6421
6422 IRBuilder<> Builder(BI);
6423 Builder.CreateUnreachable();
6424 BI->eraseFromParent();
6425 if (DTU)
6426 DTU->applyUpdates(Updates);
6427 return true;
6428 }
6429 return false;
6430}
6431
6432bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) {
6433 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder)
6434 : simplifyCondBranch(Branch, Builder);
6435}
6436
6437bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI,
6438 IRBuilder<> &Builder) {
6439 BasicBlock *BB = BI->getParent();
6440 BasicBlock *Succ = BI->getSuccessor(0);
6441
6442 // If the Terminator is the only non-phi instruction, simplify the block.
6443 // If LoopHeader is provided, check if the block or its successor is a loop
6444 // header. (This is for early invocations before loop simplify and
6445 // vectorization to keep canonical loop forms for nested loops. These blocks
6446 // can be eliminated when the pass is invoked later in the back-end.)
6447 // Note that if BB has only one predecessor then we do not introduce new
6448 // backedge, so we can eliminate BB.
6449 bool NeedCanonicalLoop =
6450 Options.NeedCanonicalLoop &&
6451 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) &&
6452 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ)));
6453 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator();
6454 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
6455 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
6456 return true;
6457
6458 // If the only instruction in the block is a seteq/setne comparison against a
6459 // constant, try to simplify the block.
6460 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
6461 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
6462 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6463 ;
6464 if (I->isTerminator() &&
6465 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
6466 return true;
6467 }
6468
6469 // See if we can merge an empty landing pad block with another which is
6470 // equivalent.
6471 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
6472 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
6473 ;
6474 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU))
6475 return true;
6476 }
6477
6478 // If this basic block is ONLY a compare and a branch, and if a predecessor
6479 // branches to us and our successor, fold the comparison into the
6480 // predecessor and use logical operations to update the incoming value
6481 // for PHI nodes in common successor.
6482 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6483 Options.BonusInstThreshold))
6484 return requestResimplify();
6485 return false;
6486}
6487
6488static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
6489 BasicBlock *PredPred = nullptr;
6490 for (auto *P : predecessors(BB)) {
6491 BasicBlock *PPred = P->getSinglePredecessor();
6492 if (!PPred || (PredPred && PredPred != PPred))
6493 return nullptr;
6494 PredPred = PPred;
6495 }
6496 return PredPred;
6497}
6498
6499bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
6500 BasicBlock *BB = BI->getParent();
6501 if (!Options.SimplifyCondBranch)
6502 return false;
6503
6504 // Conditional branch
6505 if (isValueEqualityComparison(BI)) {
6506 // If we only have one predecessor, and if it is a branch on this value,
6507 // see if that predecessor totally determines the outcome of this
6508 // switch.
6509 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
6510 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
6511 return requestResimplify();
6512
6513 // This block must be empty, except for the setcond inst, if it exists.
6514 // Ignore dbg and pseudo intrinsics.
6515 auto I = BB->instructionsWithoutDebug(true).begin();
6516 if (&*I == BI) {
6517 if (FoldValueComparisonIntoPredecessors(BI, Builder))
6518 return requestResimplify();
6519 } else if (&*I == cast<Instruction>(BI->getCondition())) {
6520 ++I;
6521 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
6522 return requestResimplify();
6523 }
6524 }
6525
6526 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
6527 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
6528 return true;
6529
6530 // If this basic block has dominating predecessor blocks and the dominating
6531 // blocks' conditions imply BI's condition, we know the direction of BI.
6532 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
6533 if (Imp) {
6534 // Turn this into a branch on constant.
6535 auto *OldCond = BI->getCondition();
6536 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
6537 : ConstantInt::getFalse(BB->getContext());
6538 BI->setCondition(TorF);
6539 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
6540 return requestResimplify();
6541 }
6542
6543 // If this basic block is ONLY a compare and a branch, and if a predecessor
6544 // branches to us and one of our successors, fold the comparison into the
6545 // predecessor and use logical operations to pick the right destination.
6546 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI,
6547 Options.BonusInstThreshold))
6548 return requestResimplify();
6549
6550 // We have a conditional branch to two blocks that are only reachable
6551 // from BI. We know that the condbr dominates the two blocks, so see if
6552 // there is any identical code in the "then" and "else" blocks. If so, we
6553 // can hoist it up to the branching block.
6554 if (BI->getSuccessor(0)->getSinglePredecessor()) {
6555 if (BI->getSuccessor(1)->getSinglePredecessor()) {
6556 if (HoistCommon &&
6557 HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts))
6558 return requestResimplify();
6559 } else {
6560 // If Successor #1 has multiple preds, we may be able to conditionally
6561 // execute Successor #0 if it branches to Successor #1.
6562 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
6563 if (Succ0TI->getNumSuccessors() == 1 &&
6564 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
6565 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
6566 return requestResimplify();
6567 }
6568 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
6569 // If Successor #0 has multiple preds, we may be able to conditionally
6570 // execute Successor #1 if it branches to Successor #0.
6571 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
6572 if (Succ1TI->getNumSuccessors() == 1 &&
6573 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
6574 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
6575 return requestResimplify();
6576 }
6577
6578 // If this is a branch on a phi node in the current block, thread control
6579 // through this block if any PHI node entries are constants.
6580 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6581 if (PN->getParent() == BI->getParent())
6582 if (FoldCondBranchOnPHI(BI, DTU, DL, Options.AC))
6583 return requestResimplify();
6584
6585 // Scan predecessor blocks for conditional branches.
6586 for (BasicBlock *Pred : predecessors(BB))
6587 if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
6588 if (PBI != BI && PBI->isConditional())
6589 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
6590 return requestResimplify();
6591
6592 // Look for diamond patterns.
6593 if (MergeCondStores)
6594 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6595 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6596 if (PBI != BI && PBI->isConditional())
6597 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
6598 return requestResimplify();
6599
6600 return false;
6601}
6602
6603/// Check if passing a value to an instruction will cause undefined behavior.
6604static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
6605 Constant *C = dyn_cast<Constant>(V);
6606 if (!C)
6607 return false;
6608
6609 if (I->use_empty())
6610 return false;
6611
6612 if (C->isNullValue() || isa<UndefValue>(C)) {
6613 // Only look at the first use, avoid hurting compile time with long uselists
6614 User *Use = *I->user_begin();
6615
6616 // Now make sure that there are no instructions in between that can alter
6617 // control flow (eg. calls)
6618 for (BasicBlock::iterator
6619 i = ++BasicBlock::iterator(I),
6620 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
6621 i != UI; ++i) {
6622 if (i == I->getParent()->end())
6623 return false;
6624 if (!isGuaranteedToTransferExecutionToSuccessor(&*i))
6625 return false;
6626 }
6627
6628 // Look through GEPs. A load from a GEP derived from NULL is still undefined
6629 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6630 if (GEP->getPointerOperand() == I) {
6631 if (!GEP->isInBounds() || !GEP->hasAllZeroIndices())
6632 PtrValueMayBeModified = true;
6633 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified);
6634 }
6635
6636 // Look through bitcasts.
6637 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6638 return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified);
6639
6640 // Load from null is undefined.
6641 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6642 if (!LI->isVolatile())
6643 return !NullPointerIsDefined(LI->getFunction(),
6644 LI->getPointerAddressSpace());
6645
6646 // Store to null is undefined.
6647 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6648 if (!SI->isVolatile())
6649 return (!NullPointerIsDefined(SI->getFunction(),
6650 SI->getPointerAddressSpace())) &&
6651 SI->getPointerOperand() == I;
6652
6653 if (auto *CB = dyn_cast<CallBase>(Use)) {
6654 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction()))
6655 return false;
6656 // A call to null is undefined.
6657 if (CB->getCalledOperand() == I)
6658 return true;
6659
6660 if (C->isNullValue()) {
6661 for (const llvm::Use &Arg : CB->args())
6662 if (Arg == I) {
6663 unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6664 if (CB->isPassingUndefUB(ArgIdx) &&
6665 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) {
6666 // Passing null to a nonnnull+noundef argument is undefined.
6667 return !PtrValueMayBeModified;
6668 }
6669 }
6670 } else if (isa<UndefValue>(C)) {
6671 // Passing undef to a noundef argument is undefined.
6672 for (const llvm::Use &Arg : CB->args())
6673 if (Arg == I) {
6674 unsigned ArgIdx = CB->getArgOperandNo(&Arg);
6675 if (CB->isPassingUndefUB(ArgIdx)) {
6676 // Passing undef to a noundef argument is undefined.
6677 return true;
6678 }
6679 }
6680 }
6681 }
6682 }
6683 return false;
6684}
6685
6686/// If BB has an incoming value that will always trigger undefined behavior
6687/// (eg. null pointer dereference), remove the branch leading here.
6688static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
6689 DomTreeUpdater *DTU) {
6690 for (PHINode &PHI : BB->phis())
6691 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6692 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6693 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
6694 Instruction *T = Predecessor->getTerminator();
6695 IRBuilder<> Builder(T);
6696 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6697 BB->removePredecessor(Predecessor);
6698 // Turn uncoditional branches into unreachables and remove the dead
6699 // destination from conditional branches.
6700 if (BI->isUnconditional())
6701 Builder.CreateUnreachable();
6702 else
6703 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
6704 : BI->getSuccessor(0));
6705 BI->eraseFromParent();
6706 if (DTU)
6707 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
6708 return true;
6709 }
6710 // TODO: SwitchInst.
6711 }
6712
6713 return false;
6714}
6715
6716bool SimplifyCFGOpt::simplifyOnceImpl(BasicBlock *BB) {
6717 bool Changed = false;
6718
6719 assert(BB && BB->getParent() && "Block not embedded in function!")(static_cast <bool> (BB && BB->getParent() &&
"Block not embedded in function!") ? void (0) : __assert_fail
("BB && BB->getParent() && \"Block not embedded in function!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6719, __extension__ __PRETTY_FUNCTION__))
;
4
Assuming the condition is true
5
'?' condition is true
6720 assert(BB->getTerminator() && "Degenerate basic block encountered!")(static_cast <bool> (BB->getTerminator() && "Degenerate basic block encountered!"
) ? void (0) : __assert_fail ("BB->getTerminator() && \"Degenerate basic block encountered!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Transforms/Utils/SimplifyCFG.cpp"
, 6720, __extension__ __PRETTY_FUNCTION__))
;
6
Assuming the condition is true
7
'?' condition is true
6721
6722 // Remove basic blocks that have no predecessors (except the entry block)...
6723 // or that just have themself as a predecessor. These are unreachable.
6724 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
8
Assuming the condition is false
10
Taking false branch
6725 BB->getSinglePredecessor() == BB) {
9
Assuming the condition is false
6726 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("simplifycfg")) { dbgs() << "Removing BB: \n" <<
*BB; } } while (false)
;
6727 DeleteDeadBlock(BB, DTU);
6728 return true;
6729 }
6730
6731 // Check to see if we can constant propagate this terminator instruction
6732 // away...
6733 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
6734 /*TLI=*/nullptr, DTU);
6735
6736 // Check for and eliminate duplicate PHI nodes in this block.
6737 Changed |= EliminateDuplicatePHINodes(BB);
6738
6739 // Check for and remove branches that will always cause undefined behavior.
6740 Changed |= removeUndefIntroducingPredecessor(BB, DTU);
6741
6742 // Merge basic blocks into their predecessor if there is only one distinct
6743 // pred, and if there is only one distinct successor of the predecessor, and
6744 // if there are no PHI nodes.
6745 if (MergeBlockIntoPredecessor(BB, DTU))
11
Assuming the condition is false
12
Taking false branch
6746 return true;
6747
6748 if (SinkCommon && Options.SinkCommonInsts)
13
Assuming the condition is false
6749 if (SinkCommonCodeFromPredecessors(BB, DTU)) {
6750 // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
6751 // so we may now how duplicate PHI's.
6752 // Let's rerun EliminateDuplicatePHINodes() first,
6753 // before FoldTwoEntryPHINode() potentially converts them into select's,
6754 // after which we'd need a whole EarlyCSE pass run to cleanup them.
6755 return true;
6756 }
6757
6758 IRBuilder<> Builder(BB);
6759
6760 if (Options.FoldTwoEntryPHINode) {
14
Assuming field 'FoldTwoEntryPHINode' is false
15
Taking false branch
6761 // If there is a trivial two-entry PHI node in this basic block, and we can
6762 // eliminate it, do so now.
6763 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
6764 if (PN->getNumIncomingValues() == 2)
6765 Changed |= FoldTwoEntryPHINode(PN, TTI, DTU, DL);
6766 }
6767
6768 Instruction *Terminator = BB->getTerminator();
6769 Builder.SetInsertPoint(Terminator);
6770 switch (Terminator->getOpcode()) {
16
Control jumps to 'case Resume:' at line 6777
6771 case Instruction::Br:
6772 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder);
6773 break;
6774 case Instruction::Ret:
6775 Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder);
6776 break;
6777 case Instruction::Resume:
6778 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder);
17
'Terminator' is a 'ResumeInst'
18
Calling 'SimplifyCFGOpt::simplifyResume'
6779 break;
6780 case Instruction::CleanupRet:
6781 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator));
6782 break;
6783 case Instruction::Switch:
6784 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder);
6785 break;
6786 case Instruction::Unreachable:
6787 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator));
6788 break;
6789 case Instruction::IndirectBr:
6790 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator));
6791 break;
6792 }
6793
6794 return Changed;
6795}
6796
6797bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
6798 bool Changed = simplifyOnceImpl(BB);
3
Calling 'SimplifyCFGOpt::simplifyOnceImpl'
6799
6800 return Changed;
6801}
6802
6803bool SimplifyCFGOpt::run(BasicBlock *BB) {
6804 bool Changed = false;
6805
6806 // Repeated simplify BB as long as resimplification is requested.
6807 do {
6808 Resimplify = false;
6809
6810 // Perform one round of simplifcation. Resimplify flag will be set if
6811 // another iteration is requested.
6812 Changed |= simplifyOnce(BB);
2
Calling 'SimplifyCFGOpt::simplifyOnce'
6813 } while (Resimplify);
6814
6815 return Changed;
6816}
6817
6818bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6819 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
6820 ArrayRef<WeakVH> LoopHeaders) {
6821 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders,
1
Calling 'SimplifyCFGOpt::run'
6822 Options)
6823 .run(BB);
6824}