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