1 //===- AMDGPUAttributor.cpp -----------------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This pass uses Attributor framework to deduce AMDGPU attributes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AMDGPU.h"
14 #include "GCNSubtarget.h"
15 #include "llvm/CodeGen/TargetPassConfig.h"
16 #include "llvm/IR/IntrinsicsAMDGPU.h"
17 #include "llvm/IR/IntrinsicsR600.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Transforms/IPO/Attributor.h"
20 
21 #define DEBUG_TYPE "amdgpu-attributor"
22 
23 using namespace llvm;
24 
25 enum ImplicitArgumentMask {
26   NOT_IMPLICIT_INPUT = 0,
27 
28   // SGPRs
29   DISPATCH_PTR = 1 << 0,
30   QUEUE_PTR = 1 << 1,
31   DISPATCH_ID = 1 << 2,
32   IMPLICIT_ARG_PTR = 1 << 3,
33   WORKGROUP_ID_X = 1 << 4,
34   WORKGROUP_ID_Y = 1 << 5,
35   WORKGROUP_ID_Z = 1 << 6,
36 
37   // VGPRS:
38   WORKITEM_ID_X = 1 << 7,
39   WORKITEM_ID_Y = 1 << 8,
40   WORKITEM_ID_Z = 1 << 9,
41   ALL_ARGUMENT_MASK = (1 << 10) - 1
42 };
43 
44 static constexpr std::pair<ImplicitArgumentMask,
45                            StringLiteral> ImplicitAttrs[] = {
46   {DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
47   {QUEUE_PTR, "amdgpu-no-queue-ptr"},
48   {DISPATCH_ID, "amdgpu-no-dispatch-id"},
49   {IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
50   {WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
51   {WORKGROUP_ID_Y, "amdgpu-no-workgroup-id-y"},
52   {WORKGROUP_ID_Z, "amdgpu-no-workgroup-id-z"},
53   {WORKITEM_ID_X, "amdgpu-no-workitem-id-x"},
54   {WORKITEM_ID_Y, "amdgpu-no-workitem-id-y"},
55   {WORKITEM_ID_Z, "amdgpu-no-workitem-id-z"}
56 };
57 
58 // We do not need to note the x workitem or workgroup id because they are always
59 // initialized.
60 //
61 // TODO: We should not add the attributes if the known compile time workgroup
62 // size is 1 for y/z.
63 static ImplicitArgumentMask
64 intrinsicToAttrMask(Intrinsic::ID ID, bool &NonKernelOnly, bool &IsQueuePtr) {
65   switch (ID) {
66   case Intrinsic::amdgcn_workitem_id_x:
67     NonKernelOnly = true;
68     return WORKITEM_ID_X;
69   case Intrinsic::amdgcn_workgroup_id_x:
70     NonKernelOnly = true;
71     return WORKGROUP_ID_X;
72   case Intrinsic::amdgcn_workitem_id_y:
73   case Intrinsic::r600_read_tidig_y:
74     return WORKITEM_ID_Y;
75   case Intrinsic::amdgcn_workitem_id_z:
76   case Intrinsic::r600_read_tidig_z:
77     return WORKITEM_ID_Z;
78   case Intrinsic::amdgcn_workgroup_id_y:
79   case Intrinsic::r600_read_tgid_y:
80     return WORKGROUP_ID_Y;
81   case Intrinsic::amdgcn_workgroup_id_z:
82   case Intrinsic::r600_read_tgid_z:
83     return WORKGROUP_ID_Z;
84   case Intrinsic::amdgcn_dispatch_ptr:
85     return DISPATCH_PTR;
86   case Intrinsic::amdgcn_dispatch_id:
87     return DISPATCH_ID;
88   case Intrinsic::amdgcn_implicitarg_ptr:
89     return IMPLICIT_ARG_PTR;
90   case Intrinsic::amdgcn_queue_ptr:
91   case Intrinsic::amdgcn_is_shared:
92   case Intrinsic::amdgcn_is_private:
93     // TODO: Does not require queue ptr on gfx9+
94   case Intrinsic::trap:
95   case Intrinsic::debugtrap:
96     IsQueuePtr = true;
97     return QUEUE_PTR;
98   default:
99     return NOT_IMPLICIT_INPUT;
100   }
101 }
102 
103 static bool castRequiresQueuePtr(unsigned SrcAS) {
104   return SrcAS == AMDGPUAS::LOCAL_ADDRESS || SrcAS == AMDGPUAS::PRIVATE_ADDRESS;
105 }
106 
107 static bool isDSAddress(const Constant *C) {
108   const GlobalValue *GV = dyn_cast<GlobalValue>(C);
109   if (!GV)
110     return false;
111   unsigned AS = GV->getAddressSpace();
112   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS;
113 }
114 
115 class AMDGPUInformationCache : public InformationCache {
116 public:
117   AMDGPUInformationCache(const Module &M, AnalysisGetter &AG,
118                          BumpPtrAllocator &Allocator,
119                          SetVector<Function *> *CGSCC, TargetMachine &TM)
120       : InformationCache(M, AG, Allocator, CGSCC), TM(TM) {}
121   TargetMachine &TM;
122 
123   enum ConstantStatus { DS_GLOBAL = 1 << 0, ADDR_SPACE_CAST = 1 << 1 };
124 
125   /// Check if the subtarget has aperture regs.
126   bool hasApertureRegs(Function &F) {
127     const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
128     return ST.hasApertureRegs();
129   }
130 
131 private:
132   /// Check if the ConstantExpr \p CE requires queue ptr attribute.
133   static bool visitConstExpr(const ConstantExpr *CE) {
134     if (CE->getOpcode() == Instruction::AddrSpaceCast) {
135       unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
136       return castRequiresQueuePtr(SrcAS);
137     }
138     return false;
139   }
140 
141   /// Get the constant access bitmap for \p C.
142   uint8_t getConstantAccess(const Constant *C) {
143     auto It = ConstantStatus.find(C);
144     if (It != ConstantStatus.end())
145       return It->second;
146 
147     uint8_t Result = 0;
148     if (isDSAddress(C))
149       Result = DS_GLOBAL;
150 
151     if (const auto *CE = dyn_cast<ConstantExpr>(C))
152       if (visitConstExpr(CE))
153         Result |= ADDR_SPACE_CAST;
154 
155     for (const Use &U : C->operands()) {
156       const auto *OpC = dyn_cast<Constant>(U);
157       if (!OpC)
158         continue;
159 
160       Result |= getConstantAccess(OpC);
161     }
162     return Result;
163   }
164 
165 public:
166   /// Returns true if \p Fn needs a queue ptr attribute because of \p C.
167   bool needsQueuePtr(const Constant *C, Function &Fn) {
168     bool IsNonEntryFunc = !AMDGPU::isEntryFunctionCC(Fn.getCallingConv());
169     bool HasAperture = hasApertureRegs(Fn);
170 
171     // No need to explore the constants.
172     if (!IsNonEntryFunc && HasAperture)
173       return false;
174 
175     uint8_t Access = getConstantAccess(C);
176 
177     // We need to trap on DS globals in non-entry functions.
178     if (IsNonEntryFunc && (Access & DS_GLOBAL))
179       return true;
180 
181     return !HasAperture && (Access & ADDR_SPACE_CAST);
182   }
183 
184 private:
185   /// Used to determine if the Constant needs a queue ptr attribute.
186   DenseMap<const Constant *, uint8_t> ConstantStatus;
187 };
188 
189 struct AAAMDAttributes : public StateWrapper<
190   BitIntegerState<uint16_t, ALL_ARGUMENT_MASK, 0>, AbstractAttribute> {
191   using Base = StateWrapper<BitIntegerState<uint16_t, ALL_ARGUMENT_MASK, 0>,
192                             AbstractAttribute>;
193 
194   AAAMDAttributes(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
195 
196   /// Create an abstract attribute view for the position \p IRP.
197   static AAAMDAttributes &createForPosition(const IRPosition &IRP,
198                                             Attributor &A);
199 
200   /// See AbstractAttribute::getName().
201   const std::string getName() const override { return "AAAMDAttributes"; }
202 
203   /// See AbstractAttribute::getIdAddr().
204   const char *getIdAddr() const override { return &ID; }
205 
206   /// This function should return true if the type of the \p AA is
207   /// AAAMDAttributes.
208   static bool classof(const AbstractAttribute *AA) {
209     return (AA->getIdAddr() == &ID);
210   }
211 
212   /// Unique ID (due to the unique address)
213   static const char ID;
214 };
215 const char AAAMDAttributes::ID = 0;
216 
217 struct AAUniformWorkGroupSize
218     : public StateWrapper<BooleanState, AbstractAttribute> {
219   using Base = StateWrapper<BooleanState, AbstractAttribute>;
220   AAUniformWorkGroupSize(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
221 
222   /// Create an abstract attribute view for the position \p IRP.
223   static AAUniformWorkGroupSize &createForPosition(const IRPosition &IRP,
224                                                    Attributor &A);
225 
226   /// See AbstractAttribute::getName().
227   const std::string getName() const override {
228     return "AAUniformWorkGroupSize";
229   }
230 
231   /// See AbstractAttribute::getIdAddr().
232   const char *getIdAddr() const override { return &ID; }
233 
234   /// This function should return true if the type of the \p AA is
235   /// AAAMDAttributes.
236   static bool classof(const AbstractAttribute *AA) {
237     return (AA->getIdAddr() == &ID);
238   }
239 
240   /// Unique ID (due to the unique address)
241   static const char ID;
242 };
243 const char AAUniformWorkGroupSize::ID = 0;
244 
245 struct AAUniformWorkGroupSizeFunction : public AAUniformWorkGroupSize {
246   AAUniformWorkGroupSizeFunction(const IRPosition &IRP, Attributor &A)
247       : AAUniformWorkGroupSize(IRP, A) {}
248 
249   void initialize(Attributor &A) override {
250     Function *F = getAssociatedFunction();
251     CallingConv::ID CC = F->getCallingConv();
252 
253     if (CC != CallingConv::AMDGPU_KERNEL)
254       return;
255 
256     bool InitialValue = false;
257     if (F->hasFnAttribute("uniform-work-group-size"))
258       InitialValue = F->getFnAttribute("uniform-work-group-size")
259                          .getValueAsString()
260                          .equals("true");
261 
262     if (InitialValue)
263       indicateOptimisticFixpoint();
264     else
265       indicatePessimisticFixpoint();
266   }
267 
268   ChangeStatus updateImpl(Attributor &A) override {
269     ChangeStatus Change = ChangeStatus::UNCHANGED;
270 
271     auto CheckCallSite = [&](AbstractCallSite CS) {
272       Function *Caller = CS.getInstruction()->getFunction();
273       LLVM_DEBUG(dbgs() << "[AAUniformWorkGroupSize] Call " << Caller->getName()
274                         << "->" << getAssociatedFunction()->getName() << "\n");
275 
276       const auto &CallerInfo = A.getAAFor<AAUniformWorkGroupSize>(
277           *this, IRPosition::function(*Caller), DepClassTy::REQUIRED);
278 
279       Change = Change | clampStateAndIndicateChange(this->getState(),
280                                                     CallerInfo.getState());
281 
282       return true;
283     };
284 
285     bool AllCallSitesKnown = true;
286     if (!A.checkForAllCallSites(CheckCallSite, *this, true, AllCallSitesKnown))
287       indicatePessimisticFixpoint();
288 
289     return Change;
290   }
291 
292   ChangeStatus manifest(Attributor &A) override {
293     SmallVector<Attribute, 8> AttrList;
294     LLVMContext &Ctx = getAssociatedFunction()->getContext();
295 
296     AttrList.push_back(Attribute::get(Ctx, "uniform-work-group-size",
297                                       getAssumed() ? "true" : "false"));
298     return IRAttributeManifest::manifestAttrs(A, getIRPosition(), AttrList,
299                                               /* ForceReplace */ true);
300   }
301 
302   bool isValidState() const override {
303     // This state is always valid, even when the state is false.
304     return true;
305   }
306 
307   const std::string getAsStr() const override {
308     return "AMDWorkGroupSize[" + std::to_string(getAssumed()) + "]";
309   }
310 
311   /// See AbstractAttribute::trackStatistics()
312   void trackStatistics() const override {}
313 };
314 
315 AAUniformWorkGroupSize &
316 AAUniformWorkGroupSize::createForPosition(const IRPosition &IRP,
317                                           Attributor &A) {
318   if (IRP.getPositionKind() == IRPosition::IRP_FUNCTION)
319     return *new (A.Allocator) AAUniformWorkGroupSizeFunction(IRP, A);
320   llvm_unreachable(
321       "AAUniformWorkGroupSize is only valid for function position");
322 }
323 
324 struct AAAMDAttributesFunction : public AAAMDAttributes {
325   AAAMDAttributesFunction(const IRPosition &IRP, Attributor &A)
326       : AAAMDAttributes(IRP, A) {}
327 
328   void initialize(Attributor &A) override {
329     Function *F = getAssociatedFunction();
330     for (auto Attr : ImplicitAttrs) {
331       if (F->hasFnAttribute(Attr.second))
332         addKnownBits(Attr.first);
333     }
334 
335     if (F->isDeclaration())
336       return;
337 
338     // Ignore functions with graphics calling conventions, these are currently
339     // not allowed to have kernel arguments.
340     if (AMDGPU::isGraphics(F->getCallingConv())) {
341       indicatePessimisticFixpoint();
342       return;
343     }
344   }
345 
346   ChangeStatus updateImpl(Attributor &A) override {
347     Function *F = getAssociatedFunction();
348     // The current assumed state used to determine a change.
349     auto OrigAssumed = getAssumed();
350 
351     // Check for Intrinsics and propagate attributes.
352     const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
353         *this, this->getIRPosition(), DepClassTy::REQUIRED);
354     if (AAEdges.hasNonAsmUnknownCallee())
355       return indicatePessimisticFixpoint();
356 
357     bool IsNonEntryFunc = !AMDGPU::isEntryFunctionCC(F->getCallingConv());
358     auto &InfoCache = static_cast<AMDGPUInformationCache &>(A.getInfoCache());
359 
360     bool NeedsQueuePtr = false;
361 
362     for (Function *Callee : AAEdges.getOptimisticEdges()) {
363       Intrinsic::ID IID = Callee->getIntrinsicID();
364       if (IID == Intrinsic::not_intrinsic) {
365         const AAAMDAttributes &AAAMD = A.getAAFor<AAAMDAttributes>(
366           *this, IRPosition::function(*Callee), DepClassTy::REQUIRED);
367         *this &= AAAMD;
368         continue;
369       }
370 
371       bool NonKernelOnly = false;
372       ImplicitArgumentMask AttrMask =
373           intrinsicToAttrMask(IID, NonKernelOnly, NeedsQueuePtr);
374       if (AttrMask != NOT_IMPLICIT_INPUT) {
375         if ((IsNonEntryFunc || !NonKernelOnly))
376           removeAssumedBits(AttrMask);
377       }
378     }
379 
380     // If we found that we need amdgpu-queue-ptr, nothing else to do.
381     if (NeedsQueuePtr) {
382       removeAssumedBits(QUEUE_PTR);
383       return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED :
384                                            ChangeStatus::UNCHANGED;
385     }
386 
387     auto CheckAddrSpaceCasts = [&](Instruction &I) {
388       unsigned SrcAS = static_cast<AddrSpaceCastInst &>(I).getSrcAddressSpace();
389       if (castRequiresQueuePtr(SrcAS)) {
390         NeedsQueuePtr = true;
391         return false;
392       }
393       return true;
394     };
395 
396     bool HasApertureRegs = InfoCache.hasApertureRegs(*F);
397 
398     // `checkForAllInstructions` is much more cheaper than going through all
399     // instructions, try it first.
400 
401     // amdgpu-queue-ptr is not needed if aperture regs is present.
402     if (!HasApertureRegs) {
403       bool UsedAssumedInformation = false;
404       A.checkForAllInstructions(CheckAddrSpaceCasts, *this,
405                                 {Instruction::AddrSpaceCast},
406                                 UsedAssumedInformation);
407     }
408 
409     // If we found  that we need amdgpu-queue-ptr, nothing else to do.
410     if (NeedsQueuePtr) {
411       removeAssumedBits(QUEUE_PTR);
412       return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED :
413                                            ChangeStatus::UNCHANGED;
414     }
415 
416     if (!IsNonEntryFunc && HasApertureRegs) {
417       return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED :
418                                            ChangeStatus::UNCHANGED;
419     }
420 
421     for (BasicBlock &BB : *F) {
422       for (Instruction &I : BB) {
423         for (const Use &U : I.operands()) {
424           if (const auto *C = dyn_cast<Constant>(U)) {
425             if (InfoCache.needsQueuePtr(C, *F)) {
426               removeAssumedBits(QUEUE_PTR);
427               return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED :
428                                                    ChangeStatus::UNCHANGED;
429             }
430           }
431         }
432       }
433     }
434 
435     return getAssumed() != OrigAssumed ? ChangeStatus::CHANGED :
436                                          ChangeStatus::UNCHANGED;
437   }
438 
439   ChangeStatus manifest(Attributor &A) override {
440     SmallVector<Attribute, 8> AttrList;
441     LLVMContext &Ctx = getAssociatedFunction()->getContext();
442 
443     for (auto Attr : ImplicitAttrs) {
444       if (isKnown(Attr.first))
445         AttrList.push_back(Attribute::get(Ctx, Attr.second));
446     }
447 
448     return IRAttributeManifest::manifestAttrs(A, getIRPosition(), AttrList,
449                                               /* ForceReplace */ true);
450   }
451 
452   const std::string getAsStr() const override {
453     std::string Str;
454     raw_string_ostream OS(Str);
455     OS << "AMDInfo[";
456     for (auto Attr : ImplicitAttrs)
457       OS << ' ' << Attr.second;
458     OS << " ]";
459     return OS.str();
460   }
461 
462   /// See AbstractAttribute::trackStatistics()
463   void trackStatistics() const override {}
464 };
465 
466 AAAMDAttributes &AAAMDAttributes::createForPosition(const IRPosition &IRP,
467                                                     Attributor &A) {
468   if (IRP.getPositionKind() == IRPosition::IRP_FUNCTION)
469     return *new (A.Allocator) AAAMDAttributesFunction(IRP, A);
470   llvm_unreachable("AAAMDAttributes is only valid for function position");
471 }
472 
473 class AMDGPUAttributor : public ModulePass {
474 public:
475   AMDGPUAttributor() : ModulePass(ID) {}
476 
477   /// doInitialization - Virtual method overridden by subclasses to do
478   /// any necessary initialization before any pass is run.
479   bool doInitialization(Module &) override {
480     auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
481     if (!TPC)
482       report_fatal_error("TargetMachine is required");
483 
484     TM = &TPC->getTM<TargetMachine>();
485     return false;
486   }
487 
488   bool runOnModule(Module &M) override {
489     SetVector<Function *> Functions;
490     AnalysisGetter AG;
491     for (Function &F : M) {
492       if (!F.isIntrinsic())
493         Functions.insert(&F);
494     }
495 
496     CallGraphUpdater CGUpdater;
497     BumpPtrAllocator Allocator;
498     AMDGPUInformationCache InfoCache(M, AG, Allocator, nullptr, *TM);
499     DenseSet<const char *> Allowed(
500         {&AAAMDAttributes::ID, &AAUniformWorkGroupSize::ID, &AACallEdges::ID});
501 
502     Attributor A(Functions, InfoCache, CGUpdater, &Allowed);
503 
504     for (Function &F : M) {
505       if (!F.isIntrinsic()) {
506         A.getOrCreateAAFor<AAAMDAttributes>(IRPosition::function(F));
507         A.getOrCreateAAFor<AAUniformWorkGroupSize>(IRPosition::function(F));
508       }
509     }
510 
511     ChangeStatus Change = A.run();
512     return Change == ChangeStatus::CHANGED;
513   }
514 
515   StringRef getPassName() const override { return "AMDGPU Attributor"; }
516   TargetMachine *TM;
517   static char ID;
518 };
519 
520 char AMDGPUAttributor::ID = 0;
521 
522 Pass *llvm::createAMDGPUAttributorPass() { return new AMDGPUAttributor(); }
523 INITIALIZE_PASS(AMDGPUAttributor, DEBUG_TYPE, "AMDGPU Attributor", false, false)
524