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 
43 using namespace llvm;
44 
45 // TODO: This should get the default rounding mode from the kernel. We just set
46 // the default here, but this could change if the OpenCL rounding mode pragmas
47 // are used.
48 //
49 // The denormal mode here should match what is reported by the OpenCL runtime
50 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
51 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
52 //
53 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
54 // precision, and leaves single precision to flush all and does not report
55 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
56 // CL_FP_DENORM for both.
57 //
58 // FIXME: It seems some instructions do not support single precision denormals
59 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
60 // and sin_f32, cos_f32 on most parts).
61 
62 // We want to use these instructions, and using fp32 denormals also causes
63 // instructions to run at the double precision rate for the device so it's
64 // probably best to just report no single precision denormals.
65 static uint32_t getFPMode(const MachineFunction &F) {
66   const SISubtarget& ST = F.getSubtarget<SISubtarget>();
67   // TODO: Is there any real use for the flush in only / flush out only modes?
68 
69   uint32_t FP32Denormals =
70     ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
71 
72   uint32_t FP64Denormals =
73     ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
74 
75   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
76          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
77          FP_DENORM_MODE_SP(FP32Denormals) |
78          FP_DENORM_MODE_DP(FP64Denormals);
79 }
80 
81 static AsmPrinter *
82 createAMDGPUAsmPrinterPass(TargetMachine &tm,
83                            std::unique_ptr<MCStreamer> &&Streamer) {
84   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
85 }
86 
87 extern "C" void LLVMInitializeAMDGPUAsmPrinter() {
88   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
89                                      createAMDGPUAsmPrinterPass);
90   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
91                                      createAMDGPUAsmPrinterPass);
92 }
93 
94 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
95                                    std::unique_ptr<MCStreamer> Streamer)
96   : AsmPrinter(TM, std::move(Streamer)) {}
97 
98 StringRef 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   AMDGPUTargetStreamer *TS =
107       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
108 
109   TS->EmitDirectiveHSACodeObjectVersion(2, 1);
110 
111   const MCSubtargetInfo *STI = TM.getMCSubtargetInfo();
112   AMDGPU::IsaInfo::IsaVersion ISA =
113       AMDGPU::IsaInfo::getIsaVersion(STI->getFeatureBits());
114   TS->EmitDirectiveHSACodeObjectISA(ISA.Major, ISA.Minor, ISA.Stepping,
115                                     "AMD", "AMDGPU");
116 
117   // Emit runtime metadata.
118   TS->EmitRuntimeMetadata(STI->getFeatureBits(), M);
119 }
120 
121 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
122   const MachineBasicBlock *MBB) const {
123   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
124     return false;
125 
126   if (MBB->empty())
127     return true;
128 
129   // If this is a block implementing a long branch, an expression relative to
130   // the start of the block is needed.  to the start of the block.
131   // XXX - Is there a smarter way to check this?
132   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
133 }
134 
135 
136 void AMDGPUAsmPrinter::EmitFunctionBodyStart() {
137   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
138   SIProgramInfo KernelInfo;
139   if (STM.isAmdCodeObjectV2(*MF)) {
140     getSIProgramInfo(KernelInfo, *MF);
141     EmitAmdKernelCodeT(*MF, KernelInfo);
142   }
143 }
144 
145 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() {
146   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
147   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
148   if (MFI->isKernel() && STM.isAmdCodeObjectV2(*MF)) {
149     AMDGPUTargetStreamer *TS =
150         static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
151     SmallString<128> SymbolName;
152     getNameWithPrefix(SymbolName, MF->getFunction()),
153     TS->EmitAMDGPUSymbolType(SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
154   }
155 
156   AsmPrinter::EmitFunctionEntryLabel();
157 }
158 
159 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
160 
161   // Group segment variables aren't emitted in HSA.
162   if (AMDGPU::isGroupSegment(GV))
163     return;
164 
165   AsmPrinter::EmitGlobalVariable(GV);
166 }
167 
168 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
169 
170   // The starting address of all shader programs must be 256 bytes aligned.
171   MF.setAlignment(8);
172 
173   SetupMachineFunction(MF);
174 
175   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
176   MCContext &Context = getObjFileLowering().getContext();
177   if (!STM.isAmdHsaOS()) {
178     MCSectionELF *ConfigSection =
179         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
180     OutStreamer->SwitchSection(ConfigSection);
181   }
182 
183   SIProgramInfo KernelInfo;
184   if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
185     getSIProgramInfo(KernelInfo, MF);
186     if (!STM.isAmdHsaOS()) {
187       EmitProgramInfoSI(MF, KernelInfo);
188     }
189   } else {
190     EmitProgramInfoR600(MF);
191   }
192 
193   DisasmLines.clear();
194   HexLines.clear();
195   DisasmLineMaxLen = 0;
196 
197   EmitFunctionBody();
198 
199   if (isVerbose()) {
200     MCSectionELF *CommentSection =
201         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
202     OutStreamer->SwitchSection(CommentSection);
203 
204     if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
205       OutStreamer->emitRawComment(" Kernel info:", false);
206       OutStreamer->emitRawComment(" codeLenInByte = " + Twine(KernelInfo.CodeLen),
207                                   false);
208       OutStreamer->emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR),
209                                   false);
210       OutStreamer->emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR),
211                                   false);
212       OutStreamer->emitRawComment(" FloatMode: " + Twine(KernelInfo.FloatMode),
213                                   false);
214       OutStreamer->emitRawComment(" IeeeMode: " + Twine(KernelInfo.IEEEMode),
215                                   false);
216       OutStreamer->emitRawComment(" ScratchSize: " + Twine(KernelInfo.ScratchSize),
217                                   false);
218       OutStreamer->emitRawComment(" LDSByteSize: " + Twine(KernelInfo.LDSSize) +
219                                   " bytes/workgroup (compile time only)", false);
220 
221       OutStreamer->emitRawComment(" SGPRBlocks: " +
222                                   Twine(KernelInfo.SGPRBlocks), false);
223       OutStreamer->emitRawComment(" VGPRBlocks: " +
224                                   Twine(KernelInfo.VGPRBlocks), false);
225 
226       OutStreamer->emitRawComment(" NumSGPRsForWavesPerEU: " +
227                                   Twine(KernelInfo.NumSGPRsForWavesPerEU), false);
228       OutStreamer->emitRawComment(" NumVGPRsForWavesPerEU: " +
229                                   Twine(KernelInfo.NumVGPRsForWavesPerEU), false);
230 
231       OutStreamer->emitRawComment(" ReservedVGPRFirst: " + Twine(KernelInfo.ReservedVGPRFirst),
232                                   false);
233       OutStreamer->emitRawComment(" ReservedVGPRCount: " + Twine(KernelInfo.ReservedVGPRCount),
234                                   false);
235 
236       if (MF.getSubtarget<SISubtarget>().debuggerEmitPrologue()) {
237         OutStreamer->emitRawComment(" DebuggerWavefrontPrivateSegmentOffsetSGPR: s" +
238                                     Twine(KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false);
239         OutStreamer->emitRawComment(" DebuggerPrivateSegmentBufferSGPR: s" +
240                                     Twine(KernelInfo.DebuggerPrivateSegmentBufferSGPR), false);
241       }
242 
243       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:USER_SGPR: " +
244                                   Twine(G_00B84C_USER_SGPR(KernelInfo.ComputePGMRSrc2)),
245                                   false);
246       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_X_EN: " +
247                                   Twine(G_00B84C_TGID_X_EN(KernelInfo.ComputePGMRSrc2)),
248                                   false);
249       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
250                                   Twine(G_00B84C_TGID_Y_EN(KernelInfo.ComputePGMRSrc2)),
251                                   false);
252       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
253                                   Twine(G_00B84C_TGID_Z_EN(KernelInfo.ComputePGMRSrc2)),
254                                   false);
255       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
256                                   Twine(G_00B84C_TIDIG_COMP_CNT(KernelInfo.ComputePGMRSrc2)),
257                                   false);
258 
259     } else {
260       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
261       OutStreamer->emitRawComment(
262         Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->CFStackSize)));
263     }
264   }
265 
266   if (STM.dumpCode()) {
267 
268     OutStreamer->SwitchSection(
269         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
270 
271     for (size_t i = 0; i < DisasmLines.size(); ++i) {
272       std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
273       Comment += " ; " + HexLines[i] + "\n";
274 
275       OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
276       OutStreamer->EmitBytes(StringRef(Comment));
277     }
278   }
279 
280   return false;
281 }
282 
283 void AMDGPUAsmPrinter::EmitProgramInfoR600(const MachineFunction &MF) {
284   unsigned MaxGPR = 0;
285   bool killPixel = false;
286   const R600Subtarget &STM = MF.getSubtarget<R600Subtarget>();
287   const R600RegisterInfo *RI = STM.getRegisterInfo();
288   const R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
289 
290   for (const MachineBasicBlock &MBB : MF) {
291     for (const MachineInstr &MI : MBB) {
292       if (MI.getOpcode() == AMDGPU::KILLGT)
293         killPixel = true;
294       unsigned numOperands = MI.getNumOperands();
295       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
296         const MachineOperand &MO = MI.getOperand(op_idx);
297         if (!MO.isReg())
298           continue;
299         unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;
300 
301         // Register with value > 127 aren't GPR
302         if (HWReg > 127)
303           continue;
304         MaxGPR = std::max(MaxGPR, HWReg);
305       }
306     }
307   }
308 
309   unsigned RsrcReg;
310   if (STM.getGeneration() >= R600Subtarget::EVERGREEN) {
311     // Evergreen / Northern Islands
312     switch (MF.getFunction()->getCallingConv()) {
313     default: LLVM_FALLTHROUGH;
314     case CallingConv::AMDGPU_CS: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
315     case CallingConv::AMDGPU_GS: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
316     case CallingConv::AMDGPU_PS: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
317     case CallingConv::AMDGPU_VS: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
318     }
319   } else {
320     // R600 / R700
321     switch (MF.getFunction()->getCallingConv()) {
322     default: LLVM_FALLTHROUGH;
323     case CallingConv::AMDGPU_GS: LLVM_FALLTHROUGH;
324     case CallingConv::AMDGPU_CS: LLVM_FALLTHROUGH;
325     case CallingConv::AMDGPU_VS: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
326     case CallingConv::AMDGPU_PS: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
327     }
328   }
329 
330   OutStreamer->EmitIntValue(RsrcReg, 4);
331   OutStreamer->EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
332                            S_STACK_SIZE(MFI->CFStackSize), 4);
333   OutStreamer->EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
334   OutStreamer->EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);
335 
336   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
337     OutStreamer->EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
338     OutStreamer->EmitIntValue(alignTo(MFI->getLDSSize(), 4) >> 2, 4);
339   }
340 }
341 
342 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
343                                         const MachineFunction &MF) const {
344   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
345   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
346   uint64_t CodeSize = 0;
347   unsigned MaxSGPR = 0;
348   unsigned MaxVGPR = 0;
349   bool VCCUsed = false;
350   bool FlatUsed = false;
351   const SIRegisterInfo *RI = STM.getRegisterInfo();
352   const SIInstrInfo *TII = STM.getInstrInfo();
353 
354   for (const MachineBasicBlock &MBB : MF) {
355     for (const MachineInstr &MI : MBB) {
356       // TODO: CodeSize should account for multiple functions.
357 
358       // TODO: Should we count size of debug info?
359       if (MI.isDebugValue())
360         continue;
361 
362       if (isVerbose())
363         CodeSize += TII->getInstSizeInBytes(MI);
364 
365       unsigned numOperands = MI.getNumOperands();
366       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
367         const MachineOperand &MO = MI.getOperand(op_idx);
368         unsigned width = 0;
369         bool isSGPR = false;
370 
371         if (!MO.isReg())
372           continue;
373 
374         unsigned reg = MO.getReg();
375         switch (reg) {
376         case AMDGPU::EXEC:
377         case AMDGPU::EXEC_LO:
378         case AMDGPU::EXEC_HI:
379         case AMDGPU::SCC:
380         case AMDGPU::M0:
381           continue;
382 
383         case AMDGPU::VCC:
384         case AMDGPU::VCC_LO:
385         case AMDGPU::VCC_HI:
386           VCCUsed = true;
387           continue;
388 
389         case AMDGPU::FLAT_SCR:
390         case AMDGPU::FLAT_SCR_LO:
391         case AMDGPU::FLAT_SCR_HI:
392           // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
393           // instructions aren't used to access the scratch buffer.
394           if (MFI->hasFlatScratchInit())
395             FlatUsed = true;
396           continue;
397 
398         case AMDGPU::TBA:
399         case AMDGPU::TBA_LO:
400         case AMDGPU::TBA_HI:
401         case AMDGPU::TMA:
402         case AMDGPU::TMA_LO:
403         case AMDGPU::TMA_HI:
404           llvm_unreachable("trap handler registers should not be used");
405 
406         default:
407           break;
408         }
409 
410         if (AMDGPU::SReg_32RegClass.contains(reg)) {
411           assert(!AMDGPU::TTMP_32RegClass.contains(reg) &&
412                  "trap handler registers should not be used");
413           isSGPR = true;
414           width = 1;
415         } else if (AMDGPU::VGPR_32RegClass.contains(reg)) {
416           isSGPR = false;
417           width = 1;
418         } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
419           assert(!AMDGPU::TTMP_64RegClass.contains(reg) &&
420                  "trap handler registers should not be used");
421           isSGPR = true;
422           width = 2;
423         } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
424           isSGPR = false;
425           width = 2;
426         } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
427           isSGPR = false;
428           width = 3;
429         } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
430           isSGPR = true;
431           width = 4;
432         } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
433           isSGPR = false;
434           width = 4;
435         } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
436           isSGPR = true;
437           width = 8;
438         } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
439           isSGPR = false;
440           width = 8;
441         } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
442           isSGPR = true;
443           width = 16;
444         } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
445           isSGPR = false;
446           width = 16;
447         } else {
448           llvm_unreachable("Unknown register class");
449         }
450         unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
451         unsigned maxUsed = hwReg + width - 1;
452         if (isSGPR) {
453           MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
454         } else {
455           MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
456         }
457       }
458     }
459   }
460 
461   unsigned ExtraSGPRs = 0;
462 
463   if (VCCUsed)
464     ExtraSGPRs = 2;
465 
466   if (STM.getGeneration() < SISubtarget::VOLCANIC_ISLANDS) {
467     if (FlatUsed)
468       ExtraSGPRs = 4;
469   } else {
470     if (STM.isXNACKEnabled())
471       ExtraSGPRs = 4;
472 
473     if (FlatUsed)
474       ExtraSGPRs = 6;
475   }
476 
477   unsigned ExtraVGPRs = STM.getReservedNumVGPRs(MF);
478 
479   // Check the addressable register limit before we add ExtraSGPRs.
480   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
481       !STM.hasSGPRInitBug()) {
482     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
483     if (MaxSGPR + 1 > MaxAddressableNumSGPRs) {
484       // This can happen due to a compiler bug or when using inline asm.
485       LLVMContext &Ctx = MF.getFunction()->getContext();
486       DiagnosticInfoResourceLimit Diag(*MF.getFunction(),
487                                        "addressable scalar registers",
488                                        MaxSGPR + 1, DS_Error,
489                                        DK_ResourceLimit,
490                                        MaxAddressableNumSGPRs);
491       Ctx.diagnose(Diag);
492       MaxSGPR = MaxAddressableNumSGPRs - 1;
493     }
494   }
495 
496   // Account for extra SGPRs and VGPRs reserved for debugger use.
497   MaxSGPR += ExtraSGPRs;
498   MaxVGPR += ExtraVGPRs;
499 
500   // We found the maximum register index. They start at 0, so add one to get the
501   // number of registers.
502   ProgInfo.NumSGPR = MaxSGPR + 1;
503   ProgInfo.NumVGPR = MaxVGPR + 1;
504 
505   // Adjust number of registers used to meet default/requested minimum/maximum
506   // number of waves per execution unit request.
507   ProgInfo.NumSGPRsForWavesPerEU = std::max(
508     ProgInfo.NumSGPR, STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
509   ProgInfo.NumVGPRsForWavesPerEU = std::max(
510     ProgInfo.NumVGPR, STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
511 
512   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
513       STM.hasSGPRInitBug()) {
514     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
515     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
516       // This can happen due to a compiler bug or when using inline asm to use
517       // the registers which are usually reserved for vcc etc.
518       LLVMContext &Ctx = MF.getFunction()->getContext();
519       DiagnosticInfoResourceLimit Diag(*MF.getFunction(),
520                                        "scalar registers",
521                                        ProgInfo.NumSGPR, DS_Error,
522                                        DK_ResourceLimit,
523                                        MaxAddressableNumSGPRs);
524       Ctx.diagnose(Diag);
525       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
526       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
527     }
528   }
529 
530   if (STM.hasSGPRInitBug()) {
531     ProgInfo.NumSGPR =
532         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
533     ProgInfo.NumSGPRsForWavesPerEU =
534         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
535   }
536 
537   if (MFI->NumUserSGPRs > STM.getMaxNumUserSGPRs()) {
538     LLVMContext &Ctx = MF.getFunction()->getContext();
539     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "user SGPRs",
540                                      MFI->NumUserSGPRs, DS_Error);
541     Ctx.diagnose(Diag);
542   }
543 
544   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
545     LLVMContext &Ctx = MF.getFunction()->getContext();
546     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "local memory",
547                                      MFI->getLDSSize(), DS_Error);
548     Ctx.diagnose(Diag);
549   }
550 
551   // SGPRBlocks is actual number of SGPR blocks minus 1.
552   ProgInfo.SGPRBlocks = alignTo(ProgInfo.NumSGPRsForWavesPerEU,
553                                 STM.getSGPREncodingGranule());
554   ProgInfo.SGPRBlocks = ProgInfo.SGPRBlocks / STM.getSGPREncodingGranule() - 1;
555 
556   // VGPRBlocks is actual number of VGPR blocks minus 1.
557   ProgInfo.VGPRBlocks = alignTo(ProgInfo.NumVGPRsForWavesPerEU,
558                                 STM.getVGPREncodingGranule());
559   ProgInfo.VGPRBlocks = ProgInfo.VGPRBlocks / STM.getVGPREncodingGranule() - 1;
560 
561   // Record first reserved VGPR and number of reserved VGPRs.
562   ProgInfo.ReservedVGPRFirst = STM.debuggerReserveRegs() ? MaxVGPR + 1 : 0;
563   ProgInfo.ReservedVGPRCount = STM.getReservedNumVGPRs(MF);
564 
565   // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and
566   // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue"
567   // attribute was requested.
568   if (STM.debuggerEmitPrologue()) {
569     ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR =
570       RI->getHWRegIndex(MFI->getScratchWaveOffsetReg());
571     ProgInfo.DebuggerPrivateSegmentBufferSGPR =
572       RI->getHWRegIndex(MFI->getScratchRSrcReg());
573   }
574 
575   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
576   // register.
577   ProgInfo.FloatMode = getFPMode(MF);
578 
579   ProgInfo.IEEEMode = STM.enableIEEEBit(MF);
580 
581   // Make clamp modifier on NaN input returns 0.
582   ProgInfo.DX10Clamp = 1;
583 
584   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
585   ProgInfo.ScratchSize = FrameInfo.getStackSize();
586 
587   ProgInfo.FlatUsed = FlatUsed;
588   ProgInfo.VCCUsed = VCCUsed;
589   ProgInfo.CodeLen = CodeSize;
590 
591   unsigned LDSAlignShift;
592   if (STM.getGeneration() < SISubtarget::SEA_ISLANDS) {
593     // LDS is allocated in 64 dword blocks.
594     LDSAlignShift = 8;
595   } else {
596     // LDS is allocated in 128 dword blocks.
597     LDSAlignShift = 9;
598   }
599 
600   unsigned LDSSpillSize =
601     MFI->LDSWaveSpillSize * MFI->getMaxFlatWorkGroupSize();
602 
603   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
604   ProgInfo.LDSBlocks =
605       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
606 
607   // Scratch is allocated in 256 dword blocks.
608   unsigned ScratchAlignShift = 10;
609   // We need to program the hardware with the amount of scratch memory that
610   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
611   // scratch memory used per thread.
612   ProgInfo.ScratchBlocks =
613       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
614               1ULL << ScratchAlignShift) >>
615       ScratchAlignShift;
616 
617   ProgInfo.ComputePGMRSrc1 =
618       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
619       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
620       S_00B848_PRIORITY(ProgInfo.Priority) |
621       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
622       S_00B848_PRIV(ProgInfo.Priv) |
623       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
624       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
625       S_00B848_IEEE_MODE(ProgInfo.IEEEMode);
626 
627   // 0 = X, 1 = XY, 2 = XYZ
628   unsigned TIDIGCompCnt = 0;
629   if (MFI->hasWorkItemIDZ())
630     TIDIGCompCnt = 2;
631   else if (MFI->hasWorkItemIDY())
632     TIDIGCompCnt = 1;
633 
634   ProgInfo.ComputePGMRSrc2 =
635       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
636       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
637       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
638       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
639       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
640       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
641       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
642       S_00B84C_EXCP_EN_MSB(0) |
643       S_00B84C_LDS_SIZE(ProgInfo.LDSBlocks) |
644       S_00B84C_EXCP_EN(0);
645 }
646 
647 static unsigned getRsrcReg(CallingConv::ID CallConv) {
648   switch (CallConv) {
649   default: LLVM_FALLTHROUGH;
650   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
651   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
652   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
653   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
654   }
655 }
656 
657 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
658                                          const SIProgramInfo &KernelInfo) {
659   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
660   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
661   unsigned RsrcReg = getRsrcReg(MF.getFunction()->getCallingConv());
662 
663   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
664     OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
665 
666     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc1, 4);
667 
668     OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
669     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc2, 4);
670 
671     OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
672     OutStreamer->EmitIntValue(S_00B860_WAVESIZE(KernelInfo.ScratchBlocks), 4);
673 
674     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
675     // 0" comment but I don't see a corresponding field in the register spec.
676   } else {
677     OutStreamer->EmitIntValue(RsrcReg, 4);
678     OutStreamer->EmitIntValue(S_00B028_VGPRS(KernelInfo.VGPRBlocks) |
679                               S_00B028_SGPRS(KernelInfo.SGPRBlocks), 4);
680     if (STM.isVGPRSpillingEnabled(*MF.getFunction())) {
681       OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
682       OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(KernelInfo.ScratchBlocks), 4);
683     }
684   }
685 
686   if (MF.getFunction()->getCallingConv() == CallingConv::AMDGPU_PS) {
687     OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
688     OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(KernelInfo.LDSBlocks), 4);
689     OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
690     OutStreamer->EmitIntValue(MFI->PSInputEna, 4);
691     OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
692     OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
693   }
694 
695   OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4);
696   OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4);
697   OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4);
698   OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4);
699 }
700 
701 // This is supposed to be log2(Size)
702 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
703   switch (Size) {
704   case 4:
705     return AMD_ELEMENT_4_BYTES;
706   case 8:
707     return AMD_ELEMENT_8_BYTES;
708   case 16:
709     return AMD_ELEMENT_16_BYTES;
710   default:
711     llvm_unreachable("invalid private_element_size");
712   }
713 }
714 
715 void AMDGPUAsmPrinter::EmitAmdKernelCodeT(const MachineFunction &MF,
716                                          const SIProgramInfo &KernelInfo) const {
717   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
718   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
719   amd_kernel_code_t header;
720 
721   AMDGPU::initDefaultAMDKernelCodeT(header, STM.getFeatureBits());
722 
723   header.compute_pgm_resource_registers =
724       KernelInfo.ComputePGMRSrc1 |
725       (KernelInfo.ComputePGMRSrc2 << 32);
726   header.code_properties = AMD_CODE_PROPERTY_IS_PTR64;
727 
728 
729   AMD_HSA_BITS_SET(header.code_properties,
730                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
731                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
732 
733   if (MFI->hasPrivateSegmentBuffer()) {
734     header.code_properties |=
735       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
736   }
737 
738   if (MFI->hasDispatchPtr())
739     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
740 
741   if (MFI->hasQueuePtr())
742     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
743 
744   if (MFI->hasKernargSegmentPtr())
745     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
746 
747   if (MFI->hasDispatchID())
748     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
749 
750   if (MFI->hasFlatScratchInit())
751     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
752 
753   // TODO: Private segment size
754 
755   if (MFI->hasGridWorkgroupCountX()) {
756     header.code_properties |=
757       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X;
758   }
759 
760   if (MFI->hasGridWorkgroupCountY()) {
761     header.code_properties |=
762       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y;
763   }
764 
765   if (MFI->hasGridWorkgroupCountZ()) {
766     header.code_properties |=
767       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z;
768   }
769 
770   if (MFI->hasDispatchPtr())
771     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
772 
773   if (STM.debuggerSupported())
774     header.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED;
775 
776   if (STM.isXNACKEnabled())
777     header.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
778 
779   // FIXME: Should use getKernArgSize
780   header.kernarg_segment_byte_size =
781     STM.getKernArgSegmentSize(MF, MFI->getABIArgOffset());
782   header.wavefront_sgpr_count = KernelInfo.NumSGPR;
783   header.workitem_vgpr_count = KernelInfo.NumVGPR;
784   header.workitem_private_segment_byte_size = KernelInfo.ScratchSize;
785   header.workgroup_group_segment_byte_size = KernelInfo.LDSSize;
786   header.reserved_vgpr_first = KernelInfo.ReservedVGPRFirst;
787   header.reserved_vgpr_count = KernelInfo.ReservedVGPRCount;
788 
789   // These alignment values are specified in powers of two, so alignment =
790   // 2^n.  The minimum alignment is 2^4 = 16.
791   header.kernarg_segment_alignment = std::max((size_t)4,
792       countTrailingZeros(MFI->getMaxKernArgAlign()));
793 
794   if (STM.debuggerEmitPrologue()) {
795     header.debug_wavefront_private_segment_offset_sgpr =
796       KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR;
797     header.debug_private_segment_buffer_sgpr =
798       KernelInfo.DebuggerPrivateSegmentBufferSGPR;
799   }
800 
801   AMDGPUTargetStreamer *TS =
802       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
803 
804   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
805   TS->EmitAMDKernelCodeT(header);
806 }
807 
808 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
809                                        unsigned AsmVariant,
810                                        const char *ExtraCode, raw_ostream &O) {
811   if (ExtraCode && ExtraCode[0]) {
812     if (ExtraCode[1] != 0)
813       return true; // Unknown modifier.
814 
815     switch (ExtraCode[0]) {
816     default:
817       // See if this is a generic print operand
818       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
819     case 'r':
820       break;
821     }
822   }
823 
824   AMDGPUInstPrinter::printRegOperand(MI->getOperand(OpNo).getReg(), O,
825                    *TM.getSubtargetImpl(*MF->getFunction())->getRegisterInfo());
826   return false;
827 }
828