1 //===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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):
33 // which could later be optimized to
41 // Later passes sink back much of the speculated code that did not enable
42 // further optimization.
44 //===----------------------------------------------------------------------===//
46 #include "llvm/ADT/SmallSet.h"
47 #include "llvm/Analysis/TargetTransformInfo.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/Operator.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
57 #define DEBUG_TYPE "speculative-execution"
59 // The risk that speculation will not pay off increases with the
60 // number of instructions speculated, so we put a limit on that.
61 static cl::opt<unsigned> SpecExecMaxSpeculationCost(
62 "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
63 cl::desc("Speculative execution is not applied to basic blocks where "
64 "the cost of the instructions to speculatively execute "
65 "exceeds this limit."));
67 // Speculating just a few instructions from a larger block tends not
68 // to be profitable and this limit prevents that. A reason for that is
69 // that small basic blocks are more likely to be candidates for
70 // further optimization.
71 static cl::opt<unsigned> SpecExecMaxNotHoisted(
72 "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
73 cl::desc("Speculative execution is not applied to basic blocks where the "
74 "number of instructions that would not be speculatively executed "
75 "exceeds this limit."));
78 class SpeculativeExecution : public FunctionPass {
81 SpeculativeExecution(): FunctionPass(ID) {}
83 void getAnalysisUsage(AnalysisUsage &AU) const override;
84 bool runOnFunction(Function &F) override;
87 bool runOnBasicBlock(BasicBlock &B);
88 bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
90 const TargetTransformInfo *TTI = nullptr;
94 char SpeculativeExecution::ID = 0;
95 INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
96 "Speculatively execute instructions", false, false)
97 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
98 INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
99 "Speculatively execute instructions", false, false)
101 void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequired<TargetTransformInfoWrapperPass>();
105 bool SpeculativeExecution::runOnFunction(Function &F) {
106 if (skipOptnoneFunction(F))
109 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
111 bool Changed = false;
113 Changed |= runOnBasicBlock(B);
118 bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
119 BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
123 if (BI->getNumSuccessors() != 2)
125 BasicBlock &Succ0 = *BI->getSuccessor(0);
126 BasicBlock &Succ1 = *BI->getSuccessor(1);
128 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
132 // Hoist from if-then (triangle).
133 if (Succ0.getSinglePredecessor() != nullptr &&
134 Succ0.getSingleSuccessor() == &Succ1) {
135 return considerHoistingFromTo(Succ0, B);
138 // Hoist from if-else (triangle).
139 if (Succ1.getSinglePredecessor() != nullptr &&
140 Succ1.getSingleSuccessor() == &Succ0) {
141 return considerHoistingFromTo(Succ1, B);
144 // Hoist from if-then-else (diamond), but only if it is equivalent to
145 // an if-else or if-then due to one of the branches doing nothing.
146 if (Succ0.getSinglePredecessor() != nullptr &&
147 Succ1.getSinglePredecessor() != nullptr &&
148 Succ1.getSingleSuccessor() != nullptr &&
149 Succ1.getSingleSuccessor() != &B &&
150 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
151 // If a block has only one instruction, then that is a terminator
152 // instruction so that the block does nothing. This does happen.
153 if (Succ1.size() == 1) // equivalent to if-then
154 return considerHoistingFromTo(Succ0, B);
155 if (Succ0.size() == 1) // equivalent to if-else
156 return considerHoistingFromTo(Succ1, B);
162 static unsigned ComputeSpeculationCost(const Instruction *I,
163 const TargetTransformInfo &TTI) {
164 switch (Operator::getOpcode(I)) {
165 case Instruction::GetElementPtr:
166 case Instruction::Add:
167 case Instruction::Mul:
168 case Instruction::And:
169 case Instruction::Or:
170 case Instruction::Select:
171 case Instruction::Shl:
172 case Instruction::Sub:
173 case Instruction::LShr:
174 case Instruction::AShr:
175 case Instruction::Xor:
176 case Instruction::ZExt:
177 case Instruction::SExt:
178 return TTI.getUserCost(I);
181 return UINT_MAX; // Disallow anything not whitelisted.
185 bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
186 BasicBlock &ToBlock) {
187 SmallSet<const Instruction *, 8> NotHoisted;
188 const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
189 for (Value* V : U->operand_values()) {
190 if (Instruction *I = dyn_cast<Instruction>(V)) {
191 if (NotHoisted.count(I) > 0)
198 unsigned TotalSpeculationCost = 0;
199 for (auto& I : FromBlock) {
200 const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
201 if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
202 AllPrecedingUsesFromBlockHoisted(&I)) {
203 TotalSpeculationCost += Cost;
204 if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
205 return false; // too much to hoist
207 NotHoisted.insert(&I);
208 if (NotHoisted.size() > SpecExecMaxNotHoisted)
209 return false; // too much left behind
213 if (TotalSpeculationCost == 0)
214 return false; // nothing to hoist
216 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
217 // We have to increment I before moving Current as moving Current
218 // changes the list that I is iterating through.
221 if (!NotHoisted.count(Current)) {
222 Current->moveBefore(ToBlock.getTerminator());
230 FunctionPass *createSpeculativeExecutionPass() {
231 return new SpeculativeExecution();