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