#include "AMDGPU.h"
#include "GCNSubtarget.h"
#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#include "llvm/InitializePasses.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#define DEBUG_TYPE "amdgpu-atomic-optimizer"
using namespace llvm;
using namespace llvm::AMDGPU;
namespace {
struct ReplacementInfo {
Instruction *I;
AtomicRMWInst::BinOp Op;
unsigned ValIdx;
bool ValDivergent;
};
class AMDGPUAtomicOptimizer : public FunctionPass,
public InstVisitor<AMDGPUAtomicOptimizer> {
private:
SmallVector<ReplacementInfo, 8> ToReplace;
const LegacyDivergenceAnalysis *DA;
const DataLayout *DL;
DominatorTree *DT;
const GCNSubtarget *ST;
bool IsPixelShader;
Value *buildReduction(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
Value *const Identity) const;
Value *buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
Value *const Identity) const;
Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const;
void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
bool ValDivergent) const;
public:
static char ID;
AMDGPUAtomicOptimizer() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<LegacyDivergenceAnalysis>();
AU.addRequired<TargetPassConfig>();
}
void visitAtomicRMWInst(AtomicRMWInst &I);
void visitIntrinsicInst(IntrinsicInst &I);
};
}
char AMDGPUAtomicOptimizer::ID = 0;
char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
if (skipFunction(F)) {
return false;
}
DA = &getAnalysis<LegacyDivergenceAnalysis>();
DL = &F.getParent()->getDataLayout();
DominatorTreeWrapperPass *const DTW =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTW ? &DTW->getDomTree() : nullptr;
const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
const TargetMachine &TM = TPC.getTM<TargetMachine>();
ST = &TM.getSubtarget<GCNSubtarget>(F);
IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
visit(F);
const bool Changed = !ToReplace.empty();
for (ReplacementInfo &Info : ToReplace) {
optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
}
ToReplace.clear();
return Changed;
}
void AMDGPUAtomicOptimizer::visitAtomicRMWInst(AtomicRMWInst &I) {
switch (I.getPointerAddressSpace()) {
default:
return;
case AMDGPUAS::GLOBAL_ADDRESS:
case AMDGPUAS::LOCAL_ADDRESS:
break;
}
AtomicRMWInst::BinOp Op = I.getOperation();
switch (Op) {
default:
return;
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub:
case AtomicRMWInst::And:
case AtomicRMWInst::Or:
case AtomicRMWInst::Xor:
case AtomicRMWInst::Max:
case AtomicRMWInst::Min:
case AtomicRMWInst::UMax:
case AtomicRMWInst::UMin:
break;
}
const unsigned PtrIdx = 0;
const unsigned ValIdx = 1;
if (DA->isDivergentUse(&I.getOperandUse(PtrIdx))) {
return;
}
const bool ValDivergent = DA->isDivergentUse(&I.getOperandUse(ValIdx));
if (ValDivergent &&
(!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
return;
}
const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
ToReplace.push_back(Info);
}
void AMDGPUAtomicOptimizer::visitIntrinsicInst(IntrinsicInst &I) {
AtomicRMWInst::BinOp Op;
switch (I.getIntrinsicID()) {
default:
return;
case Intrinsic::amdgcn_buffer_atomic_add:
case Intrinsic::amdgcn_struct_buffer_atomic_add:
case Intrinsic::amdgcn_raw_buffer_atomic_add:
Op = AtomicRMWInst::Add;
break;
case Intrinsic::amdgcn_buffer_atomic_sub:
case Intrinsic::amdgcn_struct_buffer_atomic_sub:
case Intrinsic::amdgcn_raw_buffer_atomic_sub:
Op = AtomicRMWInst::Sub;
break;
case Intrinsic::amdgcn_buffer_atomic_and:
case Intrinsic::amdgcn_struct_buffer_atomic_and:
case Intrinsic::amdgcn_raw_buffer_atomic_and:
Op = AtomicRMWInst::And;
break;
case Intrinsic::amdgcn_buffer_atomic_or:
case Intrinsic::amdgcn_struct_buffer_atomic_or:
case Intrinsic::amdgcn_raw_buffer_atomic_or:
Op = AtomicRMWInst::Or;
break;
case Intrinsic::amdgcn_buffer_atomic_xor:
case Intrinsic::amdgcn_struct_buffer_atomic_xor:
case Intrinsic::amdgcn_raw_buffer_atomic_xor:
Op = AtomicRMWInst::Xor;
break;
case Intrinsic::amdgcn_buffer_atomic_smin:
case Intrinsic::amdgcn_struct_buffer_atomic_smin:
case Intrinsic::amdgcn_raw_buffer_atomic_smin:
Op = AtomicRMWInst::Min;
break;
case Intrinsic::amdgcn_buffer_atomic_umin:
case Intrinsic::amdgcn_struct_buffer_atomic_umin:
case Intrinsic::amdgcn_raw_buffer_atomic_umin:
Op = AtomicRMWInst::UMin;
break;
case Intrinsic::amdgcn_buffer_atomic_smax:
case Intrinsic::amdgcn_struct_buffer_atomic_smax:
case Intrinsic::amdgcn_raw_buffer_atomic_smax:
Op = AtomicRMWInst::Max;
break;
case Intrinsic::amdgcn_buffer_atomic_umax:
case Intrinsic::amdgcn_struct_buffer_atomic_umax:
case Intrinsic::amdgcn_raw_buffer_atomic_umax:
Op = AtomicRMWInst::UMax;
break;
}
const unsigned ValIdx = 0;
const bool ValDivergent = DA->isDivergentUse(&I.getOperandUse(ValIdx));
if (ValDivergent &&
(!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
return;
}
for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
if (DA->isDivergentUse(&I.getOperandUse(Idx))) {
return;
}
}
const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
ToReplace.push_back(Info);
}
static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
Value *LHS, Value *RHS) {
CmpInst::Predicate Pred;
switch (Op) {
default:
llvm_unreachable("Unhandled atomic op");
case AtomicRMWInst::Add:
return B.CreateBinOp(Instruction::Add, LHS, RHS);
case AtomicRMWInst::Sub:
return B.CreateBinOp(Instruction::Sub, LHS, RHS);
case AtomicRMWInst::And:
return B.CreateBinOp(Instruction::And, LHS, RHS);
case AtomicRMWInst::Or:
return B.CreateBinOp(Instruction::Or, LHS, RHS);
case AtomicRMWInst::Xor:
return B.CreateBinOp(Instruction::Xor, LHS, RHS);
case AtomicRMWInst::Max:
Pred = CmpInst::ICMP_SGT;
break;
case AtomicRMWInst::Min:
Pred = CmpInst::ICMP_SLT;
break;
case AtomicRMWInst::UMax:
Pred = CmpInst::ICMP_UGT;
break;
case AtomicRMWInst::UMin:
Pred = CmpInst::ICMP_ULT;
break;
}
Value *Cond = B.CreateICmp(Pred, LHS, RHS);
return B.CreateSelect(Cond, LHS, RHS);
}
Value *AMDGPUAtomicOptimizer::buildReduction(IRBuilder<> &B,
AtomicRMWInst::BinOp Op, Value *V,
Value *const Identity) const {
Type *const Ty = V->getType();
Module *M = B.GetInsertBlock()->getModule();
Function *UpdateDPP =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, Ty);
for (unsigned Idx = 0; Idx < 4; Idx++) {
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::ROW_XMASK0 | 1 << Idx),
B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
}
assert(ST->hasPermLaneX16());
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateIntrinsic(
Intrinsic::amdgcn_permlanex16, {},
{V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()}));
if (ST->isWave32())
return V;
if (ST->hasPermLane64()) {
return buildNonAtomicBinOp(
B, Op, V, B.CreateIntrinsic(Intrinsic::amdgcn_permlane64, {}, V));
}
Function *ReadLane =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
Value *const Lane0 = B.CreateCall(ReadLane, {V, B.getInt32(0)});
Value *const Lane32 = B.CreateCall(ReadLane, {V, B.getInt32(32)});
return buildNonAtomicBinOp(B, Op, Lane0, Lane32);
}
Value *AMDGPUAtomicOptimizer::buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
Value *V, Value *const Identity) const {
Type *const Ty = V->getType();
Module *M = B.GetInsertBlock()->getModule();
Function *UpdateDPP =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, Ty);
for (unsigned Idx = 0; Idx < 4; Idx++) {
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::ROW_SHR0 | 1 << Idx),
B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
}
if (ST->hasDPPBroadcasts()) {
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::BCAST15), B.getInt32(0xa),
B.getInt32(0xf), B.getFalse()}));
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::BCAST31), B.getInt32(0xc),
B.getInt32(0xf), B.getFalse()}));
} else {
assert(ST->hasPermLaneX16());
Value *const PermX = B.CreateIntrinsic(
Intrinsic::amdgcn_permlanex16, {},
{V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()});
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, PermX, B.getInt32(DPP::QUAD_PERM_ID),
B.getInt32(0xa), B.getInt32(0xf), B.getFalse()}));
if (!ST->isWave32()) {
Value *const Lane31 = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
{V, B.getInt32(31)});
V = buildNonAtomicBinOp(
B, Op, V,
B.CreateCall(UpdateDPP,
{Identity, Lane31, B.getInt32(DPP::QUAD_PERM_ID),
B.getInt32(0xc), B.getInt32(0xf), B.getFalse()}));
}
}
return V;
}
Value *AMDGPUAtomicOptimizer::buildShiftRight(IRBuilder<> &B, Value *V,
Value *const Identity) const {
Type *const Ty = V->getType();
Module *M = B.GetInsertBlock()->getModule();
Function *UpdateDPP =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, Ty);
if (ST->hasDPPWavefrontShifts()) {
V = B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::WAVE_SHR1), B.getInt32(0xf),
B.getInt32(0xf), B.getFalse()});
} else {
Function *ReadLane =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
Function *WriteLane =
Intrinsic::getDeclaration(M, Intrinsic::amdgcn_writelane, {});
Value *Old = V;
V = B.CreateCall(UpdateDPP,
{Identity, V, B.getInt32(DPP::ROW_SHR0 + 1),
B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
V = B.CreateCall(WriteLane, {B.CreateCall(ReadLane, {Old, B.getInt32(15)}),
B.getInt32(16), V});
if (!ST->isWave32()) {
V = B.CreateCall(
WriteLane,
{B.CreateCall(ReadLane, {Old, B.getInt32(31)}), B.getInt32(32), V});
V = B.CreateCall(
WriteLane,
{B.CreateCall(ReadLane, {Old, B.getInt32(47)}), B.getInt32(48), V});
}
}
return V;
}
static APInt getIdentityValueForAtomicOp(AtomicRMWInst::BinOp Op,
unsigned BitWidth) {
switch (Op) {
default:
llvm_unreachable("Unhandled atomic op");
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub:
case AtomicRMWInst::Or:
case AtomicRMWInst::Xor:
case AtomicRMWInst::UMax:
return APInt::getMinValue(BitWidth);
case AtomicRMWInst::And:
case AtomicRMWInst::UMin:
return APInt::getMaxValue(BitWidth);
case AtomicRMWInst::Max:
return APInt::getSignedMinValue(BitWidth);
case AtomicRMWInst::Min:
return APInt::getSignedMaxValue(BitWidth);
}
}
static Value *buildMul(IRBuilder<> &B, Value *LHS, Value *RHS) {
const ConstantInt *CI = dyn_cast<ConstantInt>(LHS);
return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS);
}
void AMDGPUAtomicOptimizer::optimizeAtomic(Instruction &I,
AtomicRMWInst::BinOp Op,
unsigned ValIdx,
bool ValDivergent) const {
IRBuilder<> B(&I);
BasicBlock *PixelEntryBB = nullptr;
BasicBlock *PixelExitBB = nullptr;
if (IsPixelShader) {
PixelEntryBB = I.getParent();
Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
Instruction *const NonHelperTerminator =
SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
PixelExitBB = I.getParent();
I.moveBefore(NonHelperTerminator);
B.SetInsertPoint(&I);
}
Type *const Ty = I.getType();
const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
auto *const VecTy = FixedVectorType::get(B.getInt32Ty(), 2);
Value *const V = I.getOperand(ValIdx);
Type *const WaveTy = B.getIntNTy(ST->getWavefrontSize());
CallInst *const Ballot =
B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
Value *Mbcnt;
if (ST->isWave32()) {
Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
{Ballot, B.getInt32(0)});
} else {
Value *const BitCast = B.CreateBitCast(Ballot, VecTy);
Value *const ExtractLo = B.CreateExtractElement(BitCast, B.getInt32(0));
Value *const ExtractHi = B.CreateExtractElement(BitCast, B.getInt32(1));
Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
{ExtractLo, B.getInt32(0)});
Mbcnt =
B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {}, {ExtractHi, Mbcnt});
}
Mbcnt = B.CreateIntCast(Mbcnt, Ty, false);
Value *const Identity = B.getInt(getIdentityValueForAtomicOp(Op, TyBitWidth));
Value *ExclScan = nullptr;
Value *NewV = nullptr;
const bool NeedResult = !I.use_empty();
if (ValDivergent) {
NewV = B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, Ty, {V, Identity});
const AtomicRMWInst::BinOp ScanOp =
Op == AtomicRMWInst::Sub ? AtomicRMWInst::Add : Op;
if (!NeedResult && ST->hasPermLaneX16()) {
NewV = buildReduction(B, ScanOp, NewV, Identity);
} else {
NewV = buildScan(B, ScanOp, NewV, Identity);
if (NeedResult)
ExclScan = buildShiftRight(B, NewV, Identity);
Value *const LastLaneIdx = B.getInt32(ST->getWavefrontSize() - 1);
assert(TyBitWidth == 32);
NewV = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
{NewV, LastLaneIdx});
}
NewV = B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, NewV);
} else {
switch (Op) {
default:
llvm_unreachable("Unhandled atomic op");
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub: {
Value *const Ctpop = B.CreateIntCast(
B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
NewV = buildMul(B, V, Ctpop);
break;
}
case AtomicRMWInst::And:
case AtomicRMWInst::Or:
case AtomicRMWInst::Max:
case AtomicRMWInst::Min:
case AtomicRMWInst::UMax:
case AtomicRMWInst::UMin:
NewV = V;
break;
case AtomicRMWInst::Xor:
Value *const Ctpop = B.CreateIntCast(
B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
NewV = buildMul(B, V, B.CreateAnd(Ctpop, 1));
break;
}
}
Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getIntN(TyBitWidth, 0));
BasicBlock *const EntryBB = I.getParent();
Instruction *const SingleLaneTerminator =
SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
B.SetInsertPoint(SingleLaneTerminator);
Instruction *const NewI = I.clone();
B.Insert(NewI);
NewI->setOperand(ValIdx, NewV);
B.SetInsertPoint(&I);
if (NeedResult) {
PHINode *const PHI = B.CreatePHI(Ty, 2);
PHI->addIncoming(UndefValue::get(Ty), EntryBB);
PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
Value *BroadcastI = nullptr;
if (TyBitWidth == 64) {
Value *const ExtractLo = B.CreateTrunc(PHI, B.getInt32Ty());
Value *const ExtractHi =
B.CreateTrunc(B.CreateLShr(PHI, 32), B.getInt32Ty());
CallInst *const ReadFirstLaneLo =
B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractLo);
CallInst *const ReadFirstLaneHi =
B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractHi);
Value *const PartialInsert = B.CreateInsertElement(
UndefValue::get(VecTy), ReadFirstLaneLo, B.getInt32(0));
Value *const Insert =
B.CreateInsertElement(PartialInsert, ReadFirstLaneHi, B.getInt32(1));
BroadcastI = B.CreateBitCast(Insert, Ty);
} else if (TyBitWidth == 32) {
BroadcastI = B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, PHI);
} else {
llvm_unreachable("Unhandled atomic bit width");
}
Value *LaneOffset = nullptr;
if (ValDivergent) {
LaneOffset =
B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, ExclScan);
} else {
switch (Op) {
default:
llvm_unreachable("Unhandled atomic op");
case AtomicRMWInst::Add:
case AtomicRMWInst::Sub:
LaneOffset = buildMul(B, V, Mbcnt);
break;
case AtomicRMWInst::And:
case AtomicRMWInst::Or:
case AtomicRMWInst::Max:
case AtomicRMWInst::Min:
case AtomicRMWInst::UMax:
case AtomicRMWInst::UMin:
LaneOffset = B.CreateSelect(Cond, Identity, V);
break;
case AtomicRMWInst::Xor:
LaneOffset = buildMul(B, V, B.CreateAnd(Mbcnt, 1));
break;
}
}
Value *const Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
if (IsPixelShader) {
B.SetInsertPoint(PixelExitBB->getFirstNonPHI());
PHINode *const PHI = B.CreatePHI(Ty, 2);
PHI->addIncoming(UndefValue::get(Ty), PixelEntryBB);
PHI->addIncoming(Result, I.getParent());
I.replaceAllUsesWith(PHI);
} else {
I.replaceAllUsesWith(Result);
}
}
I.eraseFromParent();
}
INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
"AMDGPU atomic optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
"AMDGPU atomic optimizations", false, false)
FunctionPass *llvm::createAMDGPUAtomicOptimizerPass() {
return new AMDGPUAtomicOptimizer();
}