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