LLVM 20.0.0git
SpeculativeExecution.cpp
Go to the documentation of this file.
1//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
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// This pass hoists instructions to enable speculative execution on
10// targets where branches are expensive. This is aimed at GPUs. It
11// currently works on simple if-then and if-then-else
12// patterns.
13//
14// Removing branches is not the only motivation for this
15// pass. E.g. consider this code and assume that there is no
16// addressing mode for multiplying by sizeof(*a):
17//
18// if (b > 0)
19// c = a[i + 1]
20// if (d > 0)
21// e = a[i + 2]
22//
23// turns into
24//
25// p = &a[i + 1];
26// if (b > 0)
27// c = *p;
28// q = &a[i + 2];
29// if (d > 0)
30// e = *q;
31//
32// which could later be optimized to
33//
34// r = &a[i];
35// if (b > 0)
36// c = r[1];
37// if (d > 0)
38// e = r[2];
39//
40// Later passes sink back much of the speculated code that did not enable
41// further optimization.
42//
43// This pass is more aggressive than the function SpeculativeyExecuteBB in
44// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
45// it will speculate at most one instruction. It also will not speculate if
46// there is a value defined in the if-block that is only used in the then-block.
47// These restrictions make sense since the speculation in SimplifyCFG seems
48// aimed at introducing cheap selects, while this pass is intended to do more
49// aggressive speculation while counting on later passes to either capitalize on
50// that or clean it up.
51//
52// If the pass was created by calling
53// createSpeculativeExecutionIfHasBranchDivergencePass or the
54// -spec-exec-only-if-divergent-target option is present, this pass only has an
55// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
56// on other targets, it is a nop.
57//
58// This lets you include this pass unconditionally in the IR pass pipeline, but
59// only enable it for relevant targets.
60//
61//===----------------------------------------------------------------------===//
62
70#include "llvm/IR/Operator.h"
73#include "llvm/Support/Debug.h"
75
76using namespace llvm;
77
78#define DEBUG_TYPE "speculative-execution"
79
80// The risk that speculation will not pay off increases with the
81// number of instructions speculated, so we put a limit on that.
83 "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
84 cl::desc("Speculative execution is not applied to basic blocks where "
85 "the cost of the instructions to speculatively execute "
86 "exceeds this limit."));
87
88// Speculating just a few instructions from a larger block tends not
89// to be profitable and this limit prevents that. A reason for that is
90// that small basic blocks are more likely to be candidates for
91// further optimization.
93 "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
94 cl::desc("Speculative execution is not applied to basic blocks where the "
95 "number of instructions that would not be speculatively executed "
96 "exceeds this limit."));
97
99 "spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
100 cl::desc("Speculative execution is applied only to targets with divergent "
101 "branches, even if the pass was configured to apply only to all "
102 "targets."));
103
104namespace {
105
106class SpeculativeExecutionLegacyPass : public FunctionPass {
107public:
108 static char ID;
109 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
110 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
112 Impl(OnlyIfDivergentTarget) {}
113
114 void getAnalysisUsage(AnalysisUsage &AU) const override;
115 bool runOnFunction(Function &F) override;
116
117 StringRef getPassName() const override {
118 if (OnlyIfDivergentTarget)
119 return "Speculatively execute instructions if target has divergent "
120 "branches";
121 return "Speculatively execute instructions";
122 }
123
124private:
125 // Variable preserved purely for correct name printing.
126 const bool OnlyIfDivergentTarget;
127
129};
130} // namespace
131
132char SpeculativeExecutionLegacyPass::ID = 0;
133INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
134 "Speculatively execute instructions", false, false)
136INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
137 "Speculatively execute instructions", false, false)
138
139void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
140 AU.addRequired<TargetTransformInfoWrapperPass>();
141 AU.addPreserved<GlobalsAAWrapperPass>();
142 AU.setPreservesCFG();
143}
144
145bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
146 if (skipFunction(F))
147 return false;
148
149 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
150 return Impl.runImpl(F, TTI);
151}
152
153namespace llvm {
154
156 if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence(&F)) {
157 LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
158 "TTI->hasBranchDivergence() is false.\n");
159 return false;
160 }
161
162 this->TTI = TTI;
163 bool Changed = false;
164 for (auto& B : F) {
165 Changed |= runOnBasicBlock(B);
166 }
167 return Changed;
168}
169
170bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
171 BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
172 if (BI == nullptr)
173 return false;
174
175 if (BI->getNumSuccessors() != 2)
176 return false;
177 BasicBlock &Succ0 = *BI->getSuccessor(0);
178 BasicBlock &Succ1 = *BI->getSuccessor(1);
179
180 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
181 return false;
182 }
183
184 // Hoist from if-then (triangle).
185 if (Succ0.getSinglePredecessor() != nullptr &&
186 Succ0.getSingleSuccessor() == &Succ1) {
187 return considerHoistingFromTo(Succ0, B);
188 }
189
190 // Hoist from if-else (triangle).
191 if (Succ1.getSinglePredecessor() != nullptr &&
192 Succ1.getSingleSuccessor() == &Succ0) {
193 return considerHoistingFromTo(Succ1, B);
194 }
195
196 // Hoist from if-then-else (diamond), but only if it is equivalent to
197 // an if-else or if-then due to one of the branches doing nothing.
198 if (Succ0.getSinglePredecessor() != nullptr &&
199 Succ1.getSinglePredecessor() != nullptr &&
200 Succ1.getSingleSuccessor() != nullptr &&
201 Succ1.getSingleSuccessor() != &B &&
202 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
203 // If a block has only one instruction, then that is a terminator
204 // instruction so that the block does nothing. This does happen.
205 if (Succ1.size() == 1) // equivalent to if-then
206 return considerHoistingFromTo(Succ0, B);
207 if (Succ0.size() == 1) // equivalent to if-else
208 return considerHoistingFromTo(Succ1, B);
209 }
210
211 return false;
212}
213
215 const TargetTransformInfo &TTI) {
216 switch (Operator::getOpcode(I)) {
217 case Instruction::GetElementPtr:
218 case Instruction::Add:
219 case Instruction::Mul:
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Select:
223 case Instruction::Shl:
224 case Instruction::Sub:
225 case Instruction::LShr:
226 case Instruction::AShr:
227 case Instruction::Xor:
228 case Instruction::ZExt:
229 case Instruction::SExt:
230 case Instruction::Call:
231 case Instruction::BitCast:
232 case Instruction::PtrToInt:
233 case Instruction::IntToPtr:
234 case Instruction::AddrSpaceCast:
235 case Instruction::FPToUI:
236 case Instruction::FPToSI:
237 case Instruction::UIToFP:
238 case Instruction::SIToFP:
239 case Instruction::FPExt:
240 case Instruction::FPTrunc:
241 case Instruction::FAdd:
242 case Instruction::FSub:
243 case Instruction::FMul:
244 case Instruction::FDiv:
245 case Instruction::FRem:
246 case Instruction::FNeg:
247 case Instruction::ICmp:
248 case Instruction::FCmp:
249 case Instruction::Trunc:
250 case Instruction::Freeze:
251 case Instruction::ExtractElement:
252 case Instruction::InsertElement:
253 case Instruction::ShuffleVector:
254 case Instruction::ExtractValue:
255 case Instruction::InsertValue:
257
258 default:
259 return InstructionCost::getInvalid(); // Disallow anything not explicitly
260 // listed.
261 }
262}
263
264// Do not hoist any debug info intrinsics.
265// ...
266// if (cond) {
267// x = y * z;
268// foo();
269// }
270// ...
271// -------- Which then becomes:
272// ...
273// if.then:
274// %x = mul i32 %y, %z
275// call void @llvm.dbg.value(%x, !"x", !DIExpression())
276// call void foo()
277//
278// SpeculativeExecution might decide to hoist the 'y * z' calculation
279// out of the 'if' block, because it is more efficient that way, so the
280// '%x = mul i32 %y, %z' moves to the block above. But it might also
281// decide to hoist the 'llvm.dbg.value' call.
282// This is incorrect, because even if we've moved the calculation of
283// 'y * z', we should not see the value of 'x' change unless we
284// actually go inside the 'if' block.
285
286bool SpeculativeExecutionPass::considerHoistingFromTo(
287 BasicBlock &FromBlock, BasicBlock &ToBlock) {
289 auto HasNoUnhoistedInstr = [&NotHoisted](auto Values) {
290 for (const Value *V : Values) {
291 if (const auto *I = dyn_cast_or_null<Instruction>(V))
292 if (NotHoisted.contains(I))
293 return false;
294 }
295 return true;
296 };
297 auto AllPrecedingUsesFromBlockHoisted =
298 [&HasNoUnhoistedInstr](const User *U) {
299 // Do not hoist any debug info intrinsics.
300 if (isa<DbgInfoIntrinsic>(U))
301 return false;
302
303 return HasNoUnhoistedInstr(U->operand_values());
304 };
305
306 InstructionCost TotalSpeculationCost = 0;
307 unsigned NotHoistedInstCount = 0;
308 for (const auto &I : FromBlock) {
311 AllPrecedingUsesFromBlockHoisted(&I)) {
312 TotalSpeculationCost += Cost;
313 if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
314 return false; // too much to hoist
315 } else {
316 // Debug info intrinsics should not be counted for threshold.
317 if (!isa<DbgInfoIntrinsic>(I))
318 NotHoistedInstCount++;
319 if (NotHoistedInstCount > SpecExecMaxNotHoisted)
320 return false; // too much left behind
321 NotHoisted.insert(&I);
322 }
323 }
324
325 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
326 // We have to increment I before moving Current as moving Current
327 // changes the list that I is iterating through.
328 auto Current = I;
329 ++I;
330 if (!NotHoisted.count(&*Current)) {
331 Current->moveBefore(ToBlock.getTerminator());
332 Current->dropLocation();
333 }
334 }
335 return true;
336}
337
339 return new SpeculativeExecutionLegacyPass();
340}
341
343 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
344}
345
347 : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
349
352 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
353
354 bool Changed = runImpl(F, TTI);
355
356 if (!Changed)
357 return PreservedAnalyses::all();
360 return PA;
361}
362
364 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
366 OS, MapClassName2PassName);
367 OS << '<';
368 if (OnlyIfDivergentTarget)
369 OS << "only-if-divergent-target";
370 OS << '>';
371}
372} // namespace llvm
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This is the interface for a simple mod/ref and alias analysis over globals.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
static cl::opt< unsigned > SpecExecMaxNotHoisted("spec-exec-max-not-hoisted", cl::init(5), cl::Hidden, cl::desc("Speculative execution is not applied to basic blocks where the " "number of instructions that would not be speculatively executed " "exceeds this limit."))
speculative Speculatively execute instructions
static cl::opt< unsigned > SpecExecMaxSpeculationCost("spec-exec-max-speculation-cost", cl::init(7), cl::Hidden, cl::desc("Speculative execution is not applied to basic blocks where " "the cost of the instructions to speculatively execute " "exceeds this limit."))
static cl::opt< bool > SpecExecOnlyIfDivergentTarget("spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden, cl::desc("Speculative execution is applied only to targets with divergent " "branches, even if the pass was configured to apply only to all " "targets."))
speculative execution
This pass exposes codegen information to IR-level passes.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:459
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:489
size_t size() const
Definition: BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
Conditional or Unconditional Branch instruction.
unsigned getNumSuccessors() const
BasicBlock * getSuccessor(unsigned i) const
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Legacy wrapper pass to provide the GlobalsAAResult object.
static InstructionCost getInvalid(CostType Val=0)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:42
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:452
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:458
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
SpeculativeExecutionPass(bool OnlyIfDivergentTarget=false)
bool runImpl(Function &F, TargetTransformInfo *TTI)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createSpeculativeExecutionIfHasBranchDivergencePass()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createSpeculativeExecutionPass()
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
InstructionCost Cost
static InstructionCost ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:69