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