1*0b57cec5SDimitry Andric //===-- AMDGPUAtomicOptimizer.cpp -----------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric /// \file
10*0b57cec5SDimitry Andric /// This pass optimizes atomic operations by using a single lane of a wavefront
11*0b57cec5SDimitry Andric /// to perform the atomic operation, thus reducing contention on that memory
12*0b57cec5SDimitry Andric /// location.
13*0b57cec5SDimitry Andric //
14*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15*0b57cec5SDimitry Andric 
16*0b57cec5SDimitry Andric #include "AMDGPU.h"
17*0b57cec5SDimitry Andric #include "AMDGPUSubtarget.h"
18*0b57cec5SDimitry Andric #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
19*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
20*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
21*0b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
22*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23*0b57cec5SDimitry Andric 
24*0b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-atomic-optimizer"
25*0b57cec5SDimitry Andric 
26*0b57cec5SDimitry Andric using namespace llvm;
27*0b57cec5SDimitry Andric 
28*0b57cec5SDimitry Andric namespace {
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric enum DPP_CTRL {
31*0b57cec5SDimitry Andric   DPP_ROW_SR1 = 0x111,
32*0b57cec5SDimitry Andric   DPP_ROW_SR2 = 0x112,
33*0b57cec5SDimitry Andric   DPP_ROW_SR3 = 0x113,
34*0b57cec5SDimitry Andric   DPP_ROW_SR4 = 0x114,
35*0b57cec5SDimitry Andric   DPP_ROW_SR8 = 0x118,
36*0b57cec5SDimitry Andric   DPP_WF_SR1 = 0x138,
37*0b57cec5SDimitry Andric   DPP_ROW_BCAST15 = 0x142,
38*0b57cec5SDimitry Andric   DPP_ROW_BCAST31 = 0x143
39*0b57cec5SDimitry Andric };
40*0b57cec5SDimitry Andric 
41*0b57cec5SDimitry Andric struct ReplacementInfo {
42*0b57cec5SDimitry Andric   Instruction *I;
43*0b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op;
44*0b57cec5SDimitry Andric   unsigned ValIdx;
45*0b57cec5SDimitry Andric   bool ValDivergent;
46*0b57cec5SDimitry Andric };
47*0b57cec5SDimitry Andric 
48*0b57cec5SDimitry Andric class AMDGPUAtomicOptimizer : public FunctionPass,
49*0b57cec5SDimitry Andric                               public InstVisitor<AMDGPUAtomicOptimizer> {
50*0b57cec5SDimitry Andric private:
51*0b57cec5SDimitry Andric   SmallVector<ReplacementInfo, 8> ToReplace;
52*0b57cec5SDimitry Andric   const LegacyDivergenceAnalysis *DA;
53*0b57cec5SDimitry Andric   const DataLayout *DL;
54*0b57cec5SDimitry Andric   DominatorTree *DT;
55*0b57cec5SDimitry Andric   bool HasDPP;
56*0b57cec5SDimitry Andric   bool IsPixelShader;
57*0b57cec5SDimitry Andric 
58*0b57cec5SDimitry Andric   void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
59*0b57cec5SDimitry Andric                       bool ValDivergent) const;
60*0b57cec5SDimitry Andric 
61*0b57cec5SDimitry Andric public:
62*0b57cec5SDimitry Andric   static char ID;
63*0b57cec5SDimitry Andric 
64*0b57cec5SDimitry Andric   AMDGPUAtomicOptimizer() : FunctionPass(ID) {}
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric   bool runOnFunction(Function &F) override;
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
69*0b57cec5SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
70*0b57cec5SDimitry Andric     AU.addRequired<LegacyDivergenceAnalysis>();
71*0b57cec5SDimitry Andric     AU.addRequired<TargetPassConfig>();
72*0b57cec5SDimitry Andric   }
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &I);
75*0b57cec5SDimitry Andric   void visitIntrinsicInst(IntrinsicInst &I);
76*0b57cec5SDimitry Andric };
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric } // namespace
79*0b57cec5SDimitry Andric 
80*0b57cec5SDimitry Andric char AMDGPUAtomicOptimizer::ID = 0;
81*0b57cec5SDimitry Andric 
82*0b57cec5SDimitry Andric char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
83*0b57cec5SDimitry Andric 
84*0b57cec5SDimitry Andric bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
85*0b57cec5SDimitry Andric   if (skipFunction(F)) {
86*0b57cec5SDimitry Andric     return false;
87*0b57cec5SDimitry Andric   }
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric   DA = &getAnalysis<LegacyDivergenceAnalysis>();
90*0b57cec5SDimitry Andric   DL = &F.getParent()->getDataLayout();
91*0b57cec5SDimitry Andric   DominatorTreeWrapperPass *const DTW =
92*0b57cec5SDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
93*0b57cec5SDimitry Andric   DT = DTW ? &DTW->getDomTree() : nullptr;
94*0b57cec5SDimitry Andric   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
95*0b57cec5SDimitry Andric   const TargetMachine &TM = TPC.getTM<TargetMachine>();
96*0b57cec5SDimitry Andric   const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
97*0b57cec5SDimitry Andric   HasDPP = ST.hasDPP();
98*0b57cec5SDimitry Andric   IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
99*0b57cec5SDimitry Andric 
100*0b57cec5SDimitry Andric   visit(F);
101*0b57cec5SDimitry Andric 
102*0b57cec5SDimitry Andric   const bool Changed = !ToReplace.empty();
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric   for (ReplacementInfo &Info : ToReplace) {
105*0b57cec5SDimitry Andric     optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
106*0b57cec5SDimitry Andric   }
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric   ToReplace.clear();
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric   return Changed;
111*0b57cec5SDimitry Andric }
112*0b57cec5SDimitry Andric 
113*0b57cec5SDimitry Andric void AMDGPUAtomicOptimizer::visitAtomicRMWInst(AtomicRMWInst &I) {
114*0b57cec5SDimitry Andric   // Early exit for unhandled address space atomic instructions.
115*0b57cec5SDimitry Andric   switch (I.getPointerAddressSpace()) {
116*0b57cec5SDimitry Andric   default:
117*0b57cec5SDimitry Andric     return;
118*0b57cec5SDimitry Andric   case AMDGPUAS::GLOBAL_ADDRESS:
119*0b57cec5SDimitry Andric   case AMDGPUAS::LOCAL_ADDRESS:
120*0b57cec5SDimitry Andric     break;
121*0b57cec5SDimitry Andric   }
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op = I.getOperation();
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric   switch (Op) {
126*0b57cec5SDimitry Andric   default:
127*0b57cec5SDimitry Andric     return;
128*0b57cec5SDimitry Andric   case AtomicRMWInst::Add:
129*0b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
130*0b57cec5SDimitry Andric   case AtomicRMWInst::And:
131*0b57cec5SDimitry Andric   case AtomicRMWInst::Or:
132*0b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
133*0b57cec5SDimitry Andric   case AtomicRMWInst::Max:
134*0b57cec5SDimitry Andric   case AtomicRMWInst::Min:
135*0b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
136*0b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
137*0b57cec5SDimitry Andric     break;
138*0b57cec5SDimitry Andric   }
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric   const unsigned PtrIdx = 0;
141*0b57cec5SDimitry Andric   const unsigned ValIdx = 1;
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric   // If the pointer operand is divergent, then each lane is doing an atomic
144*0b57cec5SDimitry Andric   // operation on a different address, and we cannot optimize that.
145*0b57cec5SDimitry Andric   if (DA->isDivergent(I.getOperand(PtrIdx))) {
146*0b57cec5SDimitry Andric     return;
147*0b57cec5SDimitry Andric   }
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric   const bool ValDivergent = DA->isDivergent(I.getOperand(ValIdx));
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
152*0b57cec5SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
153*0b57cec5SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
154*0b57cec5SDimitry Andric   // bits.
155*0b57cec5SDimitry Andric   if (ValDivergent && (!HasDPP || (DL->getTypeSizeInBits(I.getType()) != 32))) {
156*0b57cec5SDimitry Andric     return;
157*0b57cec5SDimitry Andric   }
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
160*0b57cec5SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
161*0b57cec5SDimitry Andric   // remember the instruction so we can come back to it.
162*0b57cec5SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric   ToReplace.push_back(Info);
165*0b57cec5SDimitry Andric }
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric void AMDGPUAtomicOptimizer::visitIntrinsicInst(IntrinsicInst &I) {
168*0b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op;
169*0b57cec5SDimitry Andric 
170*0b57cec5SDimitry Andric   switch (I.getIntrinsicID()) {
171*0b57cec5SDimitry Andric   default:
172*0b57cec5SDimitry Andric     return;
173*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_add:
174*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_add:
175*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_add:
176*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Add;
177*0b57cec5SDimitry Andric     break;
178*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_sub:
179*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
180*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
181*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Sub;
182*0b57cec5SDimitry Andric     break;
183*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_and:
184*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_and:
185*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_and:
186*0b57cec5SDimitry Andric     Op = AtomicRMWInst::And;
187*0b57cec5SDimitry Andric     break;
188*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_or:
189*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_or:
190*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_or:
191*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Or;
192*0b57cec5SDimitry Andric     break;
193*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_xor:
194*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
195*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
196*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Xor;
197*0b57cec5SDimitry Andric     break;
198*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_smin:
199*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
200*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
201*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Min;
202*0b57cec5SDimitry Andric     break;
203*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_umin:
204*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
205*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
206*0b57cec5SDimitry Andric     Op = AtomicRMWInst::UMin;
207*0b57cec5SDimitry Andric     break;
208*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_smax:
209*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
210*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
211*0b57cec5SDimitry Andric     Op = AtomicRMWInst::Max;
212*0b57cec5SDimitry Andric     break;
213*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_umax:
214*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
215*0b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
216*0b57cec5SDimitry Andric     Op = AtomicRMWInst::UMax;
217*0b57cec5SDimitry Andric     break;
218*0b57cec5SDimitry Andric   }
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric   const unsigned ValIdx = 0;
221*0b57cec5SDimitry Andric 
222*0b57cec5SDimitry Andric   const bool ValDivergent = DA->isDivergent(I.getOperand(ValIdx));
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
225*0b57cec5SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
226*0b57cec5SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
227*0b57cec5SDimitry Andric   // bits.
228*0b57cec5SDimitry Andric   if (ValDivergent && (!HasDPP || (DL->getTypeSizeInBits(I.getType()) != 32))) {
229*0b57cec5SDimitry Andric     return;
230*0b57cec5SDimitry Andric   }
231*0b57cec5SDimitry Andric 
232*0b57cec5SDimitry Andric   // If any of the other arguments to the intrinsic are divergent, we can't
233*0b57cec5SDimitry Andric   // optimize the operation.
234*0b57cec5SDimitry Andric   for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
235*0b57cec5SDimitry Andric     if (DA->isDivergent(I.getOperand(Idx))) {
236*0b57cec5SDimitry Andric       return;
237*0b57cec5SDimitry Andric     }
238*0b57cec5SDimitry Andric   }
239*0b57cec5SDimitry Andric 
240*0b57cec5SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
241*0b57cec5SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
242*0b57cec5SDimitry Andric   // remember the instruction so we can come back to it.
243*0b57cec5SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
244*0b57cec5SDimitry Andric 
245*0b57cec5SDimitry Andric   ToReplace.push_back(Info);
246*0b57cec5SDimitry Andric }
247*0b57cec5SDimitry Andric 
248*0b57cec5SDimitry Andric // Use the builder to create the non-atomic counterpart of the specified
249*0b57cec5SDimitry Andric // atomicrmw binary op.
250*0b57cec5SDimitry Andric static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
251*0b57cec5SDimitry Andric                                   Value *LHS, Value *RHS) {
252*0b57cec5SDimitry Andric   CmpInst::Predicate Pred;
253*0b57cec5SDimitry Andric 
254*0b57cec5SDimitry Andric   switch (Op) {
255*0b57cec5SDimitry Andric   default:
256*0b57cec5SDimitry Andric     llvm_unreachable("Unhandled atomic op");
257*0b57cec5SDimitry Andric   case AtomicRMWInst::Add:
258*0b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Add, LHS, RHS);
259*0b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
260*0b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Sub, LHS, RHS);
261*0b57cec5SDimitry Andric   case AtomicRMWInst::And:
262*0b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::And, LHS, RHS);
263*0b57cec5SDimitry Andric   case AtomicRMWInst::Or:
264*0b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Or, LHS, RHS);
265*0b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
266*0b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Xor, LHS, RHS);
267*0b57cec5SDimitry Andric 
268*0b57cec5SDimitry Andric   case AtomicRMWInst::Max:
269*0b57cec5SDimitry Andric     Pred = CmpInst::ICMP_SGT;
270*0b57cec5SDimitry Andric     break;
271*0b57cec5SDimitry Andric   case AtomicRMWInst::Min:
272*0b57cec5SDimitry Andric     Pred = CmpInst::ICMP_SLT;
273*0b57cec5SDimitry Andric     break;
274*0b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
275*0b57cec5SDimitry Andric     Pred = CmpInst::ICMP_UGT;
276*0b57cec5SDimitry Andric     break;
277*0b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
278*0b57cec5SDimitry Andric     Pred = CmpInst::ICMP_ULT;
279*0b57cec5SDimitry Andric     break;
280*0b57cec5SDimitry Andric   }
281*0b57cec5SDimitry Andric   Value *Cond = B.CreateICmp(Pred, LHS, RHS);
282*0b57cec5SDimitry Andric   return B.CreateSelect(Cond, LHS, RHS);
283*0b57cec5SDimitry Andric }
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric static APInt getIdentityValueForAtomicOp(AtomicRMWInst::BinOp Op,
286*0b57cec5SDimitry Andric                                          unsigned BitWidth) {
287*0b57cec5SDimitry Andric   switch (Op) {
288*0b57cec5SDimitry Andric   default:
289*0b57cec5SDimitry Andric     llvm_unreachable("Unhandled atomic op");
290*0b57cec5SDimitry Andric   case AtomicRMWInst::Add:
291*0b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
292*0b57cec5SDimitry Andric   case AtomicRMWInst::Or:
293*0b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
294*0b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
295*0b57cec5SDimitry Andric     return APInt::getMinValue(BitWidth);
296*0b57cec5SDimitry Andric   case AtomicRMWInst::And:
297*0b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
298*0b57cec5SDimitry Andric     return APInt::getMaxValue(BitWidth);
299*0b57cec5SDimitry Andric   case AtomicRMWInst::Max:
300*0b57cec5SDimitry Andric     return APInt::getSignedMinValue(BitWidth);
301*0b57cec5SDimitry Andric   case AtomicRMWInst::Min:
302*0b57cec5SDimitry Andric     return APInt::getSignedMaxValue(BitWidth);
303*0b57cec5SDimitry Andric   }
304*0b57cec5SDimitry Andric }
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric void AMDGPUAtomicOptimizer::optimizeAtomic(Instruction &I,
307*0b57cec5SDimitry Andric                                            AtomicRMWInst::BinOp Op,
308*0b57cec5SDimitry Andric                                            unsigned ValIdx,
309*0b57cec5SDimitry Andric                                            bool ValDivergent) const {
310*0b57cec5SDimitry Andric   // Start building just before the instruction.
311*0b57cec5SDimitry Andric   IRBuilder<> B(&I);
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric   // If we are in a pixel shader, because of how we have to mask out helper
314*0b57cec5SDimitry Andric   // lane invocations, we need to record the entry and exit BB's.
315*0b57cec5SDimitry Andric   BasicBlock *PixelEntryBB = nullptr;
316*0b57cec5SDimitry Andric   BasicBlock *PixelExitBB = nullptr;
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric   // If we're optimizing an atomic within a pixel shader, we need to wrap the
319*0b57cec5SDimitry Andric   // entire atomic operation in a helper-lane check. We do not want any helper
320*0b57cec5SDimitry Andric   // lanes that are around only for the purposes of derivatives to take part
321*0b57cec5SDimitry Andric   // in any cross-lane communication, and we use a branch on whether the lane is
322*0b57cec5SDimitry Andric   // live to do this.
323*0b57cec5SDimitry Andric   if (IsPixelShader) {
324*0b57cec5SDimitry Andric     // Record I's original position as the entry block.
325*0b57cec5SDimitry Andric     PixelEntryBB = I.getParent();
326*0b57cec5SDimitry Andric 
327*0b57cec5SDimitry Andric     Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
328*0b57cec5SDimitry Andric     Instruction *const NonHelperTerminator =
329*0b57cec5SDimitry Andric         SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
330*0b57cec5SDimitry Andric 
331*0b57cec5SDimitry Andric     // Record I's new position as the exit block.
332*0b57cec5SDimitry Andric     PixelExitBB = I.getParent();
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric     I.moveBefore(NonHelperTerminator);
335*0b57cec5SDimitry Andric     B.SetInsertPoint(&I);
336*0b57cec5SDimitry Andric   }
337*0b57cec5SDimitry Andric 
338*0b57cec5SDimitry Andric   Type *const Ty = I.getType();
339*0b57cec5SDimitry Andric   const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
340*0b57cec5SDimitry Andric   Type *const VecTy = VectorType::get(B.getInt32Ty(), 2);
341*0b57cec5SDimitry Andric 
342*0b57cec5SDimitry Andric   // This is the value in the atomic operation we need to combine in order to
343*0b57cec5SDimitry Andric   // reduce the number of atomic operations.
344*0b57cec5SDimitry Andric   Value *const V = I.getOperand(ValIdx);
345*0b57cec5SDimitry Andric 
346*0b57cec5SDimitry Andric   // We need to know how many lanes are active within the wavefront, and we do
347*0b57cec5SDimitry Andric   // this by doing a ballot of active lanes.
348*0b57cec5SDimitry Andric   CallInst *const Ballot = B.CreateIntrinsic(
349*0b57cec5SDimitry Andric       Intrinsic::amdgcn_icmp, {B.getInt64Ty(), B.getInt32Ty()},
350*0b57cec5SDimitry Andric       {B.getInt32(1), B.getInt32(0), B.getInt32(CmpInst::ICMP_NE)});
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric   // We need to know how many lanes are active within the wavefront that are
353*0b57cec5SDimitry Andric   // below us. If we counted each lane linearly starting from 0, a lane is
354*0b57cec5SDimitry Andric   // below us only if its associated index was less than ours. We do this by
355*0b57cec5SDimitry Andric   // using the mbcnt intrinsic.
356*0b57cec5SDimitry Andric   Value *const BitCast = B.CreateBitCast(Ballot, VecTy);
357*0b57cec5SDimitry Andric   Value *const ExtractLo = B.CreateExtractElement(BitCast, B.getInt32(0));
358*0b57cec5SDimitry Andric   Value *const ExtractHi = B.CreateExtractElement(BitCast, B.getInt32(1));
359*0b57cec5SDimitry Andric   CallInst *const PartialMbcnt = B.CreateIntrinsic(
360*0b57cec5SDimitry Andric       Intrinsic::amdgcn_mbcnt_lo, {}, {ExtractLo, B.getInt32(0)});
361*0b57cec5SDimitry Andric   Value *const Mbcnt =
362*0b57cec5SDimitry Andric       B.CreateIntCast(B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {},
363*0b57cec5SDimitry Andric                                         {ExtractHi, PartialMbcnt}),
364*0b57cec5SDimitry Andric                       Ty, false);
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   Value *const Identity = B.getInt(getIdentityValueForAtomicOp(Op, TyBitWidth));
367*0b57cec5SDimitry Andric 
368*0b57cec5SDimitry Andric   Value *ExclScan = nullptr;
369*0b57cec5SDimitry Andric   Value *NewV = nullptr;
370*0b57cec5SDimitry Andric 
371*0b57cec5SDimitry Andric   // If we have a divergent value in each lane, we need to combine the value
372*0b57cec5SDimitry Andric   // using DPP.
373*0b57cec5SDimitry Andric   if (ValDivergent) {
374*0b57cec5SDimitry Andric     // First we need to set all inactive invocations to the identity value, so
375*0b57cec5SDimitry Andric     // that they can correctly contribute to the final result.
376*0b57cec5SDimitry Andric     CallInst *const SetInactive =
377*0b57cec5SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, Ty, {V, Identity});
378*0b57cec5SDimitry Andric 
379*0b57cec5SDimitry Andric     CallInst *const FirstDPP =
380*0b57cec5SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_update_dpp, Ty,
381*0b57cec5SDimitry Andric                           {Identity, SetInactive, B.getInt32(DPP_WF_SR1),
382*0b57cec5SDimitry Andric                            B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
383*0b57cec5SDimitry Andric     ExclScan = FirstDPP;
384*0b57cec5SDimitry Andric 
385*0b57cec5SDimitry Andric     const unsigned Iters = 7;
386*0b57cec5SDimitry Andric     const unsigned DPPCtrl[Iters] = {
387*0b57cec5SDimitry Andric         DPP_ROW_SR1, DPP_ROW_SR2,     DPP_ROW_SR3,    DPP_ROW_SR4,
388*0b57cec5SDimitry Andric         DPP_ROW_SR8, DPP_ROW_BCAST15, DPP_ROW_BCAST31};
389*0b57cec5SDimitry Andric     const unsigned RowMask[Iters] = {0xf, 0xf, 0xf, 0xf, 0xf, 0xa, 0xc};
390*0b57cec5SDimitry Andric     const unsigned BankMask[Iters] = {0xf, 0xf, 0xf, 0xe, 0xc, 0xf, 0xf};
391*0b57cec5SDimitry Andric 
392*0b57cec5SDimitry Andric     // This loop performs an exclusive scan across the wavefront, with all lanes
393*0b57cec5SDimitry Andric     // active (by using the WWM intrinsic).
394*0b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < Iters; Idx++) {
395*0b57cec5SDimitry Andric       Value *const UpdateValue = Idx < 3 ? FirstDPP : ExclScan;
396*0b57cec5SDimitry Andric       CallInst *const DPP = B.CreateIntrinsic(
397*0b57cec5SDimitry Andric           Intrinsic::amdgcn_update_dpp, Ty,
398*0b57cec5SDimitry Andric           {Identity, UpdateValue, B.getInt32(DPPCtrl[Idx]),
399*0b57cec5SDimitry Andric            B.getInt32(RowMask[Idx]), B.getInt32(BankMask[Idx]), B.getFalse()});
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric       ExclScan = buildNonAtomicBinOp(B, Op, ExclScan, DPP);
402*0b57cec5SDimitry Andric     }
403*0b57cec5SDimitry Andric 
404*0b57cec5SDimitry Andric     NewV = buildNonAtomicBinOp(B, Op, SetInactive, ExclScan);
405*0b57cec5SDimitry Andric 
406*0b57cec5SDimitry Andric     // Read the value from the last lane, which has accumlated the values of
407*0b57cec5SDimitry Andric     // each active lane in the wavefront. This will be our new value which we
408*0b57cec5SDimitry Andric     // will provide to the atomic operation.
409*0b57cec5SDimitry Andric     if (TyBitWidth == 64) {
410*0b57cec5SDimitry Andric       Value *const ExtractLo = B.CreateTrunc(NewV, B.getInt32Ty());
411*0b57cec5SDimitry Andric       Value *const ExtractHi =
412*0b57cec5SDimitry Andric           B.CreateTrunc(B.CreateLShr(NewV, B.getInt64(32)), B.getInt32Ty());
413*0b57cec5SDimitry Andric       CallInst *const ReadLaneLo = B.CreateIntrinsic(
414*0b57cec5SDimitry Andric           Intrinsic::amdgcn_readlane, {}, {ExtractLo, B.getInt32(63)});
415*0b57cec5SDimitry Andric       CallInst *const ReadLaneHi = B.CreateIntrinsic(
416*0b57cec5SDimitry Andric           Intrinsic::amdgcn_readlane, {}, {ExtractHi, B.getInt32(63)});
417*0b57cec5SDimitry Andric       Value *const PartialInsert = B.CreateInsertElement(
418*0b57cec5SDimitry Andric           UndefValue::get(VecTy), ReadLaneLo, B.getInt32(0));
419*0b57cec5SDimitry Andric       Value *const Insert =
420*0b57cec5SDimitry Andric           B.CreateInsertElement(PartialInsert, ReadLaneHi, B.getInt32(1));
421*0b57cec5SDimitry Andric       NewV = B.CreateBitCast(Insert, Ty);
422*0b57cec5SDimitry Andric     } else if (TyBitWidth == 32) {
423*0b57cec5SDimitry Andric       NewV = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
424*0b57cec5SDimitry Andric                                {NewV, B.getInt32(63)});
425*0b57cec5SDimitry Andric     } else {
426*0b57cec5SDimitry Andric       llvm_unreachable("Unhandled atomic bit width");
427*0b57cec5SDimitry Andric     }
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric     // Finally mark the readlanes in the WWM section.
430*0b57cec5SDimitry Andric     NewV = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, NewV);
431*0b57cec5SDimitry Andric   } else {
432*0b57cec5SDimitry Andric     switch (Op) {
433*0b57cec5SDimitry Andric     default:
434*0b57cec5SDimitry Andric       llvm_unreachable("Unhandled atomic op");
435*0b57cec5SDimitry Andric 
436*0b57cec5SDimitry Andric     case AtomicRMWInst::Add:
437*0b57cec5SDimitry Andric     case AtomicRMWInst::Sub: {
438*0b57cec5SDimitry Andric       // The new value we will be contributing to the atomic operation is the
439*0b57cec5SDimitry Andric       // old value times the number of active lanes.
440*0b57cec5SDimitry Andric       Value *const Ctpop = B.CreateIntCast(
441*0b57cec5SDimitry Andric           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
442*0b57cec5SDimitry Andric       NewV = B.CreateMul(V, Ctpop);
443*0b57cec5SDimitry Andric       break;
444*0b57cec5SDimitry Andric     }
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric     case AtomicRMWInst::And:
447*0b57cec5SDimitry Andric     case AtomicRMWInst::Or:
448*0b57cec5SDimitry Andric     case AtomicRMWInst::Max:
449*0b57cec5SDimitry Andric     case AtomicRMWInst::Min:
450*0b57cec5SDimitry Andric     case AtomicRMWInst::UMax:
451*0b57cec5SDimitry Andric     case AtomicRMWInst::UMin:
452*0b57cec5SDimitry Andric       // These operations with a uniform value are idempotent: doing the atomic
453*0b57cec5SDimitry Andric       // operation multiple times has the same effect as doing it once.
454*0b57cec5SDimitry Andric       NewV = V;
455*0b57cec5SDimitry Andric       break;
456*0b57cec5SDimitry Andric 
457*0b57cec5SDimitry Andric     case AtomicRMWInst::Xor:
458*0b57cec5SDimitry Andric       // The new value we will be contributing to the atomic operation is the
459*0b57cec5SDimitry Andric       // old value times the parity of the number of active lanes.
460*0b57cec5SDimitry Andric       Value *const Ctpop = B.CreateIntCast(
461*0b57cec5SDimitry Andric           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
462*0b57cec5SDimitry Andric       NewV = B.CreateMul(V, B.CreateAnd(Ctpop, 1));
463*0b57cec5SDimitry Andric       break;
464*0b57cec5SDimitry Andric     }
465*0b57cec5SDimitry Andric   }
466*0b57cec5SDimitry Andric 
467*0b57cec5SDimitry Andric   // We only want a single lane to enter our new control flow, and we do this
468*0b57cec5SDimitry Andric   // by checking if there are any active lanes below us. Only one lane will
469*0b57cec5SDimitry Andric   // have 0 active lanes below us, so that will be the only one to progress.
470*0b57cec5SDimitry Andric   Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getIntN(TyBitWidth, 0));
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   // Store I's original basic block before we split the block.
473*0b57cec5SDimitry Andric   BasicBlock *const EntryBB = I.getParent();
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric   // We need to introduce some new control flow to force a single lane to be
476*0b57cec5SDimitry Andric   // active. We do this by splitting I's basic block at I, and introducing the
477*0b57cec5SDimitry Andric   // new block such that:
478*0b57cec5SDimitry Andric   // entry --> single_lane -\
479*0b57cec5SDimitry Andric   //       \------------------> exit
480*0b57cec5SDimitry Andric   Instruction *const SingleLaneTerminator =
481*0b57cec5SDimitry Andric       SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, DT, nullptr);
482*0b57cec5SDimitry Andric 
483*0b57cec5SDimitry Andric   // Move the IR builder into single_lane next.
484*0b57cec5SDimitry Andric   B.SetInsertPoint(SingleLaneTerminator);
485*0b57cec5SDimitry Andric 
486*0b57cec5SDimitry Andric   // Clone the original atomic operation into single lane, replacing the
487*0b57cec5SDimitry Andric   // original value with our newly created one.
488*0b57cec5SDimitry Andric   Instruction *const NewI = I.clone();
489*0b57cec5SDimitry Andric   B.Insert(NewI);
490*0b57cec5SDimitry Andric   NewI->setOperand(ValIdx, NewV);
491*0b57cec5SDimitry Andric 
492*0b57cec5SDimitry Andric   // Move the IR builder into exit next, and start inserting just before the
493*0b57cec5SDimitry Andric   // original instruction.
494*0b57cec5SDimitry Andric   B.SetInsertPoint(&I);
495*0b57cec5SDimitry Andric 
496*0b57cec5SDimitry Andric   // Create a PHI node to get our new atomic result into the exit block.
497*0b57cec5SDimitry Andric   PHINode *const PHI = B.CreatePHI(Ty, 2);
498*0b57cec5SDimitry Andric   PHI->addIncoming(UndefValue::get(Ty), EntryBB);
499*0b57cec5SDimitry Andric   PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
500*0b57cec5SDimitry Andric 
501*0b57cec5SDimitry Andric   // We need to broadcast the value who was the lowest active lane (the first
502*0b57cec5SDimitry Andric   // lane) to all other lanes in the wavefront. We use an intrinsic for this,
503*0b57cec5SDimitry Andric   // but have to handle 64-bit broadcasts with two calls to this intrinsic.
504*0b57cec5SDimitry Andric   Value *BroadcastI = nullptr;
505*0b57cec5SDimitry Andric 
506*0b57cec5SDimitry Andric   if (TyBitWidth == 64) {
507*0b57cec5SDimitry Andric     Value *const ExtractLo = B.CreateTrunc(PHI, B.getInt32Ty());
508*0b57cec5SDimitry Andric     Value *const ExtractHi =
509*0b57cec5SDimitry Andric         B.CreateTrunc(B.CreateLShr(PHI, B.getInt64(32)), B.getInt32Ty());
510*0b57cec5SDimitry Andric     CallInst *const ReadFirstLaneLo =
511*0b57cec5SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractLo);
512*0b57cec5SDimitry Andric     CallInst *const ReadFirstLaneHi =
513*0b57cec5SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractHi);
514*0b57cec5SDimitry Andric     Value *const PartialInsert = B.CreateInsertElement(
515*0b57cec5SDimitry Andric         UndefValue::get(VecTy), ReadFirstLaneLo, B.getInt32(0));
516*0b57cec5SDimitry Andric     Value *const Insert =
517*0b57cec5SDimitry Andric         B.CreateInsertElement(PartialInsert, ReadFirstLaneHi, B.getInt32(1));
518*0b57cec5SDimitry Andric     BroadcastI = B.CreateBitCast(Insert, Ty);
519*0b57cec5SDimitry Andric   } else if (TyBitWidth == 32) {
520*0b57cec5SDimitry Andric 
521*0b57cec5SDimitry Andric     BroadcastI = B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, PHI);
522*0b57cec5SDimitry Andric   } else {
523*0b57cec5SDimitry Andric     llvm_unreachable("Unhandled atomic bit width");
524*0b57cec5SDimitry Andric   }
525*0b57cec5SDimitry Andric 
526*0b57cec5SDimitry Andric   // Now that we have the result of our single atomic operation, we need to
527*0b57cec5SDimitry Andric   // get our individual lane's slice into the result. We use the lane offset we
528*0b57cec5SDimitry Andric   // previously calculated combined with the atomic result value we got from the
529*0b57cec5SDimitry Andric   // first lane, to get our lane's index into the atomic result.
530*0b57cec5SDimitry Andric   Value *LaneOffset = nullptr;
531*0b57cec5SDimitry Andric   if (ValDivergent) {
532*0b57cec5SDimitry Andric     LaneOffset = B.CreateIntrinsic(Intrinsic::amdgcn_wwm, Ty, ExclScan);
533*0b57cec5SDimitry Andric   } else {
534*0b57cec5SDimitry Andric     switch (Op) {
535*0b57cec5SDimitry Andric     default:
536*0b57cec5SDimitry Andric       llvm_unreachable("Unhandled atomic op");
537*0b57cec5SDimitry Andric     case AtomicRMWInst::Add:
538*0b57cec5SDimitry Andric     case AtomicRMWInst::Sub:
539*0b57cec5SDimitry Andric       LaneOffset = B.CreateMul(V, Mbcnt);
540*0b57cec5SDimitry Andric       break;
541*0b57cec5SDimitry Andric     case AtomicRMWInst::And:
542*0b57cec5SDimitry Andric     case AtomicRMWInst::Or:
543*0b57cec5SDimitry Andric     case AtomicRMWInst::Max:
544*0b57cec5SDimitry Andric     case AtomicRMWInst::Min:
545*0b57cec5SDimitry Andric     case AtomicRMWInst::UMax:
546*0b57cec5SDimitry Andric     case AtomicRMWInst::UMin:
547*0b57cec5SDimitry Andric       LaneOffset = B.CreateSelect(Cond, Identity, V);
548*0b57cec5SDimitry Andric       break;
549*0b57cec5SDimitry Andric     case AtomicRMWInst::Xor:
550*0b57cec5SDimitry Andric       LaneOffset = B.CreateMul(V, B.CreateAnd(Mbcnt, 1));
551*0b57cec5SDimitry Andric       break;
552*0b57cec5SDimitry Andric     }
553*0b57cec5SDimitry Andric   }
554*0b57cec5SDimitry Andric   Value *const Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
555*0b57cec5SDimitry Andric 
556*0b57cec5SDimitry Andric   if (IsPixelShader) {
557*0b57cec5SDimitry Andric     // Need a final PHI to reconverge to above the helper lane branch mask.
558*0b57cec5SDimitry Andric     B.SetInsertPoint(PixelExitBB->getFirstNonPHI());
559*0b57cec5SDimitry Andric 
560*0b57cec5SDimitry Andric     PHINode *const PHI = B.CreatePHI(Ty, 2);
561*0b57cec5SDimitry Andric     PHI->addIncoming(UndefValue::get(Ty), PixelEntryBB);
562*0b57cec5SDimitry Andric     PHI->addIncoming(Result, I.getParent());
563*0b57cec5SDimitry Andric     I.replaceAllUsesWith(PHI);
564*0b57cec5SDimitry Andric   } else {
565*0b57cec5SDimitry Andric     // Replace the original atomic instruction with the new one.
566*0b57cec5SDimitry Andric     I.replaceAllUsesWith(Result);
567*0b57cec5SDimitry Andric   }
568*0b57cec5SDimitry Andric 
569*0b57cec5SDimitry Andric   // And delete the original.
570*0b57cec5SDimitry Andric   I.eraseFromParent();
571*0b57cec5SDimitry Andric }
572*0b57cec5SDimitry Andric 
573*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
574*0b57cec5SDimitry Andric                       "AMDGPU atomic optimizations", false, false)
575*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
576*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
577*0b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
578*0b57cec5SDimitry Andric                     "AMDGPU atomic optimizations", false, false)
579*0b57cec5SDimitry Andric 
580*0b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUAtomicOptimizerPass() {
581*0b57cec5SDimitry Andric   return new AMDGPUAtomicOptimizer();
582*0b57cec5SDimitry Andric }
583