1*b5893f02SDimitry Andric //===-- AMDGPUAtomicOptimizer.cpp -----------------------------------------===//
2*b5893f02SDimitry Andric //
3*b5893f02SDimitry Andric //                     The LLVM Compiler Infrastructure
4*b5893f02SDimitry Andric //
5*b5893f02SDimitry Andric // This file is distributed under the University of Illinois Open Source
6*b5893f02SDimitry Andric // License. See LICENSE.TXT for details.
7*b5893f02SDimitry Andric //
8*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
9*b5893f02SDimitry Andric //
10*b5893f02SDimitry Andric /// \file
11*b5893f02SDimitry Andric /// This pass optimizes atomic operations by using a single lane of a wavefront
12*b5893f02SDimitry Andric /// to perform the atomic operation, thus reducing contention on that memory
13*b5893f02SDimitry Andric /// location.
14*b5893f02SDimitry Andric //
15*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
16*b5893f02SDimitry Andric 
17*b5893f02SDimitry Andric #include "AMDGPU.h"
18*b5893f02SDimitry Andric #include "AMDGPUSubtarget.h"
19*b5893f02SDimitry Andric #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
20*b5893f02SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
21*b5893f02SDimitry Andric #include "llvm/IR/IRBuilder.h"
22*b5893f02SDimitry Andric #include "llvm/IR/InstVisitor.h"
23*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24*b5893f02SDimitry Andric 
25*b5893f02SDimitry Andric #define DEBUG_TYPE "amdgpu-atomic-optimizer"
26*b5893f02SDimitry Andric 
27*b5893f02SDimitry Andric using namespace llvm;
28*b5893f02SDimitry Andric 
29*b5893f02SDimitry Andric namespace {
30*b5893f02SDimitry Andric 
31*b5893f02SDimitry Andric enum DPP_CTRL {
32*b5893f02SDimitry Andric   DPP_ROW_SR1 = 0x111,
33*b5893f02SDimitry Andric   DPP_ROW_SR2 = 0x112,
34*b5893f02SDimitry Andric   DPP_ROW_SR4 = 0x114,
35*b5893f02SDimitry Andric   DPP_ROW_SR8 = 0x118,
36*b5893f02SDimitry Andric   DPP_WF_SR1 = 0x138,
37*b5893f02SDimitry Andric   DPP_ROW_BCAST15 = 0x142,
38*b5893f02SDimitry Andric   DPP_ROW_BCAST31 = 0x143
39*b5893f02SDimitry Andric };
40*b5893f02SDimitry Andric 
41*b5893f02SDimitry Andric struct ReplacementInfo {
42*b5893f02SDimitry Andric   Instruction *I;
43*b5893f02SDimitry Andric   Instruction::BinaryOps Op;
44*b5893f02SDimitry Andric   unsigned ValIdx;
45*b5893f02SDimitry Andric   bool ValDivergent;
46*b5893f02SDimitry Andric };
47*b5893f02SDimitry Andric 
48*b5893f02SDimitry Andric class AMDGPUAtomicOptimizer : public FunctionPass,
49*b5893f02SDimitry Andric                               public InstVisitor<AMDGPUAtomicOptimizer> {
50*b5893f02SDimitry Andric private:
51*b5893f02SDimitry Andric   SmallVector<ReplacementInfo, 8> ToReplace;
52*b5893f02SDimitry Andric   const LegacyDivergenceAnalysis *DA;
53*b5893f02SDimitry Andric   const DataLayout *DL;
54*b5893f02SDimitry Andric   DominatorTree *DT;
55*b5893f02SDimitry Andric   bool HasDPP;
56*b5893f02SDimitry Andric   bool IsPixelShader;
57*b5893f02SDimitry Andric 
58*b5893f02SDimitry Andric   void optimizeAtomic(Instruction &I, Instruction::BinaryOps Op,
59*b5893f02SDimitry Andric                       unsigned ValIdx, bool ValDivergent) const;
60*b5893f02SDimitry Andric 
61*b5893f02SDimitry Andric   void setConvergent(CallInst *const CI) const;
62*b5893f02SDimitry Andric 
63*b5893f02SDimitry Andric public:
64*b5893f02SDimitry Andric   static char ID;
65*b5893f02SDimitry Andric 
AMDGPUAtomicOptimizer()66*b5893f02SDimitry Andric   AMDGPUAtomicOptimizer() : FunctionPass(ID) {}
67*b5893f02SDimitry Andric 
68*b5893f02SDimitry Andric   bool runOnFunction(Function &F) override;
69*b5893f02SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const70*b5893f02SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
71*b5893f02SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
72*b5893f02SDimitry Andric     AU.addRequired<LegacyDivergenceAnalysis>();
73*b5893f02SDimitry Andric     AU.addRequired<TargetPassConfig>();
74*b5893f02SDimitry Andric   }
75*b5893f02SDimitry Andric 
76*b5893f02SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &I);
77*b5893f02SDimitry Andric   void visitIntrinsicInst(IntrinsicInst &I);
78*b5893f02SDimitry Andric };
79*b5893f02SDimitry Andric 
80*b5893f02SDimitry Andric } // namespace
81*b5893f02SDimitry Andric 
82*b5893f02SDimitry Andric char AMDGPUAtomicOptimizer::ID = 0;
83*b5893f02SDimitry Andric 
84*b5893f02SDimitry Andric char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
85*b5893f02SDimitry Andric 
runOnFunction(Function & F)86*b5893f02SDimitry Andric bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
87*b5893f02SDimitry Andric   if (skipFunction(F)) {
88*b5893f02SDimitry Andric     return false;
89*b5893f02SDimitry Andric   }
90*b5893f02SDimitry Andric 
91*b5893f02SDimitry Andric   DA = &getAnalysis<LegacyDivergenceAnalysis>();
92*b5893f02SDimitry Andric   DL = &F.getParent()->getDataLayout();
93*b5893f02SDimitry Andric   DominatorTreeWrapperPass *const DTW =
94*b5893f02SDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
95*b5893f02SDimitry Andric   DT = DTW ? &DTW->getDomTree() : nullptr;
96*b5893f02SDimitry Andric   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
97*b5893f02SDimitry Andric   const TargetMachine &TM = TPC.getTM<TargetMachine>();
98*b5893f02SDimitry Andric   const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
99*b5893f02SDimitry Andric   HasDPP = ST.hasDPP();
100*b5893f02SDimitry Andric   IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
101*b5893f02SDimitry Andric 
102*b5893f02SDimitry Andric   visit(F);
103*b5893f02SDimitry Andric 
104*b5893f02SDimitry Andric   const bool Changed = !ToReplace.empty();
105*b5893f02SDimitry Andric 
106*b5893f02SDimitry Andric   for (ReplacementInfo &Info : ToReplace) {
107*b5893f02SDimitry Andric     optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
108*b5893f02SDimitry Andric   }
109*b5893f02SDimitry Andric 
110*b5893f02SDimitry Andric   ToReplace.clear();
111*b5893f02SDimitry Andric 
112*b5893f02SDimitry Andric   return Changed;
113*b5893f02SDimitry Andric }
114*b5893f02SDimitry Andric 
visitAtomicRMWInst(AtomicRMWInst & I)115*b5893f02SDimitry Andric void AMDGPUAtomicOptimizer::visitAtomicRMWInst(AtomicRMWInst &I) {
116*b5893f02SDimitry Andric   // Early exit for unhandled address space atomic instructions.
117*b5893f02SDimitry Andric   switch (I.getPointerAddressSpace()) {
118*b5893f02SDimitry Andric   default:
119*b5893f02SDimitry Andric     return;
120*b5893f02SDimitry Andric   case AMDGPUAS::GLOBAL_ADDRESS:
121*b5893f02SDimitry Andric   case AMDGPUAS::LOCAL_ADDRESS:
122*b5893f02SDimitry Andric     break;
123*b5893f02SDimitry Andric   }
124*b5893f02SDimitry Andric 
125*b5893f02SDimitry Andric   Instruction::BinaryOps Op;
126*b5893f02SDimitry Andric 
127*b5893f02SDimitry Andric   switch (I.getOperation()) {
128*b5893f02SDimitry Andric   default:
129*b5893f02SDimitry Andric     return;
130*b5893f02SDimitry Andric   case AtomicRMWInst::Add:
131*b5893f02SDimitry Andric     Op = Instruction::Add;
132*b5893f02SDimitry Andric     break;
133*b5893f02SDimitry Andric   case AtomicRMWInst::Sub:
134*b5893f02SDimitry Andric     Op = Instruction::Sub;
135*b5893f02SDimitry Andric     break;
136*b5893f02SDimitry Andric   }
137*b5893f02SDimitry Andric 
138*b5893f02SDimitry Andric   const unsigned PtrIdx = 0;
139*b5893f02SDimitry Andric   const unsigned ValIdx = 1;
140*b5893f02SDimitry Andric 
141*b5893f02SDimitry Andric   // If the pointer operand is divergent, then each lane is doing an atomic
142*b5893f02SDimitry Andric   // operation on a different address, and we cannot optimize that.
143*b5893f02SDimitry Andric   if (DA->isDivergent(I.getOperand(PtrIdx))) {
144*b5893f02SDimitry Andric     return;
145*b5893f02SDimitry Andric   }
146*b5893f02SDimitry Andric 
147*b5893f02SDimitry Andric   const bool ValDivergent = DA->isDivergent(I.getOperand(ValIdx));
148*b5893f02SDimitry Andric 
149*b5893f02SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
150*b5893f02SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
151*b5893f02SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
152*b5893f02SDimitry Andric   // bits.
153*b5893f02SDimitry Andric   if (ValDivergent && (!HasDPP || (DL->getTypeSizeInBits(I.getType()) != 32))) {
154*b5893f02SDimitry Andric     return;
155*b5893f02SDimitry Andric   }
156*b5893f02SDimitry Andric 
157*b5893f02SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
158*b5893f02SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
159*b5893f02SDimitry Andric   // remember the instruction so we can come back to it.
160*b5893f02SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
161*b5893f02SDimitry Andric 
162*b5893f02SDimitry Andric   ToReplace.push_back(Info);
163*b5893f02SDimitry Andric }
164*b5893f02SDimitry Andric 
visitIntrinsicInst(IntrinsicInst & I)165*b5893f02SDimitry Andric void AMDGPUAtomicOptimizer::visitIntrinsicInst(IntrinsicInst &I) {
166*b5893f02SDimitry Andric   Instruction::BinaryOps Op;
167*b5893f02SDimitry Andric 
168*b5893f02SDimitry Andric   switch (I.getIntrinsicID()) {
169*b5893f02SDimitry Andric   default:
170*b5893f02SDimitry Andric     return;
171*b5893f02SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_add:
172*b5893f02SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_add:
173*b5893f02SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_add:
174*b5893f02SDimitry Andric     Op = Instruction::Add;
175*b5893f02SDimitry Andric     break;
176*b5893f02SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_sub:
177*b5893f02SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
178*b5893f02SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
179*b5893f02SDimitry Andric     Op = Instruction::Sub;
180*b5893f02SDimitry Andric     break;
181*b5893f02SDimitry Andric   }
182*b5893f02SDimitry Andric 
183*b5893f02SDimitry Andric   const unsigned ValIdx = 0;
184*b5893f02SDimitry Andric 
185*b5893f02SDimitry Andric   const bool ValDivergent = DA->isDivergent(I.getOperand(ValIdx));
186*b5893f02SDimitry Andric 
187*b5893f02SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
188*b5893f02SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
189*b5893f02SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
190*b5893f02SDimitry Andric   // bits.
191*b5893f02SDimitry Andric   if (ValDivergent && (!HasDPP || (DL->getTypeSizeInBits(I.getType()) != 32))) {
192*b5893f02SDimitry Andric     return;
193*b5893f02SDimitry Andric   }
194*b5893f02SDimitry Andric 
195*b5893f02SDimitry Andric   // If any of the other arguments to the intrinsic are divergent, we can't
196*b5893f02SDimitry Andric   // optimize the operation.
197*b5893f02SDimitry Andric   for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
198*b5893f02SDimitry Andric     if (DA->isDivergent(I.getOperand(Idx))) {
199*b5893f02SDimitry Andric       return;
200*b5893f02SDimitry Andric     }
201*b5893f02SDimitry Andric   }
202*b5893f02SDimitry Andric 
203*b5893f02SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
204*b5893f02SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
205*b5893f02SDimitry Andric   // remember the instruction so we can come back to it.
206*b5893f02SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
207*b5893f02SDimitry Andric 
208*b5893f02SDimitry Andric   ToReplace.push_back(Info);
209*b5893f02SDimitry Andric }
210*b5893f02SDimitry Andric 
optimizeAtomic(Instruction & I,Instruction::BinaryOps Op,unsigned ValIdx,bool ValDivergent) const211*b5893f02SDimitry Andric void AMDGPUAtomicOptimizer::optimizeAtomic(Instruction &I,
212*b5893f02SDimitry Andric                                            Instruction::BinaryOps Op,
213*b5893f02SDimitry Andric                                            unsigned ValIdx,
214*b5893f02SDimitry Andric                                            bool ValDivergent) const {
215*b5893f02SDimitry Andric   LLVMContext &Context = I.getContext();
216*b5893f02SDimitry Andric 
217*b5893f02SDimitry Andric   // Start building just before the instruction.
218*b5893f02SDimitry Andric   IRBuilder<> B(&I);
219*b5893f02SDimitry Andric 
220*b5893f02SDimitry Andric   // If we are in a pixel shader, because of how we have to mask out helper
221*b5893f02SDimitry Andric   // lane invocations, we need to record the entry and exit BB's.
222*b5893f02SDimitry Andric   BasicBlock *PixelEntryBB = nullptr;
223*b5893f02SDimitry Andric   BasicBlock *PixelExitBB = nullptr;
224*b5893f02SDimitry Andric 
225*b5893f02SDimitry Andric   // If we're optimizing an atomic within a pixel shader, we need to wrap the
226*b5893f02SDimitry Andric   // entire atomic operation in a helper-lane check. We do not want any helper
227*b5893f02SDimitry Andric   // lanes that are around only for the purposes of derivatives to take part
228*b5893f02SDimitry Andric   // in any cross-lane communication, and we use a branch on whether the lane is
229*b5893f02SDimitry Andric   // live to do this.
230*b5893f02SDimitry Andric   if (IsPixelShader) {
231*b5893f02SDimitry Andric     // Record I's original position as the entry block.
232*b5893f02SDimitry Andric     PixelEntryBB = I.getParent();
233*b5893f02SDimitry Andric 
234*b5893f02SDimitry Andric     Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
235*b5893f02SDimitry Andric     Instruction *const NonHelperTerminator =
236*b5893f02SDimitry Andric         SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
237*b5893f02SDimitry Andric 
238*b5893f02SDimitry Andric     // Record I's new position as the exit block.
239*b5893f02SDimitry Andric     PixelExitBB = I.getParent();
240*b5893f02SDimitry Andric 
241*b5893f02SDimitry Andric     I.moveBefore(NonHelperTerminator);
242*b5893f02SDimitry Andric     B.SetInsertPoint(&I);
243*b5893f02SDimitry Andric   }
244*b5893f02SDimitry Andric 
245*b5893f02SDimitry Andric   Type *const Ty = I.getType();
246*b5893f02SDimitry Andric   const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
247*b5893f02SDimitry Andric   Type *const VecTy = VectorType::get(B.getInt32Ty(), 2);
248*b5893f02SDimitry Andric 
249*b5893f02SDimitry Andric   // This is the value in the atomic operation we need to combine in order to
250*b5893f02SDimitry Andric   // reduce the number of atomic operations.
251*b5893f02SDimitry Andric   Value *const V = I.getOperand(ValIdx);
252*b5893f02SDimitry Andric 
253*b5893f02SDimitry Andric   // We need to know how many lanes are active within the wavefront, and we do
254*b5893f02SDimitry Andric   // this by getting the exec register, which tells us all the lanes that are
255*b5893f02SDimitry Andric   // active.
256*b5893f02SDimitry Andric   MDNode *const RegName =
257*b5893f02SDimitry Andric       llvm::MDNode::get(Context, llvm::MDString::get(Context, "exec"));
258*b5893f02SDimitry Andric   Value *const Metadata = llvm::MetadataAsValue::get(Context, RegName);
259*b5893f02SDimitry Andric   CallInst *const Exec =
260*b5893f02SDimitry Andric       B.CreateIntrinsic(Intrinsic::read_register, {B.getInt64Ty()}, {Metadata});
261*b5893f02SDimitry Andric   setConvergent(Exec);
262*b5893f02SDimitry Andric 
263*b5893f02SDimitry Andric   // We need to know how many lanes are active within the wavefront that are
264*b5893f02SDimitry Andric   // below us. If we counted each lane linearly starting from 0, a lane is
265*b5893f02SDimitry Andric   // below us only if its associated index was less than ours. We do this by
266*b5893f02SDimitry Andric   // using the mbcnt intrinsic.
267*b5893f02SDimitry Andric   Value *const BitCast = B.CreateBitCast(Exec, VecTy);
268*b5893f02SDimitry Andric   Value *const ExtractLo = B.CreateExtractElement(BitCast, B.getInt32(0));
269*b5893f02SDimitry Andric   Value *const ExtractHi = B.CreateExtractElement(BitCast, B.getInt32(1));
270*b5893f02SDimitry Andric   CallInst *const PartialMbcnt = B.CreateIntrinsic(
271*b5893f02SDimitry Andric       Intrinsic::amdgcn_mbcnt_lo, {}, {ExtractLo, B.getInt32(0)});
272*b5893f02SDimitry Andric   CallInst *const Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {},
273*b5893f02SDimitry Andric                                             {ExtractHi, PartialMbcnt});
274*b5893f02SDimitry Andric 
275*b5893f02SDimitry Andric   Value *const MbcntCast = B.CreateIntCast(Mbcnt, Ty, false);
276*b5893f02SDimitry Andric 
277*b5893f02SDimitry Andric   Value *LaneOffset = nullptr;
278*b5893f02SDimitry Andric   Value *NewV = nullptr;
279*b5893f02SDimitry Andric 
280*b5893f02SDimitry Andric   // If we have a divergent value in each lane, we need to combine the value
281*b5893f02SDimitry Andric   // using DPP.
282*b5893f02SDimitry Andric   if (ValDivergent) {
283*b5893f02SDimitry Andric     // First we need to set all inactive invocations to 0, so that they can
284*b5893f02SDimitry Andric     // correctly contribute to the final result.
285*b5893f02SDimitry Andric     CallInst *const SetInactive = B.CreateIntrinsic(
286*b5893f02SDimitry Andric         Intrinsic::amdgcn_set_inactive, Ty, {V, B.getIntN(TyBitWidth, 0)});
287*b5893f02SDimitry Andric     setConvergent(SetInactive);
288*b5893f02SDimitry Andric     NewV = SetInactive;
289*b5893f02SDimitry Andric 
290*b5893f02SDimitry Andric     const unsigned Iters = 6;
291*b5893f02SDimitry Andric     const unsigned DPPCtrl[Iters] = {DPP_ROW_SR1,     DPP_ROW_SR2,
292*b5893f02SDimitry Andric                                      DPP_ROW_SR4,     DPP_ROW_SR8,
293*b5893f02SDimitry Andric                                      DPP_ROW_BCAST15, DPP_ROW_BCAST31};
294*b5893f02SDimitry Andric     const unsigned RowMask[Iters] = {0xf, 0xf, 0xf, 0xf, 0xa, 0xc};
295*b5893f02SDimitry Andric 
296*b5893f02SDimitry Andric     // This loop performs an inclusive scan across the wavefront, with all lanes
297*b5893f02SDimitry Andric     // active (by using the WWM intrinsic).
298*b5893f02SDimitry Andric     for (unsigned Idx = 0; Idx < Iters; Idx++) {
299*b5893f02SDimitry Andric       CallInst *const DPP = B.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp, Ty,
300*b5893f02SDimitry Andric                                               {NewV, B.getInt32(DPPCtrl[Idx]),
301*b5893f02SDimitry Andric                                                B.getInt32(RowMask[Idx]),
302*b5893f02SDimitry Andric                                                B.getInt32(0xf), B.getFalse()});
303*b5893f02SDimitry Andric       setConvergent(DPP);
304*b5893f02SDimitry Andric       Value *const WWM = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, DPP);
305*b5893f02SDimitry Andric 
306*b5893f02SDimitry Andric       NewV = B.CreateBinOp(Op, NewV, WWM);
307*b5893f02SDimitry Andric       NewV = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, NewV);
308*b5893f02SDimitry Andric     }
309*b5893f02SDimitry Andric 
310*b5893f02SDimitry Andric     // NewV has returned the inclusive scan of V, but for the lane offset we
311*b5893f02SDimitry Andric     // require an exclusive scan. We do this by shifting the values from the
312*b5893f02SDimitry Andric     // entire wavefront right by 1, and by setting the bound_ctrl (last argument
313*b5893f02SDimitry Andric     // to the intrinsic below) to true, we can guarantee that 0 will be shifted
314*b5893f02SDimitry Andric     // into the 0'th invocation.
315*b5893f02SDimitry Andric     CallInst *const DPP =
316*b5893f02SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp, {Ty},
317*b5893f02SDimitry Andric                           {NewV, B.getInt32(DPP_WF_SR1), B.getInt32(0xf),
318*b5893f02SDimitry Andric                            B.getInt32(0xf), B.getTrue()});
319*b5893f02SDimitry Andric     setConvergent(DPP);
320*b5893f02SDimitry Andric     LaneOffset = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, DPP);
321*b5893f02SDimitry Andric 
322*b5893f02SDimitry Andric     // Read the value from the last lane, which has accumlated the values of
323*b5893f02SDimitry Andric     // each active lane in the wavefront. This will be our new value with which
324*b5893f02SDimitry Andric     // we will provide to the atomic operation.
325*b5893f02SDimitry Andric     if (TyBitWidth == 64) {
326*b5893f02SDimitry Andric       Value *const ExtractLo = B.CreateTrunc(NewV, B.getInt32Ty());
327*b5893f02SDimitry Andric       Value *const ExtractHi =
328*b5893f02SDimitry Andric           B.CreateTrunc(B.CreateLShr(NewV, B.getInt64(32)), B.getInt32Ty());
329*b5893f02SDimitry Andric       CallInst *const ReadLaneLo = B.CreateIntrinsic(
330*b5893f02SDimitry Andric           Intrinsic::amdgcn_readlane, {}, {ExtractLo, B.getInt32(63)});
331*b5893f02SDimitry Andric       setConvergent(ReadLaneLo);
332*b5893f02SDimitry Andric       CallInst *const ReadLaneHi = B.CreateIntrinsic(
333*b5893f02SDimitry Andric           Intrinsic::amdgcn_readlane, {}, {ExtractHi, B.getInt32(63)});
334*b5893f02SDimitry Andric       setConvergent(ReadLaneHi);
335*b5893f02SDimitry Andric       Value *const PartialInsert = B.CreateInsertElement(
336*b5893f02SDimitry Andric           UndefValue::get(VecTy), ReadLaneLo, B.getInt32(0));
337*b5893f02SDimitry Andric       Value *const Insert =
338*b5893f02SDimitry Andric           B.CreateInsertElement(PartialInsert, ReadLaneHi, B.getInt32(1));
339*b5893f02SDimitry Andric       NewV = B.CreateBitCast(Insert, Ty);
340*b5893f02SDimitry Andric     } else if (TyBitWidth == 32) {
341*b5893f02SDimitry Andric       CallInst *const ReadLane = B.CreateIntrinsic(Intrinsic::amdgcn_readlane,
342*b5893f02SDimitry Andric                                                    {}, {NewV, B.getInt32(63)});
343*b5893f02SDimitry Andric       setConvergent(ReadLane);
344*b5893f02SDimitry Andric       NewV = ReadLane;
345*b5893f02SDimitry Andric     } else {
346*b5893f02SDimitry Andric       llvm_unreachable("Unhandled atomic bit width");
347*b5893f02SDimitry Andric     }
348*b5893f02SDimitry Andric   } else {
349*b5893f02SDimitry Andric     // Get the total number of active lanes we have by using popcount.
350*b5893f02SDimitry Andric     Instruction *const Ctpop = B.CreateUnaryIntrinsic(Intrinsic::ctpop, Exec);
351*b5893f02SDimitry Andric     Value *const CtpopCast = B.CreateIntCast(Ctpop, Ty, false);
352*b5893f02SDimitry Andric 
353*b5893f02SDimitry Andric     // Calculate the new value we will be contributing to the atomic operation
354*b5893f02SDimitry Andric     // for the entire wavefront.
355*b5893f02SDimitry Andric     NewV = B.CreateMul(V, CtpopCast);
356*b5893f02SDimitry Andric     LaneOffset = B.CreateMul(V, MbcntCast);
357*b5893f02SDimitry Andric   }
358*b5893f02SDimitry Andric 
359*b5893f02SDimitry Andric   // We only want a single lane to enter our new control flow, and we do this
360*b5893f02SDimitry Andric   // by checking if there are any active lanes below us. Only one lane will
361*b5893f02SDimitry Andric   // have 0 active lanes below us, so that will be the only one to progress.
362*b5893f02SDimitry Andric   Value *const Cond = B.CreateICmpEQ(MbcntCast, B.getIntN(TyBitWidth, 0));
363*b5893f02SDimitry Andric 
364*b5893f02SDimitry Andric   // Store I's original basic block before we split the block.
365*b5893f02SDimitry Andric   BasicBlock *const EntryBB = I.getParent();
366*b5893f02SDimitry Andric 
367*b5893f02SDimitry Andric   // We need to introduce some new control flow to force a single lane to be
368*b5893f02SDimitry Andric   // active. We do this by splitting I's basic block at I, and introducing the
369*b5893f02SDimitry Andric   // new block such that:
370*b5893f02SDimitry Andric   // entry --> single_lane -\
371*b5893f02SDimitry Andric   //       \------------------> exit
372*b5893f02SDimitry Andric   Instruction *const SingleLaneTerminator =
373*b5893f02SDimitry Andric       SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
374*b5893f02SDimitry Andric 
375*b5893f02SDimitry Andric   // Move the IR builder into single_lane next.
376*b5893f02SDimitry Andric   B.SetInsertPoint(SingleLaneTerminator);
377*b5893f02SDimitry Andric 
378*b5893f02SDimitry Andric   // Clone the original atomic operation into single lane, replacing the
379*b5893f02SDimitry Andric   // original value with our newly created one.
380*b5893f02SDimitry Andric   Instruction *const NewI = I.clone();
381*b5893f02SDimitry Andric   B.Insert(NewI);
382*b5893f02SDimitry Andric   NewI->setOperand(ValIdx, NewV);
383*b5893f02SDimitry Andric 
384*b5893f02SDimitry Andric   // Move the IR builder into exit next, and start inserting just before the
385*b5893f02SDimitry Andric   // original instruction.
386*b5893f02SDimitry Andric   B.SetInsertPoint(&I);
387*b5893f02SDimitry Andric 
388*b5893f02SDimitry Andric   // Create a PHI node to get our new atomic result into the exit block.
389*b5893f02SDimitry Andric   PHINode *const PHI = B.CreatePHI(Ty, 2);
390*b5893f02SDimitry Andric   PHI->addIncoming(UndefValue::get(Ty), EntryBB);
391*b5893f02SDimitry Andric   PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
392*b5893f02SDimitry Andric 
393*b5893f02SDimitry Andric   // We need to broadcast the value who was the lowest active lane (the first
394*b5893f02SDimitry Andric   // lane) to all other lanes in the wavefront. We use an intrinsic for this,
395*b5893f02SDimitry Andric   // but have to handle 64-bit broadcasts with two calls to this intrinsic.
396*b5893f02SDimitry Andric   Value *BroadcastI = nullptr;
397*b5893f02SDimitry Andric 
398*b5893f02SDimitry Andric   if (TyBitWidth == 64) {
399*b5893f02SDimitry Andric     Value *const ExtractLo = B.CreateTrunc(PHI, B.getInt32Ty());
400*b5893f02SDimitry Andric     Value *const ExtractHi =
401*b5893f02SDimitry Andric         B.CreateTrunc(B.CreateLShr(PHI, B.getInt64(32)), B.getInt32Ty());
402*b5893f02SDimitry Andric     CallInst *const ReadFirstLaneLo =
403*b5893f02SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractLo);
404*b5893f02SDimitry Andric     setConvergent(ReadFirstLaneLo);
405*b5893f02SDimitry Andric     CallInst *const ReadFirstLaneHi =
406*b5893f02SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractHi);
407*b5893f02SDimitry Andric     setConvergent(ReadFirstLaneHi);
408*b5893f02SDimitry Andric     Value *const PartialInsert = B.CreateInsertElement(
409*b5893f02SDimitry Andric         UndefValue::get(VecTy), ReadFirstLaneLo, B.getInt32(0));
410*b5893f02SDimitry Andric     Value *const Insert =
411*b5893f02SDimitry Andric         B.CreateInsertElement(PartialInsert, ReadFirstLaneHi, B.getInt32(1));
412*b5893f02SDimitry Andric     BroadcastI = B.CreateBitCast(Insert, Ty);
413*b5893f02SDimitry Andric   } else if (TyBitWidth == 32) {
414*b5893f02SDimitry Andric     CallInst *const ReadFirstLane =
415*b5893f02SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, PHI);
416*b5893f02SDimitry Andric     setConvergent(ReadFirstLane);
417*b5893f02SDimitry Andric     BroadcastI = ReadFirstLane;
418*b5893f02SDimitry Andric   } else {
419*b5893f02SDimitry Andric     llvm_unreachable("Unhandled atomic bit width");
420*b5893f02SDimitry Andric   }
421*b5893f02SDimitry Andric 
422*b5893f02SDimitry Andric   // Now that we have the result of our single atomic operation, we need to
423*b5893f02SDimitry Andric   // get our individual lane's slice into the result. We use the lane offset we
424*b5893f02SDimitry Andric   // previously calculated combined with the atomic result value we got from the
425*b5893f02SDimitry Andric   // first lane, to get our lane's index into the atomic result.
426*b5893f02SDimitry Andric   Value *const Result = B.CreateBinOp(Op, BroadcastI, LaneOffset);
427*b5893f02SDimitry Andric 
428*b5893f02SDimitry Andric   if (IsPixelShader) {
429*b5893f02SDimitry Andric     // Need a final PHI to reconverge to above the helper lane branch mask.
430*b5893f02SDimitry Andric     B.SetInsertPoint(PixelExitBB->getFirstNonPHI());
431*b5893f02SDimitry Andric 
432*b5893f02SDimitry Andric     PHINode *const PHI = B.CreatePHI(Ty, 2);
433*b5893f02SDimitry Andric     PHI->addIncoming(UndefValue::get(Ty), PixelEntryBB);
434*b5893f02SDimitry Andric     PHI->addIncoming(Result, I.getParent());
435*b5893f02SDimitry Andric     I.replaceAllUsesWith(PHI);
436*b5893f02SDimitry Andric   } else {
437*b5893f02SDimitry Andric     // Replace the original atomic instruction with the new one.
438*b5893f02SDimitry Andric     I.replaceAllUsesWith(Result);
439*b5893f02SDimitry Andric   }
440*b5893f02SDimitry Andric 
441*b5893f02SDimitry Andric   // And delete the original.
442*b5893f02SDimitry Andric   I.eraseFromParent();
443*b5893f02SDimitry Andric }
444*b5893f02SDimitry Andric 
setConvergent(CallInst * const CI) const445*b5893f02SDimitry Andric void AMDGPUAtomicOptimizer::setConvergent(CallInst *const CI) const {
446*b5893f02SDimitry Andric   CI->addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
447*b5893f02SDimitry Andric }
448*b5893f02SDimitry Andric 
449*b5893f02SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
450*b5893f02SDimitry Andric                       "AMDGPU atomic optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)451*b5893f02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
452*b5893f02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
453*b5893f02SDimitry Andric INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
454*b5893f02SDimitry Andric                     "AMDGPU atomic optimizations", false, false)
455*b5893f02SDimitry Andric 
456*b5893f02SDimitry Andric FunctionPass *llvm::createAMDGPUAtomicOptimizerPass() {
457*b5893f02SDimitry Andric   return new AMDGPUAtomicOptimizer();
458*b5893f02SDimitry Andric }
459