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 "AMDGPUHSAMetadataStreamer.h"
21 #include "AMDGPUResourceUsageAnalysis.h"
22 #include "AMDKernelCodeT.h"
23 #include "GCNSubtarget.h"
24 #include "MCTargetDesc/AMDGPUInstPrinter.h"
25 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
26 #include "R600AsmPrinter.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "TargetInfo/AMDGPUTargetInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
31 #include "llvm/BinaryFormat/ELF.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/MC/MCAssembler.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCSectionELF.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/TargetRegistry.h"
40 #include "llvm/Support/AMDHSAKernelDescriptor.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetMachine.h"
44 
45 using namespace llvm;
46 using namespace llvm::AMDGPU;
47 
48 // This should get the default rounding mode from the kernel. We just set the
49 // default here, but this could change if the OpenCL rounding mode pragmas are
50 // used.
51 //
52 // The denormal mode here should match what is reported by the OpenCL runtime
53 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
54 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
55 //
56 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
57 // precision, and leaves single precision to flush all and does not report
58 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
59 // CL_FP_DENORM for both.
60 //
61 // FIXME: It seems some instructions do not support single precision denormals
62 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
63 // and sin_f32, cos_f32 on most parts).
64 
65 // We want to use these instructions, and using fp32 denormals also causes
66 // instructions to run at the double precision rate for the device so it's
67 // probably best to just report no single precision denormals.
68 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) {
69   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
70          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
71          FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) |
72          FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue());
73 }
74 
75 static AsmPrinter *
76 createAMDGPUAsmPrinterPass(TargetMachine &tm,
77                            std::unique_ptr<MCStreamer> &&Streamer) {
78   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
79 }
80 
81 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() {
82   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
83                                      llvm::createR600AsmPrinterPass);
84   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
85                                      createAMDGPUAsmPrinterPass);
86 }
87 
88 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
89                                    std::unique_ptr<MCStreamer> Streamer)
90     : AsmPrinter(TM, std::move(Streamer)) {
91   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
92     if (isHsaAbiVersion2(getGlobalSTI())) {
93       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV2());
94     } else if (isHsaAbiVersion3(getGlobalSTI())) {
95       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV3());
96     } else if (isHsaAbiVersion5(getGlobalSTI())) {
97       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV5());
98     } else {
99       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV4());
100     }
101   }
102 }
103 
104 StringRef AMDGPUAsmPrinter::getPassName() const {
105   return "AMDGPU Assembly Printer";
106 }
107 
108 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const {
109   return TM.getMCSubtargetInfo();
110 }
111 
112 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const {
113   if (!OutStreamer)
114     return nullptr;
115   return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer());
116 }
117 
118 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) {
119   IsTargetStreamerInitialized = false;
120 }
121 
122 void AMDGPUAsmPrinter::initTargetStreamer(Module &M) {
123   IsTargetStreamerInitialized = true;
124 
125   // TODO: Which one is called first, emitStartOfAsmFile or
126   // emitFunctionBodyStart?
127   if (getTargetStreamer() && !getTargetStreamer()->getTargetID())
128     initializeTargetID(M);
129 
130   if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
131       TM.getTargetTriple().getOS() != Triple::AMDPAL)
132     return;
133 
134   if (isHsaAbiVersion3AndAbove(getGlobalSTI()))
135     getTargetStreamer()->EmitDirectiveAMDGCNTarget();
136 
137   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
138     HSAMetadataStream->begin(M, *getTargetStreamer()->getTargetID());
139 
140   if (TM.getTargetTriple().getOS() == Triple::AMDPAL)
141     getTargetStreamer()->getPALMetadata()->readFromIR(M);
142 
143   if (isHsaAbiVersion3AndAbove(getGlobalSTI()))
144     return;
145 
146   // HSA emits NT_AMD_HSA_CODE_OBJECT_VERSION for code objects v2.
147   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
148     getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1);
149 
150   // HSA and PAL emit NT_AMD_HSA_ISA_VERSION for code objects v2.
151   IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU());
152   getTargetStreamer()->EmitDirectiveHSACodeObjectISAV2(
153       Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU");
154 }
155 
156 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) {
157   // Init target streamer if it has not yet happened
158   if (!IsTargetStreamerInitialized)
159     initTargetStreamer(M);
160 
161   // Following code requires TargetStreamer to be present.
162   if (!getTargetStreamer())
163     return;
164 
165   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
166       isHsaAbiVersion2(getGlobalSTI()))
167     getTargetStreamer()->EmitISAVersion();
168 
169   // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
170   // Emit HSA Metadata (NT_AMD_HSA_METADATA).
171   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
172     HSAMetadataStream->end();
173     bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
174     (void)Success;
175     assert(Success && "Malformed HSA Metadata");
176   }
177 }
178 
179 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
180   const MachineBasicBlock *MBB) const {
181   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
182     return false;
183 
184   if (MBB->empty())
185     return true;
186 
187   // If this is a block implementing a long branch, an expression relative to
188   // the start of the block is needed.  to the start of the block.
189   // XXX - Is there a smarter way to check this?
190   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
191 }
192 
193 void AMDGPUAsmPrinter::emitFunctionBodyStart() {
194   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
195   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
196   const Function &F = MF->getFunction();
197 
198   // TODO: Which one is called first, emitStartOfAsmFile or
199   // emitFunctionBodyStart?
200   if (getTargetStreamer() && !getTargetStreamer()->getTargetID())
201     initializeTargetID(*F.getParent());
202 
203   const auto &FunctionTargetID = STM.getTargetID();
204   // Make sure function's xnack settings are compatible with module's
205   // xnack settings.
206   if (FunctionTargetID.isXnackSupported() &&
207       FunctionTargetID.getXnackSetting() != IsaInfo::TargetIDSetting::Any &&
208       FunctionTargetID.getXnackSetting() != getTargetStreamer()->getTargetID()->getXnackSetting()) {
209     OutContext.reportError({}, "xnack setting of '" + Twine(MF->getName()) +
210                            "' function does not match module xnack setting");
211     return;
212   }
213   // Make sure function's sramecc settings are compatible with module's
214   // sramecc settings.
215   if (FunctionTargetID.isSramEccSupported() &&
216       FunctionTargetID.getSramEccSetting() != IsaInfo::TargetIDSetting::Any &&
217       FunctionTargetID.getSramEccSetting() != getTargetStreamer()->getTargetID()->getSramEccSetting()) {
218     OutContext.reportError({}, "sramecc setting of '" + Twine(MF->getName()) +
219                            "' function does not match module sramecc setting");
220     return;
221   }
222 
223   if (!MFI.isEntryFunction())
224     return;
225 
226   if ((STM.isMesaKernel(F) || isHsaAbiVersion2(getGlobalSTI())) &&
227       (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
228        F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
229     amd_kernel_code_t KernelCode;
230     getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
231     getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
232   }
233 
234   if (STM.isAmdHsaOS())
235     HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
236 }
237 
238 void AMDGPUAsmPrinter::emitFunctionBodyEnd() {
239   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
240   if (!MFI.isEntryFunction())
241     return;
242 
243   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
244       isHsaAbiVersion2(getGlobalSTI()))
245     return;
246 
247   auto &Streamer = getTargetStreamer()->getStreamer();
248   auto &Context = Streamer.getContext();
249   auto &ObjectFileInfo = *Context.getObjectFileInfo();
250   auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
251 
252   Streamer.pushSection();
253   Streamer.switchSection(&ReadOnlySection);
254 
255   // CP microcode requires the kernel descriptor to be allocated on 64 byte
256   // alignment.
257   Streamer.emitValueToAlignment(64, 0, 1, 0);
258   if (ReadOnlySection.getAlignment() < 64)
259     ReadOnlySection.setAlignment(Align(64));
260 
261   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
262 
263   SmallString<128> KernelName;
264   getNameWithPrefix(KernelName, &MF->getFunction());
265   getTargetStreamer()->EmitAmdhsaKernelDescriptor(
266       STM, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
267       CurrentProgramInfo.NumVGPRsForWavesPerEU,
268       CurrentProgramInfo.NumSGPRsForWavesPerEU -
269           IsaInfo::getNumExtraSGPRs(&STM,
270                                     CurrentProgramInfo.VCCUsed,
271                                     CurrentProgramInfo.FlatUsed),
272       CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed);
273 
274   Streamer.popSection();
275 }
276 
277 void AMDGPUAsmPrinter::emitFunctionEntryLabel() {
278   if (TM.getTargetTriple().getOS() == Triple::AMDHSA &&
279       isHsaAbiVersion3AndAbove(getGlobalSTI())) {
280     AsmPrinter::emitFunctionEntryLabel();
281     return;
282   }
283 
284   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
285   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
286   if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
287     SmallString<128> SymbolName;
288     getNameWithPrefix(SymbolName, &MF->getFunction()),
289     getTargetStreamer()->EmitAMDGPUSymbolType(
290         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
291   }
292   if (DumpCodeInstEmitter) {
293     // Disassemble function name label to text.
294     DisasmLines.push_back(MF->getName().str() + ":");
295     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
296     HexLines.push_back("");
297   }
298 
299   AsmPrinter::emitFunctionEntryLabel();
300 }
301 
302 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
303   if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
304     // Write a line for the basic block label if it is not only fallthrough.
305     DisasmLines.push_back(
306         (Twine("BB") + Twine(getFunctionNumber())
307          + "_" + Twine(MBB.getNumber()) + ":").str());
308     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
309     HexLines.push_back("");
310   }
311   AsmPrinter::emitBasicBlockStart(MBB);
312 }
313 
314 void AMDGPUAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
315   if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
316     if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
317       OutContext.reportError({},
318                              Twine(GV->getName()) +
319                                  ": unsupported initializer for address space");
320       return;
321     }
322 
323     // LDS variables aren't emitted in HSA or PAL yet.
324     const Triple::OSType OS = TM.getTargetTriple().getOS();
325     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
326       return;
327 
328     MCSymbol *GVSym = getSymbol(GV);
329 
330     GVSym->redefineIfPossible();
331     if (GVSym->isDefined() || GVSym->isVariable())
332       report_fatal_error("symbol '" + Twine(GVSym->getName()) +
333                          "' is already defined");
334 
335     const DataLayout &DL = GV->getParent()->getDataLayout();
336     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
337     Align Alignment = GV->getAlign().value_or(Align(4));
338 
339     emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
340     emitLinkage(GV, GVSym);
341     if (auto TS = getTargetStreamer())
342       TS->emitAMDGPULDS(GVSym, Size, Alignment);
343     return;
344   }
345 
346   AsmPrinter::emitGlobalVariable(GV);
347 }
348 
349 bool AMDGPUAsmPrinter::doFinalization(Module &M) {
350   // Pad with s_code_end to help tools and guard against instruction prefetch
351   // causing stale data in caches. Arguably this should be done by the linker,
352   // which is why this isn't done for Mesa.
353   const MCSubtargetInfo &STI = *getGlobalSTI();
354   if ((AMDGPU::isGFX10Plus(STI) || AMDGPU::isGFX90A(STI)) &&
355       (STI.getTargetTriple().getOS() == Triple::AMDHSA ||
356        STI.getTargetTriple().getOS() == Triple::AMDPAL)) {
357     OutStreamer->switchSection(getObjFileLowering().getTextSection());
358     getTargetStreamer()->EmitCodeEnd(STI);
359   }
360 
361   return AsmPrinter::doFinalization(M);
362 }
363 
364 // Print comments that apply to both callable functions and entry points.
365 void AMDGPUAsmPrinter::emitCommonFunctionComments(
366   uint32_t NumVGPR,
367   Optional<uint32_t> NumAGPR,
368   uint32_t TotalNumVGPR,
369   uint32_t NumSGPR,
370   uint64_t ScratchSize,
371   uint64_t CodeSize,
372   const AMDGPUMachineFunction *MFI) {
373   OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
374   OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
375   OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
376   if (NumAGPR) {
377     OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false);
378     OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR),
379                                 false);
380   }
381   OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
382   OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
383                               false);
384 }
385 
386 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
387     const MachineFunction &MF) const {
388   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
389   uint16_t KernelCodeProperties = 0;
390 
391   if (MFI.hasPrivateSegmentBuffer()) {
392     KernelCodeProperties |=
393         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
394   }
395   if (MFI.hasDispatchPtr()) {
396     KernelCodeProperties |=
397         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
398   }
399   if (MFI.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
400     KernelCodeProperties |=
401         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
402   }
403   if (MFI.hasKernargSegmentPtr()) {
404     KernelCodeProperties |=
405         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
406   }
407   if (MFI.hasDispatchID()) {
408     KernelCodeProperties |=
409         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
410   }
411   if (MFI.hasFlatScratchInit()) {
412     KernelCodeProperties |=
413         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
414   }
415   if (MF.getSubtarget<GCNSubtarget>().isWave32()) {
416     KernelCodeProperties |=
417         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
418   }
419 
420   return KernelCodeProperties;
421 }
422 
423 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
424     const MachineFunction &MF,
425     const SIProgramInfo &PI) const {
426   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
427   const Function &F = MF.getFunction();
428 
429   amdhsa::kernel_descriptor_t KernelDescriptor;
430   memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
431 
432   assert(isUInt<32>(PI.ScratchSize));
433   assert(isUInt<32>(PI.getComputePGMRSrc1()));
434   assert(isUInt<32>(PI.ComputePGMRSrc2));
435 
436   KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
437   KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
438 
439   Align MaxKernArgAlign;
440   KernelDescriptor.kernarg_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
441 
442   KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1();
443   KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
444   KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
445 
446   assert(STM.hasGFX90AInsts() || CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0);
447   if (STM.hasGFX90AInsts())
448     KernelDescriptor.compute_pgm_rsrc3 =
449       CurrentProgramInfo.ComputePGMRSrc3GFX90A;
450 
451   return KernelDescriptor;
452 }
453 
454 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
455   // Init target streamer lazily on the first function so that previous passes
456   // can set metadata.
457   if (!IsTargetStreamerInitialized)
458     initTargetStreamer(*MF.getFunction().getParent());
459 
460   ResourceUsage = &getAnalysis<AMDGPUResourceUsageAnalysis>();
461   CurrentProgramInfo = SIProgramInfo();
462 
463   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
464 
465   // The starting address of all shader programs must be 256 bytes aligned.
466   // Regular functions just need the basic required instruction alignment.
467   MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4));
468 
469   SetupMachineFunction(MF);
470 
471   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
472   MCContext &Context = getObjFileLowering().getContext();
473   // FIXME: This should be an explicit check for Mesa.
474   if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
475     MCSectionELF *ConfigSection =
476         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
477     OutStreamer->switchSection(ConfigSection);
478   }
479 
480   if (MFI->isModuleEntryFunction()) {
481     getSIProgramInfo(CurrentProgramInfo, MF);
482   }
483 
484   if (STM.isAmdPalOS()) {
485     if (MFI->isEntryFunction())
486       EmitPALMetadata(MF, CurrentProgramInfo);
487     else if (MFI->isModuleEntryFunction())
488       emitPALFunctionMetadata(MF);
489   } else if (!STM.isAmdHsaOS()) {
490     EmitProgramInfoSI(MF, CurrentProgramInfo);
491   }
492 
493   DumpCodeInstEmitter = nullptr;
494   if (STM.dumpCode()) {
495     // For -dumpcode, get the assembler out of the streamer, even if it does
496     // not really want to let us have it. This only works with -filetype=obj.
497     bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing();
498     OutStreamer->setUseAssemblerInfoForParsing(true);
499     MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
500     OutStreamer->setUseAssemblerInfoForParsing(SaveFlag);
501     if (Assembler)
502       DumpCodeInstEmitter = Assembler->getEmitterPtr();
503   }
504 
505   DisasmLines.clear();
506   HexLines.clear();
507   DisasmLineMaxLen = 0;
508 
509   emitFunctionBody();
510 
511   emitResourceUsageRemarks(MF, CurrentProgramInfo, MFI->isModuleEntryFunction(),
512                            STM.hasMAIInsts());
513 
514   if (isVerbose()) {
515     MCSectionELF *CommentSection =
516         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
517     OutStreamer->switchSection(CommentSection);
518 
519     if (!MFI->isEntryFunction()) {
520       OutStreamer->emitRawComment(" Function info:", false);
521       const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info =
522           ResourceUsage->getResourceInfo(&MF.getFunction());
523       emitCommonFunctionComments(
524         Info.NumVGPR,
525         STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(),
526         Info.getTotalNumVGPRs(STM),
527         Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
528         Info.PrivateSegmentSize,
529         getFunctionCodeSize(MF), MFI);
530       return false;
531     }
532 
533     OutStreamer->emitRawComment(" Kernel info:", false);
534     emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR,
535                                STM.hasMAIInsts()
536                                  ? CurrentProgramInfo.NumAccVGPR
537                                  : Optional<uint32_t>(),
538                                CurrentProgramInfo.NumVGPR,
539                                CurrentProgramInfo.NumSGPR,
540                                CurrentProgramInfo.ScratchSize,
541                                getFunctionCodeSize(MF), MFI);
542 
543     OutStreamer->emitRawComment(
544       " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
545     OutStreamer->emitRawComment(
546       " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
547     OutStreamer->emitRawComment(
548       " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
549       " bytes/workgroup (compile time only)", false);
550 
551     OutStreamer->emitRawComment(
552       " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
553     OutStreamer->emitRawComment(
554       " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
555 
556     OutStreamer->emitRawComment(
557       " NumSGPRsForWavesPerEU: " +
558       Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
559     OutStreamer->emitRawComment(
560       " NumVGPRsForWavesPerEU: " +
561       Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
562 
563     if (STM.hasGFX90AInsts())
564       OutStreamer->emitRawComment(
565         " AccumOffset: " +
566         Twine((CurrentProgramInfo.AccumOffset + 1) * 4), false);
567 
568     OutStreamer->emitRawComment(
569       " Occupancy: " +
570       Twine(CurrentProgramInfo.Occupancy), false);
571 
572     OutStreamer->emitRawComment(
573       " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
574 
575     OutStreamer->emitRawComment(
576       " COMPUTE_PGM_RSRC2:SCRATCH_EN: " +
577       Twine(G_00B84C_SCRATCH_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
578     OutStreamer->emitRawComment(
579       " COMPUTE_PGM_RSRC2:USER_SGPR: " +
580       Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
581     OutStreamer->emitRawComment(
582       " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
583       Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
584     OutStreamer->emitRawComment(
585       " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
586       Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
587     OutStreamer->emitRawComment(
588       " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
589       Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
590     OutStreamer->emitRawComment(
591       " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
592       Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
593     OutStreamer->emitRawComment(
594       " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
595       Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
596       false);
597 
598     assert(STM.hasGFX90AInsts() ||
599            CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0);
600     if (STM.hasGFX90AInsts()) {
601       OutStreamer->emitRawComment(
602         " COMPUTE_PGM_RSRC3_GFX90A:ACCUM_OFFSET: " +
603         Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A,
604                                amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET))),
605                                false);
606       OutStreamer->emitRawComment(
607         " COMPUTE_PGM_RSRC3_GFX90A:TG_SPLIT: " +
608         Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A,
609                                amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT))),
610                                false);
611     }
612   }
613 
614   if (DumpCodeInstEmitter) {
615 
616     OutStreamer->switchSection(
617         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0));
618 
619     for (size_t i = 0; i < DisasmLines.size(); ++i) {
620       std::string Comment = "\n";
621       if (!HexLines[i].empty()) {
622         Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
623         Comment += " ; " + HexLines[i] + "\n";
624       }
625 
626       OutStreamer->emitBytes(StringRef(DisasmLines[i]));
627       OutStreamer->emitBytes(StringRef(Comment));
628     }
629   }
630 
631   return false;
632 }
633 
634 // TODO: Fold this into emitFunctionBodyStart.
635 void AMDGPUAsmPrinter::initializeTargetID(const Module &M) {
636   // In the beginning all features are either 'Any' or 'NotSupported',
637   // depending on global target features. This will cover empty modules.
638   getTargetStreamer()->initializeTargetID(
639       *getGlobalSTI(), getGlobalSTI()->getFeatureString());
640 
641   // If module is empty, we are done.
642   if (M.empty())
643     return;
644 
645   // If module is not empty, need to find first 'Off' or 'On' feature
646   // setting per feature from functions in module.
647   for (auto &F : M) {
648     auto &TSTargetID = getTargetStreamer()->getTargetID();
649     if ((!TSTargetID->isXnackSupported() || TSTargetID->isXnackOnOrOff()) &&
650         (!TSTargetID->isSramEccSupported() || TSTargetID->isSramEccOnOrOff()))
651       break;
652 
653     const GCNSubtarget &STM = TM.getSubtarget<GCNSubtarget>(F);
654     const IsaInfo::AMDGPUTargetID &STMTargetID = STM.getTargetID();
655     if (TSTargetID->isXnackSupported())
656       if (TSTargetID->getXnackSetting() == IsaInfo::TargetIDSetting::Any)
657         TSTargetID->setXnackSetting(STMTargetID.getXnackSetting());
658     if (TSTargetID->isSramEccSupported())
659       if (TSTargetID->getSramEccSetting() == IsaInfo::TargetIDSetting::Any)
660         TSTargetID->setSramEccSetting(STMTargetID.getSramEccSetting());
661   }
662 }
663 
664 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
665   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
666   const SIInstrInfo *TII = STM.getInstrInfo();
667 
668   uint64_t CodeSize = 0;
669 
670   for (const MachineBasicBlock &MBB : MF) {
671     for (const MachineInstr &MI : MBB) {
672       // TODO: CodeSize should account for multiple functions.
673 
674       // TODO: Should we count size of debug info?
675       if (MI.isDebugInstr())
676         continue;
677 
678       CodeSize += TII->getInstSizeInBytes(MI);
679     }
680   }
681 
682   return CodeSize;
683 }
684 
685 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
686                                         const MachineFunction &MF) {
687   const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info =
688       ResourceUsage->getResourceInfo(&MF.getFunction());
689   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
690 
691   ProgInfo.NumArchVGPR = Info.NumVGPR;
692   ProgInfo.NumAccVGPR = Info.NumAGPR;
693   ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM);
694   ProgInfo.AccumOffset = alignTo(std::max(1, Info.NumVGPR), 4) / 4 - 1;
695   ProgInfo.TgSplit = STM.isTgSplitEnabled();
696   ProgInfo.NumSGPR = Info.NumExplicitSGPR;
697   ProgInfo.ScratchSize = Info.PrivateSegmentSize;
698   ProgInfo.VCCUsed = Info.UsesVCC;
699   ProgInfo.FlatUsed = Info.UsesFlatScratch;
700   ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
701 
702   const uint64_t MaxScratchPerWorkitem =
703       STM.getMaxWaveScratchSize() / STM.getWavefrontSize();
704   if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) {
705     DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
706                                           ProgInfo.ScratchSize,
707                                           MaxScratchPerWorkitem, DS_Error);
708     MF.getFunction().getContext().diagnose(DiagStackSize);
709   }
710 
711   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
712 
713   // The calculations related to SGPR/VGPR blocks are
714   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
715   // unified.
716   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
717       &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
718 
719   // Check the addressable register limit before we add ExtraSGPRs.
720   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
721       !STM.hasSGPRInitBug()) {
722     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
723     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
724       // This can happen due to a compiler bug or when using inline asm.
725       LLVMContext &Ctx = MF.getFunction().getContext();
726       DiagnosticInfoResourceLimit Diag(
727           MF.getFunction(), "addressable scalar registers", ProgInfo.NumSGPR,
728           MaxAddressableNumSGPRs, DS_Error, DK_ResourceLimit);
729       Ctx.diagnose(Diag);
730       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
731     }
732   }
733 
734   // Account for extra SGPRs and VGPRs reserved for debugger use.
735   ProgInfo.NumSGPR += ExtraSGPRs;
736 
737   const Function &F = MF.getFunction();
738 
739   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
740   // dispatch registers are function args.
741   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
742 
743   if (isShader(F.getCallingConv())) {
744     bool IsPixelShader =
745         F.getCallingConv() == CallingConv::AMDGPU_PS && !STM.isAmdHsaOS();
746 
747     // Calculate the number of VGPR registers based on the SPI input registers
748     uint32_t InputEna = 0;
749     uint32_t InputAddr = 0;
750     unsigned LastEna = 0;
751 
752     if (IsPixelShader) {
753       // Note for IsPixelShader:
754       // By this stage, all enabled inputs are tagged in InputAddr as well.
755       // We will use InputAddr to determine whether the input counts against the
756       // vgpr total and only use the InputEnable to determine the last input
757       // that is relevant - if extra arguments are used, then we have to honour
758       // the InputAddr for any intermediate non-enabled inputs.
759       InputEna = MFI->getPSInputEnable();
760       InputAddr = MFI->getPSInputAddr();
761 
762       // We only need to consider input args up to the last used arg.
763       assert((InputEna || InputAddr) &&
764              "PSInputAddr and PSInputEnable should "
765              "never both be 0 for AMDGPU_PS shaders");
766       // There are some rare circumstances where InputAddr is non-zero and
767       // InputEna can be set to 0. In this case we default to setting LastEna
768       // to 1.
769       LastEna = InputEna ? findLastSet(InputEna) + 1 : 1;
770     }
771 
772     // FIXME: We should be using the number of registers determined during
773     // calling convention lowering to legalize the types.
774     const DataLayout &DL = F.getParent()->getDataLayout();
775     unsigned PSArgCount = 0;
776     unsigned IntermediateVGPR = 0;
777     for (auto &Arg : F.args()) {
778       unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32;
779       if (Arg.hasAttribute(Attribute::InReg)) {
780         WaveDispatchNumSGPR += NumRegs;
781       } else {
782         // If this is a PS shader and we're processing the PS Input args (first
783         // 16 VGPR), use the InputEna and InputAddr bits to define how many
784         // VGPRs are actually used.
785         // Any extra VGPR arguments are handled as normal arguments (and
786         // contribute to the VGPR count whether they're used or not).
787         if (IsPixelShader && PSArgCount < 16) {
788           if ((1 << PSArgCount) & InputAddr) {
789             if (PSArgCount < LastEna)
790               WaveDispatchNumVGPR += NumRegs;
791             else
792               IntermediateVGPR += NumRegs;
793           }
794           PSArgCount++;
795         } else {
796           // If there are extra arguments we have to include the allocation for
797           // the non-used (but enabled with InputAddr) input arguments
798           if (IntermediateVGPR) {
799             WaveDispatchNumVGPR += IntermediateVGPR;
800             IntermediateVGPR = 0;
801           }
802           WaveDispatchNumVGPR += NumRegs;
803         }
804       }
805     }
806     ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
807     ProgInfo.NumArchVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
808     ProgInfo.NumVGPR =
809         Info.getTotalNumVGPRs(STM, Info.NumAGPR, ProgInfo.NumArchVGPR);
810   }
811 
812   // Adjust number of registers used to meet default/requested minimum/maximum
813   // number of waves per execution unit request.
814   ProgInfo.NumSGPRsForWavesPerEU = std::max(
815     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
816   ProgInfo.NumVGPRsForWavesPerEU = std::max(
817     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
818 
819   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
820       STM.hasSGPRInitBug()) {
821     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
822     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
823       // This can happen due to a compiler bug or when using inline asm to use
824       // the registers which are usually reserved for vcc etc.
825       LLVMContext &Ctx = MF.getFunction().getContext();
826       DiagnosticInfoResourceLimit Diag(MF.getFunction(), "scalar registers",
827                                        ProgInfo.NumSGPR, MaxAddressableNumSGPRs,
828                                        DS_Error, DK_ResourceLimit);
829       Ctx.diagnose(Diag);
830       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
831       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
832     }
833   }
834 
835   if (STM.hasSGPRInitBug()) {
836     ProgInfo.NumSGPR =
837         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
838     ProgInfo.NumSGPRsForWavesPerEU =
839         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
840   }
841 
842   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
843     LLVMContext &Ctx = MF.getFunction().getContext();
844     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
845                                      MFI->getNumUserSGPRs(),
846                                      STM.getMaxNumUserSGPRs(), DS_Error);
847     Ctx.diagnose(Diag);
848   }
849 
850   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
851     LLVMContext &Ctx = MF.getFunction().getContext();
852     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
853                                      MFI->getLDSSize(),
854                                      STM.getLocalMemorySize(), DS_Error);
855     Ctx.diagnose(Diag);
856   }
857 
858   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
859       &STM, ProgInfo.NumSGPRsForWavesPerEU);
860   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
861       &STM, ProgInfo.NumVGPRsForWavesPerEU);
862 
863   const SIModeRegisterDefaults Mode = MFI->getMode();
864 
865   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
866   // register.
867   ProgInfo.FloatMode = getFPMode(Mode);
868 
869   ProgInfo.IEEEMode = Mode.IEEE;
870 
871   // Make clamp modifier on NaN input returns 0.
872   ProgInfo.DX10Clamp = Mode.DX10Clamp;
873 
874   unsigned LDSAlignShift;
875   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
876     // LDS is allocated in 64 dword blocks.
877     LDSAlignShift = 8;
878   } else {
879     // LDS is allocated in 128 dword blocks.
880     LDSAlignShift = 9;
881   }
882 
883   ProgInfo.SGPRSpill = MFI->getNumSpilledSGPRs();
884   ProgInfo.VGPRSpill = MFI->getNumSpilledVGPRs();
885 
886   ProgInfo.LDSSize = MFI->getLDSSize();
887   ProgInfo.LDSBlocks =
888       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
889 
890   // Scratch is allocated in 64-dword or 256-dword blocks.
891   unsigned ScratchAlignShift =
892       STM.getGeneration() >= AMDGPUSubtarget::GFX11 ? 8 : 10;
893   // We need to program the hardware with the amount of scratch memory that
894   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
895   // scratch memory used per thread.
896   ProgInfo.ScratchBlocks = divideCeil(
897       ProgInfo.ScratchSize * STM.getWavefrontSize(), 1ULL << ScratchAlignShift);
898 
899   if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
900     ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
901     ProgInfo.MemOrdered = 1;
902   }
903 
904   // 0 = X, 1 = XY, 2 = XYZ
905   unsigned TIDIGCompCnt = 0;
906   if (MFI->hasWorkItemIDZ())
907     TIDIGCompCnt = 2;
908   else if (MFI->hasWorkItemIDY())
909     TIDIGCompCnt = 1;
910 
911   // The private segment wave byte offset is the last of the system SGPRs. We
912   // initially assumed it was allocated, and may have used it. It shouldn't harm
913   // anything to disable it if we know the stack isn't used here. We may still
914   // have emitted code reading it to initialize scratch, but if that's unused
915   // reading garbage should be OK.
916   const bool EnablePrivateSegment = ProgInfo.ScratchBlocks > 0;
917   ProgInfo.ComputePGMRSrc2 =
918       S_00B84C_SCRATCH_EN(EnablePrivateSegment) |
919       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
920       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
921       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
922       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
923       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
924       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
925       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
926       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
927       S_00B84C_EXCP_EN_MSB(0) |
928       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
929       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
930       S_00B84C_EXCP_EN(0);
931 
932   if (STM.hasGFX90AInsts()) {
933     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
934                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
935                     ProgInfo.AccumOffset);
936     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
937                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
938                     ProgInfo.TgSplit);
939   }
940 
941   ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize,
942                                             ProgInfo.NumSGPRsForWavesPerEU,
943                                             ProgInfo.NumVGPRsForWavesPerEU);
944 }
945 
946 static unsigned getRsrcReg(CallingConv::ID CallConv) {
947   switch (CallConv) {
948   default: LLVM_FALLTHROUGH;
949   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
950   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
951   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
952   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
953   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
954   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
955   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
956   }
957 }
958 
959 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
960                                          const SIProgramInfo &CurrentProgramInfo) {
961   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
962   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
963   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
964 
965   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
966     OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1);
967 
968     OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1());
969 
970     OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2);
971     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2);
972 
973     OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE);
974     OutStreamer->emitInt32(
975         STM.getGeneration() >= AMDGPUSubtarget::GFX11
976             ? S_00B860_WAVESIZE_GFX11Plus(CurrentProgramInfo.ScratchBlocks)
977             : S_00B860_WAVESIZE_PreGFX11(CurrentProgramInfo.ScratchBlocks));
978 
979     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
980     // 0" comment but I don't see a corresponding field in the register spec.
981   } else {
982     OutStreamer->emitInt32(RsrcReg);
983     OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
984                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
985     OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE);
986     OutStreamer->emitInt32(
987         STM.getGeneration() >= AMDGPUSubtarget::GFX11
988             ? S_0286E8_WAVESIZE_GFX11Plus(CurrentProgramInfo.ScratchBlocks)
989             : S_0286E8_WAVESIZE_PreGFX11(CurrentProgramInfo.ScratchBlocks));
990   }
991 
992   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
993     OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS);
994     unsigned ExtraLDSSize = STM.getGeneration() >= AMDGPUSubtarget::GFX11
995                                 ? divideCeil(CurrentProgramInfo.LDSBlocks, 2)
996                                 : CurrentProgramInfo.LDSBlocks;
997     OutStreamer->emitInt32(S_00B02C_EXTRA_LDS_SIZE(ExtraLDSSize));
998     OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA);
999     OutStreamer->emitInt32(MFI->getPSInputEnable());
1000     OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR);
1001     OutStreamer->emitInt32(MFI->getPSInputAddr());
1002   }
1003 
1004   OutStreamer->emitInt32(R_SPILLED_SGPRS);
1005   OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
1006   OutStreamer->emitInt32(R_SPILLED_VGPRS);
1007   OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
1008 }
1009 
1010 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1011 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
1012 // metadata items into the PALMD::Metadata, combining with any provided by the
1013 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
1014 // is then written as a single block in the .note section.
1015 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
1016        const SIProgramInfo &CurrentProgramInfo) {
1017   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1018   auto CC = MF.getFunction().getCallingConv();
1019   auto MD = getTargetStreamer()->getPALMetadata();
1020 
1021   MD->setEntryPoint(CC, MF.getFunction().getName());
1022   MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1023 
1024   // Only set AGPRs for supported devices
1025   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1026   if (STM.hasMAIInsts()) {
1027     MD->setNumUsedAgprs(CC, CurrentProgramInfo.NumAccVGPR);
1028   }
1029 
1030   MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1031   MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC));
1032   if (AMDGPU::isCompute(CC)) {
1033     MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
1034   } else {
1035     if (CurrentProgramInfo.ScratchBlocks > 0)
1036       MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
1037   }
1038   // ScratchSize is in bytes, 16 aligned.
1039   MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
1040   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1041     unsigned ExtraLDSSize = STM.getGeneration() >= AMDGPUSubtarget::GFX11
1042                                 ? divideCeil(CurrentProgramInfo.LDSBlocks, 2)
1043                                 : CurrentProgramInfo.LDSBlocks;
1044     MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(ExtraLDSSize));
1045     MD->setSpiPsInputEna(MFI->getPSInputEnable());
1046     MD->setSpiPsInputAddr(MFI->getPSInputAddr());
1047   }
1048 
1049   if (STM.isWave32())
1050     MD->setWave32(MF.getFunction().getCallingConv());
1051 }
1052 
1053 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) {
1054   auto *MD = getTargetStreamer()->getPALMetadata();
1055   const MachineFrameInfo &MFI = MF.getFrameInfo();
1056   MD->setFunctionScratchSize(MF, MFI.getStackSize());
1057 
1058   // Set compute registers
1059   MD->setRsrc1(CallingConv::AMDGPU_CS,
1060                CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS));
1061   MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2);
1062 
1063   // Set optional info
1064   MD->setFunctionLdsSize(MF, CurrentProgramInfo.LDSSize);
1065   MD->setFunctionNumUsedVgprs(MF, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1066   MD->setFunctionNumUsedSgprs(MF, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1067 }
1068 
1069 // This is supposed to be log2(Size)
1070 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
1071   switch (Size) {
1072   case 4:
1073     return AMD_ELEMENT_4_BYTES;
1074   case 8:
1075     return AMD_ELEMENT_8_BYTES;
1076   case 16:
1077     return AMD_ELEMENT_16_BYTES;
1078   default:
1079     llvm_unreachable("invalid private_element_size");
1080   }
1081 }
1082 
1083 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1084                                         const SIProgramInfo &CurrentProgramInfo,
1085                                         const MachineFunction &MF) const {
1086   const Function &F = MF.getFunction();
1087   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
1088          F.getCallingConv() == CallingConv::SPIR_KERNEL);
1089 
1090   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1091   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1092 
1093   AMDGPU::initDefaultAMDKernelCodeT(Out, &STM);
1094 
1095   Out.compute_pgm_resource_registers =
1096       CurrentProgramInfo.getComputePGMRSrc1() |
1097       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1098   Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
1099 
1100   if (CurrentProgramInfo.DynamicCallStack)
1101     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1102 
1103   AMD_HSA_BITS_SET(Out.code_properties,
1104                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1105                    getElementByteSizeValue(STM.getMaxPrivateElementSize(true)));
1106 
1107   if (MFI->hasPrivateSegmentBuffer()) {
1108     Out.code_properties |=
1109       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1110   }
1111 
1112   if (MFI->hasDispatchPtr())
1113     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1114 
1115   if (MFI->hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
1116     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1117 
1118   if (MFI->hasKernargSegmentPtr())
1119     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1120 
1121   if (MFI->hasDispatchID())
1122     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1123 
1124   if (MFI->hasFlatScratchInit())
1125     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1126 
1127   if (MFI->hasDispatchPtr())
1128     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1129 
1130   if (STM.isXNACKEnabled())
1131     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1132 
1133   Align MaxKernArgAlign;
1134   Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1135   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1136   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1137   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1138   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1139 
1140   // kernarg_segment_alignment is specified as log of the alignment.
1141   // The minimum alignment is 16.
1142   // FIXME: The metadata treats the minimum as 4?
1143   Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign));
1144 }
1145 
1146 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1147                                        const char *ExtraCode, raw_ostream &O) {
1148   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1149   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1150     return false;
1151 
1152   if (ExtraCode && ExtraCode[0]) {
1153     if (ExtraCode[1] != 0)
1154       return true; // Unknown modifier.
1155 
1156     switch (ExtraCode[0]) {
1157     case 'r':
1158       break;
1159     default:
1160       return true;
1161     }
1162   }
1163 
1164   // TODO: Should be able to support other operand types like globals.
1165   const MachineOperand &MO = MI->getOperand(OpNo);
1166   if (MO.isReg()) {
1167     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1168                                        *MF->getSubtarget().getRegisterInfo());
1169     return false;
1170   } else if (MO.isImm()) {
1171     int64_t Val = MO.getImm();
1172     if (AMDGPU::isInlinableIntLiteral(Val)) {
1173       O << Val;
1174     } else if (isUInt<16>(Val)) {
1175       O << format("0x%" PRIx16, static_cast<uint16_t>(Val));
1176     } else if (isUInt<32>(Val)) {
1177       O << format("0x%" PRIx32, static_cast<uint32_t>(Val));
1178     } else {
1179       O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1180     }
1181     return false;
1182   }
1183   return true;
1184 }
1185 
1186 void AMDGPUAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
1187   AU.addRequired<AMDGPUResourceUsageAnalysis>();
1188   AU.addPreserved<AMDGPUResourceUsageAnalysis>();
1189   AsmPrinter::getAnalysisUsage(AU);
1190 }
1191 
1192 void AMDGPUAsmPrinter::emitResourceUsageRemarks(
1193     const MachineFunction &MF, const SIProgramInfo &CurrentProgramInfo,
1194     bool isModuleEntryFunction, bool hasMAIInsts) {
1195   if (!ORE)
1196     return;
1197 
1198   const char *Name = "kernel-resource-usage";
1199   const char *Indent = "    ";
1200 
1201   // If the remark is not specifically enabled, do not output to yaml
1202   LLVMContext &Ctx = MF.getFunction().getContext();
1203   if (!Ctx.getDiagHandlerPtr()->isAnalysisRemarkEnabled(Name))
1204     return;
1205 
1206   auto EmitResourceUsageRemark = [&](StringRef RemarkName,
1207                                      StringRef RemarkLabel, auto Argument) {
1208     // Add an indent for every line besides the line with the kernel name. This
1209     // makes it easier to tell which resource usage go with which kernel since
1210     // the kernel name will always be displayed first.
1211     std::string LabelStr = RemarkLabel.str() + ": ";
1212     if (!RemarkName.equals("FunctionName"))
1213       LabelStr = Indent + LabelStr;
1214 
1215     ORE->emit([&]() {
1216       return MachineOptimizationRemarkAnalysis(Name, RemarkName,
1217                                                MF.getFunction().getSubprogram(),
1218                                                &MF.front())
1219              << LabelStr << ore::NV(RemarkName, Argument);
1220     });
1221   };
1222 
1223   // FIXME: Formatting here is pretty nasty because clang does not accept
1224   // newlines from diagnostics. This forces us to emit multiple diagnostic
1225   // remarks to simulate newlines. If and when clang does accept newlines, this
1226   // formatting should be aggregated into one remark with newlines to avoid
1227   // printing multiple diagnostic location and diag opts.
1228   EmitResourceUsageRemark("FunctionName", "Function Name",
1229                           MF.getFunction().getName());
1230   EmitResourceUsageRemark("NumSGPR", "SGPRs", CurrentProgramInfo.NumSGPR);
1231   EmitResourceUsageRemark("NumVGPR", "VGPRs", CurrentProgramInfo.NumArchVGPR);
1232   if (hasMAIInsts)
1233     EmitResourceUsageRemark("NumAGPR", "AGPRs", CurrentProgramInfo.NumAccVGPR);
1234   EmitResourceUsageRemark("ScratchSize", "ScratchSize [bytes/lane]",
1235                           CurrentProgramInfo.ScratchSize);
1236   EmitResourceUsageRemark("Occupancy", "Occupancy [waves/SIMD]",
1237                           CurrentProgramInfo.Occupancy);
1238   EmitResourceUsageRemark("SGPRSpill", "SGPRs Spill",
1239                           CurrentProgramInfo.SGPRSpill);
1240   EmitResourceUsageRemark("VGPRSpill", "VGPRs Spill",
1241                           CurrentProgramInfo.VGPRSpill);
1242   if (isModuleEntryFunction)
1243     EmitResourceUsageRemark("BytesLDS", "LDS Size [bytes/block]",
1244                             CurrentProgramInfo.LDSSize);
1245 }
1246