1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer --------------------===//
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 ///
11 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary
12 /// code.  When passed an MCAsmStreamer it prints assembly and when passed
13 /// an MCObjectStreamer it outputs binary code.
14 //
15 //===----------------------------------------------------------------------===//
16 //
17 
18 #include "AMDGPUAsmPrinter.h"
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "MCTargetDesc/AMDGPUInstPrinter.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
25 #include "R600AsmPrinter.h"
26 #include "R600Defines.h"
27 #include "R600MachineFunctionInfo.h"
28 #include "R600RegisterInfo.h"
29 #include "SIDefines.h"
30 #include "SIInstrInfo.h"
31 #include "SIMachineFunctionInfo.h"
32 #include "SIRegisterInfo.h"
33 #include "TargetInfo/AMDGPUTargetInfo.h"
34 #include "Utils/AMDGPUBaseInfo.h"
35 #include "llvm/BinaryFormat/ELF.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/MC/MCAssembler.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionELF.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/Support/AMDGPUMetadata.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/TargetParser.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 
48 using namespace llvm;
49 using namespace llvm::AMDGPU;
50 using namespace llvm::AMDGPU::HSAMD;
51 
52 // We need to tell the runtime some amount ahead of time if we don't know the
53 // true stack size. Assume a smaller number if this is only due to dynamic /
54 // non-entry block allocas.
55 static cl::opt<uint32_t> AssumedStackSizeForExternalCall(
56   "amdgpu-assume-external-call-stack-size",
57   cl::desc("Assumed stack use of any external call (in bytes)"),
58   cl::Hidden,
59   cl::init(16384));
60 
61 static cl::opt<uint32_t> AssumedStackSizeForDynamicSizeObjects(
62   "amdgpu-assume-dynamic-stack-object-size",
63   cl::desc("Assumed extra stack use if there are any "
64            "variable sized objects (in bytes)"),
65   cl::Hidden,
66   cl::init(4096));
67 
68 // This should get the default rounding mode from the kernel. We just set the
69 // default here, but this could change if the OpenCL rounding mode pragmas are
70 // used.
71 //
72 // The denormal mode here should match what is reported by the OpenCL runtime
73 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
74 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
75 //
76 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
77 // precision, and leaves single precision to flush all and does not report
78 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
79 // CL_FP_DENORM for both.
80 //
81 // FIXME: It seems some instructions do not support single precision denormals
82 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
83 // and sin_f32, cos_f32 on most parts).
84 
85 // We want to use these instructions, and using fp32 denormals also causes
86 // instructions to run at the double precision rate for the device so it's
87 // probably best to just report no single precision denormals.
88 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) {
89   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
90          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
91          FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) |
92          FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue());
93 }
94 
95 static AsmPrinter *
96 createAMDGPUAsmPrinterPass(TargetMachine &tm,
97                            std::unique_ptr<MCStreamer> &&Streamer) {
98   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
99 }
100 
101 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() {
102   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
103                                      llvm::createR600AsmPrinterPass);
104   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
105                                      createAMDGPUAsmPrinterPass);
106 }
107 
108 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
109                                    std::unique_ptr<MCStreamer> Streamer)
110   : AsmPrinter(TM, std::move(Streamer)) {
111   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
112     if (isHsaAbiVersion2(getGlobalSTI())) {
113       HSAMetadataStream.reset(new MetadataStreamerV2());
114     } else {
115       HSAMetadataStream.reset(new MetadataStreamerV3());
116     }
117   }
118 }
119 
120 StringRef AMDGPUAsmPrinter::getPassName() const {
121   return "AMDGPU Assembly Printer";
122 }
123 
124 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const {
125   return TM.getMCSubtargetInfo();
126 }
127 
128 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const {
129   if (!OutStreamer)
130     return nullptr;
131   return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer());
132 }
133 
134 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) {
135   if (isHsaAbiVersion3(getGlobalSTI())) {
136     std::string ExpectedTarget;
137     raw_string_ostream ExpectedTargetOS(ExpectedTarget);
138     IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS);
139 
140     getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget);
141   }
142 
143   if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
144       TM.getTargetTriple().getOS() != Triple::AMDPAL)
145     return;
146 
147   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
148     HSAMetadataStream->begin(M);
149 
150   if (TM.getTargetTriple().getOS() == Triple::AMDPAL)
151     getTargetStreamer()->getPALMetadata()->readFromIR(M);
152 
153   if (isHsaAbiVersion3(getGlobalSTI()))
154     return;
155 
156   // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2.
157   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
158     getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1);
159 
160   // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2.
161   IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU());
162   getTargetStreamer()->EmitDirectiveHSACodeObjectISA(
163       Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU");
164 }
165 
166 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) {
167   // Following code requires TargetStreamer to be present.
168   if (!getTargetStreamer())
169     return;
170 
171   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
172       isHsaAbiVersion2(getGlobalSTI())) {
173     // Emit ISA Version (NT_AMD_AMDGPU_ISA).
174     std::string ISAVersionString;
175     raw_string_ostream ISAVersionStream(ISAVersionString);
176     IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream);
177     getTargetStreamer()->EmitISAVersion(ISAVersionStream.str());
178   }
179 
180   // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
181   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
182     HSAMetadataStream->end();
183     bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
184     (void)Success;
185     assert(Success && "Malformed HSA Metadata");
186   }
187 }
188 
189 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
190   const MachineBasicBlock *MBB) const {
191   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
192     return false;
193 
194   if (MBB->empty())
195     return true;
196 
197   // If this is a block implementing a long branch, an expression relative to
198   // the start of the block is needed.  to the start of the block.
199   // XXX - Is there a smarter way to check this?
200   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
201 }
202 
203 void AMDGPUAsmPrinter::emitFunctionBodyStart() {
204   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
205   if (!MFI.isEntryFunction())
206     return;
207 
208   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
209   const Function &F = MF->getFunction();
210   if ((STM.isMesaKernel(F) || isHsaAbiVersion2(getGlobalSTI())) &&
211       (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
212        F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
213     amd_kernel_code_t KernelCode;
214     getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
215     getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
216   }
217 
218   if (STM.isAmdHsaOS())
219     HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
220 }
221 
222 void AMDGPUAsmPrinter::emitFunctionBodyEnd() {
223   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
224   if (!MFI.isEntryFunction())
225     return;
226 
227   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
228       isHsaAbiVersion2(getGlobalSTI()))
229     return;
230 
231   auto &Streamer = getTargetStreamer()->getStreamer();
232   auto &Context = Streamer.getContext();
233   auto &ObjectFileInfo = *Context.getObjectFileInfo();
234   auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
235 
236   Streamer.PushSection();
237   Streamer.SwitchSection(&ReadOnlySection);
238 
239   // CP microcode requires the kernel descriptor to be allocated on 64 byte
240   // alignment.
241   Streamer.emitValueToAlignment(64, 0, 1, 0);
242   if (ReadOnlySection.getAlignment() < 64)
243     ReadOnlySection.setAlignment(Align(64));
244 
245   const MCSubtargetInfo &STI = MF->getSubtarget();
246 
247   SmallString<128> KernelName;
248   getNameWithPrefix(KernelName, &MF->getFunction());
249   getTargetStreamer()->EmitAmdhsaKernelDescriptor(
250       STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
251       CurrentProgramInfo.NumVGPRsForWavesPerEU,
252       CurrentProgramInfo.NumSGPRsForWavesPerEU -
253           IsaInfo::getNumExtraSGPRs(&STI,
254                                     CurrentProgramInfo.VCCUsed,
255                                     CurrentProgramInfo.FlatUsed),
256       CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed,
257       hasXNACK(STI));
258 
259   Streamer.PopSection();
260 }
261 
262 void AMDGPUAsmPrinter::emitFunctionEntryLabel() {
263   if (TM.getTargetTriple().getOS() == Triple::AMDHSA &&
264       isHsaAbiVersion3(getGlobalSTI())) {
265     AsmPrinter::emitFunctionEntryLabel();
266     return;
267   }
268 
269   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
270   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
271   if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
272     SmallString<128> SymbolName;
273     getNameWithPrefix(SymbolName, &MF->getFunction()),
274     getTargetStreamer()->EmitAMDGPUSymbolType(
275         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
276   }
277   if (DumpCodeInstEmitter) {
278     // Disassemble function name label to text.
279     DisasmLines.push_back(MF->getName().str() + ":");
280     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
281     HexLines.push_back("");
282   }
283 
284   AsmPrinter::emitFunctionEntryLabel();
285 }
286 
287 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
288   if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
289     // Write a line for the basic block label if it is not only fallthrough.
290     DisasmLines.push_back(
291         (Twine("BB") + Twine(getFunctionNumber())
292          + "_" + Twine(MBB.getNumber()) + ":").str());
293     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
294     HexLines.push_back("");
295   }
296   AsmPrinter::emitBasicBlockStart(MBB);
297 }
298 
299 void AMDGPUAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
300   if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
301     if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
302       OutContext.reportError({},
303                              Twine(GV->getName()) +
304                                  ": unsupported initializer for address space");
305       return;
306     }
307 
308     // LDS variables aren't emitted in HSA or PAL yet.
309     const Triple::OSType OS = TM.getTargetTriple().getOS();
310     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
311       return;
312 
313     MCSymbol *GVSym = getSymbol(GV);
314 
315     GVSym->redefineIfPossible();
316     if (GVSym->isDefined() || GVSym->isVariable())
317       report_fatal_error("symbol '" + Twine(GVSym->getName()) +
318                          "' is already defined");
319 
320     const DataLayout &DL = GV->getParent()->getDataLayout();
321     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
322     Align Alignment = GV->getAlign().getValueOr(Align(4));
323 
324     emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
325     emitLinkage(GV, GVSym);
326     if (auto TS = getTargetStreamer())
327       TS->emitAMDGPULDS(GVSym, Size, Alignment);
328     return;
329   }
330 
331   AsmPrinter::emitGlobalVariable(GV);
332 }
333 
334 bool AMDGPUAsmPrinter::doFinalization(Module &M) {
335   CallGraphResourceInfo.clear();
336 
337   // Pad with s_code_end to help tools and guard against instruction prefetch
338   // causing stale data in caches. Arguably this should be done by the linker,
339   // which is why this isn't done for Mesa.
340   const MCSubtargetInfo &STI = *getGlobalSTI();
341   if (AMDGPU::isGFX10Plus(STI) &&
342       (STI.getTargetTriple().getOS() == Triple::AMDHSA ||
343        STI.getTargetTriple().getOS() == Triple::AMDPAL)) {
344     OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
345     getTargetStreamer()->EmitCodeEnd();
346   }
347 
348   return AsmPrinter::doFinalization(M);
349 }
350 
351 // Print comments that apply to both callable functions and entry points.
352 void AMDGPUAsmPrinter::emitCommonFunctionComments(
353   uint32_t NumVGPR,
354   Optional<uint32_t> NumAGPR,
355   uint32_t TotalNumVGPR,
356   uint32_t NumSGPR,
357   uint64_t ScratchSize,
358   uint64_t CodeSize,
359   const AMDGPUMachineFunction *MFI) {
360   OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
361   OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
362   OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
363   if (NumAGPR) {
364     OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false);
365     OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR),
366                                 false);
367   }
368   OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
369   OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
370                               false);
371 }
372 
373 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
374     const MachineFunction &MF) const {
375   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
376   uint16_t KernelCodeProperties = 0;
377 
378   if (MFI.hasPrivateSegmentBuffer()) {
379     KernelCodeProperties |=
380         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
381   }
382   if (MFI.hasDispatchPtr()) {
383     KernelCodeProperties |=
384         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
385   }
386   if (MFI.hasQueuePtr()) {
387     KernelCodeProperties |=
388         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
389   }
390   if (MFI.hasKernargSegmentPtr()) {
391     KernelCodeProperties |=
392         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
393   }
394   if (MFI.hasDispatchID()) {
395     KernelCodeProperties |=
396         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
397   }
398   if (MFI.hasFlatScratchInit()) {
399     KernelCodeProperties |=
400         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
401   }
402   if (MF.getSubtarget<GCNSubtarget>().isWave32()) {
403     KernelCodeProperties |=
404         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
405   }
406 
407   return KernelCodeProperties;
408 }
409 
410 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
411     const MachineFunction &MF,
412     const SIProgramInfo &PI) const {
413   amdhsa::kernel_descriptor_t KernelDescriptor;
414   memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
415 
416   assert(isUInt<32>(PI.ScratchSize));
417   assert(isUInt<32>(PI.getComputePGMRSrc1()));
418   assert(isUInt<32>(PI.ComputePGMRSrc2));
419 
420   KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
421   KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
422   KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1();
423   KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
424   KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
425 
426   return KernelDescriptor;
427 }
428 
429 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
430   CurrentProgramInfo = SIProgramInfo();
431 
432   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
433 
434   // The starting address of all shader programs must be 256 bytes aligned.
435   // Regular functions just need the basic required instruction alignment.
436   MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4));
437 
438   SetupMachineFunction(MF);
439 
440   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
441   MCContext &Context = getObjFileLowering().getContext();
442   // FIXME: This should be an explicit check for Mesa.
443   if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
444     MCSectionELF *ConfigSection =
445         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
446     OutStreamer->SwitchSection(ConfigSection);
447   }
448 
449   if (MFI->isEntryFunction()) {
450     getSIProgramInfo(CurrentProgramInfo, MF);
451   } else {
452     auto I = CallGraphResourceInfo.insert(
453       std::make_pair(&MF.getFunction(), SIFunctionResourceInfo()));
454     SIFunctionResourceInfo &Info = I.first->second;
455     assert(I.second && "should only be called once per function");
456     Info = analyzeResourceUsage(MF);
457   }
458 
459   if (STM.isAmdPalOS()) {
460     if (MFI->isEntryFunction())
461       EmitPALMetadata(MF, CurrentProgramInfo);
462     else
463       emitPALFunctionMetadata(MF);
464   } else if (!STM.isAmdHsaOS()) {
465     EmitProgramInfoSI(MF, CurrentProgramInfo);
466   }
467 
468   DumpCodeInstEmitter = nullptr;
469   if (STM.dumpCode()) {
470     // For -dumpcode, get the assembler out of the streamer, even if it does
471     // not really want to let us have it. This only works with -filetype=obj.
472     bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing();
473     OutStreamer->setUseAssemblerInfoForParsing(true);
474     MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
475     OutStreamer->setUseAssemblerInfoForParsing(SaveFlag);
476     if (Assembler)
477       DumpCodeInstEmitter = Assembler->getEmitterPtr();
478   }
479 
480   DisasmLines.clear();
481   HexLines.clear();
482   DisasmLineMaxLen = 0;
483 
484   emitFunctionBody();
485 
486   if (isVerbose()) {
487     MCSectionELF *CommentSection =
488         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
489     OutStreamer->SwitchSection(CommentSection);
490 
491     if (!MFI->isEntryFunction()) {
492       OutStreamer->emitRawComment(" Function info:", false);
493       SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()];
494       emitCommonFunctionComments(
495         Info.NumVGPR,
496         STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(),
497         Info.getTotalNumVGPRs(STM),
498         Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
499         Info.PrivateSegmentSize,
500         getFunctionCodeSize(MF), MFI);
501       return false;
502     }
503 
504     OutStreamer->emitRawComment(" Kernel info:", false);
505     emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR,
506                                STM.hasMAIInsts()
507                                  ? CurrentProgramInfo.NumAccVGPR
508                                  : Optional<uint32_t>(),
509                                CurrentProgramInfo.NumVGPR,
510                                CurrentProgramInfo.NumSGPR,
511                                CurrentProgramInfo.ScratchSize,
512                                getFunctionCodeSize(MF), MFI);
513 
514     OutStreamer->emitRawComment(
515       " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
516     OutStreamer->emitRawComment(
517       " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
518     OutStreamer->emitRawComment(
519       " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
520       " bytes/workgroup (compile time only)", false);
521 
522     OutStreamer->emitRawComment(
523       " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
524     OutStreamer->emitRawComment(
525       " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
526 
527     OutStreamer->emitRawComment(
528       " NumSGPRsForWavesPerEU: " +
529       Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
530     OutStreamer->emitRawComment(
531       " NumVGPRsForWavesPerEU: " +
532       Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
533 
534     OutStreamer->emitRawComment(
535       " Occupancy: " +
536       Twine(CurrentProgramInfo.Occupancy), false);
537 
538     OutStreamer->emitRawComment(
539       " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
540 
541     OutStreamer->emitRawComment(
542       " COMPUTE_PGM_RSRC2:USER_SGPR: " +
543       Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
544     OutStreamer->emitRawComment(
545       " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
546       Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
547     OutStreamer->emitRawComment(
548       " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
549       Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
550     OutStreamer->emitRawComment(
551       " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
552       Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
553     OutStreamer->emitRawComment(
554       " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
555       Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
556     OutStreamer->emitRawComment(
557       " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
558       Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
559       false);
560   }
561 
562   if (DumpCodeInstEmitter) {
563 
564     OutStreamer->SwitchSection(
565         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0));
566 
567     for (size_t i = 0; i < DisasmLines.size(); ++i) {
568       std::string Comment = "\n";
569       if (!HexLines[i].empty()) {
570         Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
571         Comment += " ; " + HexLines[i] + "\n";
572       }
573 
574       OutStreamer->emitBytes(StringRef(DisasmLines[i]));
575       OutStreamer->emitBytes(StringRef(Comment));
576     }
577   }
578 
579   return false;
580 }
581 
582 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
583   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
584   const SIInstrInfo *TII = STM.getInstrInfo();
585 
586   uint64_t CodeSize = 0;
587 
588   for (const MachineBasicBlock &MBB : MF) {
589     for (const MachineInstr &MI : MBB) {
590       // TODO: CodeSize should account for multiple functions.
591 
592       // TODO: Should we count size of debug info?
593       if (MI.isDebugInstr())
594         continue;
595 
596       CodeSize += TII->getInstSizeInBytes(MI);
597     }
598   }
599 
600   return CodeSize;
601 }
602 
603 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI,
604                                   const SIInstrInfo &TII,
605                                   unsigned Reg) {
606   for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) {
607     if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent()))
608       return true;
609   }
610 
611   return false;
612 }
613 
614 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs(
615   const GCNSubtarget &ST) const {
616   return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST,
617                                                      UsesVCC, UsesFlatScratch);
618 }
619 
620 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumVGPRs(
621   const GCNSubtarget &ST) const {
622   return std::max(NumVGPR, NumAGPR);
623 }
624 
625 static const Function *getCalleeFunction(const MachineOperand &Op) {
626   if (Op.isImm()) {
627     assert(Op.getImm() == 0);
628     return nullptr;
629   }
630 
631   return cast<Function>(Op.getGlobal());
632 }
633 
634 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage(
635   const MachineFunction &MF) const {
636   SIFunctionResourceInfo Info;
637 
638   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
639   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
640   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
641   const MachineRegisterInfo &MRI = MF.getRegInfo();
642   const SIInstrInfo *TII = ST.getInstrInfo();
643   const SIRegisterInfo &TRI = TII->getRegisterInfo();
644 
645   Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) ||
646                          MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI);
647 
648   // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
649   // instructions aren't used to access the scratch buffer. Inline assembly may
650   // need it though.
651   //
652   // If we only have implicit uses of flat_scr on flat instructions, it is not
653   // really needed.
654   if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() &&
655       (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) &&
656        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) &&
657        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) {
658     Info.UsesFlatScratch = false;
659   }
660 
661   Info.PrivateSegmentSize = FrameInfo.getStackSize();
662 
663   // Assume a big number if there are any unknown sized objects.
664   Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects();
665   if (Info.HasDynamicallySizedStack)
666     Info.PrivateSegmentSize += AssumedStackSizeForDynamicSizeObjects;
667 
668   if (MFI->isStackRealigned())
669     Info.PrivateSegmentSize += FrameInfo.getMaxAlign().value();
670 
671   Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) ||
672                  MRI.isPhysRegUsed(AMDGPU::VCC_HI);
673 
674   // If there are no calls, MachineRegisterInfo can tell us the used register
675   // count easily.
676   // A tail call isn't considered a call for MachineFrameInfo's purposes.
677   if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) {
678     MCPhysReg HighestVGPRReg = AMDGPU::NoRegister;
679     for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) {
680       if (MRI.isPhysRegUsed(Reg)) {
681         HighestVGPRReg = Reg;
682         break;
683       }
684     }
685 
686     if (ST.hasMAIInsts()) {
687       MCPhysReg HighestAGPRReg = AMDGPU::NoRegister;
688       for (MCPhysReg Reg : reverse(AMDGPU::AGPR_32RegClass.getRegisters())) {
689         if (MRI.isPhysRegUsed(Reg)) {
690           HighestAGPRReg = Reg;
691           break;
692         }
693       }
694       Info.NumAGPR = HighestAGPRReg == AMDGPU::NoRegister ? 0 :
695         TRI.getHWRegIndex(HighestAGPRReg) + 1;
696     }
697 
698     MCPhysReg HighestSGPRReg = AMDGPU::NoRegister;
699     for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) {
700       if (MRI.isPhysRegUsed(Reg)) {
701         HighestSGPRReg = Reg;
702         break;
703       }
704     }
705 
706     // We found the maximum register index. They start at 0, so add one to get the
707     // number of registers.
708     Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 :
709       TRI.getHWRegIndex(HighestVGPRReg) + 1;
710     Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 :
711       TRI.getHWRegIndex(HighestSGPRReg) + 1;
712 
713     return Info;
714   }
715 
716   int32_t MaxVGPR = -1;
717   int32_t MaxAGPR = -1;
718   int32_t MaxSGPR = -1;
719   uint64_t CalleeFrameSize = 0;
720 
721   for (const MachineBasicBlock &MBB : MF) {
722     for (const MachineInstr &MI : MBB) {
723       // TODO: Check regmasks? Do they occur anywhere except calls?
724       for (const MachineOperand &MO : MI.operands()) {
725         unsigned Width = 0;
726         bool IsSGPR = false;
727         bool IsAGPR = false;
728 
729         if (!MO.isReg())
730           continue;
731 
732         Register Reg = MO.getReg();
733         switch (Reg) {
734         case AMDGPU::EXEC:
735         case AMDGPU::EXEC_LO:
736         case AMDGPU::EXEC_HI:
737         case AMDGPU::SCC:
738         case AMDGPU::M0:
739         case AMDGPU::SRC_SHARED_BASE:
740         case AMDGPU::SRC_SHARED_LIMIT:
741         case AMDGPU::SRC_PRIVATE_BASE:
742         case AMDGPU::SRC_PRIVATE_LIMIT:
743         case AMDGPU::SGPR_NULL:
744         case AMDGPU::MODE:
745           continue;
746 
747         case AMDGPU::SRC_POPS_EXITING_WAVE_ID:
748           llvm_unreachable("src_pops_exiting_wave_id should not be used");
749 
750         case AMDGPU::NoRegister:
751           assert(MI.isDebugInstr() && "Instruction uses invalid noreg register");
752           continue;
753 
754         case AMDGPU::VCC:
755         case AMDGPU::VCC_LO:
756         case AMDGPU::VCC_HI:
757         case AMDGPU::VCC_LO_LO16:
758         case AMDGPU::VCC_LO_HI16:
759         case AMDGPU::VCC_HI_LO16:
760         case AMDGPU::VCC_HI_HI16:
761           Info.UsesVCC = true;
762           continue;
763 
764         case AMDGPU::FLAT_SCR:
765         case AMDGPU::FLAT_SCR_LO:
766         case AMDGPU::FLAT_SCR_HI:
767           continue;
768 
769         case AMDGPU::XNACK_MASK:
770         case AMDGPU::XNACK_MASK_LO:
771         case AMDGPU::XNACK_MASK_HI:
772           llvm_unreachable("xnack_mask registers should not be used");
773 
774         case AMDGPU::LDS_DIRECT:
775           llvm_unreachable("lds_direct register should not be used");
776 
777         case AMDGPU::TBA:
778         case AMDGPU::TBA_LO:
779         case AMDGPU::TBA_HI:
780         case AMDGPU::TMA:
781         case AMDGPU::TMA_LO:
782         case AMDGPU::TMA_HI:
783           llvm_unreachable("trap handler registers should not be used");
784 
785         case AMDGPU::SRC_VCCZ:
786           llvm_unreachable("src_vccz register should not be used");
787 
788         case AMDGPU::SRC_EXECZ:
789           llvm_unreachable("src_execz register should not be used");
790 
791         case AMDGPU::SRC_SCC:
792           llvm_unreachable("src_scc register should not be used");
793 
794         default:
795           break;
796         }
797 
798         if (AMDGPU::SReg_32RegClass.contains(Reg) ||
799             AMDGPU::SReg_LO16RegClass.contains(Reg) ||
800             AMDGPU::SGPR_HI16RegClass.contains(Reg)) {
801           assert(!AMDGPU::TTMP_32RegClass.contains(Reg) &&
802                  "trap handler registers should not be used");
803           IsSGPR = true;
804           Width = 1;
805         } else if (AMDGPU::VGPR_32RegClass.contains(Reg) ||
806                    AMDGPU::VGPR_LO16RegClass.contains(Reg) ||
807                    AMDGPU::VGPR_HI16RegClass.contains(Reg)) {
808           IsSGPR = false;
809           Width = 1;
810         } else if (AMDGPU::AGPR_32RegClass.contains(Reg) ||
811                    AMDGPU::AGPR_LO16RegClass.contains(Reg)) {
812           IsSGPR = false;
813           IsAGPR = true;
814           Width = 1;
815         } else if (AMDGPU::SReg_64RegClass.contains(Reg)) {
816           assert(!AMDGPU::TTMP_64RegClass.contains(Reg) &&
817                  "trap handler registers should not be used");
818           IsSGPR = true;
819           Width = 2;
820         } else if (AMDGPU::VReg_64RegClass.contains(Reg)) {
821           IsSGPR = false;
822           Width = 2;
823         } else if (AMDGPU::AReg_64RegClass.contains(Reg)) {
824           IsSGPR = false;
825           IsAGPR = true;
826           Width = 2;
827         } else if (AMDGPU::VReg_96RegClass.contains(Reg)) {
828           IsSGPR = false;
829           Width = 3;
830         } else if (AMDGPU::SReg_96RegClass.contains(Reg)) {
831           IsSGPR = true;
832           Width = 3;
833         } else if (AMDGPU::AReg_96RegClass.contains(Reg)) {
834           IsSGPR = false;
835           IsAGPR = true;
836           Width = 3;
837         } else if (AMDGPU::SReg_128RegClass.contains(Reg)) {
838           assert(!AMDGPU::TTMP_128RegClass.contains(Reg) &&
839             "trap handler registers should not be used");
840           IsSGPR = true;
841           Width = 4;
842         } else if (AMDGPU::VReg_128RegClass.contains(Reg)) {
843           IsSGPR = false;
844           Width = 4;
845         } else if (AMDGPU::AReg_128RegClass.contains(Reg)) {
846           IsSGPR = false;
847           IsAGPR = true;
848           Width = 4;
849         } else if (AMDGPU::VReg_160RegClass.contains(Reg)) {
850           IsSGPR = false;
851           Width = 5;
852         } else if (AMDGPU::SReg_160RegClass.contains(Reg)) {
853           IsSGPR = true;
854           Width = 5;
855         } else if (AMDGPU::AReg_160RegClass.contains(Reg)) {
856           IsSGPR = false;
857           IsAGPR = true;
858           Width = 5;
859         } else if (AMDGPU::VReg_192RegClass.contains(Reg)) {
860           IsSGPR = false;
861           Width = 6;
862         } else if (AMDGPU::SReg_192RegClass.contains(Reg)) {
863           IsSGPR = true;
864           Width = 6;
865         } else if (AMDGPU::AReg_192RegClass.contains(Reg)) {
866           IsSGPR = false;
867           IsAGPR = true;
868           Width = 6;
869         } else if (AMDGPU::SReg_256RegClass.contains(Reg)) {
870           assert(!AMDGPU::TTMP_256RegClass.contains(Reg) &&
871             "trap handler registers should not be used");
872           IsSGPR = true;
873           Width = 8;
874         } else if (AMDGPU::VReg_256RegClass.contains(Reg)) {
875           IsSGPR = false;
876           Width = 8;
877         } else if (AMDGPU::AReg_256RegClass.contains(Reg)) {
878           IsSGPR = false;
879           IsAGPR = true;
880           Width = 8;
881         } else if (AMDGPU::SReg_512RegClass.contains(Reg)) {
882           assert(!AMDGPU::TTMP_512RegClass.contains(Reg) &&
883             "trap handler registers should not be used");
884           IsSGPR = true;
885           Width = 16;
886         } else if (AMDGPU::VReg_512RegClass.contains(Reg)) {
887           IsSGPR = false;
888           Width = 16;
889         } else if (AMDGPU::AReg_512RegClass.contains(Reg)) {
890           IsSGPR = false;
891           IsAGPR = true;
892           Width = 16;
893         } else if (AMDGPU::SReg_1024RegClass.contains(Reg)) {
894           IsSGPR = true;
895           Width = 32;
896         } else if (AMDGPU::VReg_1024RegClass.contains(Reg)) {
897           IsSGPR = false;
898           Width = 32;
899         } else if (AMDGPU::AReg_1024RegClass.contains(Reg)) {
900           IsSGPR = false;
901           IsAGPR = true;
902           Width = 32;
903         } else {
904           llvm_unreachable("Unknown register class");
905         }
906         unsigned HWReg = TRI.getHWRegIndex(Reg);
907         int MaxUsed = HWReg + Width - 1;
908         if (IsSGPR) {
909           MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR;
910         } else if (IsAGPR) {
911           MaxAGPR = MaxUsed > MaxAGPR ? MaxUsed : MaxAGPR;
912         } else {
913           MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR;
914         }
915       }
916 
917       if (MI.isCall()) {
918         // Pseudo used just to encode the underlying global. Is there a better
919         // way to track this?
920 
921         const MachineOperand *CalleeOp
922           = TII->getNamedOperand(MI, AMDGPU::OpName::callee);
923 
924         const Function *Callee = getCalleeFunction(*CalleeOp);
925         if (!Callee || Callee->isDeclaration()) {
926           // If this is a call to an external function, we can't do much. Make
927           // conservative guesses.
928 
929           // 48 SGPRs - vcc, - flat_scr, -xnack
930           int MaxSGPRGuess =
931             47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace());
932           MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess);
933           MaxVGPR = std::max(MaxVGPR, 23);
934           MaxAGPR = std::max(MaxAGPR, 23);
935 
936           CalleeFrameSize = std::max(CalleeFrameSize,
937             static_cast<uint64_t>(AssumedStackSizeForExternalCall));
938 
939           Info.UsesVCC = true;
940           Info.UsesFlatScratch = ST.hasFlatAddressSpace();
941           Info.HasDynamicallySizedStack = true;
942         } else {
943           // We force CodeGen to run in SCC order, so the callee's register
944           // usage etc. should be the cumulative usage of all callees.
945 
946           auto I = CallGraphResourceInfo.find(Callee);
947           if (I == CallGraphResourceInfo.end()) {
948             // Avoid crashing on undefined behavior with an illegal call to a
949             // kernel. If a callsite's calling convention doesn't match the
950             // function's, it's undefined behavior. If the callsite calling
951             // convention does match, that would have errored earlier.
952             // FIXME: The verifier shouldn't allow this.
953             if (AMDGPU::isEntryFunctionCC(Callee->getCallingConv()))
954               report_fatal_error("invalid call to entry function");
955 
956             llvm_unreachable("callee should have been handled before caller");
957           }
958 
959           MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR);
960           MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR);
961           MaxAGPR = std::max(I->second.NumAGPR - 1, MaxAGPR);
962           CalleeFrameSize
963             = std::max(I->second.PrivateSegmentSize, CalleeFrameSize);
964           Info.UsesVCC |= I->second.UsesVCC;
965           Info.UsesFlatScratch |= I->second.UsesFlatScratch;
966           Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack;
967           Info.HasRecursion |= I->second.HasRecursion;
968         }
969 
970         // FIXME: Call site could have norecurse on it
971         if (!Callee || !Callee->doesNotRecurse())
972           Info.HasRecursion = true;
973       }
974     }
975   }
976 
977   Info.NumExplicitSGPR = MaxSGPR + 1;
978   Info.NumVGPR = MaxVGPR + 1;
979   Info.NumAGPR = MaxAGPR + 1;
980   Info.PrivateSegmentSize += CalleeFrameSize;
981 
982   return Info;
983 }
984 
985 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
986                                         const MachineFunction &MF) {
987   SIFunctionResourceInfo Info = analyzeResourceUsage(MF);
988   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
989 
990   ProgInfo.NumArchVGPR = Info.NumVGPR;
991   ProgInfo.NumAccVGPR = Info.NumAGPR;
992   ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM);
993   ProgInfo.NumSGPR = Info.NumExplicitSGPR;
994   ProgInfo.ScratchSize = Info.PrivateSegmentSize;
995   ProgInfo.VCCUsed = Info.UsesVCC;
996   ProgInfo.FlatUsed = Info.UsesFlatScratch;
997   ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
998 
999   const uint64_t MaxScratchPerWorkitem =
1000       GCNSubtarget::MaxWaveScratchSize / STM.getWavefrontSize();
1001   if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) {
1002     DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
1003                                           ProgInfo.ScratchSize, DS_Error);
1004     MF.getFunction().getContext().diagnose(DiagStackSize);
1005   }
1006 
1007   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1008 
1009   // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are
1010   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
1011   // unified.
1012   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
1013       &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
1014 
1015   // Check the addressable register limit before we add ExtraSGPRs.
1016   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
1017       !STM.hasSGPRInitBug()) {
1018     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1019     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
1020       // This can happen due to a compiler bug or when using inline asm.
1021       LLVMContext &Ctx = MF.getFunction().getContext();
1022       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
1023                                        "addressable scalar registers",
1024                                        ProgInfo.NumSGPR, DS_Error,
1025                                        DK_ResourceLimit,
1026                                        MaxAddressableNumSGPRs);
1027       Ctx.diagnose(Diag);
1028       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
1029     }
1030   }
1031 
1032   // Account for extra SGPRs and VGPRs reserved for debugger use.
1033   ProgInfo.NumSGPR += ExtraSGPRs;
1034 
1035   const Function &F = MF.getFunction();
1036 
1037   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
1038   // dispatch registers are function args.
1039   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
1040 
1041   if (isShader(F.getCallingConv())) {
1042     // FIXME: We should be using the number of registers determined during
1043     // calling convention lowering to legalize the types.
1044     const DataLayout &DL = F.getParent()->getDataLayout();
1045     for (auto &Arg : F.args()) {
1046       unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32;
1047       if (Arg.hasAttribute(Attribute::InReg))
1048         WaveDispatchNumSGPR += NumRegs;
1049       else
1050         WaveDispatchNumVGPR += NumRegs;
1051     }
1052     ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
1053     ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
1054   }
1055 
1056   // Adjust number of registers used to meet default/requested minimum/maximum
1057   // number of waves per execution unit request.
1058   ProgInfo.NumSGPRsForWavesPerEU = std::max(
1059     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
1060   ProgInfo.NumVGPRsForWavesPerEU = std::max(
1061     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
1062 
1063   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
1064       STM.hasSGPRInitBug()) {
1065     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1066     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
1067       // This can happen due to a compiler bug or when using inline asm to use
1068       // the registers which are usually reserved for vcc etc.
1069       LLVMContext &Ctx = MF.getFunction().getContext();
1070       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
1071                                        "scalar registers",
1072                                        ProgInfo.NumSGPR, DS_Error,
1073                                        DK_ResourceLimit,
1074                                        MaxAddressableNumSGPRs);
1075       Ctx.diagnose(Diag);
1076       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
1077       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
1078     }
1079   }
1080 
1081   if (STM.hasSGPRInitBug()) {
1082     ProgInfo.NumSGPR =
1083         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
1084     ProgInfo.NumSGPRsForWavesPerEU =
1085         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
1086   }
1087 
1088   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
1089     LLVMContext &Ctx = MF.getFunction().getContext();
1090     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
1091                                      MFI->getNumUserSGPRs(), DS_Error);
1092     Ctx.diagnose(Diag);
1093   }
1094 
1095   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
1096     LLVMContext &Ctx = MF.getFunction().getContext();
1097     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
1098                                      MFI->getLDSSize(), DS_Error);
1099     Ctx.diagnose(Diag);
1100   }
1101 
1102   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
1103       &STM, ProgInfo.NumSGPRsForWavesPerEU);
1104   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
1105       &STM, ProgInfo.NumVGPRsForWavesPerEU);
1106 
1107   const SIModeRegisterDefaults Mode = MFI->getMode();
1108 
1109   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
1110   // register.
1111   ProgInfo.FloatMode = getFPMode(Mode);
1112 
1113   ProgInfo.IEEEMode = Mode.IEEE;
1114 
1115   // Make clamp modifier on NaN input returns 0.
1116   ProgInfo.DX10Clamp = Mode.DX10Clamp;
1117 
1118   unsigned LDSAlignShift;
1119   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
1120     // LDS is allocated in 64 dword blocks.
1121     LDSAlignShift = 8;
1122   } else {
1123     // LDS is allocated in 128 dword blocks.
1124     LDSAlignShift = 9;
1125   }
1126 
1127   unsigned LDSSpillSize =
1128     MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
1129 
1130   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
1131   ProgInfo.LDSBlocks =
1132       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
1133 
1134   // Scratch is allocated in 256 dword blocks.
1135   unsigned ScratchAlignShift = 10;
1136   // We need to program the hardware with the amount of scratch memory that
1137   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
1138   // scratch memory used per thread.
1139   ProgInfo.ScratchBlocks =
1140       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
1141               1ULL << ScratchAlignShift) >>
1142       ScratchAlignShift;
1143 
1144   if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
1145     ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
1146     ProgInfo.MemOrdered = 1;
1147   }
1148 
1149   // 0 = X, 1 = XY, 2 = XYZ
1150   unsigned TIDIGCompCnt = 0;
1151   if (MFI->hasWorkItemIDZ())
1152     TIDIGCompCnt = 2;
1153   else if (MFI->hasWorkItemIDY())
1154     TIDIGCompCnt = 1;
1155 
1156   ProgInfo.ComputePGMRSrc2 =
1157       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
1158       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
1159       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
1160       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
1161       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
1162       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
1163       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
1164       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
1165       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
1166       S_00B84C_EXCP_EN_MSB(0) |
1167       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
1168       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
1169       S_00B84C_EXCP_EN(0);
1170 
1171   ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize,
1172                                             ProgInfo.NumSGPRsForWavesPerEU,
1173                                             ProgInfo.NumVGPRsForWavesPerEU);
1174 }
1175 
1176 static unsigned getRsrcReg(CallingConv::ID CallConv) {
1177   switch (CallConv) {
1178   default: LLVM_FALLTHROUGH;
1179   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
1180   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
1181   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
1182   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
1183   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
1184   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
1185   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
1186   }
1187 }
1188 
1189 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
1190                                          const SIProgramInfo &CurrentProgramInfo) {
1191   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1192   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
1193 
1194   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1195     OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1);
1196 
1197     OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1());
1198 
1199     OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2);
1200     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2);
1201 
1202     OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE);
1203     OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks));
1204 
1205     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
1206     // 0" comment but I don't see a corresponding field in the register spec.
1207   } else {
1208     OutStreamer->emitInt32(RsrcReg);
1209     OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1210                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
1211     OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE);
1212     OutStreamer->emitIntValue(
1213         S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1214   }
1215 
1216   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1217     OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS);
1218     OutStreamer->emitInt32(
1219         S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
1220     OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA);
1221     OutStreamer->emitInt32(MFI->getPSInputEnable());
1222     OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR);
1223     OutStreamer->emitInt32(MFI->getPSInputAddr());
1224   }
1225 
1226   OutStreamer->emitInt32(R_SPILLED_SGPRS);
1227   OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
1228   OutStreamer->emitInt32(R_SPILLED_VGPRS);
1229   OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
1230 }
1231 
1232 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1233 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
1234 // metadata items into the PALMD::Metadata, combining with any provided by the
1235 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
1236 // is then written as a single block in the .note section.
1237 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
1238        const SIProgramInfo &CurrentProgramInfo) {
1239   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1240   auto CC = MF.getFunction().getCallingConv();
1241   auto MD = getTargetStreamer()->getPALMetadata();
1242 
1243   MD->setEntryPoint(CC, MF.getFunction().getName());
1244   MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1245   MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1246   MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC));
1247   if (AMDGPU::isCompute(CC)) {
1248     MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
1249   } else {
1250     if (CurrentProgramInfo.ScratchBlocks > 0)
1251       MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
1252   }
1253   // ScratchSize is in bytes, 16 aligned.
1254   MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
1255   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1256     MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
1257     MD->setSpiPsInputEna(MFI->getPSInputEnable());
1258     MD->setSpiPsInputAddr(MFI->getPSInputAddr());
1259   }
1260 
1261   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1262   if (STM.isWave32())
1263     MD->setWave32(MF.getFunction().getCallingConv());
1264 }
1265 
1266 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) {
1267   auto *MD = getTargetStreamer()->getPALMetadata();
1268   const MachineFrameInfo &MFI = MF.getFrameInfo();
1269   MD->setStackFrameSize(MF, MFI.getStackSize());
1270 }
1271 
1272 // This is supposed to be log2(Size)
1273 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
1274   switch (Size) {
1275   case 4:
1276     return AMD_ELEMENT_4_BYTES;
1277   case 8:
1278     return AMD_ELEMENT_8_BYTES;
1279   case 16:
1280     return AMD_ELEMENT_16_BYTES;
1281   default:
1282     llvm_unreachable("invalid private_element_size");
1283   }
1284 }
1285 
1286 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1287                                         const SIProgramInfo &CurrentProgramInfo,
1288                                         const MachineFunction &MF) const {
1289   const Function &F = MF.getFunction();
1290   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
1291          F.getCallingConv() == CallingConv::SPIR_KERNEL);
1292 
1293   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1294   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1295 
1296   AMDGPU::initDefaultAMDKernelCodeT(Out, &STM);
1297 
1298   Out.compute_pgm_resource_registers =
1299       CurrentProgramInfo.getComputePGMRSrc1() |
1300       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1301   Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
1302 
1303   if (CurrentProgramInfo.DynamicCallStack)
1304     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1305 
1306   AMD_HSA_BITS_SET(Out.code_properties,
1307                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1308                    getElementByteSizeValue(STM.getMaxPrivateElementSize(true)));
1309 
1310   if (MFI->hasPrivateSegmentBuffer()) {
1311     Out.code_properties |=
1312       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1313   }
1314 
1315   if (MFI->hasDispatchPtr())
1316     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1317 
1318   if (MFI->hasQueuePtr())
1319     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1320 
1321   if (MFI->hasKernargSegmentPtr())
1322     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1323 
1324   if (MFI->hasDispatchID())
1325     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1326 
1327   if (MFI->hasFlatScratchInit())
1328     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1329 
1330   if (MFI->hasDispatchPtr())
1331     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1332 
1333   if (STM.isXNACKEnabled())
1334     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1335 
1336   Align MaxKernArgAlign;
1337   Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1338   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1339   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1340   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1341   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1342 
1343   // kernarg_segment_alignment is specified as log of the alignment.
1344   // The minimum alignment is 16.
1345   Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign));
1346 }
1347 
1348 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1349                                        const char *ExtraCode, raw_ostream &O) {
1350   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1351   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1352     return false;
1353 
1354   if (ExtraCode && ExtraCode[0]) {
1355     if (ExtraCode[1] != 0)
1356       return true; // Unknown modifier.
1357 
1358     switch (ExtraCode[0]) {
1359     case 'r':
1360       break;
1361     default:
1362       return true;
1363     }
1364   }
1365 
1366   // TODO: Should be able to support other operand types like globals.
1367   const MachineOperand &MO = MI->getOperand(OpNo);
1368   if (MO.isReg()) {
1369     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1370                                        *MF->getSubtarget().getRegisterInfo());
1371     return false;
1372   } else if (MO.isImm()) {
1373     int64_t Val = MO.getImm();
1374     if (AMDGPU::isInlinableIntLiteral(Val)) {
1375       O << Val;
1376     } else if (isUInt<16>(Val)) {
1377       O << format("0x%" PRIx16, static_cast<uint16_t>(Val));
1378     } else if (isUInt<32>(Val)) {
1379       O << format("0x%" PRIx32, static_cast<uint32_t>(Val));
1380     } else {
1381       O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1382     }
1383     return false;
1384   }
1385   return true;
1386 }
1387