1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly 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 "MCTargetDesc/AMDGPUTargetStreamer.h"
21 #include "InstPrinter/AMDGPUInstPrinter.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "AMDGPU.h"
24 #include "AMDKernelCodeT.h"
25 #include "AMDGPUSubtarget.h"
26 #include "R600Defines.h"
27 #include "R600MachineFunctionInfo.h"
28 #include "R600RegisterInfo.h"
29 #include "SIDefines.h"
30 #include "SIMachineFunctionInfo.h"
31 #include "SIInstrInfo.h"
32 #include "SIRegisterInfo.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionELF.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/Support/ELF.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "AMDGPURuntimeMetadata.h"
43 
44 using namespace ::AMDGPU;
45 using namespace llvm;
46 
47 // TODO: This should get the default rounding mode from the kernel. We just set
48 // the default here, but this could change if the OpenCL rounding mode pragmas
49 // are used.
50 //
51 // The denormal mode here should match what is reported by the OpenCL runtime
52 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
53 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
54 //
55 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
56 // precision, and leaves single precision to flush all and does not report
57 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
58 // CL_FP_DENORM for both.
59 //
60 // FIXME: It seems some instructions do not support single precision denormals
61 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
62 // and sin_f32, cos_f32 on most parts).
63 
64 // We want to use these instructions, and using fp32 denormals also causes
65 // instructions to run at the double precision rate for the device so it's
66 // probably best to just report no single precision denormals.
67 static uint32_t getFPMode(const MachineFunction &F) {
68   const SISubtarget& ST = F.getSubtarget<SISubtarget>();
69   // TODO: Is there any real use for the flush in only / flush out only modes?
70 
71   uint32_t FP32Denormals =
72     ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
73 
74   uint32_t FP64Denormals =
75     ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
76 
77   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
78          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
79          FP_DENORM_MODE_SP(FP32Denormals) |
80          FP_DENORM_MODE_DP(FP64Denormals);
81 }
82 
83 static AsmPrinter *
84 createAMDGPUAsmPrinterPass(TargetMachine &tm,
85                            std::unique_ptr<MCStreamer> &&Streamer) {
86   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
87 }
88 
89 extern "C" void LLVMInitializeAMDGPUAsmPrinter() {
90   TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);
91   TargetRegistry::RegisterAsmPrinter(TheGCNTarget, createAMDGPUAsmPrinterPass);
92 }
93 
94 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
95                                    std::unique_ptr<MCStreamer> Streamer)
96     : AsmPrinter(TM, std::move(Streamer)) {}
97 
98 const char *AMDGPUAsmPrinter::getPassName() const  {
99   return "AMDGPU Assembly Printer";
100 }
101 
102 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) {
103   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
104     return;
105 
106   // Need to construct an MCSubtargetInfo here in case we have no functions
107   // in the module.
108   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
109         TM.getTargetTriple().str(), TM.getTargetCPU(),
110         TM.getTargetFeatureString()));
111 
112   AMDGPUTargetStreamer *TS =
113       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
114 
115   TS->EmitDirectiveHSACodeObjectVersion(2, 1);
116 
117   AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(STI->getFeatureBits());
118   TS->EmitDirectiveHSACodeObjectISA(ISA.Major, ISA.Minor, ISA.Stepping,
119                                     "AMD", "AMDGPU");
120   emitStartOfRuntimeMetadata(M);
121 }
122 
123 void AMDGPUAsmPrinter::EmitFunctionBodyStart() {
124   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
125   SIProgramInfo KernelInfo;
126   if (STM.isAmdHsaOS()) {
127     getSIProgramInfo(KernelInfo, *MF);
128     EmitAmdKernelCodeT(*MF, KernelInfo);
129   }
130 }
131 
132 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() {
133   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
134   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
135   if (MFI->isKernel() && STM.isAmdHsaOS()) {
136     AMDGPUTargetStreamer *TS =
137         static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
138     TS->EmitAMDGPUSymbolType(CurrentFnSym->getName(),
139                              ELF::STT_AMDGPU_HSA_KERNEL);
140   }
141 
142   AsmPrinter::EmitFunctionEntryLabel();
143 }
144 
145 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
146 
147   // Group segment variables aren't emitted in HSA.
148   if (AMDGPU::isGroupSegment(GV))
149     return;
150 
151   AsmPrinter::EmitGlobalVariable(GV);
152 }
153 
154 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
155 
156   // The starting address of all shader programs must be 256 bytes aligned.
157   MF.setAlignment(8);
158 
159   SetupMachineFunction(MF);
160 
161   MCContext &Context = getObjFileLowering().getContext();
162   MCSectionELF *ConfigSection =
163       Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
164   OutStreamer->SwitchSection(ConfigSection);
165 
166   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
167   SIProgramInfo KernelInfo;
168   if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
169     getSIProgramInfo(KernelInfo, MF);
170     if (!STM.isAmdHsaOS()) {
171       EmitProgramInfoSI(MF, KernelInfo);
172     }
173   } else {
174     EmitProgramInfoR600(MF);
175   }
176 
177   DisasmLines.clear();
178   HexLines.clear();
179   DisasmLineMaxLen = 0;
180 
181   EmitFunctionBody();
182 
183   if (isVerbose()) {
184     MCSectionELF *CommentSection =
185         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
186     OutStreamer->SwitchSection(CommentSection);
187 
188     if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
189       OutStreamer->emitRawComment(" Kernel info:", false);
190       OutStreamer->emitRawComment(" codeLenInByte = " + Twine(KernelInfo.CodeLen),
191                                   false);
192       OutStreamer->emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR),
193                                   false);
194       OutStreamer->emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR),
195                                   false);
196       OutStreamer->emitRawComment(" FloatMode: " + Twine(KernelInfo.FloatMode),
197                                   false);
198       OutStreamer->emitRawComment(" IeeeMode: " + Twine(KernelInfo.IEEEMode),
199                                   false);
200       OutStreamer->emitRawComment(" ScratchSize: " + Twine(KernelInfo.ScratchSize),
201                                   false);
202       OutStreamer->emitRawComment(" LDSByteSize: " + Twine(KernelInfo.LDSSize) +
203                                   " bytes/workgroup (compile time only)", false);
204 
205       OutStreamer->emitRawComment(" SGPRBlocks: " +
206                                   Twine(KernelInfo.SGPRBlocks), false);
207       OutStreamer->emitRawComment(" VGPRBlocks: " +
208                                   Twine(KernelInfo.VGPRBlocks), false);
209 
210       OutStreamer->emitRawComment(" NumSGPRsForWavesPerEU: " +
211                                   Twine(KernelInfo.NumSGPRsForWavesPerEU), false);
212       OutStreamer->emitRawComment(" NumVGPRsForWavesPerEU: " +
213                                   Twine(KernelInfo.NumVGPRsForWavesPerEU), false);
214 
215       OutStreamer->emitRawComment(" ReservedVGPRFirst: " + Twine(KernelInfo.ReservedVGPRFirst),
216                                   false);
217       OutStreamer->emitRawComment(" ReservedVGPRCount: " + Twine(KernelInfo.ReservedVGPRCount),
218                                   false);
219 
220       if (MF.getSubtarget<SISubtarget>().debuggerEmitPrologue()) {
221         OutStreamer->emitRawComment(" DebuggerWavefrontPrivateSegmentOffsetSGPR: s" +
222                                     Twine(KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false);
223         OutStreamer->emitRawComment(" DebuggerPrivateSegmentBufferSGPR: s" +
224                                     Twine(KernelInfo.DebuggerPrivateSegmentBufferSGPR), false);
225       }
226 
227       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:USER_SGPR: " +
228                                   Twine(G_00B84C_USER_SGPR(KernelInfo.ComputePGMRSrc2)),
229                                   false);
230       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_X_EN: " +
231                                   Twine(G_00B84C_TGID_X_EN(KernelInfo.ComputePGMRSrc2)),
232                                   false);
233       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
234                                   Twine(G_00B84C_TGID_Y_EN(KernelInfo.ComputePGMRSrc2)),
235                                   false);
236       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
237                                   Twine(G_00B84C_TGID_Z_EN(KernelInfo.ComputePGMRSrc2)),
238                                   false);
239       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
240                                   Twine(G_00B84C_TIDIG_COMP_CNT(KernelInfo.ComputePGMRSrc2)),
241                                   false);
242 
243     } else {
244       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
245       OutStreamer->emitRawComment(
246         Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->CFStackSize)));
247     }
248   }
249 
250   if (STM.dumpCode()) {
251 
252     OutStreamer->SwitchSection(
253         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
254 
255     for (size_t i = 0; i < DisasmLines.size(); ++i) {
256       std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
257       Comment += " ; " + HexLines[i] + "\n";
258 
259       OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
260       OutStreamer->EmitBytes(StringRef(Comment));
261     }
262   }
263 
264   emitRuntimeMetadata(*MF.getFunction());
265 
266   return false;
267 }
268 
269 void AMDGPUAsmPrinter::EmitProgramInfoR600(const MachineFunction &MF) {
270   unsigned MaxGPR = 0;
271   bool killPixel = false;
272   const R600Subtarget &STM = MF.getSubtarget<R600Subtarget>();
273   const R600RegisterInfo *RI = STM.getRegisterInfo();
274   const R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
275 
276   for (const MachineBasicBlock &MBB : MF) {
277     for (const MachineInstr &MI : MBB) {
278       if (MI.getOpcode() == AMDGPU::KILLGT)
279         killPixel = true;
280       unsigned numOperands = MI.getNumOperands();
281       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
282         const MachineOperand &MO = MI.getOperand(op_idx);
283         if (!MO.isReg())
284           continue;
285         unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;
286 
287         // Register with value > 127 aren't GPR
288         if (HWReg > 127)
289           continue;
290         MaxGPR = std::max(MaxGPR, HWReg);
291       }
292     }
293   }
294 
295   unsigned RsrcReg;
296   if (STM.getGeneration() >= R600Subtarget::EVERGREEN) {
297     // Evergreen / Northern Islands
298     switch (MF.getFunction()->getCallingConv()) {
299     default: LLVM_FALLTHROUGH;
300     case CallingConv::AMDGPU_CS: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
301     case CallingConv::AMDGPU_GS: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
302     case CallingConv::AMDGPU_PS: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
303     case CallingConv::AMDGPU_VS: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
304     }
305   } else {
306     // R600 / R700
307     switch (MF.getFunction()->getCallingConv()) {
308     default: LLVM_FALLTHROUGH;
309     case CallingConv::AMDGPU_GS: LLVM_FALLTHROUGH;
310     case CallingConv::AMDGPU_CS: LLVM_FALLTHROUGH;
311     case CallingConv::AMDGPU_VS: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
312     case CallingConv::AMDGPU_PS: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
313     }
314   }
315 
316   OutStreamer->EmitIntValue(RsrcReg, 4);
317   OutStreamer->EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
318                            S_STACK_SIZE(MFI->CFStackSize), 4);
319   OutStreamer->EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
320   OutStreamer->EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);
321 
322   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
323     OutStreamer->EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
324     OutStreamer->EmitIntValue(alignTo(MFI->getLDSSize(), 4) >> 2, 4);
325   }
326 }
327 
328 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
329                                         const MachineFunction &MF) const {
330   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
331   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
332   uint64_t CodeSize = 0;
333   unsigned MaxSGPR = 0;
334   unsigned MaxVGPR = 0;
335   bool VCCUsed = false;
336   bool FlatUsed = false;
337   const SIRegisterInfo *RI = STM.getRegisterInfo();
338   const SIInstrInfo *TII = STM.getInstrInfo();
339 
340   for (const MachineBasicBlock &MBB : MF) {
341     for (const MachineInstr &MI : MBB) {
342       // TODO: CodeSize should account for multiple functions.
343 
344       // TODO: Should we count size of debug info?
345       if (MI.isDebugValue())
346         continue;
347 
348       CodeSize += TII->getInstSizeInBytes(MI);
349 
350       unsigned numOperands = MI.getNumOperands();
351       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
352         const MachineOperand &MO = MI.getOperand(op_idx);
353         unsigned width = 0;
354         bool isSGPR = false;
355 
356         if (!MO.isReg())
357           continue;
358 
359         unsigned reg = MO.getReg();
360         switch (reg) {
361         case AMDGPU::EXEC:
362         case AMDGPU::EXEC_LO:
363         case AMDGPU::EXEC_HI:
364         case AMDGPU::SCC:
365         case AMDGPU::M0:
366           continue;
367 
368         case AMDGPU::VCC:
369         case AMDGPU::VCC_LO:
370         case AMDGPU::VCC_HI:
371           VCCUsed = true;
372           continue;
373 
374         case AMDGPU::FLAT_SCR:
375         case AMDGPU::FLAT_SCR_LO:
376         case AMDGPU::FLAT_SCR_HI:
377           FlatUsed = true;
378           continue;
379 
380         case AMDGPU::TBA:
381         case AMDGPU::TBA_LO:
382         case AMDGPU::TBA_HI:
383         case AMDGPU::TMA:
384         case AMDGPU::TMA_LO:
385         case AMDGPU::TMA_HI:
386           llvm_unreachable("trap handler registers should not be used");
387 
388         default:
389           break;
390         }
391 
392         if (AMDGPU::SReg_32RegClass.contains(reg)) {
393           assert(!AMDGPU::TTMP_32RegClass.contains(reg) &&
394                  "trap handler registers should not be used");
395           isSGPR = true;
396           width = 1;
397         } else if (AMDGPU::VGPR_32RegClass.contains(reg)) {
398           isSGPR = false;
399           width = 1;
400         } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
401           assert(!AMDGPU::TTMP_64RegClass.contains(reg) &&
402                  "trap handler registers should not be used");
403           isSGPR = true;
404           width = 2;
405         } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
406           isSGPR = false;
407           width = 2;
408         } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
409           isSGPR = false;
410           width = 3;
411         } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
412           isSGPR = true;
413           width = 4;
414         } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
415           isSGPR = false;
416           width = 4;
417         } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
418           isSGPR = true;
419           width = 8;
420         } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
421           isSGPR = false;
422           width = 8;
423         } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
424           isSGPR = true;
425           width = 16;
426         } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
427           isSGPR = false;
428           width = 16;
429         } else {
430           llvm_unreachable("Unknown register class");
431         }
432         unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
433         unsigned maxUsed = hwReg + width - 1;
434         if (isSGPR) {
435           MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
436         } else {
437           MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
438         }
439       }
440     }
441   }
442 
443   unsigned ExtraSGPRs = 0;
444 
445   if (VCCUsed)
446     ExtraSGPRs = 2;
447 
448   if (STM.getGeneration() < SISubtarget::VOLCANIC_ISLANDS) {
449     if (FlatUsed)
450       ExtraSGPRs = 4;
451   } else {
452     if (STM.isXNACKEnabled())
453       ExtraSGPRs = 4;
454 
455     if (FlatUsed)
456       ExtraSGPRs = 6;
457   }
458 
459   // Record first reserved register and reserved register count fields, and
460   // update max register counts if "amdgpu-debugger-reserve-regs" attribute was
461   // requested.
462   ProgInfo.ReservedVGPRFirst = STM.debuggerReserveRegs() ? MaxVGPR + 1 : 0;
463   ProgInfo.ReservedVGPRCount = RI->getNumDebuggerReservedVGPRs(STM);
464 
465   // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and
466   // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue"
467   // attribute was requested.
468   if (STM.debuggerEmitPrologue()) {
469     ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR =
470       RI->getHWRegIndex(MFI->getScratchWaveOffsetReg());
471     ProgInfo.DebuggerPrivateSegmentBufferSGPR =
472       RI->getHWRegIndex(MFI->getScratchRSrcReg());
473   }
474 
475   // Account for extra SGPRs and VGPRs reserved for debugger use.
476   MaxSGPR += ExtraSGPRs;
477   MaxVGPR += RI->getNumDebuggerReservedVGPRs(STM);
478 
479   // We found the maximum register index. They start at 0, so add one to get the
480   // number of registers.
481   ProgInfo.NumVGPR = MaxVGPR + 1;
482   ProgInfo.NumSGPR = MaxSGPR + 1;
483 
484   // Adjust number of registers used to meet default/requested minimum/maximum
485   // number of waves per execution unit request.
486   ProgInfo.NumSGPRsForWavesPerEU = std::max(
487     ProgInfo.NumSGPR, RI->getMinNumSGPRs(STM, MFI->getMaxWavesPerEU()));
488   ProgInfo.NumVGPRsForWavesPerEU = std::max(
489     ProgInfo.NumVGPR, RI->getMinNumVGPRs(MFI->getMaxWavesPerEU()));
490 
491   if (STM.hasSGPRInitBug()) {
492     if (ProgInfo.NumSGPR > SISubtarget::FIXED_SGPR_COUNT_FOR_INIT_BUG) {
493       LLVMContext &Ctx = MF.getFunction()->getContext();
494       DiagnosticInfoResourceLimit Diag(*MF.getFunction(),
495                                        "SGPRs with SGPR init bug",
496                                        ProgInfo.NumSGPR, DS_Error);
497       Ctx.diagnose(Diag);
498     }
499 
500     ProgInfo.NumSGPR = SISubtarget::FIXED_SGPR_COUNT_FOR_INIT_BUG;
501     ProgInfo.NumSGPRsForWavesPerEU = SISubtarget::FIXED_SGPR_COUNT_FOR_INIT_BUG;
502   }
503 
504   if (MFI->NumUserSGPRs > STM.getMaxNumUserSGPRs()) {
505     LLVMContext &Ctx = MF.getFunction()->getContext();
506     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "user SGPRs",
507                                      MFI->NumUserSGPRs, DS_Error);
508     Ctx.diagnose(Diag);
509   }
510 
511   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
512     LLVMContext &Ctx = MF.getFunction()->getContext();
513     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "local memory",
514                                      MFI->getLDSSize(), DS_Error);
515     Ctx.diagnose(Diag);
516   }
517 
518   // SGPRBlocks is actual number of SGPR blocks minus 1.
519   ProgInfo.SGPRBlocks = alignTo(ProgInfo.NumSGPRsForWavesPerEU,
520                                 RI->getSGPRAllocGranule());
521   ProgInfo.SGPRBlocks = ProgInfo.SGPRBlocks / RI->getSGPRAllocGranule() - 1;
522 
523   // VGPRBlocks is actual number of VGPR blocks minus 1.
524   ProgInfo.VGPRBlocks = alignTo(ProgInfo.NumVGPRsForWavesPerEU,
525                                 RI->getVGPRAllocGranule());
526   ProgInfo.VGPRBlocks = ProgInfo.VGPRBlocks / RI->getVGPRAllocGranule() - 1;
527 
528   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
529   // register.
530   ProgInfo.FloatMode = getFPMode(MF);
531 
532   ProgInfo.IEEEMode = 0;
533 
534   // Make clamp modifier on NaN input returns 0.
535   ProgInfo.DX10Clamp = 1;
536 
537   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
538   ProgInfo.ScratchSize = FrameInfo.getStackSize();
539 
540   ProgInfo.FlatUsed = FlatUsed;
541   ProgInfo.VCCUsed = VCCUsed;
542   ProgInfo.CodeLen = CodeSize;
543 
544   unsigned LDSAlignShift;
545   if (STM.getGeneration() < SISubtarget::SEA_ISLANDS) {
546     // LDS is allocated in 64 dword blocks.
547     LDSAlignShift = 8;
548   } else {
549     // LDS is allocated in 128 dword blocks.
550     LDSAlignShift = 9;
551   }
552 
553   unsigned LDSSpillSize =
554     MFI->LDSWaveSpillSize * MFI->getMaxFlatWorkGroupSize();
555 
556   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
557   ProgInfo.LDSBlocks =
558       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
559 
560   // Scratch is allocated in 256 dword blocks.
561   unsigned ScratchAlignShift = 10;
562   // We need to program the hardware with the amount of scratch memory that
563   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
564   // scratch memory used per thread.
565   ProgInfo.ScratchBlocks =
566       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
567               1ULL << ScratchAlignShift) >>
568       ScratchAlignShift;
569 
570   ProgInfo.ComputePGMRSrc1 =
571       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
572       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
573       S_00B848_PRIORITY(ProgInfo.Priority) |
574       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
575       S_00B848_PRIV(ProgInfo.Priv) |
576       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
577       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
578       S_00B848_IEEE_MODE(ProgInfo.IEEEMode);
579 
580   // 0 = X, 1 = XY, 2 = XYZ
581   unsigned TIDIGCompCnt = 0;
582   if (MFI->hasWorkItemIDZ())
583     TIDIGCompCnt = 2;
584   else if (MFI->hasWorkItemIDY())
585     TIDIGCompCnt = 1;
586 
587   ProgInfo.ComputePGMRSrc2 =
588       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
589       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
590       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
591       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
592       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
593       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
594       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
595       S_00B84C_EXCP_EN_MSB(0) |
596       S_00B84C_LDS_SIZE(ProgInfo.LDSBlocks) |
597       S_00B84C_EXCP_EN(0);
598 }
599 
600 static unsigned getRsrcReg(CallingConv::ID CallConv) {
601   switch (CallConv) {
602   default: LLVM_FALLTHROUGH;
603   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
604   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
605   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
606   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
607   }
608 }
609 
610 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
611                                          const SIProgramInfo &KernelInfo) {
612   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
613   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
614   unsigned RsrcReg = getRsrcReg(MF.getFunction()->getCallingConv());
615 
616   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
617     OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
618 
619     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc1, 4);
620 
621     OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
622     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc2, 4);
623 
624     OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
625     OutStreamer->EmitIntValue(S_00B860_WAVESIZE(KernelInfo.ScratchBlocks), 4);
626 
627     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
628     // 0" comment but I don't see a corresponding field in the register spec.
629   } else {
630     OutStreamer->EmitIntValue(RsrcReg, 4);
631     OutStreamer->EmitIntValue(S_00B028_VGPRS(KernelInfo.VGPRBlocks) |
632                               S_00B028_SGPRS(KernelInfo.SGPRBlocks), 4);
633     if (STM.isVGPRSpillingEnabled(*MF.getFunction())) {
634       OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
635       OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(KernelInfo.ScratchBlocks), 4);
636     }
637   }
638 
639   if (MF.getFunction()->getCallingConv() == CallingConv::AMDGPU_PS) {
640     OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
641     OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(KernelInfo.LDSBlocks), 4);
642     OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
643     OutStreamer->EmitIntValue(MFI->PSInputEna, 4);
644     OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
645     OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
646   }
647 
648   OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4);
649   OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4);
650   OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4);
651   OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4);
652 }
653 
654 // This is supposed to be log2(Size)
655 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
656   switch (Size) {
657   case 4:
658     return AMD_ELEMENT_4_BYTES;
659   case 8:
660     return AMD_ELEMENT_8_BYTES;
661   case 16:
662     return AMD_ELEMENT_16_BYTES;
663   default:
664     llvm_unreachable("invalid private_element_size");
665   }
666 }
667 
668 void AMDGPUAsmPrinter::EmitAmdKernelCodeT(const MachineFunction &MF,
669                                          const SIProgramInfo &KernelInfo) const {
670   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
671   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
672   amd_kernel_code_t header;
673 
674   AMDGPU::initDefaultAMDKernelCodeT(header, STM.getFeatureBits());
675 
676   header.compute_pgm_resource_registers =
677       KernelInfo.ComputePGMRSrc1 |
678       (KernelInfo.ComputePGMRSrc2 << 32);
679   header.code_properties = AMD_CODE_PROPERTY_IS_PTR64;
680 
681 
682   AMD_HSA_BITS_SET(header.code_properties,
683                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
684                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
685 
686   if (MFI->hasPrivateSegmentBuffer()) {
687     header.code_properties |=
688       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
689   }
690 
691   if (MFI->hasDispatchPtr())
692     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
693 
694   if (MFI->hasQueuePtr())
695     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
696 
697   if (MFI->hasKernargSegmentPtr())
698     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
699 
700   if (MFI->hasDispatchID())
701     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
702 
703   if (MFI->hasFlatScratchInit())
704     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
705 
706   // TODO: Private segment size
707 
708   if (MFI->hasGridWorkgroupCountX()) {
709     header.code_properties |=
710       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X;
711   }
712 
713   if (MFI->hasGridWorkgroupCountY()) {
714     header.code_properties |=
715       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y;
716   }
717 
718   if (MFI->hasGridWorkgroupCountZ()) {
719     header.code_properties |=
720       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z;
721   }
722 
723   if (MFI->hasDispatchPtr())
724     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
725 
726   if (STM.debuggerSupported())
727     header.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED;
728 
729   if (STM.isXNACKEnabled())
730     header.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
731 
732   // FIXME: Should use getKernArgSize
733   header.kernarg_segment_byte_size = MFI->getABIArgOffset();
734   header.wavefront_sgpr_count = KernelInfo.NumSGPR;
735   header.workitem_vgpr_count = KernelInfo.NumVGPR;
736   header.workitem_private_segment_byte_size = KernelInfo.ScratchSize;
737   header.workgroup_group_segment_byte_size = KernelInfo.LDSSize;
738   header.reserved_vgpr_first = KernelInfo.ReservedVGPRFirst;
739   header.reserved_vgpr_count = KernelInfo.ReservedVGPRCount;
740 
741   if (STM.debuggerEmitPrologue()) {
742     header.debug_wavefront_private_segment_offset_sgpr =
743       KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR;
744     header.debug_private_segment_buffer_sgpr =
745       KernelInfo.DebuggerPrivateSegmentBufferSGPR;
746   }
747 
748   AMDGPUTargetStreamer *TS =
749       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
750 
751   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
752   TS->EmitAMDKernelCodeT(header);
753 }
754 
755 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
756                                        unsigned AsmVariant,
757                                        const char *ExtraCode, raw_ostream &O) {
758   if (ExtraCode && ExtraCode[0]) {
759     if (ExtraCode[1] != 0)
760       return true; // Unknown modifier.
761 
762     switch (ExtraCode[0]) {
763     default:
764       // See if this is a generic print operand
765       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
766     case 'r':
767       break;
768     }
769   }
770 
771   AMDGPUInstPrinter::printRegOperand(MI->getOperand(OpNo).getReg(), O,
772                    *TM.getSubtargetImpl(*MF->getFunction())->getRegisterInfo());
773   return false;
774 }
775 
776 // Emit a key and an integer value for runtime metadata.
777 static void emitRuntimeMDIntValue(MCStreamer &Streamer,
778                                   RuntimeMD::Key K, uint64_t V,
779                                   unsigned Size) {
780   Streamer.EmitIntValue(K, 1);
781   Streamer.EmitIntValue(V, Size);
782 }
783 
784 // Emit a key and a string value for runtime metadata.
785 static void emitRuntimeMDStringValue(MCStreamer &Streamer,
786                                      RuntimeMD::Key K, StringRef S) {
787   Streamer.EmitIntValue(K, 1);
788   Streamer.EmitIntValue(S.size(), 4);
789   Streamer.EmitBytes(S);
790 }
791 
792 // Emit a key and three integer values for runtime metadata.
793 // The three integer values are obtained from MDNode \p Node;
794 static void emitRuntimeMDThreeIntValues(MCStreamer &Streamer,
795                                         RuntimeMD::Key K, MDNode *Node,
796                                         unsigned Size) {
797   assert(Node->getNumOperands() == 3);
798 
799   Streamer.EmitIntValue(K, 1);
800   for (const MDOperand &Op : Node->operands()) {
801     const ConstantInt *CI = mdconst::extract<ConstantInt>(Op);
802     Streamer.EmitIntValue(CI->getZExtValue(), Size);
803   }
804 }
805 
806 void AMDGPUAsmPrinter::emitStartOfRuntimeMetadata(const Module &M) {
807   OutStreamer->SwitchSection(getObjFileLowering().getContext()
808     .getELFSection(RuntimeMD::SectionName, ELF::SHT_PROGBITS, 0));
809 
810   emitRuntimeMDIntValue(*OutStreamer, RuntimeMD::KeyMDVersion,
811                         RuntimeMD::MDVersion << 8 | RuntimeMD::MDRevision, 2);
812   if (auto MD = M.getNamedMetadata("opencl.ocl.version")) {
813     if (MD->getNumOperands() != 0) {
814       auto Node = MD->getOperand(0);
815       if (Node->getNumOperands() > 1) {
816         emitRuntimeMDIntValue(*OutStreamer, RuntimeMD::KeyLanguage,
817                               RuntimeMD::OpenCL_C, 1);
818         uint16_t Major = mdconst::extract<ConstantInt>(Node->getOperand(0))
819                          ->getZExtValue();
820         uint16_t Minor = mdconst::extract<ConstantInt>(Node->getOperand(1))
821                          ->getZExtValue();
822         emitRuntimeMDIntValue(*OutStreamer, RuntimeMD::KeyLanguageVersion,
823                               Major * 100 + Minor * 10, 2);
824       }
825     }
826   }
827 
828   if (auto MD = M.getNamedMetadata("llvm.printf.fmts")) {
829     for (unsigned I = 0; I < MD->getNumOperands(); ++I) {
830       auto Node = MD->getOperand(I);
831       if (Node->getNumOperands() > 0)
832         emitRuntimeMDStringValue(*OutStreamer, RuntimeMD::KeyPrintfInfo,
833             cast<MDString>(Node->getOperand(0))->getString());
834     }
835   }
836 }
837 
838 static std::string getOCLTypeName(Type *Ty, bool Signed) {
839   switch (Ty->getTypeID()) {
840   case Type::HalfTyID:
841     return "half";
842   case Type::FloatTyID:
843     return "float";
844   case Type::DoubleTyID:
845     return "double";
846   case Type::IntegerTyID: {
847     if (!Signed)
848       return (Twine('u') + getOCLTypeName(Ty, true)).str();
849     unsigned BW = Ty->getIntegerBitWidth();
850     switch (BW) {
851     case 8:
852       return "char";
853     case 16:
854       return "short";
855     case 32:
856       return "int";
857     case 64:
858       return "long";
859     default:
860       return (Twine('i') + Twine(BW)).str();
861     }
862   }
863   case Type::VectorTyID: {
864     VectorType *VecTy = cast<VectorType>(Ty);
865     Type *EleTy = VecTy->getElementType();
866     unsigned Size = VecTy->getVectorNumElements();
867     return (Twine(getOCLTypeName(EleTy, Signed)) + Twine(Size)).str();
868   }
869   default:
870     return "unknown";
871   }
872 }
873 
874 static RuntimeMD::KernelArg::ValueType getRuntimeMDValueType(
875   Type *Ty, StringRef TypeName) {
876   switch (Ty->getTypeID()) {
877   case Type::HalfTyID:
878     return RuntimeMD::KernelArg::F16;
879   case Type::FloatTyID:
880     return RuntimeMD::KernelArg::F32;
881   case Type::DoubleTyID:
882     return RuntimeMD::KernelArg::F64;
883   case Type::IntegerTyID: {
884     bool Signed = !TypeName.startswith("u");
885     switch (Ty->getIntegerBitWidth()) {
886     case 8:
887       return Signed ? RuntimeMD::KernelArg::I8 : RuntimeMD::KernelArg::U8;
888     case 16:
889       return Signed ? RuntimeMD::KernelArg::I16 : RuntimeMD::KernelArg::U16;
890     case 32:
891       return Signed ? RuntimeMD::KernelArg::I32 : RuntimeMD::KernelArg::U32;
892     case 64:
893       return Signed ? RuntimeMD::KernelArg::I64 : RuntimeMD::KernelArg::U64;
894     default:
895       // Runtime does not recognize other integer types. Report as struct type.
896       return RuntimeMD::KernelArg::Struct;
897     }
898   }
899   case Type::VectorTyID:
900     return getRuntimeMDValueType(Ty->getVectorElementType(), TypeName);
901   case Type::PointerTyID:
902     return getRuntimeMDValueType(Ty->getPointerElementType(), TypeName);
903   default:
904     return RuntimeMD::KernelArg::Struct;
905   }
906 }
907 
908 static RuntimeMD::KernelArg::AddressSpaceQualifer getRuntimeAddrSpace(
909     AMDGPUAS::AddressSpaces A) {
910   switch (A) {
911   case AMDGPUAS::GLOBAL_ADDRESS:
912     return RuntimeMD::KernelArg::Global;
913   case AMDGPUAS::CONSTANT_ADDRESS:
914     return RuntimeMD::KernelArg::Constant;
915   case AMDGPUAS::LOCAL_ADDRESS:
916     return RuntimeMD::KernelArg::Local;
917   case AMDGPUAS::FLAT_ADDRESS:
918     return RuntimeMD::KernelArg::Generic;
919   case AMDGPUAS::REGION_ADDRESS:
920     return RuntimeMD::KernelArg::Region;
921   default:
922     return RuntimeMD::KernelArg::Private;
923   }
924 }
925 
926 static void emitRuntimeMetadataForKernelArg(const DataLayout &DL,
927     MCStreamer &OutStreamer, Type *T,
928     RuntimeMD::KernelArg::Kind Kind,
929     StringRef BaseTypeName = "", StringRef TypeName = "",
930     StringRef ArgName = "", StringRef TypeQual = "", StringRef AccQual = "") {
931   // Emit KeyArgBegin.
932   OutStreamer.EmitIntValue(RuntimeMD::KeyArgBegin, 1);
933 
934   // Emit KeyArgSize and KeyArgAlign.
935   emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgSize,
936                         DL.getTypeAllocSize(T), 4);
937   emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgAlign,
938                         DL.getABITypeAlignment(T), 4);
939   if (auto PT = dyn_cast<PointerType>(T)) {
940     auto ET = PT->getElementType();
941     if (PT->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && ET->isSized())
942       emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgPointeeAlign,
943                         DL.getABITypeAlignment(ET), 4);
944   }
945 
946   // Emit KeyArgTypeName.
947   if (!TypeName.empty())
948     emitRuntimeMDStringValue(OutStreamer, RuntimeMD::KeyArgTypeName, TypeName);
949 
950   // Emit KeyArgName.
951   if (!ArgName.empty())
952     emitRuntimeMDStringValue(OutStreamer, RuntimeMD::KeyArgName, ArgName);
953 
954   // Emit KeyArgIsVolatile, KeyArgIsRestrict, KeyArgIsConst and KeyArgIsPipe.
955   SmallVector<StringRef, 1> SplitQ;
956   TypeQual.split(SplitQ, " ", -1, false /* Drop empty entry */);
957 
958   for (StringRef KeyName : SplitQ) {
959     auto Key = StringSwitch<RuntimeMD::Key>(KeyName)
960       .Case("volatile", RuntimeMD::KeyArgIsVolatile)
961       .Case("restrict", RuntimeMD::KeyArgIsRestrict)
962       .Case("const",    RuntimeMD::KeyArgIsConst)
963       .Case("pipe",     RuntimeMD::KeyArgIsPipe)
964       .Default(RuntimeMD::KeyNull);
965     OutStreamer.EmitIntValue(Key, 1);
966   }
967 
968   // Emit KeyArgKind.
969   emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgKind, Kind, 1);
970 
971   // Emit KeyArgValueType.
972   emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgValueType,
973                         getRuntimeMDValueType(T, BaseTypeName), 2);
974 
975   // Emit KeyArgAccQual.
976   if (!AccQual.empty()) {
977     auto AQ = StringSwitch<RuntimeMD::KernelArg::AccessQualifer>(AccQual)
978       .Case("read_only",  RuntimeMD::KernelArg::ReadOnly)
979       .Case("write_only", RuntimeMD::KernelArg::WriteOnly)
980       .Case("read_write", RuntimeMD::KernelArg::ReadWrite)
981       .Default(RuntimeMD::KernelArg::None);
982     emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgAccQual, AQ, 1);
983   }
984 
985   // Emit KeyArgAddrQual.
986   if (auto *PT = dyn_cast<PointerType>(T))
987     emitRuntimeMDIntValue(OutStreamer, RuntimeMD::KeyArgAddrQual,
988         getRuntimeAddrSpace(static_cast<AMDGPUAS::AddressSpaces>(
989             PT->getAddressSpace())), 1);
990 
991   // Emit KeyArgEnd
992   OutStreamer.EmitIntValue(RuntimeMD::KeyArgEnd, 1);
993 }
994 
995 void AMDGPUAsmPrinter::emitRuntimeMetadata(const Function &F) {
996   if (!F.getMetadata("kernel_arg_type"))
997     return;
998 
999   MCContext &Context = getObjFileLowering().getContext();
1000   OutStreamer->SwitchSection(
1001       Context.getELFSection(RuntimeMD::SectionName, ELF::SHT_PROGBITS, 0));
1002   OutStreamer->EmitIntValue(RuntimeMD::KeyKernelBegin, 1);
1003   emitRuntimeMDStringValue(*OutStreamer, RuntimeMD::KeyKernelName, F.getName());
1004 
1005   const DataLayout &DL = F.getParent()->getDataLayout();
1006   for (auto &Arg : F.args()) {
1007     unsigned I = Arg.getArgNo();
1008     Type *T = Arg.getType();
1009     auto TypeName = dyn_cast<MDString>(F.getMetadata(
1010         "kernel_arg_type")->getOperand(I))->getString();
1011     auto BaseTypeName = cast<MDString>(F.getMetadata(
1012         "kernel_arg_base_type")->getOperand(I))->getString();
1013     StringRef ArgName;
1014     if (auto ArgNameMD = F.getMetadata("kernel_arg_name"))
1015       ArgName = cast<MDString>(ArgNameMD->getOperand(I))->getString();
1016     auto TypeQual = cast<MDString>(F.getMetadata(
1017         "kernel_arg_type_qual")->getOperand(I))->getString();
1018     auto AccQual = cast<MDString>(F.getMetadata(
1019         "kernel_arg_access_qual")->getOperand(I))->getString();
1020     RuntimeMD::KernelArg::Kind Kind;
1021     if (TypeQual.find("pipe") != StringRef::npos)
1022       Kind = RuntimeMD::KernelArg::Pipe;
1023     else Kind = StringSwitch<RuntimeMD::KernelArg::Kind>(BaseTypeName)
1024       .Case("sampler_t", RuntimeMD::KernelArg::Sampler)
1025       .Case("queue_t",   RuntimeMD::KernelArg::Queue)
1026       .Cases("image1d_t", "image1d_array_t", "image1d_buffer_t",
1027              "image2d_t" , "image2d_array_t",  RuntimeMD::KernelArg::Image)
1028       .Cases("image2d_depth_t", "image2d_array_depth_t",
1029              "image2d_msaa_t", "image2d_array_msaa_t",
1030              "image2d_msaa_depth_t",  RuntimeMD::KernelArg::Image)
1031       .Cases("image2d_array_msaa_depth_t", "image3d_t",
1032              RuntimeMD::KernelArg::Image)
1033       .Default(isa<PointerType>(T) ?
1034                    (T->getPointerAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ?
1035                    RuntimeMD::KernelArg::DynamicSharedPointer :
1036                    RuntimeMD::KernelArg::GlobalBuffer) :
1037                    RuntimeMD::KernelArg::ByValue);
1038     emitRuntimeMetadataForKernelArg(DL, *OutStreamer, T,
1039         Kind, BaseTypeName, TypeName, ArgName, TypeQual, AccQual);
1040   }
1041 
1042   // Emit hidden kernel arguments for OpenCL kernels.
1043   if (F.getParent()->getNamedMetadata("opencl.ocl.version")) {
1044     auto Int64T = Type::getInt64Ty(F.getContext());
1045     emitRuntimeMetadataForKernelArg(DL, *OutStreamer, Int64T,
1046                                     RuntimeMD::KernelArg::HiddenGlobalOffsetX);
1047     emitRuntimeMetadataForKernelArg(DL, *OutStreamer, Int64T,
1048                                     RuntimeMD::KernelArg::HiddenGlobalOffsetY);
1049     emitRuntimeMetadataForKernelArg(DL, *OutStreamer, Int64T,
1050                                     RuntimeMD::KernelArg::HiddenGlobalOffsetZ);
1051     if (F.getParent()->getNamedMetadata("llvm.printf.fmts")) {
1052       auto Int8PtrT = Type::getInt8PtrTy(F.getContext(),
1053           RuntimeMD::KernelArg::Global);
1054       emitRuntimeMetadataForKernelArg(DL, *OutStreamer, Int8PtrT,
1055                                       RuntimeMD::KernelArg::HiddenPrintfBuffer);
1056     }
1057   }
1058 
1059   // Emit KeyReqdWorkGroupSize, KeyWorkGroupSizeHint, and KeyVecTypeHint.
1060   if (auto RWGS = F.getMetadata("reqd_work_group_size")) {
1061     emitRuntimeMDThreeIntValues(*OutStreamer, RuntimeMD::KeyReqdWorkGroupSize,
1062                                 RWGS, 4);
1063   }
1064 
1065   if (auto WGSH = F.getMetadata("work_group_size_hint")) {
1066     emitRuntimeMDThreeIntValues(*OutStreamer, RuntimeMD::KeyWorkGroupSizeHint,
1067                                 WGSH, 4);
1068   }
1069 
1070   if (auto VTH = F.getMetadata("vec_type_hint")) {
1071     auto TypeName = getOCLTypeName(cast<ValueAsMetadata>(
1072       VTH->getOperand(0))->getType(), mdconst::extract<ConstantInt>(
1073       VTH->getOperand(1))->getZExtValue());
1074     emitRuntimeMDStringValue(*OutStreamer, RuntimeMD::KeyVecTypeHint, TypeName);
1075   }
1076 
1077   // Emit KeyKernelEnd
1078   OutStreamer->EmitIntValue(RuntimeMD::KeyKernelEnd, 1);
1079 }
1080