LLVM 22.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
69#include "llvm/IR/Operator.h"
72#include "llvm/Support/Debug.h"
74
75using namespace llvm;
76
77#define DEBUG_TYPE "speculative-execution"
78
79// The risk that speculation will not pay off increases with the
80// number of instructions speculated, so we put a limit on that.
82 "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
83 cl::desc("Speculative execution is not applied to basic blocks where "
84 "the cost of the instructions to speculatively execute "
85 "exceeds this limit."));
86
87// Speculating just a few instructions from a larger block tends not
88// to be profitable and this limit prevents that. A reason for that is
89// that small basic blocks are more likely to be candidates for
90// further optimization.
92 "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
93 cl::desc("Speculative execution is not applied to basic blocks where the "
94 "number of instructions that would not be speculatively executed "
95 "exceeds this limit."));
96
98 "spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
99 cl::desc("Speculative execution is applied only to targets with divergent "
100 "branches, even if the pass was configured to apply only to all "
101 "targets."));
102
103namespace {
104
105class SpeculativeExecutionLegacyPass : public FunctionPass {
106public:
107 static char ID;
108 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
109 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
111 Impl(OnlyIfDivergentTarget) {}
112
113 void getAnalysisUsage(AnalysisUsage &AU) const override;
114 bool runOnFunction(Function &F) override;
115
116 StringRef getPassName() const override {
117 if (OnlyIfDivergentTarget)
118 return "Speculatively execute instructions if target has divergent "
119 "branches";
120 return "Speculatively execute instructions";
121 }
122
123private:
124 // Variable preserved purely for correct name printing.
125 const bool OnlyIfDivergentTarget;
126
127 SpeculativeExecutionPass Impl;
128};
129} // namespace
130
131char SpeculativeExecutionLegacyPass::ID = 0;
132INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
133 "Speculatively execute instructions", false, false)
135INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
136 "Speculatively execute instructions", false, false)
137
138void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
139 AU.addRequired<TargetTransformInfoWrapperPass>();
140 AU.addPreserved<GlobalsAAWrapperPass>();
141 AU.setPreservesCFG();
142}
143
144bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
145 if (skipFunction(F))
146 return false;
147
148 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
149 return Impl.runImpl(F, TTI);
150}
151
153 if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence(&F)) {
154 LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
155 "TTI->hasBranchDivergence() is false.\n");
156 return false;
157 }
158
159 this->TTI = TTI;
160 bool Changed = false;
161 for (auto& B : F) {
163 }
164 return Changed;
165}
166
167bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
168 BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
169 if (BI == nullptr)
170 return false;
171
172 if (BI->getNumSuccessors() != 2)
173 return false;
174 BasicBlock &Succ0 = *BI->getSuccessor(0);
175 BasicBlock &Succ1 = *BI->getSuccessor(1);
176
177 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
178 return false;
179 }
180
181 // Hoist from if-then (triangle).
182 if (Succ0.getSinglePredecessor() != nullptr &&
183 Succ0.getSingleSuccessor() == &Succ1) {
184 return considerHoistingFromTo(Succ0, B);
185 }
186
187 // Hoist from if-else (triangle).
188 if (Succ1.getSinglePredecessor() != nullptr &&
189 Succ1.getSingleSuccessor() == &Succ0) {
190 return considerHoistingFromTo(Succ1, B);
191 }
192
193 // Hoist from if-then-else (diamond), but only if it is equivalent to
194 // an if-else or if-then due to one of the branches doing nothing.
195 if (Succ0.getSinglePredecessor() != nullptr &&
196 Succ1.getSinglePredecessor() != nullptr &&
197 Succ1.getSingleSuccessor() != nullptr &&
198 Succ1.getSingleSuccessor() != &B &&
199 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
200 // If a block has only one instruction, then that is a terminator
201 // instruction so that the block does nothing. This does happen.
202 if (Succ1.size() == 1) // equivalent to if-then
203 return considerHoistingFromTo(Succ0, B);
204 if (Succ0.size() == 1) // equivalent to if-else
205 return considerHoistingFromTo(Succ1, B);
206 }
207
208 return false;
209}
210
212 const TargetTransformInfo &TTI) {
213 switch (Operator::getOpcode(I)) {
214 case Instruction::GetElementPtr:
215 case Instruction::Add:
216 case Instruction::Mul:
217 case Instruction::And:
218 case Instruction::Or:
219 case Instruction::Select:
220 case Instruction::Shl:
221 case Instruction::Sub:
222 case Instruction::LShr:
223 case Instruction::AShr:
224 case Instruction::Xor:
225 case Instruction::ZExt:
226 case Instruction::SExt:
227 case Instruction::Call:
228 case Instruction::BitCast:
229 case Instruction::PtrToInt:
230 case Instruction::IntToPtr:
231 case Instruction::AddrSpaceCast:
232 case Instruction::FPToUI:
233 case Instruction::FPToSI:
234 case Instruction::UIToFP:
235 case Instruction::SIToFP:
236 case Instruction::FPExt:
237 case Instruction::FPTrunc:
238 case Instruction::FAdd:
239 case Instruction::FSub:
240 case Instruction::FMul:
241 case Instruction::FDiv:
242 case Instruction::FRem:
243 case Instruction::FNeg:
244 case Instruction::ICmp:
245 case Instruction::FCmp:
246 case Instruction::Trunc:
247 case Instruction::Freeze:
248 case Instruction::ExtractElement:
249 case Instruction::InsertElement:
250 case Instruction::ShuffleVector:
251 case Instruction::ExtractValue:
252 case Instruction::InsertValue:
253 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
254
255 default:
256 return InstructionCost::getInvalid(); // Disallow anything not explicitly
257 // listed.
258 }
259}
260
261// Do not hoist any debug info intrinsics.
262// ...
263// if (cond) {
264// x = y * z;
265// foo();
266// }
267// ...
268// -------- Which then becomes:
269// ...
270// if.then:
271// %x = mul i32 %y, %z
272// call void @llvm.dbg.value(%x, !"x", !DIExpression())
273// call void foo()
274//
275// SpeculativeExecution might decide to hoist the 'y * z' calculation
276// out of the 'if' block, because it is more efficient that way, so the
277// '%x = mul i32 %y, %z' moves to the block above. But it might also
278// decide to hoist the 'llvm.dbg.value' call.
279// This is incorrect, because even if we've moved the calculation of
280// 'y * z', we should not see the value of 'x' change unless we
281// actually go inside the 'if' block.
282
283bool SpeculativeExecutionPass::considerHoistingFromTo(
284 BasicBlock &FromBlock, BasicBlock &ToBlock) {
285 SmallPtrSet<const Instruction *, 8> NotHoisted;
286 auto HasNoUnhoistedInstr = [&NotHoisted](auto Values) {
287 for (const Value *V : Values) {
288 if (const auto *I = dyn_cast_or_null<Instruction>(V))
289 if (NotHoisted.contains(I))
290 return false;
291 }
292 return true;
293 };
294 auto AllPrecedingUsesFromBlockHoisted =
295 [&HasNoUnhoistedInstr](const User *U) {
296 return HasNoUnhoistedInstr(U->operand_values());
297 };
298
299 InstructionCost TotalSpeculationCost = 0;
300 unsigned NotHoistedInstCount = 0;
301 for (const auto &I : FromBlock) {
304 AllPrecedingUsesFromBlockHoisted(&I)) {
305 TotalSpeculationCost += Cost;
306 if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
307 return false; // too much to hoist
308 } else {
309 NotHoistedInstCount++;
310 if (NotHoistedInstCount > SpecExecMaxNotHoisted)
311 return false; // too much left behind
312 NotHoisted.insert(&I);
313 }
314 }
315
316 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
317 // We have to increment I before moving Current as moving Current
318 // changes the list that I is iterating through.
319 auto Current = I;
320 ++I;
321 if (!NotHoisted.count(&*Current)) {
322 Current->moveBefore(ToBlock.getTerminator()->getIterator());
323 Current->dropLocation();
324 }
325 }
326 return true;
327}
328
330 return new SpeculativeExecutionLegacyPass();
331}
332
334 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
335}
336
338 : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
340
343 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
344
345 bool Changed = runImpl(F, TTI);
346
347 if (!Changed)
348 return PreservedAnalyses::all();
351 return PA;
352}
353
355 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
357 OS, MapClassName2PassName);
358 OS << '<';
359 if (OnlyIfDivergentTarget)
360 OS << "only-if-divergent-target";
361 OS << '>';
362}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
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
static bool runOnBasicBlock(MachineBasicBlock *MBB, unsigned BasicBlockNum, VRegRenamer &Renamer)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
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."))
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 InstructionCost ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
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."))
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
size_t size() const
Definition BasicBlock.h:480
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:233
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:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
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:43
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
bool runImpl(Function &F, TargetTransformInfo *TTI)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
SpeculativeExecutionPass(bool OnlyIfDivergentTarget=false)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI FunctionPass * createSpeculativeExecutionIfHasBranchDivergencePass()
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI FunctionPass * createSpeculativeExecutionPass()
TargetTransformInfo TTI
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70