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 "SIRegisterInfo.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCSectionELF.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/Support/ELF.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 
41 using namespace llvm;
42 
43 // TODO: This should get the default rounding mode from the kernel. We just set
44 // the default here, but this could change if the OpenCL rounding mode pragmas
45 // are used.
46 //
47 // The denormal mode here should match what is reported by the OpenCL runtime
48 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
49 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
50 //
51 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
52 // precision, and leaves single precision to flush all and does not report
53 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
54 // CL_FP_DENORM for both.
55 //
56 // FIXME: It seems some instructions do not support single precision denormals
57 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
58 // and sin_f32, cos_f32 on most parts).
59 
60 // We want to use these instructions, and using fp32 denormals also causes
61 // instructions to run at the double precision rate for the device so it's
62 // probably best to just report no single precision denormals.
63 static uint32_t getFPMode(const MachineFunction &F) {
64   const AMDGPUSubtarget& ST = F.getSubtarget<AMDGPUSubtarget>();
65   // TODO: Is there any real use for the flush in only / flush out only modes?
66 
67   uint32_t FP32Denormals =
68     ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
69 
70   uint32_t FP64Denormals =
71     ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
72 
73   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
74          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
75          FP_DENORM_MODE_SP(FP32Denormals) |
76          FP_DENORM_MODE_DP(FP64Denormals);
77 }
78 
79 static AsmPrinter *
80 createAMDGPUAsmPrinterPass(TargetMachine &tm,
81                            std::unique_ptr<MCStreamer> &&Streamer) {
82   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
83 }
84 
85 extern "C" void LLVMInitializeAMDGPUAsmPrinter() {
86   TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);
87   TargetRegistry::RegisterAsmPrinter(TheGCNTarget, createAMDGPUAsmPrinterPass);
88 }
89 
90 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
91                                    std::unique_ptr<MCStreamer> Streamer)
92     : AsmPrinter(TM, std::move(Streamer)) {}
93 
94 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) {
95   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
96     return;
97 
98   // Need to construct an MCSubtargetInfo here in case we have no functions
99   // in the module.
100   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
101         TM.getTargetTriple().str(), TM.getTargetCPU(),
102         TM.getTargetFeatureString()));
103 
104   AMDGPUTargetStreamer *TS =
105       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
106 
107   TS->EmitDirectiveHSACodeObjectVersion(1, 0);
108   AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(STI->getFeatureBits());
109   TS->EmitDirectiveHSACodeObjectISA(ISA.Major, ISA.Minor, ISA.Stepping,
110                                     "AMD", "AMDGPU");
111 }
112 
113 void AMDGPUAsmPrinter::EmitFunctionBodyStart() {
114   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
115   SIProgramInfo KernelInfo;
116   if (STM.isAmdHsaOS()) {
117     getSIProgramInfo(KernelInfo, *MF);
118     EmitAmdKernelCodeT(*MF, KernelInfo);
119   }
120 }
121 
122 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() {
123   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
124   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
125   if (MFI->isKernel() && STM.isAmdHsaOS()) {
126     AMDGPUTargetStreamer *TS =
127         static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
128     TS->EmitAMDGPUSymbolType(CurrentFnSym->getName(),
129                              ELF::STT_AMDGPU_HSA_KERNEL);
130   }
131 
132   AsmPrinter::EmitFunctionEntryLabel();
133 }
134 
135 static bool isModuleLinkage(const GlobalValue *GV) {
136   switch (GV->getLinkage()) {
137   case GlobalValue::LinkOnceODRLinkage:
138   case GlobalValue::LinkOnceAnyLinkage:
139   case GlobalValue::InternalLinkage:
140   case GlobalValue::CommonLinkage:
141    return true;
142   case GlobalValue::ExternalLinkage:
143    return false;
144   default: llvm_unreachable("unknown linkage type");
145   }
146 }
147 
148 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
149 
150   if (TM.getTargetTriple().getOS() != Triple::AMDHSA) {
151     AsmPrinter::EmitGlobalVariable(GV);
152     return;
153   }
154 
155   if (GV->isDeclaration() || GV->getLinkage() == GlobalValue::PrivateLinkage) {
156     AsmPrinter::EmitGlobalVariable(GV);
157     return;
158   }
159 
160   // Group segment variables aren't emitted in HSA.
161   if (AMDGPU::isGroupSegment(GV))
162     return;
163 
164   AMDGPUTargetStreamer *TS =
165       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
166   if (isModuleLinkage(GV)) {
167     TS->EmitAMDGPUHsaModuleScopeGlobal(GV->getName());
168   } else {
169     TS->EmitAMDGPUHsaProgramScopeGlobal(GV->getName());
170   }
171 
172   MCSymbolELF *GVSym = cast<MCSymbolELF>(getSymbol(GV));
173   const DataLayout &DL = getDataLayout();
174 
175   // Emit the size
176   uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
177   OutStreamer->emitELFSize(GVSym, MCConstantExpr::create(Size, OutContext));
178   OutStreamer->PushSection();
179   OutStreamer->SwitchSection(
180       getObjFileLowering().SectionForGlobal(GV, *Mang, TM));
181   const Constant *C = GV->getInitializer();
182   OutStreamer->EmitLabel(GVSym);
183   EmitGlobalConstant(DL, C);
184   OutStreamer->PopSection();
185 }
186 
187 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
188 
189   // The starting address of all shader programs must be 256 bytes aligned.
190   MF.setAlignment(8);
191 
192   SetupMachineFunction(MF);
193 
194   MCContext &Context = getObjFileLowering().getContext();
195   MCSectionELF *ConfigSection =
196       Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
197   OutStreamer->SwitchSection(ConfigSection);
198 
199   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
200   SIProgramInfo KernelInfo;
201   if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
202     getSIProgramInfo(KernelInfo, MF);
203     if (!STM.isAmdHsaOS()) {
204       EmitProgramInfoSI(MF, KernelInfo);
205     }
206   } else {
207     EmitProgramInfoR600(MF);
208   }
209 
210   DisasmLines.clear();
211   HexLines.clear();
212   DisasmLineMaxLen = 0;
213 
214   EmitFunctionBody();
215 
216   if (isVerbose()) {
217     MCSectionELF *CommentSection =
218         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
219     OutStreamer->SwitchSection(CommentSection);
220 
221     if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
222       OutStreamer->emitRawComment(" Kernel info:", false);
223       OutStreamer->emitRawComment(" codeLenInByte = " + Twine(KernelInfo.CodeLen),
224                                   false);
225       OutStreamer->emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR),
226                                   false);
227       OutStreamer->emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR),
228                                   false);
229       OutStreamer->emitRawComment(" FloatMode: " + Twine(KernelInfo.FloatMode),
230                                   false);
231       OutStreamer->emitRawComment(" IeeeMode: " + Twine(KernelInfo.IEEEMode),
232                                   false);
233       OutStreamer->emitRawComment(" ScratchSize: " + Twine(KernelInfo.ScratchSize),
234                                   false);
235       OutStreamer->emitRawComment(" LDSByteSize: " + Twine(KernelInfo.LDSSize) +
236                                   " bytes/workgroup (compile time only)", false);
237 
238       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:USER_SGPR: " +
239                                   Twine(G_00B84C_USER_SGPR(KernelInfo.ComputePGMRSrc2)),
240                                   false);
241       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_X_EN: " +
242                                   Twine(G_00B84C_TGID_X_EN(KernelInfo.ComputePGMRSrc2)),
243                                   false);
244       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
245                                   Twine(G_00B84C_TGID_Y_EN(KernelInfo.ComputePGMRSrc2)),
246                                   false);
247       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
248                                   Twine(G_00B84C_TGID_Z_EN(KernelInfo.ComputePGMRSrc2)),
249                                   false);
250       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
251                                   Twine(G_00B84C_TIDIG_COMP_CNT(KernelInfo.ComputePGMRSrc2)),
252                                   false);
253 
254     } else {
255       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
256       OutStreamer->emitRawComment(
257         Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->StackSize)));
258     }
259   }
260 
261   if (STM.dumpCode()) {
262 
263     OutStreamer->SwitchSection(
264         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
265 
266     for (size_t i = 0; i < DisasmLines.size(); ++i) {
267       std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
268       Comment += " ; " + HexLines[i] + "\n";
269 
270       OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
271       OutStreamer->EmitBytes(StringRef(Comment));
272     }
273   }
274 
275   return false;
276 }
277 
278 void AMDGPUAsmPrinter::EmitProgramInfoR600(const MachineFunction &MF) {
279   unsigned MaxGPR = 0;
280   bool killPixel = false;
281   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
282   const R600RegisterInfo *RI =
283       static_cast<const R600RegisterInfo *>(STM.getRegisterInfo());
284   const R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
285 
286   for (const MachineBasicBlock &MBB : MF) {
287     for (const MachineInstr &MI : MBB) {
288       if (MI.getOpcode() == AMDGPU::KILLGT)
289         killPixel = true;
290       unsigned numOperands = MI.getNumOperands();
291       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
292         const MachineOperand &MO = MI.getOperand(op_idx);
293         if (!MO.isReg())
294           continue;
295         unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;
296 
297         // Register with value > 127 aren't GPR
298         if (HWReg > 127)
299           continue;
300         MaxGPR = std::max(MaxGPR, HWReg);
301       }
302     }
303   }
304 
305   unsigned RsrcReg;
306   if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) {
307     // Evergreen / Northern Islands
308     switch (MF.getFunction()->getCallingConv()) {
309     default: // Fall through
310     case CallingConv::AMDGPU_CS: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
311     case CallingConv::AMDGPU_GS: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
312     case CallingConv::AMDGPU_PS: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
313     case CallingConv::AMDGPU_VS: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
314     }
315   } else {
316     // R600 / R700
317     switch (MF.getFunction()->getCallingConv()) {
318     default: // Fall through
319     case CallingConv::AMDGPU_GS: // Fall through
320     case CallingConv::AMDGPU_CS: // Fall through
321     case CallingConv::AMDGPU_VS: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
322     case CallingConv::AMDGPU_PS: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
323     }
324   }
325 
326   OutStreamer->EmitIntValue(RsrcReg, 4);
327   OutStreamer->EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
328                            S_STACK_SIZE(MFI->StackSize), 4);
329   OutStreamer->EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
330   OutStreamer->EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);
331 
332   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
333     OutStreamer->EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
334     OutStreamer->EmitIntValue(alignTo(MFI->LDSSize, 4) >> 2, 4);
335   }
336 }
337 
338 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
339                                         const MachineFunction &MF) const {
340   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
341   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
342   uint64_t CodeSize = 0;
343   unsigned MaxSGPR = 0;
344   unsigned MaxVGPR = 0;
345   bool VCCUsed = false;
346   bool FlatUsed = false;
347   const SIRegisterInfo *RI =
348       static_cast<const SIRegisterInfo *>(STM.getRegisterInfo());
349 
350   for (const MachineBasicBlock &MBB : MF) {
351     for (const MachineInstr &MI : MBB) {
352       // TODO: CodeSize should account for multiple functions.
353 
354       // TODO: Should we count size of debug info?
355       if (MI.isDebugValue())
356         continue;
357 
358       // FIXME: This is reporting 0 for many instructions.
359       CodeSize += MI.getDesc().Size;
360 
361       unsigned numOperands = MI.getNumOperands();
362       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
363         const MachineOperand &MO = MI.getOperand(op_idx);
364         unsigned width = 0;
365         bool isSGPR = false;
366 
367         if (!MO.isReg())
368           continue;
369 
370         unsigned reg = MO.getReg();
371         switch (reg) {
372         case AMDGPU::EXEC:
373         case AMDGPU::SCC:
374         case AMDGPU::M0:
375           continue;
376 
377         case AMDGPU::VCC:
378         case AMDGPU::VCC_LO:
379         case AMDGPU::VCC_HI:
380           VCCUsed = true;
381           continue;
382 
383         case AMDGPU::FLAT_SCR:
384         case AMDGPU::FLAT_SCR_LO:
385         case AMDGPU::FLAT_SCR_HI:
386           FlatUsed = true;
387           continue;
388 
389         case AMDGPU::TBA:
390         case AMDGPU::TBA_LO:
391         case AMDGPU::TBA_HI:
392         case AMDGPU::TMA:
393         case AMDGPU::TMA_LO:
394         case AMDGPU::TMA_HI:
395           llvm_unreachable("Trap Handler registers should not be used");
396           continue;
397 
398         default:
399           break;
400         }
401 
402         if (AMDGPU::SReg_32RegClass.contains(reg)) {
403           if (AMDGPU::TTMP_32RegClass.contains(reg)) {
404             llvm_unreachable("Trap Handler registers should not be used");
405           }
406           isSGPR = true;
407           width = 1;
408         } else if (AMDGPU::VGPR_32RegClass.contains(reg)) {
409           isSGPR = false;
410           width = 1;
411         } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
412           if (AMDGPU::TTMP_64RegClass.contains(reg)) {
413             llvm_unreachable("Trap Handler registers should not be used");
414           }
415           isSGPR = true;
416           width = 2;
417         } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
418           isSGPR = false;
419           width = 2;
420         } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
421           isSGPR = false;
422           width = 3;
423         } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
424           isSGPR = true;
425           width = 4;
426         } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
427           isSGPR = false;
428           width = 4;
429         } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
430           isSGPR = true;
431           width = 8;
432         } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
433           isSGPR = false;
434           width = 8;
435         } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
436           isSGPR = true;
437           width = 16;
438         } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
439           isSGPR = false;
440           width = 16;
441         } else {
442           llvm_unreachable("Unknown register class");
443         }
444         unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
445         unsigned maxUsed = hwReg + width - 1;
446         if (isSGPR) {
447           MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
448         } else {
449           MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
450         }
451       }
452     }
453   }
454 
455   unsigned ExtraSGPRs = 0;
456 
457   if (VCCUsed)
458     ExtraSGPRs = 2;
459 
460   if (STM.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) {
461     if (FlatUsed)
462       ExtraSGPRs = 4;
463   } else {
464     if (STM.isXNACKEnabled())
465       ExtraSGPRs = 4;
466 
467     if (FlatUsed)
468       ExtraSGPRs = 6;
469   }
470 
471   MaxSGPR += ExtraSGPRs;
472 
473   // We found the maximum register index. They start at 0, so add one to get the
474   // number of registers.
475   ProgInfo.NumVGPR = MaxVGPR + 1;
476   ProgInfo.NumSGPR = MaxSGPR + 1;
477 
478   if (STM.hasSGPRInitBug()) {
479     if (ProgInfo.NumSGPR > AMDGPUSubtarget::FIXED_SGPR_COUNT_FOR_INIT_BUG) {
480       LLVMContext &Ctx = MF.getFunction()->getContext();
481       Ctx.emitError("too many SGPRs used with the SGPR init bug");
482     }
483 
484     ProgInfo.NumSGPR = AMDGPUSubtarget::FIXED_SGPR_COUNT_FOR_INIT_BUG;
485   }
486 
487   if (MFI->NumUserSGPRs > STM.getMaxNumUserSGPRs()) {
488     LLVMContext &Ctx = MF.getFunction()->getContext();
489     Ctx.emitError("too many user SGPRs used");
490   }
491 
492   ProgInfo.VGPRBlocks = (ProgInfo.NumVGPR - 1) / 4;
493   ProgInfo.SGPRBlocks = (ProgInfo.NumSGPR - 1) / 8;
494   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
495   // register.
496   ProgInfo.FloatMode = getFPMode(MF);
497 
498   ProgInfo.IEEEMode = 0;
499 
500   // Make clamp modifier on NaN input returns 0.
501   ProgInfo.DX10Clamp = 1;
502 
503   const MachineFrameInfo *FrameInfo = MF.getFrameInfo();
504   ProgInfo.ScratchSize = FrameInfo->getStackSize();
505 
506   ProgInfo.FlatUsed = FlatUsed;
507   ProgInfo.VCCUsed = VCCUsed;
508   ProgInfo.CodeLen = CodeSize;
509 
510   unsigned LDSAlignShift;
511   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
512     // LDS is allocated in 64 dword blocks.
513     LDSAlignShift = 8;
514   } else {
515     // LDS is allocated in 128 dword blocks.
516     LDSAlignShift = 9;
517   }
518 
519   unsigned LDSSpillSize = MFI->LDSWaveSpillSize *
520                           MFI->getMaximumWorkGroupSize(MF);
521 
522   ProgInfo.LDSSize = MFI->LDSSize + LDSSpillSize;
523   ProgInfo.LDSBlocks =
524       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
525 
526   // Scratch is allocated in 256 dword blocks.
527   unsigned ScratchAlignShift = 10;
528   // We need to program the hardware with the amount of scratch memory that
529   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
530   // scratch memory used per thread.
531   ProgInfo.ScratchBlocks =
532       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
533               1ULL << ScratchAlignShift) >>
534       ScratchAlignShift;
535 
536   ProgInfo.ComputePGMRSrc1 =
537       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
538       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
539       S_00B848_PRIORITY(ProgInfo.Priority) |
540       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
541       S_00B848_PRIV(ProgInfo.Priv) |
542       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
543       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
544       S_00B848_IEEE_MODE(ProgInfo.IEEEMode);
545 
546   // 0 = X, 1 = XY, 2 = XYZ
547   unsigned TIDIGCompCnt = 0;
548   if (MFI->hasWorkItemIDZ())
549     TIDIGCompCnt = 2;
550   else if (MFI->hasWorkItemIDY())
551     TIDIGCompCnt = 1;
552 
553   ProgInfo.ComputePGMRSrc2 =
554       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
555       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
556       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
557       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
558       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
559       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
560       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
561       S_00B84C_EXCP_EN_MSB(0) |
562       S_00B84C_LDS_SIZE(ProgInfo.LDSBlocks) |
563       S_00B84C_EXCP_EN(0);
564 }
565 
566 static unsigned getRsrcReg(CallingConv::ID CallConv) {
567   switch (CallConv) {
568   default: // Fall through
569   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
570   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
571   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
572   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
573   }
574 }
575 
576 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
577                                          const SIProgramInfo &KernelInfo) {
578   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
579   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
580   unsigned RsrcReg = getRsrcReg(MF.getFunction()->getCallingConv());
581 
582   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
583     OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
584 
585     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc1, 4);
586 
587     OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
588     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc2, 4);
589 
590     OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
591     OutStreamer->EmitIntValue(S_00B860_WAVESIZE(KernelInfo.ScratchBlocks), 4);
592 
593     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
594     // 0" comment but I don't see a corresponding field in the register spec.
595   } else {
596     OutStreamer->EmitIntValue(RsrcReg, 4);
597     OutStreamer->EmitIntValue(S_00B028_VGPRS(KernelInfo.VGPRBlocks) |
598                               S_00B028_SGPRS(KernelInfo.SGPRBlocks), 4);
599     if (STM.isVGPRSpillingEnabled(*MF.getFunction())) {
600       OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
601       OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(KernelInfo.ScratchBlocks), 4);
602     }
603   }
604 
605   if (MF.getFunction()->getCallingConv() == CallingConv::AMDGPU_PS) {
606     OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
607     OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(KernelInfo.LDSBlocks), 4);
608     OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
609     OutStreamer->EmitIntValue(MFI->PSInputEna, 4);
610     OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
611     OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
612   }
613 }
614 
615 // This is supposed to be log2(Size)
616 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
617   switch (Size) {
618   case 4:
619     return AMD_ELEMENT_4_BYTES;
620   case 8:
621     return AMD_ELEMENT_8_BYTES;
622   case 16:
623     return AMD_ELEMENT_16_BYTES;
624   default:
625     llvm_unreachable("invalid private_element_size");
626   }
627 }
628 
629 void AMDGPUAsmPrinter::EmitAmdKernelCodeT(const MachineFunction &MF,
630                                          const SIProgramInfo &KernelInfo) const {
631   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
632   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
633   amd_kernel_code_t header;
634 
635   AMDGPU::initDefaultAMDKernelCodeT(header, STM.getFeatureBits());
636 
637   header.compute_pgm_resource_registers =
638       KernelInfo.ComputePGMRSrc1 |
639       (KernelInfo.ComputePGMRSrc2 << 32);
640   header.code_properties = AMD_CODE_PROPERTY_IS_PTR64;
641 
642 
643   AMD_HSA_BITS_SET(header.code_properties,
644                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
645                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
646 
647   if (MFI->hasPrivateSegmentBuffer()) {
648     header.code_properties |=
649       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
650   }
651 
652   if (MFI->hasDispatchPtr())
653     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
654 
655   if (MFI->hasQueuePtr())
656     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
657 
658   if (MFI->hasKernargSegmentPtr())
659     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
660 
661   if (MFI->hasDispatchID())
662     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
663 
664   if (MFI->hasFlatScratchInit())
665     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
666 
667   // TODO: Private segment size
668 
669   if (MFI->hasGridWorkgroupCountX()) {
670     header.code_properties |=
671       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X;
672   }
673 
674   if (MFI->hasGridWorkgroupCountY()) {
675     header.code_properties |=
676       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y;
677   }
678 
679   if (MFI->hasGridWorkgroupCountZ()) {
680     header.code_properties |=
681       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z;
682   }
683 
684   if (MFI->hasDispatchPtr())
685     header.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
686 
687   if (STM.isXNACKEnabled())
688     header.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
689 
690   header.kernarg_segment_byte_size = MFI->ABIArgOffset;
691   header.wavefront_sgpr_count = KernelInfo.NumSGPR;
692   header.workitem_vgpr_count = KernelInfo.NumVGPR;
693   header.workitem_private_segment_byte_size = KernelInfo.ScratchSize;
694   header.workgroup_group_segment_byte_size = KernelInfo.LDSSize;
695 
696   AMDGPUTargetStreamer *TS =
697       static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
698   TS->EmitAMDKernelCodeT(header);
699 }
700 
701 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
702                                        unsigned AsmVariant,
703                                        const char *ExtraCode, raw_ostream &O) {
704   if (ExtraCode && ExtraCode[0]) {
705     if (ExtraCode[1] != 0)
706       return true; // Unknown modifier.
707 
708     switch (ExtraCode[0]) {
709     default:
710       // See if this is a generic print operand
711       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
712     case 'r':
713       break;
714     }
715   }
716 
717   AMDGPUInstPrinter::printRegOperand(MI->getOperand(OpNo).getReg(), O,
718                    *TM.getSubtargetImpl(*MF->getFunction())->getRegisterInfo());
719   return false;
720 }
721