#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Operator.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "speculative-execution"
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<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<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."));
namespace {
class SpeculativeExecutionLegacyPass : public FunctionPass {
public:
static char ID;
explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
: FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
SpecExecOnlyIfDivergentTarget),
Impl(OnlyIfDivergentTarget) {}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
StringRef getPassName() const override {
if (OnlyIfDivergentTarget)
return "Speculatively execute instructions if target has divergent "
"branches";
return "Speculatively execute instructions";
}
private:
const bool OnlyIfDivergentTarget;
SpeculativeExecutionPass Impl;
};
}
char SpeculativeExecutionLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
"Speculatively execute instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
"Speculatively execute instructions", false, false)
void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.setPreservesCFG();
}
bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
return Impl.runImpl(F, TTI);
}
namespace llvm {
bool SpeculativeExecutionPass::runImpl(Function &F, TargetTransformInfo *TTI) {
if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
"TTI->hasBranchDivergence() is false.\n");
return false;
}
this->TTI = TTI;
bool Changed = false;
for (auto& B : F) {
Changed |= runOnBasicBlock(B);
}
return Changed;
}
bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
if (BI == nullptr)
return false;
if (BI->getNumSuccessors() != 2)
return false;
BasicBlock &Succ0 = *BI->getSuccessor(0);
BasicBlock &Succ1 = *BI->getSuccessor(1);
if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
return false;
}
if (Succ0.getSinglePredecessor() != nullptr &&
Succ0.getSingleSuccessor() == &Succ1) {
return considerHoistingFromTo(Succ0, B);
}
if (Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() == &Succ0) {
return considerHoistingFromTo(Succ1, B);
}
if (Succ0.getSinglePredecessor() != nullptr &&
Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() != nullptr &&
Succ1.getSingleSuccessor() != &B &&
Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
if (Succ1.size() == 1) return considerHoistingFromTo(Succ0, B);
if (Succ0.size() == 1) return considerHoistingFromTo(Succ1, B);
}
return false;
}
static InstructionCost ComputeSpeculationCost(const Instruction *I,
const TargetTransformInfo &TTI) {
switch (Operator::getOpcode(I)) {
case Instruction::GetElementPtr:
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Select:
case Instruction::Shl:
case Instruction::Sub:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Xor:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::Call:
case Instruction::BitCast:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::AddrSpaceCast:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPExt:
case Instruction::FPTrunc:
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
case Instruction::FNeg:
case Instruction::ICmp:
case Instruction::FCmp:
case Instruction::Trunc:
case Instruction::Freeze:
case Instruction::ExtractElement:
case Instruction::InsertElement:
case Instruction::ShuffleVector:
case Instruction::ExtractValue:
case Instruction::InsertValue:
return TTI.getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency);
default:
return InstructionCost::getInvalid(); }
}
bool SpeculativeExecutionPass::considerHoistingFromTo(
BasicBlock &FromBlock, BasicBlock &ToBlock) {
SmallPtrSet<const Instruction *, 8> NotHoisted;
const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](const User *U) {
if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(U)) {
return all_of(DVI->location_ops(), [&NotHoisted](Value *V) {
if (const auto *I = dyn_cast_or_null<Instruction>(V)) {
if (!NotHoisted.contains(I))
return true;
}
return false;
});
}
if (isa<DbgLabelInst>(U))
return false;
for (const Value *V : U->operand_values()) {
if (const Instruction *I = dyn_cast<Instruction>(V)) {
if (NotHoisted.contains(I))
return false;
}
}
return true;
};
InstructionCost TotalSpeculationCost = 0;
unsigned NotHoistedInstCount = 0;
for (const auto &I : FromBlock) {
const InstructionCost Cost = ComputeSpeculationCost(&I, *TTI);
if (Cost.isValid() && isSafeToSpeculativelyExecute(&I) &&
AllPrecedingUsesFromBlockHoisted(&I)) {
TotalSpeculationCost += Cost;
if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
return false; } else {
if (!isa<DbgInfoIntrinsic>(I))
NotHoistedInstCount++;
if (NotHoistedInstCount > SpecExecMaxNotHoisted)
return false; NotHoisted.insert(&I);
}
}
for (auto I = FromBlock.begin(); I != FromBlock.end();) {
auto Current = I;
++I;
if (!NotHoisted.count(&*Current)) {
Current->moveBefore(ToBlock.getTerminator());
}
}
return true;
}
FunctionPass *createSpeculativeExecutionPass() {
return new SpeculativeExecutionLegacyPass();
}
FunctionPass *createSpeculativeExecutionIfHasBranchDivergencePass() {
return new SpeculativeExecutionLegacyPass( true);
}
SpeculativeExecutionPass::SpeculativeExecutionPass(bool OnlyIfDivergentTarget)
: OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
SpecExecOnlyIfDivergentTarget) {}
PreservedAnalyses SpeculativeExecutionPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
bool Changed = runImpl(F, TTI);
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}
}