1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer  -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 ///
12 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary
13 /// code.  When passed an MCAsmStreamer it prints assembly and when passed
14 /// an MCObjectStreamer it outputs binary code.
15 //
16 //===----------------------------------------------------------------------===//
17 //
18 
19 #include "AMDGPUAsmPrinter.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "InstPrinter/AMDGPUInstPrinter.h"
24 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
25 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
26 #include "R600AsmPrinter.h"
27 #include "R600Defines.h"
28 #include "R600MachineFunctionInfo.h"
29 #include "R600RegisterInfo.h"
30 #include "SIDefines.h"
31 #include "SIInstrInfo.h"
32 #include "SIMachineFunctionInfo.h"
33 #include "SIRegisterInfo.h"
34 #include "Utils/AMDGPUBaseInfo.h"
35 #include "llvm/BinaryFormat/ELF.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCSectionELF.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/Support/AMDGPUMetadata.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Target/TargetLoweringObjectFile.h"
45 
46 using namespace llvm;
47 using namespace llvm::AMDGPU;
48 
49 // TODO: This should get the default rounding mode from the kernel. We just set
50 // the default here, but this could change if the OpenCL rounding mode pragmas
51 // are used.
52 //
53 // The denormal mode here should match what is reported by the OpenCL runtime
54 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
55 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
56 //
57 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
58 // precision, and leaves single precision to flush all and does not report
59 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
60 // CL_FP_DENORM for both.
61 //
62 // FIXME: It seems some instructions do not support single precision denormals
63 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
64 // and sin_f32, cos_f32 on most parts).
65 
66 // We want to use these instructions, and using fp32 denormals also causes
67 // instructions to run at the double precision rate for the device so it's
68 // probably best to just report no single precision denormals.
69 static uint32_t getFPMode(const MachineFunction &F) {
70   const GCNSubtarget& ST = F.getSubtarget<GCNSubtarget>();
71   // TODO: Is there any real use for the flush in only / flush out only modes?
72 
73   uint32_t FP32Denormals =
74     ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
75 
76   uint32_t FP64Denormals =
77     ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
78 
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(FP32Denormals) |
82          FP_DENORM_MODE_DP(FP64Denormals);
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 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     AMDGPUASI = static_cast<AMDGPUTargetMachine*>(&TM)->getAMDGPUAS();
102   }
103 
104 StringRef AMDGPUAsmPrinter::getPassName() const {
105   return "AMDGPU Assembly Printer";
106 }
107 
108 const MCSubtargetInfo* AMDGPUAsmPrinter::getSTI() 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   if (IsaInfo::hasCodeObjectV3(getSTI()) &&
120       TM.getTargetTriple().getOS() == Triple::AMDHSA)
121     return;
122 
123   if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
124       TM.getTargetTriple().getOS() != Triple::AMDPAL)
125     return;
126 
127   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
128     HSAMetadataStream.begin(M);
129 
130   if (TM.getTargetTriple().getOS() == Triple::AMDPAL)
131     readPALMetadata(M);
132 
133   // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2.
134   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
135     getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1);
136 
137   // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2.
138   IsaInfo::IsaVersion ISA = IsaInfo::getIsaVersion(getSTI()->getFeatureBits());
139   getTargetStreamer()->EmitDirectiveHSACodeObjectISA(
140       ISA.Major, ISA.Minor, ISA.Stepping, "AMD", "AMDGPU");
141 }
142 
143 void AMDGPUAsmPrinter::EmitEndOfAsmFile(Module &M) {
144   // TODO: Add metadata to code object v3.
145   if (IsaInfo::hasCodeObjectV3(getSTI()) &&
146       TM.getTargetTriple().getOS() == Triple::AMDHSA)
147     return;
148 
149   // Following code requires TargetStreamer to be present.
150   if (!getTargetStreamer())
151     return;
152 
153   // Emit ISA Version (NT_AMD_AMDGPU_ISA).
154   std::string ISAVersionString;
155   raw_string_ostream ISAVersionStream(ISAVersionString);
156   IsaInfo::streamIsaVersion(getSTI(), ISAVersionStream);
157   getTargetStreamer()->EmitISAVersion(ISAVersionStream.str());
158 
159   // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
160   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
161     HSAMetadataStream.end();
162     getTargetStreamer()->EmitHSAMetadata(HSAMetadataStream.getHSAMetadata());
163   }
164 
165   // Emit PAL Metadata (NT_AMD_AMDGPU_PAL_METADATA).
166   if (TM.getTargetTriple().getOS() == Triple::AMDPAL) {
167     // Copy the PAL metadata from the map where we collected it into a vector,
168     // then write it as a .note.
169     PALMD::Metadata PALMetadataVector;
170     for (auto i : PALMetadataMap) {
171       PALMetadataVector.push_back(i.first);
172       PALMetadataVector.push_back(i.second);
173     }
174     getTargetStreamer()->EmitPALMetadata(PALMetadataVector);
175   }
176 }
177 
178 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
179   const MachineBasicBlock *MBB) const {
180   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
181     return false;
182 
183   if (MBB->empty())
184     return true;
185 
186   // If this is a block implementing a long branch, an expression relative to
187   // the start of the block is needed.  to the start of the block.
188   // XXX - Is there a smarter way to check this?
189   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
190 }
191 
192 void AMDGPUAsmPrinter::EmitFunctionBodyStart() {
193   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
194   if (!MFI.isEntryFunction())
195     return;
196   if (IsaInfo::hasCodeObjectV3(getSTI()) &&
197       TM.getTargetTriple().getOS() == Triple::AMDHSA)
198     return;
199 
200   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
201   amd_kernel_code_t KernelCode;
202   if (STM.isAmdCodeObjectV2(MF->getFunction())) {
203     getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
204     getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
205   }
206 
207   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
208     return;
209 
210   HSAMetadataStream.emitKernel(*MF, CurrentProgramInfo);
211 }
212 
213 void AMDGPUAsmPrinter::EmitFunctionBodyEnd() {
214   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
215   if (!MFI.isEntryFunction())
216     return;
217   if (!IsaInfo::hasCodeObjectV3(getSTI()) ||
218       TM.getTargetTriple().getOS() != Triple::AMDHSA)
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(64);
234 
235   SmallString<128> KernelName;
236   getNameWithPrefix(KernelName, &MF->getFunction());
237   getTargetStreamer()->EmitAmdhsaKernelDescriptor(
238       *getSTI(), KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
239       CurrentProgramInfo.NumVGPRsForWavesPerEU,
240       CurrentProgramInfo.NumSGPRsForWavesPerEU -
241           IsaInfo::getNumExtraSGPRs(getSTI()->getFeatureBits(),
242                                     CurrentProgramInfo.VCCUsed,
243                                     CurrentProgramInfo.FlatUsed),
244       CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed,
245       hasXNACK(*getSTI()));
246 
247   Streamer.PopSection();
248 }
249 
250 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() {
251   if (IsaInfo::hasCodeObjectV3(getSTI()) &&
252       TM.getTargetTriple().getOS() == Triple::AMDHSA) {
253     AsmPrinter::EmitFunctionEntryLabel();
254     return;
255   }
256 
257   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
258   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
259   if (MFI->isEntryFunction() && STM.isAmdCodeObjectV2(MF->getFunction())) {
260     SmallString<128> SymbolName;
261     getNameWithPrefix(SymbolName, &MF->getFunction()),
262     getTargetStreamer()->EmitAMDGPUSymbolType(
263         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
264   }
265   const GCNSubtarget &STI = MF->getSubtarget<GCNSubtarget>();
266   if (STI.dumpCode()) {
267     // Disassemble function name label to text.
268     DisasmLines.push_back(MF->getName().str() + ":");
269     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
270     HexLines.push_back("");
271   }
272 
273   AsmPrinter::EmitFunctionEntryLabel();
274 }
275 
276 void AMDGPUAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
277   const GCNSubtarget &STI = MBB.getParent()->getSubtarget<GCNSubtarget>();
278   if (STI.dumpCode() && !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 
291   // Group segment variables aren't emitted in HSA.
292   if (AMDGPU::isGroupSegment(GV))
293     return;
294 
295   AsmPrinter::EmitGlobalVariable(GV);
296 }
297 
298 bool AMDGPUAsmPrinter::doFinalization(Module &M) {
299   CallGraphResourceInfo.clear();
300   return AsmPrinter::doFinalization(M);
301 }
302 
303 // For the amdpal OS type, read the amdgpu.pal.metadata supplied by the
304 // frontend into our PALMetadataMap, ready for per-function modification.  It
305 // is a NamedMD containing an MDTuple containing a number of MDNodes each of
306 // which is an integer value, and each two integer values forms a key=value
307 // pair that we store as PALMetadataMap[key]=value in the map.
308 void AMDGPUAsmPrinter::readPALMetadata(Module &M) {
309   auto NamedMD = M.getNamedMetadata("amdgpu.pal.metadata");
310   if (!NamedMD || !NamedMD->getNumOperands())
311     return;
312   auto Tuple = dyn_cast<MDTuple>(NamedMD->getOperand(0));
313   if (!Tuple)
314     return;
315   for (unsigned I = 0, E = Tuple->getNumOperands() & -2; I != E; I += 2) {
316     auto Key = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I));
317     auto Val = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I + 1));
318     if (!Key || !Val)
319       continue;
320     PALMetadataMap[Key->getZExtValue()] = Val->getZExtValue();
321   }
322 }
323 
324 // Print comments that apply to both callable functions and entry points.
325 void AMDGPUAsmPrinter::emitCommonFunctionComments(
326   uint32_t NumVGPR,
327   uint32_t NumSGPR,
328   uint64_t ScratchSize,
329   uint64_t CodeSize,
330   const AMDGPUMachineFunction *MFI) {
331   OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
332   OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
333   OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
334   OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
335   OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
336                               false);
337 }
338 
339 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
340     const MachineFunction &MF) const {
341   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
342   uint16_t KernelCodeProperties = 0;
343 
344   if (MFI.hasPrivateSegmentBuffer()) {
345     KernelCodeProperties |=
346         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
347   }
348   if (MFI.hasDispatchPtr()) {
349     KernelCodeProperties |=
350         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
351   }
352   if (MFI.hasQueuePtr()) {
353     KernelCodeProperties |=
354         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
355   }
356   if (MFI.hasKernargSegmentPtr()) {
357     KernelCodeProperties |=
358         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
359   }
360   if (MFI.hasDispatchID()) {
361     KernelCodeProperties |=
362         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
363   }
364   if (MFI.hasFlatScratchInit()) {
365     KernelCodeProperties |=
366         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
367   }
368 
369   return KernelCodeProperties;
370 }
371 
372 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
373     const MachineFunction &MF,
374     const SIProgramInfo &PI) const {
375   amdhsa::kernel_descriptor_t KernelDescriptor;
376   memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
377 
378   assert(isUInt<32>(PI.ScratchSize));
379   assert(isUInt<32>(PI.ComputePGMRSrc1));
380   assert(isUInt<32>(PI.ComputePGMRSrc2));
381 
382   KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
383   KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
384   KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1;
385   KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
386   KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
387 
388   return KernelDescriptor;
389 }
390 
391 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
392   CurrentProgramInfo = SIProgramInfo();
393 
394   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
395 
396   // The starting address of all shader programs must be 256 bytes aligned.
397   // Regular functions just need the basic required instruction alignment.
398   MF.setAlignment(MFI->isEntryFunction() ? 8 : 2);
399 
400   SetupMachineFunction(MF);
401 
402   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
403   MCContext &Context = getObjFileLowering().getContext();
404   // FIXME: This should be an explicit check for Mesa.
405   if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
406     MCSectionELF *ConfigSection =
407         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
408     OutStreamer->SwitchSection(ConfigSection);
409   }
410 
411   if (MFI->isEntryFunction()) {
412     getSIProgramInfo(CurrentProgramInfo, MF);
413   } else {
414     auto I = CallGraphResourceInfo.insert(
415       std::make_pair(&MF.getFunction(), SIFunctionResourceInfo()));
416     SIFunctionResourceInfo &Info = I.first->second;
417     assert(I.second && "should only be called once per function");
418     Info = analyzeResourceUsage(MF);
419   }
420 
421   if (STM.isAmdPalOS())
422     EmitPALMetadata(MF, CurrentProgramInfo);
423   else if (!STM.isAmdHsaOS()) {
424     EmitProgramInfoSI(MF, CurrentProgramInfo);
425   }
426 
427   DisasmLines.clear();
428   HexLines.clear();
429   DisasmLineMaxLen = 0;
430 
431   EmitFunctionBody();
432 
433   if (isVerbose()) {
434     MCSectionELF *CommentSection =
435         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
436     OutStreamer->SwitchSection(CommentSection);
437 
438     if (!MFI->isEntryFunction()) {
439       OutStreamer->emitRawComment(" Function info:", false);
440       SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()];
441       emitCommonFunctionComments(
442         Info.NumVGPR,
443         Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
444         Info.PrivateSegmentSize,
445         getFunctionCodeSize(MF), MFI);
446       return false;
447     }
448 
449     OutStreamer->emitRawComment(" Kernel info:", false);
450     emitCommonFunctionComments(CurrentProgramInfo.NumVGPR,
451                                CurrentProgramInfo.NumSGPR,
452                                CurrentProgramInfo.ScratchSize,
453                                getFunctionCodeSize(MF), MFI);
454 
455     OutStreamer->emitRawComment(
456       " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
457     OutStreamer->emitRawComment(
458       " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
459     OutStreamer->emitRawComment(
460       " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
461       " bytes/workgroup (compile time only)", false);
462 
463     OutStreamer->emitRawComment(
464       " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
465     OutStreamer->emitRawComment(
466       " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
467 
468     OutStreamer->emitRawComment(
469       " NumSGPRsForWavesPerEU: " +
470       Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
471     OutStreamer->emitRawComment(
472       " NumVGPRsForWavesPerEU: " +
473       Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
474 
475     OutStreamer->emitRawComment(
476       " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
477 
478     if (MF.getSubtarget<GCNSubtarget>().debuggerEmitPrologue()) {
479       OutStreamer->emitRawComment(
480         " DebuggerWavefrontPrivateSegmentOffsetSGPR: s" +
481         Twine(CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false);
482       OutStreamer->emitRawComment(
483         " DebuggerPrivateSegmentBufferSGPR: s" +
484         Twine(CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR), false);
485     }
486 
487     OutStreamer->emitRawComment(
488       " COMPUTE_PGM_RSRC2:USER_SGPR: " +
489       Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
490     OutStreamer->emitRawComment(
491       " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
492       Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
493     OutStreamer->emitRawComment(
494       " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
495       Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
496     OutStreamer->emitRawComment(
497       " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
498       Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
499     OutStreamer->emitRawComment(
500       " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
501       Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
502     OutStreamer->emitRawComment(
503       " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
504       Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
505       false);
506   }
507 
508   if (STM.dumpCode()) {
509 
510     OutStreamer->SwitchSection(
511         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
512 
513     for (size_t i = 0; i < DisasmLines.size(); ++i) {
514       std::string Comment = "\n";
515       if (!HexLines[i].empty()) {
516         Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
517         Comment += " ; " + HexLines[i] + "\n";
518       }
519 
520       OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
521       OutStreamer->EmitBytes(StringRef(Comment));
522     }
523   }
524 
525   return false;
526 }
527 
528 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
529   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
530   const SIInstrInfo *TII = STM.getInstrInfo();
531 
532   uint64_t CodeSize = 0;
533 
534   for (const MachineBasicBlock &MBB : MF) {
535     for (const MachineInstr &MI : MBB) {
536       // TODO: CodeSize should account for multiple functions.
537 
538       // TODO: Should we count size of debug info?
539       if (MI.isDebugInstr())
540         continue;
541 
542       CodeSize += TII->getInstSizeInBytes(MI);
543     }
544   }
545 
546   return CodeSize;
547 }
548 
549 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI,
550                                   const SIInstrInfo &TII,
551                                   unsigned Reg) {
552   for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) {
553     if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent()))
554       return true;
555   }
556 
557   return false;
558 }
559 
560 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs(
561   const GCNSubtarget &ST) const {
562   return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(ST.getFeatureBits(),
563                                                      UsesVCC, UsesFlatScratch);
564 }
565 
566 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage(
567   const MachineFunction &MF) const {
568   SIFunctionResourceInfo Info;
569 
570   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
571   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
572   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
573   const MachineRegisterInfo &MRI = MF.getRegInfo();
574   const SIInstrInfo *TII = ST.getInstrInfo();
575   const SIRegisterInfo &TRI = TII->getRegisterInfo();
576 
577   Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) ||
578                          MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI);
579 
580   // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
581   // instructions aren't used to access the scratch buffer. Inline assembly may
582   // need it though.
583   //
584   // If we only have implicit uses of flat_scr on flat instructions, it is not
585   // really needed.
586   if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() &&
587       (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) &&
588        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) &&
589        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) {
590     Info.UsesFlatScratch = false;
591   }
592 
593   Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects();
594   Info.PrivateSegmentSize = FrameInfo.getStackSize();
595   if (MFI->isStackRealigned())
596     Info.PrivateSegmentSize += FrameInfo.getMaxAlignment();
597 
598 
599   Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) ||
600                  MRI.isPhysRegUsed(AMDGPU::VCC_HI);
601 
602   // If there are no calls, MachineRegisterInfo can tell us the used register
603   // count easily.
604   // A tail call isn't considered a call for MachineFrameInfo's purposes.
605   if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) {
606     MCPhysReg HighestVGPRReg = AMDGPU::NoRegister;
607     for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) {
608       if (MRI.isPhysRegUsed(Reg)) {
609         HighestVGPRReg = Reg;
610         break;
611       }
612     }
613 
614     MCPhysReg HighestSGPRReg = AMDGPU::NoRegister;
615     for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) {
616       if (MRI.isPhysRegUsed(Reg)) {
617         HighestSGPRReg = Reg;
618         break;
619       }
620     }
621 
622     // We found the maximum register index. They start at 0, so add one to get the
623     // number of registers.
624     Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 :
625       TRI.getHWRegIndex(HighestVGPRReg) + 1;
626     Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 :
627       TRI.getHWRegIndex(HighestSGPRReg) + 1;
628 
629     return Info;
630   }
631 
632   int32_t MaxVGPR = -1;
633   int32_t MaxSGPR = -1;
634   uint64_t CalleeFrameSize = 0;
635 
636   for (const MachineBasicBlock &MBB : MF) {
637     for (const MachineInstr &MI : MBB) {
638       // TODO: Check regmasks? Do they occur anywhere except calls?
639       for (const MachineOperand &MO : MI.operands()) {
640         unsigned Width = 0;
641         bool IsSGPR = false;
642 
643         if (!MO.isReg())
644           continue;
645 
646         unsigned Reg = MO.getReg();
647         switch (Reg) {
648         case AMDGPU::EXEC:
649         case AMDGPU::EXEC_LO:
650         case AMDGPU::EXEC_HI:
651         case AMDGPU::SCC:
652         case AMDGPU::M0:
653         case AMDGPU::SRC_SHARED_BASE:
654         case AMDGPU::SRC_SHARED_LIMIT:
655         case AMDGPU::SRC_PRIVATE_BASE:
656         case AMDGPU::SRC_PRIVATE_LIMIT:
657           continue;
658 
659         case AMDGPU::NoRegister:
660           assert(MI.isDebugInstr());
661           continue;
662 
663         case AMDGPU::VCC:
664         case AMDGPU::VCC_LO:
665         case AMDGPU::VCC_HI:
666           Info.UsesVCC = true;
667           continue;
668 
669         case AMDGPU::FLAT_SCR:
670         case AMDGPU::FLAT_SCR_LO:
671         case AMDGPU::FLAT_SCR_HI:
672           continue;
673 
674         case AMDGPU::XNACK_MASK:
675         case AMDGPU::XNACK_MASK_LO:
676         case AMDGPU::XNACK_MASK_HI:
677           llvm_unreachable("xnack_mask registers should not be used");
678 
679         case AMDGPU::TBA:
680         case AMDGPU::TBA_LO:
681         case AMDGPU::TBA_HI:
682         case AMDGPU::TMA:
683         case AMDGPU::TMA_LO:
684         case AMDGPU::TMA_HI:
685           llvm_unreachable("trap handler registers should not be used");
686 
687         default:
688           break;
689         }
690 
691         if (AMDGPU::SReg_32RegClass.contains(Reg)) {
692           assert(!AMDGPU::TTMP_32RegClass.contains(Reg) &&
693                  "trap handler registers should not be used");
694           IsSGPR = true;
695           Width = 1;
696         } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) {
697           IsSGPR = false;
698           Width = 1;
699         } else if (AMDGPU::SReg_64RegClass.contains(Reg)) {
700           assert(!AMDGPU::TTMP_64RegClass.contains(Reg) &&
701                  "trap handler registers should not be used");
702           IsSGPR = true;
703           Width = 2;
704         } else if (AMDGPU::VReg_64RegClass.contains(Reg)) {
705           IsSGPR = false;
706           Width = 2;
707         } else if (AMDGPU::VReg_96RegClass.contains(Reg)) {
708           IsSGPR = false;
709           Width = 3;
710         } else if (AMDGPU::SReg_128RegClass.contains(Reg)) {
711           assert(!AMDGPU::TTMP_128RegClass.contains(Reg) &&
712             "trap handler registers should not be used");
713           IsSGPR = true;
714           Width = 4;
715         } else if (AMDGPU::VReg_128RegClass.contains(Reg)) {
716           IsSGPR = false;
717           Width = 4;
718         } else if (AMDGPU::SReg_256RegClass.contains(Reg)) {
719           assert(!AMDGPU::TTMP_256RegClass.contains(Reg) &&
720             "trap handler registers should not be used");
721           IsSGPR = true;
722           Width = 8;
723         } else if (AMDGPU::VReg_256RegClass.contains(Reg)) {
724           IsSGPR = false;
725           Width = 8;
726         } else if (AMDGPU::SReg_512RegClass.contains(Reg)) {
727           assert(!AMDGPU::TTMP_512RegClass.contains(Reg) &&
728             "trap handler registers should not be used");
729           IsSGPR = true;
730           Width = 16;
731         } else if (AMDGPU::VReg_512RegClass.contains(Reg)) {
732           IsSGPR = false;
733           Width = 16;
734         } else {
735           llvm_unreachable("Unknown register class");
736         }
737         unsigned HWReg = TRI.getHWRegIndex(Reg);
738         int MaxUsed = HWReg + Width - 1;
739         if (IsSGPR) {
740           MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR;
741         } else {
742           MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR;
743         }
744       }
745 
746       if (MI.isCall()) {
747         // Pseudo used just to encode the underlying global. Is there a better
748         // way to track this?
749 
750         const MachineOperand *CalleeOp
751           = TII->getNamedOperand(MI, AMDGPU::OpName::callee);
752         const Function *Callee = cast<Function>(CalleeOp->getGlobal());
753         if (Callee->isDeclaration()) {
754           // If this is a call to an external function, we can't do much. Make
755           // conservative guesses.
756 
757           // 48 SGPRs - vcc, - flat_scr, -xnack
758           int MaxSGPRGuess =
759               47 - IsaInfo::getNumExtraSGPRs(ST.getFeatureBits(), true,
760                                              ST.hasFlatAddressSpace());
761           MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess);
762           MaxVGPR = std::max(MaxVGPR, 23);
763 
764           CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384));
765           Info.UsesVCC = true;
766           Info.UsesFlatScratch = ST.hasFlatAddressSpace();
767           Info.HasDynamicallySizedStack = true;
768         } else {
769           // We force CodeGen to run in SCC order, so the callee's register
770           // usage etc. should be the cumulative usage of all callees.
771           auto I = CallGraphResourceInfo.find(Callee);
772           assert(I != CallGraphResourceInfo.end() &&
773                  "callee should have been handled before caller");
774 
775           MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR);
776           MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR);
777           CalleeFrameSize
778             = std::max(I->second.PrivateSegmentSize, CalleeFrameSize);
779           Info.UsesVCC |= I->second.UsesVCC;
780           Info.UsesFlatScratch |= I->second.UsesFlatScratch;
781           Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack;
782           Info.HasRecursion |= I->second.HasRecursion;
783         }
784 
785         if (!Callee->doesNotRecurse())
786           Info.HasRecursion = true;
787       }
788     }
789   }
790 
791   Info.NumExplicitSGPR = MaxSGPR + 1;
792   Info.NumVGPR = MaxVGPR + 1;
793   Info.PrivateSegmentSize += CalleeFrameSize;
794 
795   return Info;
796 }
797 
798 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
799                                         const MachineFunction &MF) {
800   SIFunctionResourceInfo Info = analyzeResourceUsage(MF);
801 
802   ProgInfo.NumVGPR = Info.NumVGPR;
803   ProgInfo.NumSGPR = Info.NumExplicitSGPR;
804   ProgInfo.ScratchSize = Info.PrivateSegmentSize;
805   ProgInfo.VCCUsed = Info.UsesVCC;
806   ProgInfo.FlatUsed = Info.UsesFlatScratch;
807   ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
808 
809   if (!isUInt<32>(ProgInfo.ScratchSize)) {
810     DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
811                                           ProgInfo.ScratchSize, DS_Error);
812     MF.getFunction().getContext().diagnose(DiagStackSize);
813   }
814 
815   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
816   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
817   const SIInstrInfo *TII = STM.getInstrInfo();
818   const SIRegisterInfo *RI = &TII->getRegisterInfo();
819 
820   // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are
821   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
822   // unified.
823   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
824       STM.getFeatureBits(), ProgInfo.VCCUsed, ProgInfo.FlatUsed);
825 
826   // Check the addressable register limit before we add ExtraSGPRs.
827   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
828       !STM.hasSGPRInitBug()) {
829     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
830     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
831       // This can happen due to a compiler bug or when using inline asm.
832       LLVMContext &Ctx = MF.getFunction().getContext();
833       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
834                                        "addressable scalar registers",
835                                        ProgInfo.NumSGPR, DS_Error,
836                                        DK_ResourceLimit,
837                                        MaxAddressableNumSGPRs);
838       Ctx.diagnose(Diag);
839       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
840     }
841   }
842 
843   // Account for extra SGPRs and VGPRs reserved for debugger use.
844   ProgInfo.NumSGPR += ExtraSGPRs;
845 
846   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
847   // dispatch registers are function args.
848   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
849   for (auto &Arg : MF.getFunction().args()) {
850     unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32;
851     if (Arg.hasAttribute(Attribute::InReg))
852       WaveDispatchNumSGPR += NumRegs;
853     else
854       WaveDispatchNumVGPR += NumRegs;
855   }
856   ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
857   ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
858 
859   // Adjust number of registers used to meet default/requested minimum/maximum
860   // number of waves per execution unit request.
861   ProgInfo.NumSGPRsForWavesPerEU = std::max(
862     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
863   ProgInfo.NumVGPRsForWavesPerEU = std::max(
864     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
865 
866   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
867       STM.hasSGPRInitBug()) {
868     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
869     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
870       // This can happen due to a compiler bug or when using inline asm to use
871       // the registers which are usually reserved for vcc etc.
872       LLVMContext &Ctx = MF.getFunction().getContext();
873       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
874                                        "scalar registers",
875                                        ProgInfo.NumSGPR, DS_Error,
876                                        DK_ResourceLimit,
877                                        MaxAddressableNumSGPRs);
878       Ctx.diagnose(Diag);
879       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
880       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
881     }
882   }
883 
884   if (STM.hasSGPRInitBug()) {
885     ProgInfo.NumSGPR =
886         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
887     ProgInfo.NumSGPRsForWavesPerEU =
888         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
889   }
890 
891   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
892     LLVMContext &Ctx = MF.getFunction().getContext();
893     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
894                                      MFI->getNumUserSGPRs(), DS_Error);
895     Ctx.diagnose(Diag);
896   }
897 
898   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
899     LLVMContext &Ctx = MF.getFunction().getContext();
900     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
901                                      MFI->getLDSSize(), DS_Error);
902     Ctx.diagnose(Diag);
903   }
904 
905   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
906       STM.getFeatureBits(), ProgInfo.NumSGPRsForWavesPerEU);
907   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
908       STM.getFeatureBits(), ProgInfo.NumVGPRsForWavesPerEU);
909 
910   // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and
911   // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue"
912   // attribute was requested.
913   if (STM.debuggerEmitPrologue()) {
914     ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR =
915       RI->getHWRegIndex(MFI->getScratchWaveOffsetReg());
916     ProgInfo.DebuggerPrivateSegmentBufferSGPR =
917       RI->getHWRegIndex(MFI->getScratchRSrcReg());
918   }
919 
920   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
921   // register.
922   ProgInfo.FloatMode = getFPMode(MF);
923 
924   ProgInfo.IEEEMode = STM.enableIEEEBit(MF);
925 
926   // Make clamp modifier on NaN input returns 0.
927   ProgInfo.DX10Clamp = STM.enableDX10Clamp();
928 
929   unsigned LDSAlignShift;
930   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
931     // LDS is allocated in 64 dword blocks.
932     LDSAlignShift = 8;
933   } else {
934     // LDS is allocated in 128 dword blocks.
935     LDSAlignShift = 9;
936   }
937 
938   unsigned LDSSpillSize =
939     MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
940 
941   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
942   ProgInfo.LDSBlocks =
943       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
944 
945   // Scratch is allocated in 256 dword blocks.
946   unsigned ScratchAlignShift = 10;
947   // We need to program the hardware with the amount of scratch memory that
948   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
949   // scratch memory used per thread.
950   ProgInfo.ScratchBlocks =
951       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
952               1ULL << ScratchAlignShift) >>
953       ScratchAlignShift;
954 
955   ProgInfo.ComputePGMRSrc1 =
956       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
957       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
958       S_00B848_PRIORITY(ProgInfo.Priority) |
959       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
960       S_00B848_PRIV(ProgInfo.Priv) |
961       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
962       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
963       S_00B848_IEEE_MODE(ProgInfo.IEEEMode);
964 
965   // 0 = X, 1 = XY, 2 = XYZ
966   unsigned TIDIGCompCnt = 0;
967   if (MFI->hasWorkItemIDZ())
968     TIDIGCompCnt = 2;
969   else if (MFI->hasWorkItemIDY())
970     TIDIGCompCnt = 1;
971 
972   ProgInfo.ComputePGMRSrc2 =
973       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
974       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
975       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
976       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
977       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
978       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
979       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
980       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
981       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
982       S_00B84C_EXCP_EN_MSB(0) |
983       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
984       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
985       S_00B84C_EXCP_EN(0);
986 }
987 
988 static unsigned getRsrcReg(CallingConv::ID CallConv) {
989   switch (CallConv) {
990   default: LLVM_FALLTHROUGH;
991   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
992   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
993   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
994   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
995   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
996   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
997   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
998   }
999 }
1000 
1001 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
1002                                          const SIProgramInfo &CurrentProgramInfo) {
1003   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1004   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1005   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
1006 
1007   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1008     OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
1009 
1010     OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4);
1011 
1012     OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
1013     OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4);
1014 
1015     OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
1016     OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1017 
1018     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
1019     // 0" comment but I don't see a corresponding field in the register spec.
1020   } else {
1021     OutStreamer->EmitIntValue(RsrcReg, 4);
1022     OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1023                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
1024     if (STM.isVGPRSpillingEnabled(MF.getFunction())) {
1025       OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
1026       OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1027     }
1028   }
1029 
1030   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1031     OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
1032     OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4);
1033     OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
1034     OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4);
1035     OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
1036     OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
1037   }
1038 
1039   OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4);
1040   OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4);
1041   OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4);
1042   OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4);
1043 }
1044 
1045 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1046 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
1047 // metadata items into the PALMetadataMap, combining with any provided by the
1048 // frontend as LLVM metadata. Once all functions are written, PALMetadataMap is
1049 // then written as a single block in the .note section.
1050 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
1051        const SIProgramInfo &CurrentProgramInfo) {
1052   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1053   // Given the calling convention, calculate the register number for rsrc1. In
1054   // principle the register number could change in future hardware, but we know
1055   // it is the same for gfx6-9 (except that LS and ES don't exist on gfx9), so
1056   // we can use the same fixed value that .AMDGPU.config has for Mesa. Note
1057   // that we use a register number rather than a byte offset, so we need to
1058   // divide by 4.
1059   unsigned Rsrc1Reg = getRsrcReg(MF.getFunction().getCallingConv()) / 4;
1060   unsigned Rsrc2Reg = Rsrc1Reg + 1;
1061   // Also calculate the PAL metadata key for *S_SCRATCH_SIZE. It can be used
1062   // with a constant offset to access any non-register shader-specific PAL
1063   // metadata key.
1064   unsigned ScratchSizeKey = PALMD::Key::CS_SCRATCH_SIZE;
1065   switch (MF.getFunction().getCallingConv()) {
1066     case CallingConv::AMDGPU_PS:
1067       ScratchSizeKey = PALMD::Key::PS_SCRATCH_SIZE;
1068       break;
1069     case CallingConv::AMDGPU_VS:
1070       ScratchSizeKey = PALMD::Key::VS_SCRATCH_SIZE;
1071       break;
1072     case CallingConv::AMDGPU_GS:
1073       ScratchSizeKey = PALMD::Key::GS_SCRATCH_SIZE;
1074       break;
1075     case CallingConv::AMDGPU_ES:
1076       ScratchSizeKey = PALMD::Key::ES_SCRATCH_SIZE;
1077       break;
1078     case CallingConv::AMDGPU_HS:
1079       ScratchSizeKey = PALMD::Key::HS_SCRATCH_SIZE;
1080       break;
1081     case CallingConv::AMDGPU_LS:
1082       ScratchSizeKey = PALMD::Key::LS_SCRATCH_SIZE;
1083       break;
1084   }
1085   unsigned NumUsedVgprsKey = ScratchSizeKey +
1086       PALMD::Key::VS_NUM_USED_VGPRS - PALMD::Key::VS_SCRATCH_SIZE;
1087   unsigned NumUsedSgprsKey = ScratchSizeKey +
1088       PALMD::Key::VS_NUM_USED_SGPRS - PALMD::Key::VS_SCRATCH_SIZE;
1089   PALMetadataMap[NumUsedVgprsKey] = CurrentProgramInfo.NumVGPRsForWavesPerEU;
1090   PALMetadataMap[NumUsedSgprsKey] = CurrentProgramInfo.NumSGPRsForWavesPerEU;
1091   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1092     PALMetadataMap[Rsrc1Reg] |= CurrentProgramInfo.ComputePGMRSrc1;
1093     PALMetadataMap[Rsrc2Reg] |= CurrentProgramInfo.ComputePGMRSrc2;
1094     // ScratchSize is in bytes, 16 aligned.
1095     PALMetadataMap[ScratchSizeKey] |=
1096         alignTo(CurrentProgramInfo.ScratchSize, 16);
1097   } else {
1098     PALMetadataMap[Rsrc1Reg] |= S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1099         S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks);
1100     if (CurrentProgramInfo.ScratchBlocks > 0)
1101       PALMetadataMap[Rsrc2Reg] |= S_00B84C_SCRATCH_EN(1);
1102     // ScratchSize is in bytes, 16 aligned.
1103     PALMetadataMap[ScratchSizeKey] |=
1104         alignTo(CurrentProgramInfo.ScratchSize, 16);
1105   }
1106   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1107     PALMetadataMap[Rsrc2Reg] |=
1108         S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks);
1109     PALMetadataMap[R_0286CC_SPI_PS_INPUT_ENA / 4] |= MFI->getPSInputEnable();
1110     PALMetadataMap[R_0286D0_SPI_PS_INPUT_ADDR / 4] |= MFI->getPSInputAddr();
1111   }
1112 }
1113 
1114 // This is supposed to be log2(Size)
1115 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
1116   switch (Size) {
1117   case 4:
1118     return AMD_ELEMENT_4_BYTES;
1119   case 8:
1120     return AMD_ELEMENT_8_BYTES;
1121   case 16:
1122     return AMD_ELEMENT_16_BYTES;
1123   default:
1124     llvm_unreachable("invalid private_element_size");
1125   }
1126 }
1127 
1128 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1129                                         const SIProgramInfo &CurrentProgramInfo,
1130                                         const MachineFunction &MF) const {
1131   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1132   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1133 
1134   AMDGPU::initDefaultAMDKernelCodeT(Out, STM.getFeatureBits());
1135 
1136   Out.compute_pgm_resource_registers =
1137       CurrentProgramInfo.ComputePGMRSrc1 |
1138       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1139   Out.code_properties = AMD_CODE_PROPERTY_IS_PTR64;
1140 
1141   if (CurrentProgramInfo.DynamicCallStack)
1142     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1143 
1144   AMD_HSA_BITS_SET(Out.code_properties,
1145                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1146                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
1147 
1148   if (MFI->hasPrivateSegmentBuffer()) {
1149     Out.code_properties |=
1150       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1151   }
1152 
1153   if (MFI->hasDispatchPtr())
1154     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1155 
1156   if (MFI->hasQueuePtr())
1157     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1158 
1159   if (MFI->hasKernargSegmentPtr())
1160     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1161 
1162   if (MFI->hasDispatchID())
1163     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1164 
1165   if (MFI->hasFlatScratchInit())
1166     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1167 
1168   if (MFI->hasDispatchPtr())
1169     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1170 
1171   if (STM.debuggerSupported())
1172     Out.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED;
1173 
1174   if (STM.isXNACKEnabled())
1175     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1176 
1177   // FIXME: Should use getKernArgSize
1178   Out.kernarg_segment_byte_size =
1179     STM.getKernArgSegmentSize(MF.getFunction(), MFI->getExplicitKernArgSize());
1180   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1181   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1182   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1183   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1184 
1185   // These alignment values are specified in powers of two, so alignment =
1186   // 2^n.  The minimum alignment is 2^4 = 16.
1187   Out.kernarg_segment_alignment = std::max((size_t)4,
1188       countTrailingZeros(MFI->getMaxKernArgAlign()));
1189 
1190   if (STM.debuggerEmitPrologue()) {
1191     Out.debug_wavefront_private_segment_offset_sgpr =
1192       CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR;
1193     Out.debug_private_segment_buffer_sgpr =
1194       CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR;
1195   }
1196 }
1197 
1198 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1199                                        unsigned AsmVariant,
1200                                        const char *ExtraCode, raw_ostream &O) {
1201   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1202   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O))
1203     return false;
1204 
1205   if (ExtraCode && ExtraCode[0]) {
1206     if (ExtraCode[1] != 0)
1207       return true; // Unknown modifier.
1208 
1209     switch (ExtraCode[0]) {
1210     case 'r':
1211       break;
1212     default:
1213       return true;
1214     }
1215   }
1216 
1217   // TODO: Should be able to support other operand types like globals.
1218   const MachineOperand &MO = MI->getOperand(OpNo);
1219   if (MO.isReg()) {
1220     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1221                                        *MF->getSubtarget().getRegisterInfo());
1222     return false;
1223   }
1224 
1225   return true;
1226 }
1227