10b57cec5SDimitry Andric //===-- AMDGPUAtomicOptimizer.cpp -----------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This pass optimizes atomic operations by using a single lane of a wavefront
110b57cec5SDimitry Andric /// to perform the atomic operation, thus reducing contention on that memory
120b57cec5SDimitry Andric /// location.
13fe013be4SDimitry Andric /// Atomic optimizer uses following strategies to compute scan and reduced
14fe013be4SDimitry Andric /// values
15fe013be4SDimitry Andric /// 1. DPP -
16fe013be4SDimitry Andric ///   This is the most efficient implementation for scan. DPP uses Whole Wave
17fe013be4SDimitry Andric ///   Mode (WWM)
18fe013be4SDimitry Andric /// 2. Iterative -
19fe013be4SDimitry Andric //    An alternative implementation iterates over all active lanes
20fe013be4SDimitry Andric ///   of Wavefront using llvm.cttz and performs scan  using readlane & writelane
21fe013be4SDimitry Andric ///   intrinsics
220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric #include "AMDGPU.h"
25e8d8bef9SDimitry Andric #include "GCNSubtarget.h"
26fe013be4SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
27fe013be4SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
290b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
300b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
31e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
32480093f4SDimitry Andric #include "llvm/InitializePasses.h"
33e8d8bef9SDimitry Andric #include "llvm/Target/TargetMachine.h"
340b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-atomic-optimizer"
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric using namespace llvm;
398bcb0991SDimitry Andric using namespace llvm::AMDGPU;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric namespace {
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric struct ReplacementInfo {
440b57cec5SDimitry Andric   Instruction *I;
450b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op;
460b57cec5SDimitry Andric   unsigned ValIdx;
470b57cec5SDimitry Andric   bool ValDivergent;
480b57cec5SDimitry Andric };
490b57cec5SDimitry Andric 
50fe013be4SDimitry Andric class AMDGPUAtomicOptimizer : public FunctionPass {
51fe013be4SDimitry Andric public:
52fe013be4SDimitry Andric   static char ID;
53fe013be4SDimitry Andric   ScanOptions ScanImpl;
AMDGPUAtomicOptimizer(ScanOptions ScanImpl)54fe013be4SDimitry Andric   AMDGPUAtomicOptimizer(ScanOptions ScanImpl)
55fe013be4SDimitry Andric       : FunctionPass(ID), ScanImpl(ScanImpl) {}
56fe013be4SDimitry Andric 
57fe013be4SDimitry Andric   bool runOnFunction(Function &F) override;
58fe013be4SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const59fe013be4SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
60fe013be4SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
61fe013be4SDimitry Andric     AU.addRequired<UniformityInfoWrapperPass>();
62fe013be4SDimitry Andric     AU.addRequired<TargetPassConfig>();
63fe013be4SDimitry Andric   }
64fe013be4SDimitry Andric };
65fe013be4SDimitry Andric 
66fe013be4SDimitry Andric class AMDGPUAtomicOptimizerImpl
67fe013be4SDimitry Andric     : public InstVisitor<AMDGPUAtomicOptimizerImpl> {
680b57cec5SDimitry Andric private:
690b57cec5SDimitry Andric   SmallVector<ReplacementInfo, 8> ToReplace;
70fe013be4SDimitry Andric   const UniformityInfo *UA;
710b57cec5SDimitry Andric   const DataLayout *DL;
72fe013be4SDimitry Andric   DomTreeUpdater &DTU;
738bcb0991SDimitry Andric   const GCNSubtarget *ST;
740b57cec5SDimitry Andric   bool IsPixelShader;
75fe013be4SDimitry Andric   ScanOptions ScanImpl;
760b57cec5SDimitry Andric 
77fe6060f1SDimitry Andric   Value *buildReduction(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
78fe6060f1SDimitry Andric                         Value *const Identity) const;
798bcb0991SDimitry Andric   Value *buildScan(IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *V,
808bcb0991SDimitry Andric                    Value *const Identity) const;
818bcb0991SDimitry Andric   Value *buildShiftRight(IRBuilder<> &B, Value *V, Value *const Identity) const;
82fe013be4SDimitry Andric 
83fe013be4SDimitry Andric   std::pair<Value *, Value *>
84fe013be4SDimitry Andric   buildScanIteratively(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
85fe013be4SDimitry Andric                        Value *const Identity, Value *V, Instruction &I,
86fe013be4SDimitry Andric                        BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const;
87fe013be4SDimitry Andric 
880b57cec5SDimitry Andric   void optimizeAtomic(Instruction &I, AtomicRMWInst::BinOp Op, unsigned ValIdx,
890b57cec5SDimitry Andric                       bool ValDivergent) const;
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric public:
92fe013be4SDimitry Andric   AMDGPUAtomicOptimizerImpl() = delete;
930b57cec5SDimitry Andric 
AMDGPUAtomicOptimizerImpl(const UniformityInfo * UA,const DataLayout * DL,DomTreeUpdater & DTU,const GCNSubtarget * ST,bool IsPixelShader,ScanOptions ScanImpl)94fe013be4SDimitry Andric   AMDGPUAtomicOptimizerImpl(const UniformityInfo *UA, const DataLayout *DL,
95fe013be4SDimitry Andric                             DomTreeUpdater &DTU, const GCNSubtarget *ST,
96fe013be4SDimitry Andric                             bool IsPixelShader, ScanOptions ScanImpl)
97fe013be4SDimitry Andric       : UA(UA), DL(DL), DTU(DTU), ST(ST), IsPixelShader(IsPixelShader),
98fe013be4SDimitry Andric         ScanImpl(ScanImpl) {}
990b57cec5SDimitry Andric 
100fe013be4SDimitry Andric   bool run(Function &F);
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &I);
1030b57cec5SDimitry Andric   void visitIntrinsicInst(IntrinsicInst &I);
1040b57cec5SDimitry Andric };
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric } // namespace
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric char AMDGPUAtomicOptimizer::ID = 0;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric char &llvm::AMDGPUAtomicOptimizerID = AMDGPUAtomicOptimizer::ID;
1110b57cec5SDimitry Andric 
runOnFunction(Function & F)1120b57cec5SDimitry Andric bool AMDGPUAtomicOptimizer::runOnFunction(Function &F) {
1130b57cec5SDimitry Andric   if (skipFunction(F)) {
1140b57cec5SDimitry Andric     return false;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric 
117fe013be4SDimitry Andric   const UniformityInfo *UA =
118fe013be4SDimitry Andric       &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
119fe013be4SDimitry Andric   const DataLayout *DL = &F.getParent()->getDataLayout();
120fe013be4SDimitry Andric 
1210b57cec5SDimitry Andric   DominatorTreeWrapperPass *const DTW =
1220b57cec5SDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
123fe013be4SDimitry Andric   DomTreeUpdater DTU(DTW ? &DTW->getDomTree() : nullptr,
124fe013be4SDimitry Andric                      DomTreeUpdater::UpdateStrategy::Lazy);
125fe013be4SDimitry Andric 
1260b57cec5SDimitry Andric   const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
1270b57cec5SDimitry Andric   const TargetMachine &TM = TPC.getTM<TargetMachine>();
128fe013be4SDimitry Andric   const GCNSubtarget *ST = &TM.getSubtarget<GCNSubtarget>(F);
129fe013be4SDimitry Andric 
130fe013be4SDimitry Andric   bool IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
131fe013be4SDimitry Andric 
132fe013be4SDimitry Andric   return AMDGPUAtomicOptimizerImpl(UA, DL, DTU, ST, IsPixelShader, ScanImpl)
133fe013be4SDimitry Andric       .run(F);
134fe013be4SDimitry Andric }
135fe013be4SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)136fe013be4SDimitry Andric PreservedAnalyses AMDGPUAtomicOptimizerPass::run(Function &F,
137fe013be4SDimitry Andric                                                  FunctionAnalysisManager &AM) {
138fe013be4SDimitry Andric 
139fe013be4SDimitry Andric   const auto *UA = &AM.getResult<UniformityInfoAnalysis>(F);
140fe013be4SDimitry Andric   const DataLayout *DL = &F.getParent()->getDataLayout();
141fe013be4SDimitry Andric 
142fe013be4SDimitry Andric   DomTreeUpdater DTU(&AM.getResult<DominatorTreeAnalysis>(F),
143fe013be4SDimitry Andric                      DomTreeUpdater::UpdateStrategy::Lazy);
144fe013be4SDimitry Andric   const GCNSubtarget *ST = &TM.getSubtarget<GCNSubtarget>(F);
145fe013be4SDimitry Andric 
146fe013be4SDimitry Andric   bool IsPixelShader = F.getCallingConv() == CallingConv::AMDGPU_PS;
147fe013be4SDimitry Andric 
148fe013be4SDimitry Andric   bool IsChanged =
149fe013be4SDimitry Andric       AMDGPUAtomicOptimizerImpl(UA, DL, DTU, ST, IsPixelShader, ScanImpl)
150fe013be4SDimitry Andric           .run(F);
151fe013be4SDimitry Andric 
152fe013be4SDimitry Andric   if (!IsChanged) {
153fe013be4SDimitry Andric     return PreservedAnalyses::all();
154fe013be4SDimitry Andric   }
155fe013be4SDimitry Andric 
156fe013be4SDimitry Andric   PreservedAnalyses PA;
157fe013be4SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
158fe013be4SDimitry Andric   return PA;
159fe013be4SDimitry Andric }
160fe013be4SDimitry Andric 
run(Function & F)161fe013be4SDimitry Andric bool AMDGPUAtomicOptimizerImpl::run(Function &F) {
162fe013be4SDimitry Andric 
163fe013be4SDimitry Andric   // Scan option None disables the Pass
164fe013be4SDimitry Andric   if (ScanImpl == ScanOptions::None) {
165fe013be4SDimitry Andric     return false;
166fe013be4SDimitry Andric   }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   visit(F);
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   const bool Changed = !ToReplace.empty();
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   for (ReplacementInfo &Info : ToReplace) {
1730b57cec5SDimitry Andric     optimizeAtomic(*Info.I, Info.Op, Info.ValIdx, Info.ValDivergent);
1740b57cec5SDimitry Andric   }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   ToReplace.clear();
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   return Changed;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
visitAtomicRMWInst(AtomicRMWInst & I)181fe013be4SDimitry Andric void AMDGPUAtomicOptimizerImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
1820b57cec5SDimitry Andric   // Early exit for unhandled address space atomic instructions.
1830b57cec5SDimitry Andric   switch (I.getPointerAddressSpace()) {
1840b57cec5SDimitry Andric   default:
1850b57cec5SDimitry Andric     return;
1860b57cec5SDimitry Andric   case AMDGPUAS::GLOBAL_ADDRESS:
1870b57cec5SDimitry Andric   case AMDGPUAS::LOCAL_ADDRESS:
1880b57cec5SDimitry Andric     break;
1890b57cec5SDimitry Andric   }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op = I.getOperation();
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   switch (Op) {
1940b57cec5SDimitry Andric   default:
1950b57cec5SDimitry Andric     return;
1960b57cec5SDimitry Andric   case AtomicRMWInst::Add:
1970b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
1980b57cec5SDimitry Andric   case AtomicRMWInst::And:
1990b57cec5SDimitry Andric   case AtomicRMWInst::Or:
2000b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
2010b57cec5SDimitry Andric   case AtomicRMWInst::Max:
2020b57cec5SDimitry Andric   case AtomicRMWInst::Min:
2030b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
2040b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
205*c9157d92SDimitry Andric   case AtomicRMWInst::FAdd:
206*c9157d92SDimitry Andric   case AtomicRMWInst::FSub:
207*c9157d92SDimitry Andric   case AtomicRMWInst::FMax:
208*c9157d92SDimitry Andric   case AtomicRMWInst::FMin:
2090b57cec5SDimitry Andric     break;
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
212*c9157d92SDimitry Andric   // Only 32-bit floating point atomic ops are supported.
213*c9157d92SDimitry Andric   if (AtomicRMWInst::isFPOperation(Op) && !I.getType()->isFloatTy()) {
214*c9157d92SDimitry Andric     return;
215*c9157d92SDimitry Andric   }
216*c9157d92SDimitry Andric 
2170b57cec5SDimitry Andric   const unsigned PtrIdx = 0;
2180b57cec5SDimitry Andric   const unsigned ValIdx = 1;
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   // If the pointer operand is divergent, then each lane is doing an atomic
2210b57cec5SDimitry Andric   // operation on a different address, and we cannot optimize that.
222fe013be4SDimitry Andric   if (UA->isDivergentUse(I.getOperandUse(PtrIdx))) {
2230b57cec5SDimitry Andric     return;
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
226fe013be4SDimitry Andric   const bool ValDivergent = UA->isDivergentUse(I.getOperandUse(ValIdx));
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
2290b57cec5SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
2300b57cec5SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
2310b57cec5SDimitry Andric   // bits.
2328bcb0991SDimitry Andric   if (ValDivergent &&
2338bcb0991SDimitry Andric       (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
2340b57cec5SDimitry Andric     return;
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
2380b57cec5SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
2390b57cec5SDimitry Andric   // remember the instruction so we can come back to it.
2400b57cec5SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   ToReplace.push_back(Info);
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
visitIntrinsicInst(IntrinsicInst & I)245fe013be4SDimitry Andric void AMDGPUAtomicOptimizerImpl::visitIntrinsicInst(IntrinsicInst &I) {
2460b57cec5SDimitry Andric   AtomicRMWInst::BinOp Op;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   switch (I.getIntrinsicID()) {
2490b57cec5SDimitry Andric   default:
2500b57cec5SDimitry Andric     return;
2510b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_add:
2520b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_add:
253fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
2540b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_add:
255fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
2560b57cec5SDimitry Andric     Op = AtomicRMWInst::Add;
2570b57cec5SDimitry Andric     break;
2580b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_sub:
2590b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
260fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
2610b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
262fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
2630b57cec5SDimitry Andric     Op = AtomicRMWInst::Sub;
2640b57cec5SDimitry Andric     break;
2650b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_and:
2660b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_and:
267fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
2680b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_and:
269fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
2700b57cec5SDimitry Andric     Op = AtomicRMWInst::And;
2710b57cec5SDimitry Andric     break;
2720b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_or:
2730b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_or:
274fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
2750b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_or:
276fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
2770b57cec5SDimitry Andric     Op = AtomicRMWInst::Or;
2780b57cec5SDimitry Andric     break;
2790b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_xor:
2800b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
281fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
2820b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
283fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
2840b57cec5SDimitry Andric     Op = AtomicRMWInst::Xor;
2850b57cec5SDimitry Andric     break;
2860b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_smin:
2870b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
288fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
2890b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
290fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
2910b57cec5SDimitry Andric     Op = AtomicRMWInst::Min;
2920b57cec5SDimitry Andric     break;
2930b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_umin:
2940b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
295fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
2960b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
297fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
2980b57cec5SDimitry Andric     Op = AtomicRMWInst::UMin;
2990b57cec5SDimitry Andric     break;
3000b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_smax:
3010b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
302fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
3030b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
304fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
3050b57cec5SDimitry Andric     Op = AtomicRMWInst::Max;
3060b57cec5SDimitry Andric     break;
3070b57cec5SDimitry Andric   case Intrinsic::amdgcn_buffer_atomic_umax:
3080b57cec5SDimitry Andric   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
309fe013be4SDimitry Andric   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
3100b57cec5SDimitry Andric   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
311fe013be4SDimitry Andric   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
3120b57cec5SDimitry Andric     Op = AtomicRMWInst::UMax;
3130b57cec5SDimitry Andric     break;
3140b57cec5SDimitry Andric   }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   const unsigned ValIdx = 0;
3170b57cec5SDimitry Andric 
318fe013be4SDimitry Andric   const bool ValDivergent = UA->isDivergentUse(I.getOperandUse(ValIdx));
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric   // If the value operand is divergent, each lane is contributing a different
3210b57cec5SDimitry Andric   // value to the atomic calculation. We can only optimize divergent values if
3220b57cec5SDimitry Andric   // we have DPP available on our subtarget, and the atomic operation is 32
3230b57cec5SDimitry Andric   // bits.
3248bcb0991SDimitry Andric   if (ValDivergent &&
3258bcb0991SDimitry Andric       (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
3260b57cec5SDimitry Andric     return;
3270b57cec5SDimitry Andric   }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   // If any of the other arguments to the intrinsic are divergent, we can't
3300b57cec5SDimitry Andric   // optimize the operation.
3310b57cec5SDimitry Andric   for (unsigned Idx = 1; Idx < I.getNumOperands(); Idx++) {
332fe013be4SDimitry Andric     if (UA->isDivergentUse(I.getOperandUse(Idx))) {
3330b57cec5SDimitry Andric       return;
3340b57cec5SDimitry Andric     }
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // If we get here, we can optimize the atomic using a single wavefront-wide
3380b57cec5SDimitry Andric   // atomic operation to do the calculation for the entire wavefront, so
3390b57cec5SDimitry Andric   // remember the instruction so we can come back to it.
3400b57cec5SDimitry Andric   const ReplacementInfo Info = {&I, Op, ValIdx, ValDivergent};
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   ToReplace.push_back(Info);
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric // Use the builder to create the non-atomic counterpart of the specified
3460b57cec5SDimitry Andric // atomicrmw binary op.
buildNonAtomicBinOp(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * LHS,Value * RHS)3470b57cec5SDimitry Andric static Value *buildNonAtomicBinOp(IRBuilder<> &B, AtomicRMWInst::BinOp Op,
3480b57cec5SDimitry Andric                                   Value *LHS, Value *RHS) {
3490b57cec5SDimitry Andric   CmpInst::Predicate Pred;
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   switch (Op) {
3520b57cec5SDimitry Andric   default:
3530b57cec5SDimitry Andric     llvm_unreachable("Unhandled atomic op");
3540b57cec5SDimitry Andric   case AtomicRMWInst::Add:
3550b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Add, LHS, RHS);
356*c9157d92SDimitry Andric   case AtomicRMWInst::FAdd:
357*c9157d92SDimitry Andric     return B.CreateFAdd(LHS, RHS);
3580b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
3590b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Sub, LHS, RHS);
360*c9157d92SDimitry Andric   case AtomicRMWInst::FSub:
361*c9157d92SDimitry Andric     return B.CreateFSub(LHS, RHS);
3620b57cec5SDimitry Andric   case AtomicRMWInst::And:
3630b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::And, LHS, RHS);
3640b57cec5SDimitry Andric   case AtomicRMWInst::Or:
3650b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Or, LHS, RHS);
3660b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
3670b57cec5SDimitry Andric     return B.CreateBinOp(Instruction::Xor, LHS, RHS);
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   case AtomicRMWInst::Max:
3700b57cec5SDimitry Andric     Pred = CmpInst::ICMP_SGT;
3710b57cec5SDimitry Andric     break;
3720b57cec5SDimitry Andric   case AtomicRMWInst::Min:
3730b57cec5SDimitry Andric     Pred = CmpInst::ICMP_SLT;
3740b57cec5SDimitry Andric     break;
3750b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
3760b57cec5SDimitry Andric     Pred = CmpInst::ICMP_UGT;
3770b57cec5SDimitry Andric     break;
3780b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
3790b57cec5SDimitry Andric     Pred = CmpInst::ICMP_ULT;
3800b57cec5SDimitry Andric     break;
381*c9157d92SDimitry Andric   case AtomicRMWInst::FMax:
382*c9157d92SDimitry Andric     return B.CreateMaxNum(LHS, RHS);
383*c9157d92SDimitry Andric   case AtomicRMWInst::FMin:
384*c9157d92SDimitry Andric     return B.CreateMinNum(LHS, RHS);
3850b57cec5SDimitry Andric   }
3860b57cec5SDimitry Andric   Value *Cond = B.CreateICmp(Pred, LHS, RHS);
3870b57cec5SDimitry Andric   return B.CreateSelect(Cond, LHS, RHS);
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
390fe6060f1SDimitry Andric // Use the builder to create a reduction of V across the wavefront, with all
391fe6060f1SDimitry Andric // lanes active, returning the same result in all lanes.
buildReduction(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * V,Value * const Identity) const392fe013be4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildReduction(IRBuilder<> &B,
393fe013be4SDimitry Andric                                                  AtomicRMWInst::BinOp Op,
394fe013be4SDimitry Andric                                                  Value *V,
395fe6060f1SDimitry Andric                                                  Value *const Identity) const {
396*c9157d92SDimitry Andric   Type *AtomicTy = V->getType();
397*c9157d92SDimitry Andric   Type *IntNTy = B.getIntNTy(AtomicTy->getPrimitiveSizeInBits());
398fe6060f1SDimitry Andric   Module *M = B.GetInsertBlock()->getModule();
399fe6060f1SDimitry Andric   Function *UpdateDPP =
400*c9157d92SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
401fe6060f1SDimitry Andric 
402fe6060f1SDimitry Andric   // Reduce within each row of 16 lanes.
403fe6060f1SDimitry Andric   for (unsigned Idx = 0; Idx < 4; Idx++) {
404fe6060f1SDimitry Andric     V = buildNonAtomicBinOp(
405fe6060f1SDimitry Andric         B, Op, V,
406fe6060f1SDimitry Andric         B.CreateCall(UpdateDPP,
407fe6060f1SDimitry Andric                      {Identity, V, B.getInt32(DPP::ROW_XMASK0 | 1 << Idx),
408fe6060f1SDimitry Andric                       B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
409fe6060f1SDimitry Andric   }
410fe6060f1SDimitry Andric 
411fe6060f1SDimitry Andric   // Reduce within each pair of rows (i.e. 32 lanes).
412fe6060f1SDimitry Andric   assert(ST->hasPermLaneX16());
413*c9157d92SDimitry Andric   V = B.CreateBitCast(V, IntNTy);
414*c9157d92SDimitry Andric   Value *Permlanex16Call = B.CreateIntrinsic(
415fe6060f1SDimitry Andric       Intrinsic::amdgcn_permlanex16, {},
416*c9157d92SDimitry Andric       {V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()});
417*c9157d92SDimitry Andric   V = buildNonAtomicBinOp(B, Op, B.CreateBitCast(V, AtomicTy),
418*c9157d92SDimitry Andric                           B.CreateBitCast(Permlanex16Call, AtomicTy));
419*c9157d92SDimitry Andric   if (ST->isWave32()) {
420fe6060f1SDimitry Andric     return V;
421*c9157d92SDimitry Andric   }
422fe6060f1SDimitry Andric 
42381ad6265SDimitry Andric   if (ST->hasPermLane64()) {
42481ad6265SDimitry Andric     // Reduce across the upper and lower 32 lanes.
425*c9157d92SDimitry Andric     V = B.CreateBitCast(V, IntNTy);
426*c9157d92SDimitry Andric     Value *Permlane64Call =
427*c9157d92SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_permlane64, {}, V);
428*c9157d92SDimitry Andric     return buildNonAtomicBinOp(B, Op, B.CreateBitCast(V, AtomicTy),
429*c9157d92SDimitry Andric                                B.CreateBitCast(Permlane64Call, AtomicTy));
43081ad6265SDimitry Andric   }
43181ad6265SDimitry Andric 
432fe6060f1SDimitry Andric   // Pick an arbitrary lane from 0..31 and an arbitrary lane from 32..63 and
433fe6060f1SDimitry Andric   // combine them with a scalar operation.
434fe6060f1SDimitry Andric   Function *ReadLane =
435fe6060f1SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
436*c9157d92SDimitry Andric   V = B.CreateBitCast(V, IntNTy);
437*c9157d92SDimitry Andric   Value *Lane0 = B.CreateCall(ReadLane, {V, B.getInt32(0)});
438*c9157d92SDimitry Andric   Value *Lane32 = B.CreateCall(ReadLane, {V, B.getInt32(32)});
439*c9157d92SDimitry Andric   return buildNonAtomicBinOp(B, Op, B.CreateBitCast(Lane0, AtomicTy),
440*c9157d92SDimitry Andric                              B.CreateBitCast(Lane32, AtomicTy));
441fe6060f1SDimitry Andric }
442fe6060f1SDimitry Andric 
4438bcb0991SDimitry Andric // Use the builder to create an inclusive scan of V across the wavefront, with
4448bcb0991SDimitry Andric // all lanes active.
buildScan(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * V,Value * Identity) const445fe013be4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildScan(IRBuilder<> &B,
446fe013be4SDimitry Andric                                             AtomicRMWInst::BinOp Op, Value *V,
447*c9157d92SDimitry Andric                                             Value *Identity) const {
448*c9157d92SDimitry Andric   Type *AtomicTy = V->getType();
449*c9157d92SDimitry Andric   Type *IntNTy = B.getIntNTy(AtomicTy->getPrimitiveSizeInBits());
450*c9157d92SDimitry Andric 
4518bcb0991SDimitry Andric   Module *M = B.GetInsertBlock()->getModule();
4528bcb0991SDimitry Andric   Function *UpdateDPP =
453*c9157d92SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
4548bcb0991SDimitry Andric 
4558bcb0991SDimitry Andric   for (unsigned Idx = 0; Idx < 4; Idx++) {
4568bcb0991SDimitry Andric     V = buildNonAtomicBinOp(
4578bcb0991SDimitry Andric         B, Op, V,
4588bcb0991SDimitry Andric         B.CreateCall(UpdateDPP,
4598bcb0991SDimitry Andric                      {Identity, V, B.getInt32(DPP::ROW_SHR0 | 1 << Idx),
4608bcb0991SDimitry Andric                       B.getInt32(0xf), B.getInt32(0xf), B.getFalse()}));
4618bcb0991SDimitry Andric   }
4628bcb0991SDimitry Andric   if (ST->hasDPPBroadcasts()) {
4638bcb0991SDimitry Andric     // GFX9 has DPP row broadcast operations.
4648bcb0991SDimitry Andric     V = buildNonAtomicBinOp(
4658bcb0991SDimitry Andric         B, Op, V,
4668bcb0991SDimitry Andric         B.CreateCall(UpdateDPP,
4678bcb0991SDimitry Andric                      {Identity, V, B.getInt32(DPP::BCAST15), B.getInt32(0xa),
4688bcb0991SDimitry Andric                       B.getInt32(0xf), B.getFalse()}));
4698bcb0991SDimitry Andric     V = buildNonAtomicBinOp(
4708bcb0991SDimitry Andric         B, Op, V,
4718bcb0991SDimitry Andric         B.CreateCall(UpdateDPP,
4728bcb0991SDimitry Andric                      {Identity, V, B.getInt32(DPP::BCAST31), B.getInt32(0xc),
4738bcb0991SDimitry Andric                       B.getInt32(0xf), B.getFalse()}));
4748bcb0991SDimitry Andric   } else {
4758bcb0991SDimitry Andric     // On GFX10 all DPP operations are confined to a single row. To get cross-
4768bcb0991SDimitry Andric     // row operations we have to use permlane or readlane.
4778bcb0991SDimitry Andric 
4788bcb0991SDimitry Andric     // Combine lane 15 into lanes 16..31 (and, for wave 64, lane 47 into lanes
4798bcb0991SDimitry Andric     // 48..63).
480fe6060f1SDimitry Andric     assert(ST->hasPermLaneX16());
481*c9157d92SDimitry Andric     V = B.CreateBitCast(V, IntNTy);
482*c9157d92SDimitry Andric     Value *PermX = B.CreateIntrinsic(
483fe6060f1SDimitry Andric         Intrinsic::amdgcn_permlanex16, {},
484fe6060f1SDimitry Andric         {V, V, B.getInt32(-1), B.getInt32(-1), B.getFalse(), B.getFalse()});
485*c9157d92SDimitry Andric 
486*c9157d92SDimitry Andric     Value *UpdateDPPCall =
487*c9157d92SDimitry Andric         B.CreateCall(UpdateDPP, {Identity, B.CreateBitCast(PermX, AtomicTy),
488*c9157d92SDimitry Andric                                  B.getInt32(DPP::QUAD_PERM_ID), B.getInt32(0xa),
489*c9157d92SDimitry Andric                                  B.getInt32(0xf), B.getFalse()});
490*c9157d92SDimitry Andric     V = buildNonAtomicBinOp(B, Op, B.CreateBitCast(V, AtomicTy), UpdateDPPCall);
491*c9157d92SDimitry Andric 
4928bcb0991SDimitry Andric     if (!ST->isWave32()) {
4938bcb0991SDimitry Andric       // Combine lane 31 into lanes 32..63.
494*c9157d92SDimitry Andric       V = B.CreateBitCast(V, IntNTy);
495fe6060f1SDimitry Andric       Value *const Lane31 = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
496fe6060f1SDimitry Andric                                               {V, B.getInt32(31)});
497*c9157d92SDimitry Andric 
498*c9157d92SDimitry Andric       Value *UpdateDPPCall = B.CreateCall(
499*c9157d92SDimitry Andric           UpdateDPP, {Identity, Lane31, B.getInt32(DPP::QUAD_PERM_ID),
500*c9157d92SDimitry Andric                       B.getInt32(0xc), B.getInt32(0xf), B.getFalse()});
501*c9157d92SDimitry Andric 
502*c9157d92SDimitry Andric       V = buildNonAtomicBinOp(B, Op, B.CreateBitCast(V, AtomicTy),
503*c9157d92SDimitry Andric                               UpdateDPPCall);
5048bcb0991SDimitry Andric     }
5058bcb0991SDimitry Andric   }
5068bcb0991SDimitry Andric   return V;
5078bcb0991SDimitry Andric }
5088bcb0991SDimitry Andric 
5098bcb0991SDimitry Andric // Use the builder to create a shift right of V across the wavefront, with all
5108bcb0991SDimitry Andric // lanes active, to turn an inclusive scan into an exclusive scan.
buildShiftRight(IRBuilder<> & B,Value * V,Value * Identity) const511fe013be4SDimitry Andric Value *AMDGPUAtomicOptimizerImpl::buildShiftRight(IRBuilder<> &B, Value *V,
512*c9157d92SDimitry Andric                                                   Value *Identity) const {
513*c9157d92SDimitry Andric   Type *AtomicTy = V->getType();
514*c9157d92SDimitry Andric   Type *IntNTy = B.getIntNTy(AtomicTy->getPrimitiveSizeInBits());
515*c9157d92SDimitry Andric 
5168bcb0991SDimitry Andric   Module *M = B.GetInsertBlock()->getModule();
5178bcb0991SDimitry Andric   Function *UpdateDPP =
518*c9157d92SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::amdgcn_update_dpp, AtomicTy);
5198bcb0991SDimitry Andric   if (ST->hasDPPWavefrontShifts()) {
5208bcb0991SDimitry Andric     // GFX9 has DPP wavefront shift operations.
5218bcb0991SDimitry Andric     V = B.CreateCall(UpdateDPP,
5228bcb0991SDimitry Andric                      {Identity, V, B.getInt32(DPP::WAVE_SHR1), B.getInt32(0xf),
5238bcb0991SDimitry Andric                       B.getInt32(0xf), B.getFalse()});
5248bcb0991SDimitry Andric   } else {
525fe6060f1SDimitry Andric     Function *ReadLane =
526fe6060f1SDimitry Andric         Intrinsic::getDeclaration(M, Intrinsic::amdgcn_readlane, {});
527fe6060f1SDimitry Andric     Function *WriteLane =
528fe6060f1SDimitry Andric         Intrinsic::getDeclaration(M, Intrinsic::amdgcn_writelane, {});
529fe6060f1SDimitry Andric 
5308bcb0991SDimitry Andric     // On GFX10 all DPP operations are confined to a single row. To get cross-
5318bcb0991SDimitry Andric     // row operations we have to use permlane or readlane.
5328bcb0991SDimitry Andric     Value *Old = V;
5338bcb0991SDimitry Andric     V = B.CreateCall(UpdateDPP,
5348bcb0991SDimitry Andric                      {Identity, V, B.getInt32(DPP::ROW_SHR0 + 1),
5358bcb0991SDimitry Andric                       B.getInt32(0xf), B.getInt32(0xf), B.getFalse()});
5368bcb0991SDimitry Andric 
5378bcb0991SDimitry Andric     // Copy the old lane 15 to the new lane 16.
5388bcb0991SDimitry Andric     V = B.CreateCall(
5398bcb0991SDimitry Andric         WriteLane,
540*c9157d92SDimitry Andric         {B.CreateCall(ReadLane, {B.CreateBitCast(Old, IntNTy), B.getInt32(15)}),
541*c9157d92SDimitry Andric          B.getInt32(16), B.CreateBitCast(V, IntNTy)});
542*c9157d92SDimitry Andric     V = B.CreateBitCast(V, AtomicTy);
543*c9157d92SDimitry Andric     if (!ST->isWave32()) {
544*c9157d92SDimitry Andric       // Copy the old lane 31 to the new lane 32.
545*c9157d92SDimitry Andric       V = B.CreateBitCast(V, IntNTy);
546*c9157d92SDimitry Andric       V = B.CreateCall(WriteLane,
547*c9157d92SDimitry Andric                        {B.CreateCall(ReadLane, {B.CreateBitCast(Old, IntNTy),
548*c9157d92SDimitry Andric                                                 B.getInt32(31)}),
549*c9157d92SDimitry Andric                         B.getInt32(32), V});
5508bcb0991SDimitry Andric 
5518bcb0991SDimitry Andric       // Copy the old lane 47 to the new lane 48.
5528bcb0991SDimitry Andric       V = B.CreateCall(
5538bcb0991SDimitry Andric           WriteLane,
5548bcb0991SDimitry Andric           {B.CreateCall(ReadLane, {Old, B.getInt32(47)}), B.getInt32(48), V});
555*c9157d92SDimitry Andric       V = B.CreateBitCast(V, AtomicTy);
5568bcb0991SDimitry Andric     }
5578bcb0991SDimitry Andric   }
5588bcb0991SDimitry Andric 
5598bcb0991SDimitry Andric   return V;
5608bcb0991SDimitry Andric }
5618bcb0991SDimitry Andric 
562fe013be4SDimitry Andric // Use the builder to create an exclusive scan and compute the final reduced
563fe013be4SDimitry Andric // value using an iterative approach. This provides an alternative
564fe013be4SDimitry Andric // implementation to DPP which uses WMM for scan computations. This API iterate
565fe013be4SDimitry Andric // over active lanes to read, compute and update the value using
566fe013be4SDimitry Andric // readlane and writelane intrinsics.
buildScanIteratively(IRBuilder<> & B,AtomicRMWInst::BinOp Op,Value * const Identity,Value * V,Instruction & I,BasicBlock * ComputeLoop,BasicBlock * ComputeEnd) const567fe013be4SDimitry Andric std::pair<Value *, Value *> AMDGPUAtomicOptimizerImpl::buildScanIteratively(
568fe013be4SDimitry Andric     IRBuilder<> &B, AtomicRMWInst::BinOp Op, Value *const Identity, Value *V,
569fe013be4SDimitry Andric     Instruction &I, BasicBlock *ComputeLoop, BasicBlock *ComputeEnd) const {
570fe013be4SDimitry Andric   auto *Ty = I.getType();
571fe013be4SDimitry Andric   auto *WaveTy = B.getIntNTy(ST->getWavefrontSize());
572fe013be4SDimitry Andric   auto *EntryBB = I.getParent();
573fe013be4SDimitry Andric   auto NeedResult = !I.use_empty();
574fe013be4SDimitry Andric 
575fe013be4SDimitry Andric   auto *Ballot =
576fe013be4SDimitry Andric       B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
577fe013be4SDimitry Andric 
578fe013be4SDimitry Andric   // Start inserting instructions for ComputeLoop block
579fe013be4SDimitry Andric   B.SetInsertPoint(ComputeLoop);
580fe013be4SDimitry Andric   // Phi nodes for Accumulator, Scan results destination, and Active Lanes
581fe013be4SDimitry Andric   auto *Accumulator = B.CreatePHI(Ty, 2, "Accumulator");
582fe013be4SDimitry Andric   Accumulator->addIncoming(Identity, EntryBB);
583fe013be4SDimitry Andric   PHINode *OldValuePhi = nullptr;
584fe013be4SDimitry Andric   if (NeedResult) {
585fe013be4SDimitry Andric     OldValuePhi = B.CreatePHI(Ty, 2, "OldValuePhi");
586fe013be4SDimitry Andric     OldValuePhi->addIncoming(PoisonValue::get(Ty), EntryBB);
587fe013be4SDimitry Andric   }
588fe013be4SDimitry Andric   auto *ActiveBits = B.CreatePHI(WaveTy, 2, "ActiveBits");
589fe013be4SDimitry Andric   ActiveBits->addIncoming(Ballot, EntryBB);
590fe013be4SDimitry Andric 
591fe013be4SDimitry Andric   // Use llvm.cttz instrinsic to find the lowest remaining active lane.
592fe013be4SDimitry Andric   auto *FF1 =
593fe013be4SDimitry Andric       B.CreateIntrinsic(Intrinsic::cttz, WaveTy, {ActiveBits, B.getTrue()});
594*c9157d92SDimitry Andric 
595*c9157d92SDimitry Andric   Type *IntNTy = B.getIntNTy(Ty->getPrimitiveSizeInBits());
596*c9157d92SDimitry Andric   auto *LaneIdxInt = B.CreateTrunc(FF1, IntNTy);
597fe013be4SDimitry Andric 
598fe013be4SDimitry Andric   // Get the value required for atomic operation
599*c9157d92SDimitry Andric   V = B.CreateBitCast(V, IntNTy);
600*c9157d92SDimitry Andric   Value *LaneValue =
601fe013be4SDimitry Andric       B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {}, {V, LaneIdxInt});
602*c9157d92SDimitry Andric   LaneValue = B.CreateBitCast(LaneValue, Ty);
603fe013be4SDimitry Andric 
604fe013be4SDimitry Andric   // Perform writelane if intermediate scan results are required later in the
605fe013be4SDimitry Andric   // kernel computations
606fe013be4SDimitry Andric   Value *OldValue = nullptr;
607fe013be4SDimitry Andric   if (NeedResult) {
608*c9157d92SDimitry Andric     OldValue =
609*c9157d92SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_writelane, {},
610*c9157d92SDimitry Andric                           {B.CreateBitCast(Accumulator, IntNTy), LaneIdxInt,
611*c9157d92SDimitry Andric                            B.CreateBitCast(OldValuePhi, IntNTy)});
612*c9157d92SDimitry Andric     OldValue = B.CreateBitCast(OldValue, Ty);
613fe013be4SDimitry Andric     OldValuePhi->addIncoming(OldValue, ComputeLoop);
614fe013be4SDimitry Andric   }
615fe013be4SDimitry Andric 
616fe013be4SDimitry Andric   // Accumulate the results
617fe013be4SDimitry Andric   auto *NewAccumulator = buildNonAtomicBinOp(B, Op, Accumulator, LaneValue);
618fe013be4SDimitry Andric   Accumulator->addIncoming(NewAccumulator, ComputeLoop);
619fe013be4SDimitry Andric 
620fe013be4SDimitry Andric   // Set bit to zero of current active lane so that for next iteration llvm.cttz
621fe013be4SDimitry Andric   // return the next active lane
622fe013be4SDimitry Andric   auto *Mask = B.CreateShl(ConstantInt::get(WaveTy, 1), FF1);
623fe013be4SDimitry Andric 
624fe013be4SDimitry Andric   auto *InverseMask = B.CreateXor(Mask, ConstantInt::get(WaveTy, -1));
625fe013be4SDimitry Andric   auto *NewActiveBits = B.CreateAnd(ActiveBits, InverseMask);
626fe013be4SDimitry Andric   ActiveBits->addIncoming(NewActiveBits, ComputeLoop);
627fe013be4SDimitry Andric 
628fe013be4SDimitry Andric   // Branch out of the loop when all lanes are processed.
629fe013be4SDimitry Andric   auto *IsEnd = B.CreateICmpEQ(NewActiveBits, ConstantInt::get(WaveTy, 0));
630fe013be4SDimitry Andric   B.CreateCondBr(IsEnd, ComputeEnd, ComputeLoop);
631fe013be4SDimitry Andric 
632fe013be4SDimitry Andric   B.SetInsertPoint(ComputeEnd);
633fe013be4SDimitry Andric 
634fe013be4SDimitry Andric   return {OldValue, NewAccumulator};
635fe013be4SDimitry Andric }
636fe013be4SDimitry Andric 
getIdentityValueForAtomicOp(Type * const Ty,AtomicRMWInst::BinOp Op)637*c9157d92SDimitry Andric static Constant *getIdentityValueForAtomicOp(Type *const Ty,
638*c9157d92SDimitry Andric                                              AtomicRMWInst::BinOp Op) {
639*c9157d92SDimitry Andric   LLVMContext &C = Ty->getContext();
640*c9157d92SDimitry Andric   const unsigned BitWidth = Ty->getPrimitiveSizeInBits();
6410b57cec5SDimitry Andric   switch (Op) {
6420b57cec5SDimitry Andric   default:
6430b57cec5SDimitry Andric     llvm_unreachable("Unhandled atomic op");
6440b57cec5SDimitry Andric   case AtomicRMWInst::Add:
6450b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
6460b57cec5SDimitry Andric   case AtomicRMWInst::Or:
6470b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
6480b57cec5SDimitry Andric   case AtomicRMWInst::UMax:
649*c9157d92SDimitry Andric     return ConstantInt::get(C, APInt::getMinValue(BitWidth));
6500b57cec5SDimitry Andric   case AtomicRMWInst::And:
6510b57cec5SDimitry Andric   case AtomicRMWInst::UMin:
652*c9157d92SDimitry Andric     return ConstantInt::get(C, APInt::getMaxValue(BitWidth));
6530b57cec5SDimitry Andric   case AtomicRMWInst::Max:
654*c9157d92SDimitry Andric     return ConstantInt::get(C, APInt::getSignedMinValue(BitWidth));
6550b57cec5SDimitry Andric   case AtomicRMWInst::Min:
656*c9157d92SDimitry Andric     return ConstantInt::get(C, APInt::getSignedMaxValue(BitWidth));
657*c9157d92SDimitry Andric   case AtomicRMWInst::FAdd:
658*c9157d92SDimitry Andric     return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), true));
659*c9157d92SDimitry Andric   case AtomicRMWInst::FSub:
660*c9157d92SDimitry Andric     return ConstantFP::get(C, APFloat::getZero(Ty->getFltSemantics(), false));
661*c9157d92SDimitry Andric   case AtomicRMWInst::FMin:
662*c9157d92SDimitry Andric     return ConstantFP::get(C, APFloat::getInf(Ty->getFltSemantics(), false));
663*c9157d92SDimitry Andric   case AtomicRMWInst::FMax:
664*c9157d92SDimitry Andric     return ConstantFP::get(C, APFloat::getInf(Ty->getFltSemantics(), true));
6650b57cec5SDimitry Andric   }
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
buildMul(IRBuilder<> & B,Value * LHS,Value * RHS)668e8d8bef9SDimitry Andric static Value *buildMul(IRBuilder<> &B, Value *LHS, Value *RHS) {
669e8d8bef9SDimitry Andric   const ConstantInt *CI = dyn_cast<ConstantInt>(LHS);
670e8d8bef9SDimitry Andric   return (CI && CI->isOne()) ? RHS : B.CreateMul(LHS, RHS);
671e8d8bef9SDimitry Andric }
672e8d8bef9SDimitry Andric 
optimizeAtomic(Instruction & I,AtomicRMWInst::BinOp Op,unsigned ValIdx,bool ValDivergent) const673fe013be4SDimitry Andric void AMDGPUAtomicOptimizerImpl::optimizeAtomic(Instruction &I,
6740b57cec5SDimitry Andric                                                AtomicRMWInst::BinOp Op,
6750b57cec5SDimitry Andric                                                unsigned ValIdx,
6760b57cec5SDimitry Andric                                                bool ValDivergent) const {
6770b57cec5SDimitry Andric   // Start building just before the instruction.
6780b57cec5SDimitry Andric   IRBuilder<> B(&I);
6790b57cec5SDimitry Andric 
680*c9157d92SDimitry Andric   if (AtomicRMWInst::isFPOperation(Op)) {
681*c9157d92SDimitry Andric     B.setIsFPConstrained(I.getFunction()->hasFnAttribute(Attribute::StrictFP));
682*c9157d92SDimitry Andric   }
683*c9157d92SDimitry Andric 
6840b57cec5SDimitry Andric   // If we are in a pixel shader, because of how we have to mask out helper
6850b57cec5SDimitry Andric   // lane invocations, we need to record the entry and exit BB's.
6860b57cec5SDimitry Andric   BasicBlock *PixelEntryBB = nullptr;
6870b57cec5SDimitry Andric   BasicBlock *PixelExitBB = nullptr;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   // If we're optimizing an atomic within a pixel shader, we need to wrap the
6900b57cec5SDimitry Andric   // entire atomic operation in a helper-lane check. We do not want any helper
6910b57cec5SDimitry Andric   // lanes that are around only for the purposes of derivatives to take part
6920b57cec5SDimitry Andric   // in any cross-lane communication, and we use a branch on whether the lane is
6930b57cec5SDimitry Andric   // live to do this.
6940b57cec5SDimitry Andric   if (IsPixelShader) {
6950b57cec5SDimitry Andric     // Record I's original position as the entry block.
6960b57cec5SDimitry Andric     PixelEntryBB = I.getParent();
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric     Value *const Cond = B.CreateIntrinsic(Intrinsic::amdgcn_ps_live, {}, {});
6990b57cec5SDimitry Andric     Instruction *const NonHelperTerminator =
700fe013be4SDimitry Andric         SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     // Record I's new position as the exit block.
7030b57cec5SDimitry Andric     PixelExitBB = I.getParent();
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric     I.moveBefore(NonHelperTerminator);
7060b57cec5SDimitry Andric     B.SetInsertPoint(&I);
7070b57cec5SDimitry Andric   }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   Type *const Ty = I.getType();
710*c9157d92SDimitry Andric   Type *Int32Ty = B.getInt32Ty();
711*c9157d92SDimitry Andric   Type *IntNTy = B.getIntNTy(Ty->getPrimitiveSizeInBits());
712*c9157d92SDimitry Andric   bool isAtomicFloatingPointTy = Ty->isFloatingPointTy();
7130b57cec5SDimitry Andric   const unsigned TyBitWidth = DL->getTypeSizeInBits(Ty);
714*c9157d92SDimitry Andric   auto *const VecTy = FixedVectorType::get(Int32Ty, 2);
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   // This is the value in the atomic operation we need to combine in order to
7170b57cec5SDimitry Andric   // reduce the number of atomic operations.
718*c9157d92SDimitry Andric   Value *V = I.getOperand(ValIdx);
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   // We need to know how many lanes are active within the wavefront, and we do
7210b57cec5SDimitry Andric   // this by doing a ballot of active lanes.
7228bcb0991SDimitry Andric   Type *const WaveTy = B.getIntNTy(ST->getWavefrontSize());
7235ffd83dbSDimitry Andric   CallInst *const Ballot =
7245ffd83dbSDimitry Andric       B.CreateIntrinsic(Intrinsic::amdgcn_ballot, WaveTy, B.getTrue());
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   // We need to know how many lanes are active within the wavefront that are
7270b57cec5SDimitry Andric   // below us. If we counted each lane linearly starting from 0, a lane is
7280b57cec5SDimitry Andric   // below us only if its associated index was less than ours. We do this by
7290b57cec5SDimitry Andric   // using the mbcnt intrinsic.
7308bcb0991SDimitry Andric   Value *Mbcnt;
7318bcb0991SDimitry Andric   if (ST->isWave32()) {
7328bcb0991SDimitry Andric     Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
7338bcb0991SDimitry Andric                               {Ballot, B.getInt32(0)});
7348bcb0991SDimitry Andric   } else {
735*c9157d92SDimitry Andric     Value *const ExtractLo = B.CreateTrunc(Ballot, Int32Ty);
736*c9157d92SDimitry Andric     Value *const ExtractHi = B.CreateTrunc(B.CreateLShr(Ballot, 32), Int32Ty);
7378bcb0991SDimitry Andric     Mbcnt = B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_lo, {},
7388bcb0991SDimitry Andric                               {ExtractLo, B.getInt32(0)});
7398bcb0991SDimitry Andric     Mbcnt =
7408bcb0991SDimitry Andric         B.CreateIntrinsic(Intrinsic::amdgcn_mbcnt_hi, {}, {ExtractHi, Mbcnt});
7418bcb0991SDimitry Andric   }
7420b57cec5SDimitry Andric 
743*c9157d92SDimitry Andric   Function *F = I.getFunction();
744*c9157d92SDimitry Andric   LLVMContext &C = F->getContext();
745*c9157d92SDimitry Andric 
746*c9157d92SDimitry Andric   // For atomic sub, perform scan with add operation and allow one lane to
747*c9157d92SDimitry Andric   // subtract the reduced value later.
748*c9157d92SDimitry Andric   AtomicRMWInst::BinOp ScanOp = Op;
749*c9157d92SDimitry Andric   if (Op == AtomicRMWInst::Sub) {
750*c9157d92SDimitry Andric     ScanOp = AtomicRMWInst::Add;
751*c9157d92SDimitry Andric   } else if (Op == AtomicRMWInst::FSub) {
752*c9157d92SDimitry Andric     ScanOp = AtomicRMWInst::FAdd;
753*c9157d92SDimitry Andric   }
754*c9157d92SDimitry Andric   Value *Identity = getIdentityValueForAtomicOp(Ty, ScanOp);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   Value *ExclScan = nullptr;
7570b57cec5SDimitry Andric   Value *NewV = nullptr;
7580b57cec5SDimitry Andric 
759fe6060f1SDimitry Andric   const bool NeedResult = !I.use_empty();
760fe6060f1SDimitry Andric 
761fe013be4SDimitry Andric   BasicBlock *ComputeLoop = nullptr;
762fe013be4SDimitry Andric   BasicBlock *ComputeEnd = nullptr;
7630b57cec5SDimitry Andric   // If we have a divergent value in each lane, we need to combine the value
7640b57cec5SDimitry Andric   // using DPP.
7650b57cec5SDimitry Andric   if (ValDivergent) {
766fe013be4SDimitry Andric     if (ScanImpl == ScanOptions::DPP) {
7670b57cec5SDimitry Andric       // First we need to set all inactive invocations to the identity value, so
7680b57cec5SDimitry Andric       // that they can correctly contribute to the final result.
769*c9157d92SDimitry Andric       V = B.CreateBitCast(V, IntNTy);
770*c9157d92SDimitry Andric       Identity = B.CreateBitCast(Identity, IntNTy);
771*c9157d92SDimitry Andric       NewV = B.CreateIntrinsic(Intrinsic::amdgcn_set_inactive, IntNTy,
772*c9157d92SDimitry Andric                                {V, Identity});
773*c9157d92SDimitry Andric       NewV = B.CreateBitCast(NewV, Ty);
774*c9157d92SDimitry Andric       V = B.CreateBitCast(V, Ty);
775*c9157d92SDimitry Andric       Identity = B.CreateBitCast(Identity, Ty);
776fe6060f1SDimitry Andric       if (!NeedResult && ST->hasPermLaneX16()) {
777fe013be4SDimitry Andric         // On GFX10 the permlanex16 instruction helps us build a reduction
778fe013be4SDimitry Andric         // without too many readlanes and writelanes, which are generally bad
779fe013be4SDimitry Andric         // for performance.
780fe6060f1SDimitry Andric         NewV = buildReduction(B, ScanOp, NewV, Identity);
781fe6060f1SDimitry Andric       } else {
7828bcb0991SDimitry Andric         NewV = buildScan(B, ScanOp, NewV, Identity);
783fe6060f1SDimitry Andric         if (NeedResult)
7848bcb0991SDimitry Andric           ExclScan = buildShiftRight(B, NewV, Identity);
785fe013be4SDimitry Andric         // Read the value from the last lane, which has accumulated the values
786fe013be4SDimitry Andric         // of each active lane in the wavefront. This will be our new value
787fe013be4SDimitry Andric         // which we will provide to the atomic operation.
7888bcb0991SDimitry Andric         Value *const LastLaneIdx = B.getInt32(ST->getWavefrontSize() - 1);
789fe6060f1SDimitry Andric         assert(TyBitWidth == 32);
790*c9157d92SDimitry Andric         NewV = B.CreateBitCast(NewV, IntNTy);
7910b57cec5SDimitry Andric         NewV = B.CreateIntrinsic(Intrinsic::amdgcn_readlane, {},
7928bcb0991SDimitry Andric                                  {NewV, LastLaneIdx});
793*c9157d92SDimitry Andric         NewV = B.CreateBitCast(NewV, Ty);
7940b57cec5SDimitry Andric       }
7950b57cec5SDimitry Andric       // Finally mark the readlanes in the WWM section.
796fe6060f1SDimitry Andric       NewV = B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, NewV);
797fe013be4SDimitry Andric     } else if (ScanImpl == ScanOptions::Iterative) {
798fe013be4SDimitry Andric       // Alternative implementation for scan
799fe013be4SDimitry Andric       ComputeLoop = BasicBlock::Create(C, "ComputeLoop", F);
800fe013be4SDimitry Andric       ComputeEnd = BasicBlock::Create(C, "ComputeEnd", F);
801fe013be4SDimitry Andric       std::tie(ExclScan, NewV) = buildScanIteratively(B, ScanOp, Identity, V, I,
802fe013be4SDimitry Andric                                                       ComputeLoop, ComputeEnd);
803fe013be4SDimitry Andric     } else {
804fe013be4SDimitry Andric       llvm_unreachable("Atomic Optimzer is disabled for None strategy");
805fe013be4SDimitry Andric     }
8060b57cec5SDimitry Andric   } else {
8070b57cec5SDimitry Andric     switch (Op) {
8080b57cec5SDimitry Andric     default:
8090b57cec5SDimitry Andric       llvm_unreachable("Unhandled atomic op");
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric     case AtomicRMWInst::Add:
8120b57cec5SDimitry Andric     case AtomicRMWInst::Sub: {
8130b57cec5SDimitry Andric       // The new value we will be contributing to the atomic operation is the
8140b57cec5SDimitry Andric       // old value times the number of active lanes.
8150b57cec5SDimitry Andric       Value *const Ctpop = B.CreateIntCast(
8160b57cec5SDimitry Andric           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
817e8d8bef9SDimitry Andric       NewV = buildMul(B, V, Ctpop);
8180b57cec5SDimitry Andric       break;
8190b57cec5SDimitry Andric     }
820*c9157d92SDimitry Andric     case AtomicRMWInst::FAdd:
821*c9157d92SDimitry Andric     case AtomicRMWInst::FSub: {
822*c9157d92SDimitry Andric       Value *const Ctpop = B.CreateIntCast(
823*c9157d92SDimitry Andric           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Int32Ty, false);
824*c9157d92SDimitry Andric       Value *const CtpopFP = B.CreateUIToFP(Ctpop, Ty);
825*c9157d92SDimitry Andric       NewV = B.CreateFMul(V, CtpopFP);
826*c9157d92SDimitry Andric       break;
827*c9157d92SDimitry Andric     }
8280b57cec5SDimitry Andric     case AtomicRMWInst::And:
8290b57cec5SDimitry Andric     case AtomicRMWInst::Or:
8300b57cec5SDimitry Andric     case AtomicRMWInst::Max:
8310b57cec5SDimitry Andric     case AtomicRMWInst::Min:
8320b57cec5SDimitry Andric     case AtomicRMWInst::UMax:
8330b57cec5SDimitry Andric     case AtomicRMWInst::UMin:
834*c9157d92SDimitry Andric     case AtomicRMWInst::FMin:
835*c9157d92SDimitry Andric     case AtomicRMWInst::FMax:
8360b57cec5SDimitry Andric       // These operations with a uniform value are idempotent: doing the atomic
8370b57cec5SDimitry Andric       // operation multiple times has the same effect as doing it once.
8380b57cec5SDimitry Andric       NewV = V;
8390b57cec5SDimitry Andric       break;
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     case AtomicRMWInst::Xor:
8420b57cec5SDimitry Andric       // The new value we will be contributing to the atomic operation is the
8430b57cec5SDimitry Andric       // old value times the parity of the number of active lanes.
8440b57cec5SDimitry Andric       Value *const Ctpop = B.CreateIntCast(
8450b57cec5SDimitry Andric           B.CreateUnaryIntrinsic(Intrinsic::ctpop, Ballot), Ty, false);
846e8d8bef9SDimitry Andric       NewV = buildMul(B, V, B.CreateAnd(Ctpop, 1));
8470b57cec5SDimitry Andric       break;
8480b57cec5SDimitry Andric     }
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   // We only want a single lane to enter our new control flow, and we do this
8520b57cec5SDimitry Andric   // by checking if there are any active lanes below us. Only one lane will
8530b57cec5SDimitry Andric   // have 0 active lanes below us, so that will be the only one to progress.
854*c9157d92SDimitry Andric   Value *const Cond = B.CreateICmpEQ(Mbcnt, B.getInt32(0));
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   // Store I's original basic block before we split the block.
8570b57cec5SDimitry Andric   BasicBlock *const EntryBB = I.getParent();
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // We need to introduce some new control flow to force a single lane to be
8600b57cec5SDimitry Andric   // active. We do this by splitting I's basic block at I, and introducing the
8610b57cec5SDimitry Andric   // new block such that:
8620b57cec5SDimitry Andric   // entry --> single_lane -\
8630b57cec5SDimitry Andric   //       \------------------> exit
8640b57cec5SDimitry Andric   Instruction *const SingleLaneTerminator =
865fe013be4SDimitry Andric       SplitBlockAndInsertIfThen(Cond, &I, false, nullptr, &DTU, nullptr);
8660b57cec5SDimitry Andric 
867fe013be4SDimitry Andric   // At this point, we have split the I's block to allow one lane in wavefront
868fe013be4SDimitry Andric   // to update the precomputed reduced value. Also, completed the codegen for
869fe013be4SDimitry Andric   // new control flow i.e. iterative loop which perform reduction and scan using
870fe013be4SDimitry Andric   // ComputeLoop and ComputeEnd.
871fe013be4SDimitry Andric   // For the new control flow, we need to move branch instruction i.e.
872fe013be4SDimitry Andric   // terminator created during SplitBlockAndInsertIfThen from I's block to
873fe013be4SDimitry Andric   // ComputeEnd block. We also need to set up predecessor to next block when
874fe013be4SDimitry Andric   // single lane done updating the final reduced value.
875fe013be4SDimitry Andric   BasicBlock *Predecessor = nullptr;
876fe013be4SDimitry Andric   if (ValDivergent && ScanImpl == ScanOptions::Iterative) {
877fe013be4SDimitry Andric     // Move terminator from I's block to ComputeEnd block.
878fe013be4SDimitry Andric     Instruction *Terminator = EntryBB->getTerminator();
879fe013be4SDimitry Andric     B.SetInsertPoint(ComputeEnd);
880fe013be4SDimitry Andric     Terminator->removeFromParent();
881fe013be4SDimitry Andric     B.Insert(Terminator);
882fe013be4SDimitry Andric 
883fe013be4SDimitry Andric     // Branch to ComputeLoop Block unconditionally from the I's block for
884fe013be4SDimitry Andric     // iterative approach.
885fe013be4SDimitry Andric     B.SetInsertPoint(EntryBB);
886fe013be4SDimitry Andric     B.CreateBr(ComputeLoop);
887fe013be4SDimitry Andric 
888fe013be4SDimitry Andric     // Update the dominator tree for new control flow.
889fe013be4SDimitry Andric     DTU.applyUpdates(
890fe013be4SDimitry Andric         {{DominatorTree::Insert, EntryBB, ComputeLoop},
891fe013be4SDimitry Andric          {DominatorTree::Insert, ComputeLoop, ComputeEnd},
892fe013be4SDimitry Andric          {DominatorTree::Delete, EntryBB, SingleLaneTerminator->getParent()}});
893fe013be4SDimitry Andric 
894fe013be4SDimitry Andric     Predecessor = ComputeEnd;
895fe013be4SDimitry Andric   } else {
896fe013be4SDimitry Andric     Predecessor = EntryBB;
897fe013be4SDimitry Andric   }
8980b57cec5SDimitry Andric   // Move the IR builder into single_lane next.
8990b57cec5SDimitry Andric   B.SetInsertPoint(SingleLaneTerminator);
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Clone the original atomic operation into single lane, replacing the
9020b57cec5SDimitry Andric   // original value with our newly created one.
9030b57cec5SDimitry Andric   Instruction *const NewI = I.clone();
9040b57cec5SDimitry Andric   B.Insert(NewI);
9050b57cec5SDimitry Andric   NewI->setOperand(ValIdx, NewV);
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   // Move the IR builder into exit next, and start inserting just before the
9080b57cec5SDimitry Andric   // original instruction.
9090b57cec5SDimitry Andric   B.SetInsertPoint(&I);
9100b57cec5SDimitry Andric 
9118bcb0991SDimitry Andric   if (NeedResult) {
9120b57cec5SDimitry Andric     // Create a PHI node to get our new atomic result into the exit block.
9130b57cec5SDimitry Andric     PHINode *const PHI = B.CreatePHI(Ty, 2);
914fe013be4SDimitry Andric     PHI->addIncoming(PoisonValue::get(Ty), Predecessor);
9150b57cec5SDimitry Andric     PHI->addIncoming(NewI, SingleLaneTerminator->getParent());
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric     // We need to broadcast the value who was the lowest active lane (the first
9180b57cec5SDimitry Andric     // lane) to all other lanes in the wavefront. We use an intrinsic for this,
9190b57cec5SDimitry Andric     // but have to handle 64-bit broadcasts with two calls to this intrinsic.
9200b57cec5SDimitry Andric     Value *BroadcastI = nullptr;
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric     if (TyBitWidth == 64) {
923*c9157d92SDimitry Andric       Value *const ExtractLo = B.CreateTrunc(PHI, Int32Ty);
924*c9157d92SDimitry Andric       Value *const ExtractHi = B.CreateTrunc(B.CreateLShr(PHI, 32), Int32Ty);
9250b57cec5SDimitry Andric       CallInst *const ReadFirstLaneLo =
9260b57cec5SDimitry Andric           B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractLo);
9270b57cec5SDimitry Andric       CallInst *const ReadFirstLaneHi =
9280b57cec5SDimitry Andric           B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, ExtractHi);
9290b57cec5SDimitry Andric       Value *const PartialInsert = B.CreateInsertElement(
930bdd1243dSDimitry Andric           PoisonValue::get(VecTy), ReadFirstLaneLo, B.getInt32(0));
9310b57cec5SDimitry Andric       Value *const Insert =
9320b57cec5SDimitry Andric           B.CreateInsertElement(PartialInsert, ReadFirstLaneHi, B.getInt32(1));
9330b57cec5SDimitry Andric       BroadcastI = B.CreateBitCast(Insert, Ty);
9340b57cec5SDimitry Andric     } else if (TyBitWidth == 32) {
935*c9157d92SDimitry Andric       Value *CastedPhi = B.CreateBitCast(PHI, IntNTy);
936*c9157d92SDimitry Andric       BroadcastI =
937*c9157d92SDimitry Andric           B.CreateIntrinsic(Intrinsic::amdgcn_readfirstlane, {}, CastedPhi);
938*c9157d92SDimitry Andric       BroadcastI = B.CreateBitCast(BroadcastI, Ty);
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric     } else {
9410b57cec5SDimitry Andric       llvm_unreachable("Unhandled atomic bit width");
9420b57cec5SDimitry Andric     }
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric     // Now that we have the result of our single atomic operation, we need to
9458bcb0991SDimitry Andric     // get our individual lane's slice into the result. We use the lane offset
9468bcb0991SDimitry Andric     // we previously calculated combined with the atomic result value we got
9478bcb0991SDimitry Andric     // from the first lane, to get our lane's index into the atomic result.
9480b57cec5SDimitry Andric     Value *LaneOffset = nullptr;
9490b57cec5SDimitry Andric     if (ValDivergent) {
950fe013be4SDimitry Andric       if (ScanImpl == ScanOptions::DPP) {
951fe6060f1SDimitry Andric         LaneOffset =
952fe6060f1SDimitry Andric             B.CreateIntrinsic(Intrinsic::amdgcn_strict_wwm, Ty, ExclScan);
953fe013be4SDimitry Andric       } else if (ScanImpl == ScanOptions::Iterative) {
954fe013be4SDimitry Andric         LaneOffset = ExclScan;
955fe013be4SDimitry Andric       } else {
956fe013be4SDimitry Andric         llvm_unreachable("Atomic Optimzer is disabled for None strategy");
957fe013be4SDimitry Andric       }
9580b57cec5SDimitry Andric     } else {
959*c9157d92SDimitry Andric       Mbcnt = isAtomicFloatingPointTy ? B.CreateUIToFP(Mbcnt, Ty)
960*c9157d92SDimitry Andric                                       : B.CreateIntCast(Mbcnt, Ty, false);
9610b57cec5SDimitry Andric       switch (Op) {
9620b57cec5SDimitry Andric       default:
9630b57cec5SDimitry Andric         llvm_unreachable("Unhandled atomic op");
9640b57cec5SDimitry Andric       case AtomicRMWInst::Add:
9650b57cec5SDimitry Andric       case AtomicRMWInst::Sub:
966e8d8bef9SDimitry Andric         LaneOffset = buildMul(B, V, Mbcnt);
9670b57cec5SDimitry Andric         break;
9680b57cec5SDimitry Andric       case AtomicRMWInst::And:
9690b57cec5SDimitry Andric       case AtomicRMWInst::Or:
9700b57cec5SDimitry Andric       case AtomicRMWInst::Max:
9710b57cec5SDimitry Andric       case AtomicRMWInst::Min:
9720b57cec5SDimitry Andric       case AtomicRMWInst::UMax:
9730b57cec5SDimitry Andric       case AtomicRMWInst::UMin:
974*c9157d92SDimitry Andric       case AtomicRMWInst::FMin:
975*c9157d92SDimitry Andric       case AtomicRMWInst::FMax:
9760b57cec5SDimitry Andric         LaneOffset = B.CreateSelect(Cond, Identity, V);
9770b57cec5SDimitry Andric         break;
9780b57cec5SDimitry Andric       case AtomicRMWInst::Xor:
979e8d8bef9SDimitry Andric         LaneOffset = buildMul(B, V, B.CreateAnd(Mbcnt, 1));
9800b57cec5SDimitry Andric         break;
981*c9157d92SDimitry Andric       case AtomicRMWInst::FAdd:
982*c9157d92SDimitry Andric       case AtomicRMWInst::FSub: {
983*c9157d92SDimitry Andric         LaneOffset = B.CreateFMul(V, Mbcnt);
984*c9157d92SDimitry Andric         break;
985*c9157d92SDimitry Andric       }
9860b57cec5SDimitry Andric       }
9870b57cec5SDimitry Andric     }
9880b57cec5SDimitry Andric     Value *const Result = buildNonAtomicBinOp(B, Op, BroadcastI, LaneOffset);
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     if (IsPixelShader) {
9910b57cec5SDimitry Andric       // Need a final PHI to reconverge to above the helper lane branch mask.
992*c9157d92SDimitry Andric       B.SetInsertPoint(PixelExitBB, PixelExitBB->getFirstNonPHIIt());
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric       PHINode *const PHI = B.CreatePHI(Ty, 2);
995bdd1243dSDimitry Andric       PHI->addIncoming(PoisonValue::get(Ty), PixelEntryBB);
9960b57cec5SDimitry Andric       PHI->addIncoming(Result, I.getParent());
9970b57cec5SDimitry Andric       I.replaceAllUsesWith(PHI);
9980b57cec5SDimitry Andric     } else {
9990b57cec5SDimitry Andric       // Replace the original atomic instruction with the new one.
10000b57cec5SDimitry Andric       I.replaceAllUsesWith(Result);
10010b57cec5SDimitry Andric     }
10028bcb0991SDimitry Andric   }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // And delete the original.
10050b57cec5SDimitry Andric   I.eraseFromParent();
10060b57cec5SDimitry Andric }
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUAtomicOptimizer, DEBUG_TYPE,
10090b57cec5SDimitry Andric                       "AMDGPU atomic optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)1010fe013be4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
10110b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
10120b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUAtomicOptimizer, DEBUG_TYPE,
10130b57cec5SDimitry Andric                     "AMDGPU atomic optimizations", false, false)
10140b57cec5SDimitry Andric 
1015fe013be4SDimitry Andric FunctionPass *llvm::createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy) {
1016fe013be4SDimitry Andric   return new AMDGPUAtomicOptimizer(ScanStrategy);
10170b57cec5SDimitry Andric }
1018