1 //===- AMDGPUResourceUsageAnalysis.h ---- analysis of resources -----------===//
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
10 /// \brief Analyzes how many registers and other resources are used by
11 /// functions.
12 ///
13 /// The results of this analysis are used to fill the register usage, flat
14 /// usage, etc. into hardware registers.
15 ///
16 /// The analysis takes callees into account. E.g. if a function A that needs 10
17 /// VGPRs calls a function B that needs 20 VGPRs, querying the VGPR usage of A
18 /// will return 20.
19 /// It is assumed that an indirect call can go into any function except
20 /// hardware-entrypoints. Therefore the register usage of functions with
21 /// indirect calls is estimated as the maximum of all non-entrypoint functions
22 /// in the module.
23 ///
24 //===----------------------------------------------------------------------===//
25 
26 #include "AMDGPUResourceUsageAnalysis.h"
27 #include "AMDGPU.h"
28 #include "GCNSubtarget.h"
29 #include "SIMachineFunctionInfo.h"
30 #include "llvm/ADT/PostOrderIterator.h"
31 #include "llvm/Analysis/CallGraph.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/Target/TargetMachine.h"
37 
38 using namespace llvm;
39 using namespace llvm::AMDGPU;
40 
41 #define DEBUG_TYPE "amdgpu-resource-usage"
42 
43 char llvm::AMDGPUResourceUsageAnalysis::ID = 0;
44 char &llvm::AMDGPUResourceUsageAnalysisID = AMDGPUResourceUsageAnalysis::ID;
45 
46 // We need to tell the runtime some amount ahead of time if we don't know the
47 // true stack size. Assume a smaller number if this is only due to dynamic /
48 // non-entry block allocas.
49 static cl::opt<uint32_t> AssumedStackSizeForExternalCall(
50     "amdgpu-assume-external-call-stack-size",
51     cl::desc("Assumed stack use of any external call (in bytes)"), cl::Hidden,
52     cl::init(16384));
53 
54 static cl::opt<uint32_t> AssumedStackSizeForDynamicSizeObjects(
55     "amdgpu-assume-dynamic-stack-object-size",
56     cl::desc("Assumed extra stack use if there are any "
57              "variable sized objects (in bytes)"),
58     cl::Hidden, cl::init(4096));
59 
60 INITIALIZE_PASS(AMDGPUResourceUsageAnalysis, DEBUG_TYPE,
61                 "Function register usage analysis", true, true)
62 
63 static const Function *getCalleeFunction(const MachineOperand &Op) {
64   if (Op.isImm()) {
65     assert(Op.getImm() == 0);
66     return nullptr;
67   }
68   if (auto *GA = dyn_cast<GlobalAlias>(Op.getGlobal()))
69     return cast<Function>(GA->getOperand(0));
70   return cast<Function>(Op.getGlobal());
71 }
72 
73 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI,
74                                   const SIInstrInfo &TII, unsigned Reg) {
75   for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) {
76     if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent()))
77       return true;
78   }
79 
80   return false;
81 }
82 
83 int32_t AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo::getTotalNumSGPRs(
84     const GCNSubtarget &ST) const {
85   return NumExplicitSGPR +
86          IsaInfo::getNumExtraSGPRs(&ST, UsesVCC, UsesFlatScratch,
87                                    ST.getTargetID().isXnackOnOrAny());
88 }
89 
90 int32_t AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo::getTotalNumVGPRs(
91     const GCNSubtarget &ST, int32_t ArgNumAGPR, int32_t ArgNumVGPR) const {
92   return AMDGPU::getTotalNumVGPRs(ST.hasGFX90AInsts(), ArgNumAGPR, ArgNumVGPR);
93 }
94 
95 int32_t AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo::getTotalNumVGPRs(
96     const GCNSubtarget &ST) const {
97   return getTotalNumVGPRs(ST, NumAGPR, NumVGPR);
98 }
99 
100 bool AMDGPUResourceUsageAnalysis::runOnModule(Module &M) {
101   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
102   if (!TPC)
103     return false;
104 
105   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
106   const TargetMachine &TM = TPC->getTM<TargetMachine>();
107   bool HasIndirectCall = false;
108 
109   CallGraph CG = CallGraph(M);
110   auto End = po_end(&CG);
111 
112   for (auto IT = po_begin(&CG); IT != End; ++IT) {
113     Function *F = IT->getFunction();
114     if (!F || F->isDeclaration())
115       continue;
116 
117     MachineFunction *MF = MMI.getMachineFunction(*F);
118     assert(MF && "function must have been generated already");
119 
120     auto CI = CallGraphResourceInfo.insert(
121         std::make_pair(F, SIFunctionResourceInfo()));
122     SIFunctionResourceInfo &Info = CI.first->second;
123     assert(CI.second && "should only be called once per function");
124     Info = analyzeResourceUsage(*MF, TM);
125     HasIndirectCall |= Info.HasIndirectCall;
126   }
127 
128   if (HasIndirectCall)
129     propagateIndirectCallRegisterUsage();
130 
131   return false;
132 }
133 
134 AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo
135 AMDGPUResourceUsageAnalysis::analyzeResourceUsage(
136     const MachineFunction &MF, const TargetMachine &TM) const {
137   SIFunctionResourceInfo Info;
138 
139   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
140   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
141   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
142   const MachineRegisterInfo &MRI = MF.getRegInfo();
143   const SIInstrInfo *TII = ST.getInstrInfo();
144   const SIRegisterInfo &TRI = TII->getRegisterInfo();
145 
146   Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) ||
147                          MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI) ||
148                          MRI.isLiveIn(MFI->getPreloadedReg(
149                              AMDGPUFunctionArgInfo::FLAT_SCRATCH_INIT));
150 
151   // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
152   // instructions aren't used to access the scratch buffer. Inline assembly may
153   // need it though.
154   //
155   // If we only have implicit uses of flat_scr on flat instructions, it is not
156   // really needed.
157   if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() &&
158       (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) &&
159        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) &&
160        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) {
161     Info.UsesFlatScratch = false;
162   }
163 
164   Info.PrivateSegmentSize = FrameInfo.getStackSize();
165 
166   // Assume a big number if there are any unknown sized objects.
167   Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects();
168   if (Info.HasDynamicallySizedStack)
169     Info.PrivateSegmentSize += AssumedStackSizeForDynamicSizeObjects;
170 
171   if (MFI->isStackRealigned())
172     Info.PrivateSegmentSize += FrameInfo.getMaxAlign().value();
173 
174   Info.UsesVCC =
175       MRI.isPhysRegUsed(AMDGPU::VCC_LO) || MRI.isPhysRegUsed(AMDGPU::VCC_HI);
176 
177   // If there are no calls, MachineRegisterInfo can tell us the used register
178   // count easily.
179   // A tail call isn't considered a call for MachineFrameInfo's purposes.
180   if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) {
181     MCPhysReg HighestVGPRReg = AMDGPU::NoRegister;
182     for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) {
183       if (MRI.isPhysRegUsed(Reg)) {
184         HighestVGPRReg = Reg;
185         break;
186       }
187     }
188 
189     if (ST.hasMAIInsts()) {
190       MCPhysReg HighestAGPRReg = AMDGPU::NoRegister;
191       for (MCPhysReg Reg : reverse(AMDGPU::AGPR_32RegClass.getRegisters())) {
192         if (MRI.isPhysRegUsed(Reg)) {
193           HighestAGPRReg = Reg;
194           break;
195         }
196       }
197       Info.NumAGPR = HighestAGPRReg == AMDGPU::NoRegister
198                          ? 0
199                          : TRI.getHWRegIndex(HighestAGPRReg) + 1;
200     }
201 
202     MCPhysReg HighestSGPRReg = AMDGPU::NoRegister;
203     for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) {
204       if (MRI.isPhysRegUsed(Reg)) {
205         HighestSGPRReg = Reg;
206         break;
207       }
208     }
209 
210     // We found the maximum register index. They start at 0, so add one to get
211     // the number of registers.
212     Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister
213                        ? 0
214                        : TRI.getHWRegIndex(HighestVGPRReg) + 1;
215     Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister
216                                ? 0
217                                : TRI.getHWRegIndex(HighestSGPRReg) + 1;
218 
219     return Info;
220   }
221 
222   int32_t MaxVGPR = -1;
223   int32_t MaxAGPR = -1;
224   int32_t MaxSGPR = -1;
225   uint64_t CalleeFrameSize = 0;
226 
227   for (const MachineBasicBlock &MBB : MF) {
228     for (const MachineInstr &MI : MBB) {
229       // TODO: Check regmasks? Do they occur anywhere except calls?
230       for (const MachineOperand &MO : MI.operands()) {
231         unsigned Width = 0;
232         bool IsSGPR = false;
233         bool IsAGPR = false;
234 
235         if (!MO.isReg())
236           continue;
237 
238         Register Reg = MO.getReg();
239         switch (Reg) {
240         case AMDGPU::EXEC:
241         case AMDGPU::EXEC_LO:
242         case AMDGPU::EXEC_HI:
243         case AMDGPU::SCC:
244         case AMDGPU::M0:
245         case AMDGPU::M0_LO16:
246         case AMDGPU::M0_HI16:
247         case AMDGPU::SRC_SHARED_BASE:
248         case AMDGPU::SRC_SHARED_LIMIT:
249         case AMDGPU::SRC_PRIVATE_BASE:
250         case AMDGPU::SRC_PRIVATE_LIMIT:
251         case AMDGPU::SGPR_NULL:
252         case AMDGPU::MODE:
253           continue;
254 
255         case AMDGPU::SRC_POPS_EXITING_WAVE_ID:
256           llvm_unreachable("src_pops_exiting_wave_id should not be used");
257 
258         case AMDGPU::NoRegister:
259           assert(MI.isDebugInstr() &&
260                  "Instruction uses invalid noreg register");
261           continue;
262 
263         case AMDGPU::VCC:
264         case AMDGPU::VCC_LO:
265         case AMDGPU::VCC_HI:
266         case AMDGPU::VCC_LO_LO16:
267         case AMDGPU::VCC_LO_HI16:
268         case AMDGPU::VCC_HI_LO16:
269         case AMDGPU::VCC_HI_HI16:
270           Info.UsesVCC = true;
271           continue;
272 
273         case AMDGPU::FLAT_SCR:
274         case AMDGPU::FLAT_SCR_LO:
275         case AMDGPU::FLAT_SCR_HI:
276           continue;
277 
278         case AMDGPU::XNACK_MASK:
279         case AMDGPU::XNACK_MASK_LO:
280         case AMDGPU::XNACK_MASK_HI:
281           llvm_unreachable("xnack_mask registers should not be used");
282 
283         case AMDGPU::LDS_DIRECT:
284           llvm_unreachable("lds_direct register should not be used");
285 
286         case AMDGPU::TBA:
287         case AMDGPU::TBA_LO:
288         case AMDGPU::TBA_HI:
289         case AMDGPU::TMA:
290         case AMDGPU::TMA_LO:
291         case AMDGPU::TMA_HI:
292           llvm_unreachable("trap handler registers should not be used");
293 
294         case AMDGPU::SRC_VCCZ:
295           llvm_unreachable("src_vccz register should not be used");
296 
297         case AMDGPU::SRC_EXECZ:
298           llvm_unreachable("src_execz register should not be used");
299 
300         case AMDGPU::SRC_SCC:
301           llvm_unreachable("src_scc register should not be used");
302 
303         default:
304           break;
305         }
306 
307         if (AMDGPU::SReg_32RegClass.contains(Reg) ||
308             AMDGPU::SReg_LO16RegClass.contains(Reg) ||
309             AMDGPU::SGPR_HI16RegClass.contains(Reg)) {
310           assert(!AMDGPU::TTMP_32RegClass.contains(Reg) &&
311                  "trap handler registers should not be used");
312           IsSGPR = true;
313           Width = 1;
314         } else if (AMDGPU::VGPR_32RegClass.contains(Reg) ||
315                    AMDGPU::VGPR_LO16RegClass.contains(Reg) ||
316                    AMDGPU::VGPR_HI16RegClass.contains(Reg)) {
317           IsSGPR = false;
318           Width = 1;
319         } else if (AMDGPU::AGPR_32RegClass.contains(Reg) ||
320                    AMDGPU::AGPR_LO16RegClass.contains(Reg)) {
321           IsSGPR = false;
322           IsAGPR = true;
323           Width = 1;
324         } else if (AMDGPU::SReg_64RegClass.contains(Reg)) {
325           assert(!AMDGPU::TTMP_64RegClass.contains(Reg) &&
326                  "trap handler registers should not be used");
327           IsSGPR = true;
328           Width = 2;
329         } else if (AMDGPU::VReg_64RegClass.contains(Reg)) {
330           IsSGPR = false;
331           Width = 2;
332         } else if (AMDGPU::AReg_64RegClass.contains(Reg)) {
333           IsSGPR = false;
334           IsAGPR = true;
335           Width = 2;
336         } else if (AMDGPU::VReg_96RegClass.contains(Reg)) {
337           IsSGPR = false;
338           Width = 3;
339         } else if (AMDGPU::SReg_96RegClass.contains(Reg)) {
340           IsSGPR = true;
341           Width = 3;
342         } else if (AMDGPU::AReg_96RegClass.contains(Reg)) {
343           IsSGPR = false;
344           IsAGPR = true;
345           Width = 3;
346         } else if (AMDGPU::SReg_128RegClass.contains(Reg)) {
347           assert(!AMDGPU::TTMP_128RegClass.contains(Reg) &&
348                  "trap handler registers should not be used");
349           IsSGPR = true;
350           Width = 4;
351         } else if (AMDGPU::VReg_128RegClass.contains(Reg)) {
352           IsSGPR = false;
353           Width = 4;
354         } else if (AMDGPU::AReg_128RegClass.contains(Reg)) {
355           IsSGPR = false;
356           IsAGPR = true;
357           Width = 4;
358         } else if (AMDGPU::VReg_160RegClass.contains(Reg)) {
359           IsSGPR = false;
360           Width = 5;
361         } else if (AMDGPU::SReg_160RegClass.contains(Reg)) {
362           IsSGPR = true;
363           Width = 5;
364         } else if (AMDGPU::AReg_160RegClass.contains(Reg)) {
365           IsSGPR = false;
366           IsAGPR = true;
367           Width = 5;
368         } else if (AMDGPU::VReg_192RegClass.contains(Reg)) {
369           IsSGPR = false;
370           Width = 6;
371         } else if (AMDGPU::SReg_192RegClass.contains(Reg)) {
372           IsSGPR = true;
373           Width = 6;
374         } else if (AMDGPU::AReg_192RegClass.contains(Reg)) {
375           IsSGPR = false;
376           IsAGPR = true;
377           Width = 6;
378         } else if (AMDGPU::VReg_224RegClass.contains(Reg)) {
379           IsSGPR = false;
380           Width = 7;
381         } else if (AMDGPU::SReg_224RegClass.contains(Reg)) {
382           IsSGPR = true;
383           Width = 7;
384         } else if (AMDGPU::AReg_224RegClass.contains(Reg)) {
385           IsSGPR = false;
386           IsAGPR = true;
387           Width = 7;
388         } else if (AMDGPU::SReg_256RegClass.contains(Reg)) {
389           assert(!AMDGPU::TTMP_256RegClass.contains(Reg) &&
390                  "trap handler registers should not be used");
391           IsSGPR = true;
392           Width = 8;
393         } else if (AMDGPU::VReg_256RegClass.contains(Reg)) {
394           IsSGPR = false;
395           Width = 8;
396         } else if (AMDGPU::AReg_256RegClass.contains(Reg)) {
397           IsSGPR = false;
398           IsAGPR = true;
399           Width = 8;
400         } else if (AMDGPU::SReg_512RegClass.contains(Reg)) {
401           assert(!AMDGPU::TTMP_512RegClass.contains(Reg) &&
402                  "trap handler registers should not be used");
403           IsSGPR = true;
404           Width = 16;
405         } else if (AMDGPU::VReg_512RegClass.contains(Reg)) {
406           IsSGPR = false;
407           Width = 16;
408         } else if (AMDGPU::AReg_512RegClass.contains(Reg)) {
409           IsSGPR = false;
410           IsAGPR = true;
411           Width = 16;
412         } else if (AMDGPU::SReg_1024RegClass.contains(Reg)) {
413           IsSGPR = true;
414           Width = 32;
415         } else if (AMDGPU::VReg_1024RegClass.contains(Reg)) {
416           IsSGPR = false;
417           Width = 32;
418         } else if (AMDGPU::AReg_1024RegClass.contains(Reg)) {
419           IsSGPR = false;
420           IsAGPR = true;
421           Width = 32;
422         } else {
423           llvm_unreachable("Unknown register class");
424         }
425         unsigned HWReg = TRI.getHWRegIndex(Reg);
426         int MaxUsed = HWReg + Width - 1;
427         if (IsSGPR) {
428           MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR;
429         } else if (IsAGPR) {
430           MaxAGPR = MaxUsed > MaxAGPR ? MaxUsed : MaxAGPR;
431         } else {
432           MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR;
433         }
434       }
435 
436       if (MI.isCall()) {
437         // Pseudo used just to encode the underlying global. Is there a better
438         // way to track this?
439 
440         const MachineOperand *CalleeOp =
441             TII->getNamedOperand(MI, AMDGPU::OpName::callee);
442 
443         const Function *Callee = getCalleeFunction(*CalleeOp);
444         DenseMap<const Function *, SIFunctionResourceInfo>::const_iterator I =
445             CallGraphResourceInfo.end();
446 
447         // Avoid crashing on undefined behavior with an illegal call to a
448         // kernel. If a callsite's calling convention doesn't match the
449         // function's, it's undefined behavior. If the callsite calling
450         // convention does match, that would have errored earlier.
451         if (Callee && AMDGPU::isEntryFunctionCC(Callee->getCallingConv()))
452           report_fatal_error("invalid call to entry function");
453 
454         bool IsIndirect = !Callee || Callee->isDeclaration();
455         if (!IsIndirect)
456           I = CallGraphResourceInfo.find(Callee);
457 
458         // FIXME: Call site could have norecurse on it
459         if (!Callee || !Callee->doesNotRecurse()) {
460           Info.HasRecursion = true;
461 
462           // TODO: If we happen to know there is no stack usage in the
463           // callgraph, we don't need to assume an infinitely growing stack.
464           if (!MI.isReturn()) {
465             // We don't need to assume an unknown stack size for tail calls.
466 
467             // FIXME: This only benefits in the case where the kernel does not
468             // directly call the tail called function. If a kernel directly
469             // calls a tail recursive function, we'll assume maximum stack size
470             // based on the regular call instruction.
471             CalleeFrameSize =
472               std::max(CalleeFrameSize,
473                        static_cast<uint64_t>(AssumedStackSizeForExternalCall));
474           }
475         }
476 
477         if (IsIndirect || I == CallGraphResourceInfo.end()) {
478           CalleeFrameSize =
479               std::max(CalleeFrameSize,
480                        static_cast<uint64_t>(AssumedStackSizeForExternalCall));
481 
482           // Register usage of indirect calls gets handled later
483           Info.UsesVCC = true;
484           Info.UsesFlatScratch = ST.hasFlatAddressSpace();
485           Info.HasDynamicallySizedStack = true;
486           Info.HasIndirectCall = true;
487         } else {
488           // We force CodeGen to run in SCC order, so the callee's register
489           // usage etc. should be the cumulative usage of all callees.
490           MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR);
491           MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR);
492           MaxAGPR = std::max(I->second.NumAGPR - 1, MaxAGPR);
493           CalleeFrameSize =
494               std::max(I->second.PrivateSegmentSize, CalleeFrameSize);
495           Info.UsesVCC |= I->second.UsesVCC;
496           Info.UsesFlatScratch |= I->second.UsesFlatScratch;
497           Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack;
498           Info.HasRecursion |= I->second.HasRecursion;
499           Info.HasIndirectCall |= I->second.HasIndirectCall;
500         }
501       }
502     }
503   }
504 
505   Info.NumExplicitSGPR = MaxSGPR + 1;
506   Info.NumVGPR = MaxVGPR + 1;
507   Info.NumAGPR = MaxAGPR + 1;
508   Info.PrivateSegmentSize += CalleeFrameSize;
509 
510   return Info;
511 }
512 
513 void AMDGPUResourceUsageAnalysis::propagateIndirectCallRegisterUsage() {
514   // Collect the maximum number of registers from non-hardware-entrypoints.
515   // All these functions are potential targets for indirect calls.
516   int32_t NonKernelMaxSGPRs = 0;
517   int32_t NonKernelMaxVGPRs = 0;
518   int32_t NonKernelMaxAGPRs = 0;
519 
520   for (const auto &I : CallGraphResourceInfo) {
521     if (!AMDGPU::isEntryFunctionCC(I.getFirst()->getCallingConv())) {
522       auto &Info = I.getSecond();
523       NonKernelMaxSGPRs = std::max(NonKernelMaxSGPRs, Info.NumExplicitSGPR);
524       NonKernelMaxVGPRs = std::max(NonKernelMaxVGPRs, Info.NumVGPR);
525       NonKernelMaxAGPRs = std::max(NonKernelMaxAGPRs, Info.NumAGPR);
526     }
527   }
528 
529   // Add register usage for functions with indirect calls.
530   // For calls to unknown functions, we assume the maximum register usage of
531   // all non-hardware-entrypoints in the current module.
532   for (auto &I : CallGraphResourceInfo) {
533     auto &Info = I.getSecond();
534     if (Info.HasIndirectCall) {
535       Info.NumExplicitSGPR = std::max(Info.NumExplicitSGPR, NonKernelMaxSGPRs);
536       Info.NumVGPR = std::max(Info.NumVGPR, NonKernelMaxVGPRs);
537       Info.NumAGPR = std::max(Info.NumAGPR, NonKernelMaxAGPRs);
538     }
539   }
540 }
541