LLVM  8.0.1
SpeculativeExecution.cpp
Go to the documentation of this file.
1 //===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass hoists instructions to enable speculative execution on
11 // targets where branches are expensive. This is aimed at GPUs. It
12 // currently works on simple if-then and if-then-else
13 // patterns.
14 //
15 // Removing branches is not the only motivation for this
16 // pass. E.g. consider this code and assume that there is no
17 // addressing mode for multiplying by sizeof(*a):
18 //
19 // if (b > 0)
20 // c = a[i + 1]
21 // if (d > 0)
22 // e = a[i + 2]
23 //
24 // turns into
25 //
26 // p = &a[i + 1];
27 // if (b > 0)
28 // c = *p;
29 // q = &a[i + 2];
30 // if (d > 0)
31 // e = *q;
32 //
33 // which could later be optimized to
34 //
35 // r = &a[i];
36 // if (b > 0)
37 // c = r[1];
38 // if (d > 0)
39 // e = r[2];
40 //
41 // Later passes sink back much of the speculated code that did not enable
42 // further optimization.
43 //
44 // This pass is more aggressive than the function SpeculativeyExecuteBB in
45 // SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
46 // it will speculate at most one instruction. It also will not speculate if
47 // there is a value defined in the if-block that is only used in the then-block.
48 // These restrictions make sense since the speculation in SimplifyCFG seems
49 // aimed at introducing cheap selects, while this pass is intended to do more
50 // aggressive speculation while counting on later passes to either capitalize on
51 // that or clean it up.
52 //
53 // If the pass was created by calling
54 // createSpeculativeExecutionIfHasBranchDivergencePass or the
55 // -spec-exec-only-if-divergent-target option is present, this pass only has an
56 // effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
57 // on other targets, it is a nop.
58 //
59 // This lets you include this pass unconditionally in the IR pass pipeline, but
60 // only enable it for relevant targets.
61 //
62 //===----------------------------------------------------------------------===//
63 
65 #include "llvm/ADT/SmallPtrSet.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Operator.h"
72 #include "llvm/Support/Debug.h"
73 
74 using namespace llvm;
75 
76 #define DEBUG_TYPE "speculative-execution"
77 
78 // The risk that speculation will not pay off increases with the
79 // number of instructions speculated, so we put a limit on that.
81  "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
82  cl::desc("Speculative execution is not applied to basic blocks where "
83  "the cost of the instructions to speculatively execute "
84  "exceeds this limit."));
85 
86 // Speculating just a few instructions from a larger block tends not
87 // to be profitable and this limit prevents that. A reason for that is
88 // that small basic blocks are more likely to be candidates for
89 // further optimization.
91  "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
92  cl::desc("Speculative execution is not applied to basic blocks where the "
93  "number of instructions that would not be speculatively executed "
94  "exceeds this limit."));
95 
97  "spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
98  cl::desc("Speculative execution is applied only to targets with divergent "
99  "branches, even if the pass was configured to apply only to all "
100  "targets."));
101 
102 namespace {
103 
104 class SpeculativeExecutionLegacyPass : public FunctionPass {
105 public:
106  static char ID;
107  explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
108  : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
110  Impl(OnlyIfDivergentTarget) {}
111 
112  void getAnalysisUsage(AnalysisUsage &AU) const override;
113  bool runOnFunction(Function &F) override;
114 
115  StringRef getPassName() const override {
116  if (OnlyIfDivergentTarget)
117  return "Speculatively execute instructions if target has divergent "
118  "branches";
119  return "Speculatively execute instructions";
120  }
121 
122 private:
123  // Variable preserved purely for correct name printing.
124  const bool OnlyIfDivergentTarget;
125 
127 };
128 } // namespace
129 
131 INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
132  "Speculatively execute instructions", false, false)
134 INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
135  "Speculatively execute instructions", false, false)
136 
137 void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
138  AU.addRequired<TargetTransformInfoWrapperPass>();
139  AU.addPreserved<GlobalsAAWrapperPass>();
140  AU.setPreservesCFG();
141 }
142 
144  if (skipFunction(F))
145  return false;
146 
147  auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
148  return Impl.runImpl(F, TTI);
149 }
150 
151 namespace llvm {
152 
154  if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
155  LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
156  "TTI->hasBranchDivergence() is false.\n");
157  return false;
158  }
159 
160  this->TTI = TTI;
161  bool Changed = false;
162  for (auto& B : F) {
163  Changed |= runOnBasicBlock(B);
164  }
165  return Changed;
166 }
167 
168 bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
170  if (BI == nullptr)
171  return false;
172 
173  if (BI->getNumSuccessors() != 2)
174  return false;
175  BasicBlock &Succ0 = *BI->getSuccessor(0);
176  BasicBlock &Succ1 = *BI->getSuccessor(1);
177 
178  if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
179  return false;
180  }
181 
182  // Hoist from if-then (triangle).
183  if (Succ0.getSinglePredecessor() != nullptr &&
184  Succ0.getSingleSuccessor() == &Succ1) {
185  return considerHoistingFromTo(Succ0, B);
186  }
187 
188  // Hoist from if-else (triangle).
189  if (Succ1.getSinglePredecessor() != nullptr &&
190  Succ1.getSingleSuccessor() == &Succ0) {
191  return considerHoistingFromTo(Succ1, B);
192  }
193 
194  // Hoist from if-then-else (diamond), but only if it is equivalent to
195  // an if-else or if-then due to one of the branches doing nothing.
196  if (Succ0.getSinglePredecessor() != nullptr &&
197  Succ1.getSinglePredecessor() != nullptr &&
198  Succ1.getSingleSuccessor() != nullptr &&
199  Succ1.getSingleSuccessor() != &B &&
200  Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
201  // If a block has only one instruction, then that is a terminator
202  // instruction so that the block does nothing. This does happen.
203  if (Succ1.size() == 1) // equivalent to if-then
204  return considerHoistingFromTo(Succ0, B);
205  if (Succ0.size() == 1) // equivalent to if-else
206  return considerHoistingFromTo(Succ1, B);
207  }
208 
209  return false;
210 }
211 
212 static unsigned ComputeSpeculationCost(const Instruction *I,
213  const TargetTransformInfo &TTI) {
214  switch (Operator::getOpcode(I)) {
215  case Instruction::GetElementPtr:
216  case Instruction::Add:
217  case Instruction::Mul:
218  case Instruction::And:
219  case Instruction::Or:
220  case Instruction::Select:
221  case Instruction::Shl:
222  case Instruction::Sub:
223  case Instruction::LShr:
224  case Instruction::AShr:
225  case Instruction::Xor:
226  case Instruction::ZExt:
227  case Instruction::SExt:
228  case Instruction::Call:
229  case Instruction::BitCast:
230  case Instruction::PtrToInt:
231  case Instruction::IntToPtr:
232  case Instruction::AddrSpaceCast:
233  case Instruction::FPToUI:
234  case Instruction::FPToSI:
235  case Instruction::UIToFP:
236  case Instruction::SIToFP:
237  case Instruction::FPExt:
238  case Instruction::FPTrunc:
239  case Instruction::FAdd:
240  case Instruction::FSub:
241  case Instruction::FMul:
242  case Instruction::FDiv:
243  case Instruction::FRem:
244  case Instruction::ICmp:
245  case Instruction::FCmp:
246  return TTI.getUserCost(I);
247 
248  default:
249  return UINT_MAX; // Disallow anything not whitelisted.
250  }
251 }
252 
253 bool SpeculativeExecutionPass::considerHoistingFromTo(
254  BasicBlock &FromBlock, BasicBlock &ToBlock) {
256  const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
257  for (Value* V : U->operand_values()) {
258  if (Instruction *I = dyn_cast<Instruction>(V)) {
259  if (NotHoisted.count(I) > 0)
260  return false;
261  }
262  }
263  return true;
264  };
265 
266  unsigned TotalSpeculationCost = 0;
267  for (auto& I : FromBlock) {
268  const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
269  if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
270  AllPrecedingUsesFromBlockHoisted(&I)) {
271  TotalSpeculationCost += Cost;
272  if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
273  return false; // too much to hoist
274  } else {
275  NotHoisted.insert(&I);
276  if (NotHoisted.size() > SpecExecMaxNotHoisted)
277  return false; // too much left behind
278  }
279  }
280 
281  if (TotalSpeculationCost == 0)
282  return false; // nothing to hoist
283 
284  for (auto I = FromBlock.begin(); I != FromBlock.end();) {
285  // We have to increment I before moving Current as moving Current
286  // changes the list that I is iterating through.
287  auto Current = I;
288  ++I;
289  if (!NotHoisted.count(&*Current)) {
290  Current->moveBefore(ToBlock.getTerminator());
291  }
292  }
293  return true;
294 }
295 
297  return new SpeculativeExecutionLegacyPass();
298 }
299 
301  return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
302 }
303 
305  : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
307 
310  auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
311 
312  bool Changed = runImpl(F, TTI);
313 
314  if (!Changed)
315  return PreservedAnalyses::all();
317  PA.preserve<GlobalsAA>();
318  PA.preserveSet<CFGAnalyses>();
319  return PA;
320 }
321 } // namespace llvm
Legacy wrapper pass to provide the GlobalsAAResult object.
FunctionPass * createSpeculativeExecutionPass()
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
This class represents lattice values for constants.
Definition: AllocatorList.h:24
This is the interface for a simple mod/ref and alias analysis over globals.
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."))
Analysis pass providing the TargetTransformInfo.
BasicBlock * getSuccessor(unsigned i) const
static unsigned ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
F(f)
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.cpp:138
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
bool hasBranchDivergence() const
Return true if branch divergence exists.
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."))
unsigned getNumSuccessors() const
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:269
speculative execution
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:234
INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution", "Speculatively execute instructions", false, false) INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
Conditional or Unconditional Branch instruction.
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:371
size_t size() const
Definition: BasicBlock.h:279
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
SpeculativeExecutionPass(bool OnlyIfDivergentTarget=false)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
size_type size() const
Definition: SmallPtrSet.h:93
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Module.h This file contains the declarations for the Module class.
FunctionPass * createSpeculativeExecutionIfHasBranchDivergencePass()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
static bool runOnBasicBlock(MachineBasicBlock *MBB, std::vector< StringRef > &bbNames, std::vector< unsigned > &renamedInOtherBB, unsigned &basicBlockNum, unsigned &VRegGapIndex, NamedVRegCursor &NVC)
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
int getUserCost(const User *U, ArrayRef< const Value *> Operands) const
Estimate the cost of a given IR user when lowered.
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
Definition: Value.h:73
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."))
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:41
bool runImpl(Function &F, TargetTransformInfo *TTI)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
inst_range instructions(Function *F)
Definition: InstIterator.h:134
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)