LLVM  9.0.0svn
AMDGPUAsmPrinter.cpp
Go to the documentation of this file.
1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 ///
11 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary
12 /// code. When passed an MCAsmStreamer it prints assembly and when passed
13 /// an MCObjectStreamer it outputs binary code.
14 //
15 //===----------------------------------------------------------------------===//
16 //
17 
18 #include "AMDGPUAsmPrinter.h"
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
25 #include "R600AsmPrinter.h"
26 #include "R600Defines.h"
28 #include "R600RegisterInfo.h"
29 #include "SIDefines.h"
30 #include "SIInstrInfo.h"
31 #include "SIMachineFunctionInfo.h"
32 #include "SIRegisterInfo.h"
34 #include "Utils/AMDGPUBaseInfo.h"
35 #include "llvm/BinaryFormat/ELF.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/MC/MCAssembler.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionELF.h"
41 #include "llvm/MC/MCStreamer.h"
47 
48 using namespace llvm;
49 using namespace llvm::AMDGPU;
50 using namespace llvm::AMDGPU::HSAMD;
51 
52 // TODO: This should get the default rounding mode from the kernel. We just set
53 // the default here, but this could change if the OpenCL rounding mode pragmas
54 // are used.
55 //
56 // The denormal mode here should match what is reported by the OpenCL runtime
57 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
58 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
59 //
60 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
61 // precision, and leaves single precision to flush all and does not report
62 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
63 // CL_FP_DENORM for both.
64 //
65 // FIXME: It seems some instructions do not support single precision denormals
66 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
67 // and sin_f32, cos_f32 on most parts).
68 
69 // We want to use these instructions, and using fp32 denormals also causes
70 // instructions to run at the double precision rate for the device so it's
71 // probably best to just report no single precision denormals.
74  // TODO: Is there any real use for the flush in only / flush out only modes?
75 
76  uint32_t FP32Denormals =
78 
79  uint32_t FP64Denormals =
81 
84  FP_DENORM_MODE_SP(FP32Denormals) |
85  FP_DENORM_MODE_DP(FP64Denormals);
86 }
87 
88 static AsmPrinter *
90  std::unique_ptr<MCStreamer> &&Streamer) {
91  return new AMDGPUAsmPrinter(tm, std::move(Streamer));
92 }
93 
94 extern "C" void LLVMInitializeAMDGPUAsmPrinter() {
99 }
100 
102  std::unique_ptr<MCStreamer> Streamer)
103  : AsmPrinter(TM, std::move(Streamer)) {
105  HSAMetadataStream.reset(new MetadataStreamerV3());
106  else
107  HSAMetadataStream.reset(new MetadataStreamerV2());
108 }
109 
111  return "AMDGPU Assembly Printer";
112 }
113 
115  return TM.getMCSubtargetInfo();
116 }
117 
119  if (!OutStreamer)
120  return nullptr;
121  return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer());
122 }
123 
126  std::string ExpectedTarget;
127  raw_string_ostream ExpectedTargetOS(ExpectedTarget);
128  IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS);
129 
130  getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget);
131  }
132 
133  if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
135  return;
136 
138  HSAMetadataStream->begin(M);
139 
142 
144  return;
145 
146  // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2.
149 
150  // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2.
153  Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU");
154 }
155 
157  // Following code requires TargetStreamer to be present.
158  if (!getTargetStreamer())
159  return;
160 
162  // Emit ISA Version (NT_AMD_AMDGPU_ISA).
163  std::string ISAVersionString;
164  raw_string_ostream ISAVersionStream(ISAVersionString);
165  IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream);
166  getTargetStreamer()->EmitISAVersion(ISAVersionStream.str());
167  }
168 
169  // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
170  if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
171  HSAMetadataStream->end();
172  bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
173  (void)Success;
174  assert(Success && "Malformed HSA Metadata");
175  }
176 }
177 
179  const MachineBasicBlock *MBB) const {
181  return false;
182 
183  if (MBB->empty())
184  return true;
185 
186  // If this is a block implementing a long branch, an expression relative to
187  // the start of the block is needed. to the start of the block.
188  // XXX - Is there a smarter way to check this?
189  return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
190 }
191 
194  if (!MFI.isEntryFunction())
195  return;
196 
197  const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
198  const Function &F = MF->getFunction();
199  if (!STM.hasCodeObjectV3() && STM.isAmdHsaOrMesa(F) &&
200  (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
201  F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
202  amd_kernel_code_t KernelCode;
203  getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
204  getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
205  }
206 
207  if (STM.isAmdHsaOS())
208  HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
209 
210  DumpCodeInstEmitter = nullptr;
211  if (STM.dumpCode()) {
212  // For -dumpcode, get the assembler out of the streamer, even if it does
213  // not really want to let us have it. This only works with -filetype=obj.
214  bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing();
215  OutStreamer->setUseAssemblerInfoForParsing(true);
216  MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
217  OutStreamer->setUseAssemblerInfoForParsing(SaveFlag);
218  if (Assembler)
219  DumpCodeInstEmitter = Assembler->getEmitterPtr();
220  }
221 }
222 
225  if (!MFI.isEntryFunction())
226  return;
227 
230  return;
231 
232  auto &Streamer = getTargetStreamer()->getStreamer();
233  auto &Context = Streamer.getContext();
234  auto &ObjectFileInfo = *Context.getObjectFileInfo();
235  auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
236 
237  Streamer.PushSection();
238  Streamer.SwitchSection(&ReadOnlySection);
239 
240  // CP microcode requires the kernel descriptor to be allocated on 64 byte
241  // alignment.
242  Streamer.EmitValueToAlignment(64, 0, 1, 0);
243  if (ReadOnlySection.getAlignment() < 64)
244  ReadOnlySection.setAlignment(64);
245 
246  const MCSubtargetInfo &STI = MF->getSubtarget();
247 
248  SmallString<128> KernelName;
249  getNameWithPrefix(KernelName, &MF->getFunction());
251  STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
252  CurrentProgramInfo.NumVGPRsForWavesPerEU,
253  CurrentProgramInfo.NumSGPRsForWavesPerEU -
255  CurrentProgramInfo.VCCUsed,
256  CurrentProgramInfo.FlatUsed),
257  CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed,
258  hasXNACK(STI));
259 
260  Streamer.PopSection();
261 }
262 
267  return;
268  }
269 
271  const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
272  if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
274  getNameWithPrefix(SymbolName, &MF->getFunction()),
276  SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
277  }
278  if (DumpCodeInstEmitter) {
279  // Disassemble function name label to text.
280  DisasmLines.push_back(MF->getName().str() + ":");
282  HexLines.push_back("");
283  }
284 
286 }
287 
289  if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
290  // Write a line for the basic block label if it is not only fallthrough.
291  DisasmLines.push_back(
292  (Twine("BB") + Twine(getFunctionNumber())
293  + "_" + Twine(MBB.getNumber()) + ":").str());
295  HexLines.push_back("");
296  }
298 }
299 
301 
302  // Group segment variables aren't emitted in HSA.
303  if (AMDGPU::isGroupSegment(GV))
304  return;
305 
307 }
308 
310  CallGraphResourceInfo.clear();
311 
312  if (AMDGPU::isGFX10(*getGlobalSTI())) {
313  OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
315  }
316 
317  return AsmPrinter::doFinalization(M);
318 }
319 
320 // Print comments that apply to both callable functions and entry points.
321 void AMDGPUAsmPrinter::emitCommonFunctionComments(
322  uint32_t NumVGPR,
323  uint32_t NumSGPR,
324  uint64_t ScratchSize,
325  uint64_t CodeSize,
326  const AMDGPUMachineFunction *MFI) {
327  OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
328  OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
329  OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
330  OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
331  OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
332  false);
333 }
334 
335 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
336  const MachineFunction &MF) const {
338  uint16_t KernelCodeProperties = 0;
339 
340  if (MFI.hasPrivateSegmentBuffer()) {
341  KernelCodeProperties |=
342  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
343  }
344  if (MFI.hasDispatchPtr()) {
345  KernelCodeProperties |=
346  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
347  }
348  if (MFI.hasQueuePtr()) {
349  KernelCodeProperties |=
350  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
351  }
352  if (MFI.hasKernargSegmentPtr()) {
353  KernelCodeProperties |=
354  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
355  }
356  if (MFI.hasDispatchID()) {
357  KernelCodeProperties |=
358  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
359  }
360  if (MFI.hasFlatScratchInit()) {
361  KernelCodeProperties |=
362  amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
363  }
364 
365  return KernelCodeProperties;
366 }
367 
368 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
369  const MachineFunction &MF,
370  const SIProgramInfo &PI) const {
371  amdhsa::kernel_descriptor_t KernelDescriptor;
372  memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
373 
377 
378  KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
379  KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
380  KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1;
381  KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
382  KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
383 
384  return KernelDescriptor;
385 }
386 
388  CurrentProgramInfo = SIProgramInfo();
389 
391 
392  // The starting address of all shader programs must be 256 bytes aligned.
393  // Regular functions just need the basic required instruction alignment.
394  MF.setAlignment(MFI->isEntryFunction() ? 8 : 2);
395 
397 
398  const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
400  // FIXME: This should be an explicit check for Mesa.
401  if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
402  MCSectionELF *ConfigSection =
403  Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
404  OutStreamer->SwitchSection(ConfigSection);
405  }
406 
407  if (MFI->isEntryFunction()) {
408  getSIProgramInfo(CurrentProgramInfo, MF);
409  } else {
410  auto I = CallGraphResourceInfo.insert(
411  std::make_pair(&MF.getFunction(), SIFunctionResourceInfo()));
412  SIFunctionResourceInfo &Info = I.first->second;
413  assert(I.second && "should only be called once per function");
414  Info = analyzeResourceUsage(MF);
415  }
416 
417  if (STM.isAmdPalOS())
418  EmitPALMetadata(MF, CurrentProgramInfo);
419  else if (!STM.isAmdHsaOS()) {
420  EmitProgramInfoSI(MF, CurrentProgramInfo);
421  }
422 
423  DisasmLines.clear();
424  HexLines.clear();
425  DisasmLineMaxLen = 0;
426 
428 
429  if (isVerbose()) {
430  MCSectionELF *CommentSection =
431  Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
432  OutStreamer->SwitchSection(CommentSection);
433 
434  if (!MFI->isEntryFunction()) {
435  OutStreamer->emitRawComment(" Function info:", false);
436  SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()];
437  emitCommonFunctionComments(
438  Info.NumVGPR,
439  Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
440  Info.PrivateSegmentSize,
441  getFunctionCodeSize(MF), MFI);
442  return false;
443  }
444 
445  OutStreamer->emitRawComment(" Kernel info:", false);
446  emitCommonFunctionComments(CurrentProgramInfo.NumVGPR,
447  CurrentProgramInfo.NumSGPR,
448  CurrentProgramInfo.ScratchSize,
449  getFunctionCodeSize(MF), MFI);
450 
451  OutStreamer->emitRawComment(
452  " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
453  OutStreamer->emitRawComment(
454  " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
455  OutStreamer->emitRawComment(
456  " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
457  " bytes/workgroup (compile time only)", false);
458 
459  OutStreamer->emitRawComment(
460  " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
461  OutStreamer->emitRawComment(
462  " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
463 
464  OutStreamer->emitRawComment(
465  " NumSGPRsForWavesPerEU: " +
466  Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
467  OutStreamer->emitRawComment(
468  " NumVGPRsForWavesPerEU: " +
469  Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
470 
471  OutStreamer->emitRawComment(
472  " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
473 
474  OutStreamer->emitRawComment(
475  " COMPUTE_PGM_RSRC2:USER_SGPR: " +
476  Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
477  OutStreamer->emitRawComment(
478  " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
479  Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
480  OutStreamer->emitRawComment(
481  " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
482  Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
483  OutStreamer->emitRawComment(
484  " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
485  Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
486  OutStreamer->emitRawComment(
487  " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
488  Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
489  OutStreamer->emitRawComment(
490  " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
491  Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
492  false);
493  }
494 
495  if (DumpCodeInstEmitter) {
496 
497  OutStreamer->SwitchSection(
498  Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
499 
500  for (size_t i = 0; i < DisasmLines.size(); ++i) {
501  std::string Comment = "\n";
502  if (!HexLines[i].empty()) {
503  Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
504  Comment += " ; " + HexLines[i] + "\n";
505  }
506 
507  OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
508  OutStreamer->EmitBytes(StringRef(Comment));
509  }
510  }
511 
512  return false;
513 }
514 
515 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
516  const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
517  const SIInstrInfo *TII = STM.getInstrInfo();
518 
519  uint64_t CodeSize = 0;
520 
521  for (const MachineBasicBlock &MBB : MF) {
522  for (const MachineInstr &MI : MBB) {
523  // TODO: CodeSize should account for multiple functions.
524 
525  // TODO: Should we count size of debug info?
526  if (MI.isDebugInstr())
527  continue;
528 
529  CodeSize += TII->getInstSizeInBytes(MI);
530  }
531  }
532 
533  return CodeSize;
534 }
535 
537  const SIInstrInfo &TII,
538  unsigned Reg) {
539  for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) {
540  if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent()))
541  return true;
542  }
543 
544  return false;
545 }
546 
548  const GCNSubtarget &ST) const {
549  return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST,
550  UsesVCC, UsesFlatScratch);
551 }
552 
553 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage(
554  const MachineFunction &MF) const {
555  SIFunctionResourceInfo Info;
556 
558  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
559  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
560  const MachineRegisterInfo &MRI = MF.getRegInfo();
561  const SIInstrInfo *TII = ST.getInstrInfo();
562  const SIRegisterInfo &TRI = TII->getRegisterInfo();
563 
564  Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) ||
565  MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI);
566 
567  // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
568  // instructions aren't used to access the scratch buffer. Inline assembly may
569  // need it though.
570  //
571  // If we only have implicit uses of flat_scr on flat instructions, it is not
572  // really needed.
573  if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() &&
574  (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) &&
575  !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) &&
576  !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) {
577  Info.UsesFlatScratch = false;
578  }
579 
580  Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects();
581  Info.PrivateSegmentSize = FrameInfo.getStackSize();
582  if (MFI->isStackRealigned())
583  Info.PrivateSegmentSize += FrameInfo.getMaxAlignment();
584 
585 
586  Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) ||
587  MRI.isPhysRegUsed(AMDGPU::VCC_HI);
588 
589  // If there are no calls, MachineRegisterInfo can tell us the used register
590  // count easily.
591  // A tail call isn't considered a call for MachineFrameInfo's purposes.
592  if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) {
593  MCPhysReg HighestVGPRReg = AMDGPU::NoRegister;
594  for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) {
595  if (MRI.isPhysRegUsed(Reg)) {
596  HighestVGPRReg = Reg;
597  break;
598  }
599  }
600 
601  MCPhysReg HighestSGPRReg = AMDGPU::NoRegister;
602  for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) {
603  if (MRI.isPhysRegUsed(Reg)) {
604  HighestSGPRReg = Reg;
605  break;
606  }
607  }
608 
609  // We found the maximum register index. They start at 0, so add one to get the
610  // number of registers.
611  Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 :
612  TRI.getHWRegIndex(HighestVGPRReg) + 1;
613  Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 :
614  TRI.getHWRegIndex(HighestSGPRReg) + 1;
615 
616  return Info;
617  }
618 
619  int32_t MaxVGPR = -1;
620  int32_t MaxSGPR = -1;
621  uint64_t CalleeFrameSize = 0;
622 
623  for (const MachineBasicBlock &MBB : MF) {
624  for (const MachineInstr &MI : MBB) {
625  // TODO: Check regmasks? Do they occur anywhere except calls?
626  for (const MachineOperand &MO : MI.operands()) {
627  unsigned Width = 0;
628  bool IsSGPR = false;
629 
630  if (!MO.isReg())
631  continue;
632 
633  unsigned Reg = MO.getReg();
634  switch (Reg) {
635  case AMDGPU::EXEC:
636  case AMDGPU::EXEC_LO:
637  case AMDGPU::EXEC_HI:
638  case AMDGPU::SCC:
639  case AMDGPU::M0:
640  case AMDGPU::SRC_SHARED_BASE:
641  case AMDGPU::SRC_SHARED_LIMIT:
642  case AMDGPU::SRC_PRIVATE_BASE:
643  case AMDGPU::SRC_PRIVATE_LIMIT:
644  case AMDGPU::SGPR_NULL:
645  continue;
646 
647  case AMDGPU::SRC_POPS_EXITING_WAVE_ID:
648  llvm_unreachable("src_pops_exiting_wave_id should not be used");
649 
650  case AMDGPU::NoRegister:
651  assert(MI.isDebugInstr());
652  continue;
653 
654  case AMDGPU::VCC:
655  case AMDGPU::VCC_LO:
656  case AMDGPU::VCC_HI:
657  Info.UsesVCC = true;
658  continue;
659 
660  case AMDGPU::FLAT_SCR:
661  case AMDGPU::FLAT_SCR_LO:
662  case AMDGPU::FLAT_SCR_HI:
663  continue;
664 
665  case AMDGPU::XNACK_MASK:
666  case AMDGPU::XNACK_MASK_LO:
667  case AMDGPU::XNACK_MASK_HI:
668  llvm_unreachable("xnack_mask registers should not be used");
669 
670  case AMDGPU::LDS_DIRECT:
671  llvm_unreachable("lds_direct register should not be used");
672 
673  case AMDGPU::TBA:
674  case AMDGPU::TBA_LO:
675  case AMDGPU::TBA_HI:
676  case AMDGPU::TMA:
677  case AMDGPU::TMA_LO:
678  case AMDGPU::TMA_HI:
679  llvm_unreachable("trap handler registers should not be used");
680 
681  case AMDGPU::SRC_VCCZ:
682  llvm_unreachable("src_vccz register should not be used");
683 
684  case AMDGPU::SRC_EXECZ:
685  llvm_unreachable("src_execz register should not be used");
686 
687  case AMDGPU::SRC_SCC:
688  llvm_unreachable("src_scc register should not be used");
689 
690  default:
691  break;
692  }
693 
694  if (AMDGPU::SReg_32RegClass.contains(Reg)) {
695  assert(!AMDGPU::TTMP_32RegClass.contains(Reg) &&
696  "trap handler registers should not be used");
697  IsSGPR = true;
698  Width = 1;
699  } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) {
700  IsSGPR = false;
701  Width = 1;
702  } else if (AMDGPU::SReg_64RegClass.contains(Reg)) {
703  assert(!AMDGPU::TTMP_64RegClass.contains(Reg) &&
704  "trap handler registers should not be used");
705  IsSGPR = true;
706  Width = 2;
707  } else if (AMDGPU::VReg_64RegClass.contains(Reg)) {
708  IsSGPR = false;
709  Width = 2;
710  } else if (AMDGPU::VReg_96RegClass.contains(Reg)) {
711  IsSGPR = false;
712  Width = 3;
713  } else if (AMDGPU::SReg_128RegClass.contains(Reg)) {
714  assert(!AMDGPU::TTMP_128RegClass.contains(Reg) &&
715  "trap handler registers should not be used");
716  IsSGPR = true;
717  Width = 4;
718  } else if (AMDGPU::VReg_128RegClass.contains(Reg)) {
719  IsSGPR = false;
720  Width = 4;
721  } else if (AMDGPU::SReg_256RegClass.contains(Reg)) {
722  assert(!AMDGPU::TTMP_256RegClass.contains(Reg) &&
723  "trap handler registers should not be used");
724  IsSGPR = true;
725  Width = 8;
726  } else if (AMDGPU::VReg_256RegClass.contains(Reg)) {
727  IsSGPR = false;
728  Width = 8;
729  } else if (AMDGPU::SReg_512RegClass.contains(Reg)) {
730  assert(!AMDGPU::TTMP_512RegClass.contains(Reg) &&
731  "trap handler registers should not be used");
732  IsSGPR = true;
733  Width = 16;
734  } else if (AMDGPU::VReg_512RegClass.contains(Reg)) {
735  IsSGPR = false;
736  Width = 16;
737  } else if (AMDGPU::SReg_96RegClass.contains(Reg)) {
738  IsSGPR = true;
739  Width = 3;
740  } else {
741  llvm_unreachable("Unknown register class");
742  }
743  unsigned HWReg = TRI.getHWRegIndex(Reg);
744  int MaxUsed = HWReg + Width - 1;
745  if (IsSGPR) {
746  MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR;
747  } else {
748  MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR;
749  }
750  }
751 
752  if (MI.isCall()) {
753  // Pseudo used just to encode the underlying global. Is there a better
754  // way to track this?
755 
756  const MachineOperand *CalleeOp
757  = TII->getNamedOperand(MI, AMDGPU::OpName::callee);
758  const Function *Callee = cast<Function>(CalleeOp->getGlobal());
759  if (Callee->isDeclaration()) {
760  // If this is a call to an external function, we can't do much. Make
761  // conservative guesses.
762 
763  // 48 SGPRs - vcc, - flat_scr, -xnack
764  int MaxSGPRGuess =
765  47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace());
766  MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess);
767  MaxVGPR = std::max(MaxVGPR, 23);
768 
769  CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384));
770  Info.UsesVCC = true;
771  Info.UsesFlatScratch = ST.hasFlatAddressSpace();
772  Info.HasDynamicallySizedStack = true;
773  } else {
774  // We force CodeGen to run in SCC order, so the callee's register
775  // usage etc. should be the cumulative usage of all callees.
776 
777  auto I = CallGraphResourceInfo.find(Callee);
778  if (I == CallGraphResourceInfo.end()) {
779  // Avoid crashing on undefined behavior with an illegal call to a
780  // kernel. If a callsite's calling convention doesn't match the
781  // function's, it's undefined behavior. If the callsite calling
782  // convention does match, that would have errored earlier.
783  // FIXME: The verifier shouldn't allow this.
785  report_fatal_error("invalid call to entry function");
786 
787  llvm_unreachable("callee should have been handled before caller");
788  }
789 
790  MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR);
791  MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR);
792  CalleeFrameSize
793  = std::max(I->second.PrivateSegmentSize, CalleeFrameSize);
794  Info.UsesVCC |= I->second.UsesVCC;
795  Info.UsesFlatScratch |= I->second.UsesFlatScratch;
796  Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack;
797  Info.HasRecursion |= I->second.HasRecursion;
798  }
799 
800  if (!Callee->doesNotRecurse())
801  Info.HasRecursion = true;
802  }
803  }
804  }
805 
806  Info.NumExplicitSGPR = MaxSGPR + 1;
807  Info.NumVGPR = MaxVGPR + 1;
808  Info.PrivateSegmentSize += CalleeFrameSize;
809 
810  return Info;
811 }
812 
813 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
814  const MachineFunction &MF) {
815  SIFunctionResourceInfo Info = analyzeResourceUsage(MF);
816 
817  ProgInfo.NumVGPR = Info.NumVGPR;
818  ProgInfo.NumSGPR = Info.NumExplicitSGPR;
819  ProgInfo.ScratchSize = Info.PrivateSegmentSize;
820  ProgInfo.VCCUsed = Info.UsesVCC;
821  ProgInfo.FlatUsed = Info.UsesFlatScratch;
822  ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
823 
824  if (!isUInt<32>(ProgInfo.ScratchSize)) {
825  DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
826  ProgInfo.ScratchSize, DS_Error);
827  MF.getFunction().getContext().diagnose(DiagStackSize);
828  }
829 
830  const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
832 
833  // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are
834  // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
835  // unified.
836  unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
837  &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
838 
839  // Check the addressable register limit before we add ExtraSGPRs.
841  !STM.hasSGPRInitBug()) {
842  unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
843  if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
844  // This can happen due to a compiler bug or when using inline asm.
845  LLVMContext &Ctx = MF.getFunction().getContext();
847  "addressable scalar registers",
848  ProgInfo.NumSGPR, DS_Error,
850  MaxAddressableNumSGPRs);
851  Ctx.diagnose(Diag);
852  ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
853  }
854  }
855 
856  // Account for extra SGPRs and VGPRs reserved for debugger use.
857  ProgInfo.NumSGPR += ExtraSGPRs;
858 
859  // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
860  // dispatch registers are function args.
861  unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
862  for (auto &Arg : MF.getFunction().args()) {
863  unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32;
864  if (Arg.hasAttribute(Attribute::InReg))
865  WaveDispatchNumSGPR += NumRegs;
866  else
867  WaveDispatchNumVGPR += NumRegs;
868  }
869  ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
870  ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
871 
872  // Adjust number of registers used to meet default/requested minimum/maximum
873  // number of waves per execution unit request.
874  ProgInfo.NumSGPRsForWavesPerEU = std::max(
875  std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
876  ProgInfo.NumVGPRsForWavesPerEU = std::max(
877  std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
878 
880  STM.hasSGPRInitBug()) {
881  unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
882  if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
883  // This can happen due to a compiler bug or when using inline asm to use
884  // the registers which are usually reserved for vcc etc.
885  LLVMContext &Ctx = MF.getFunction().getContext();
887  "scalar registers",
888  ProgInfo.NumSGPR, DS_Error,
890  MaxAddressableNumSGPRs);
891  Ctx.diagnose(Diag);
892  ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
893  ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
894  }
895  }
896 
897  if (STM.hasSGPRInitBug()) {
898  ProgInfo.NumSGPR =
900  ProgInfo.NumSGPRsForWavesPerEU =
902  }
903 
904  if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
905  LLVMContext &Ctx = MF.getFunction().getContext();
906  DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
907  MFI->getNumUserSGPRs(), DS_Error);
908  Ctx.diagnose(Diag);
909  }
910 
911  if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
912  LLVMContext &Ctx = MF.getFunction().getContext();
913  DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
914  MFI->getLDSSize(), DS_Error);
915  Ctx.diagnose(Diag);
916  }
917 
919  &STM, ProgInfo.NumSGPRsForWavesPerEU);
921  &STM, ProgInfo.NumVGPRsForWavesPerEU);
922 
923  // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
924  // register.
925  ProgInfo.FloatMode = getFPMode(MF);
926 
927  const SIModeRegisterDefaults Mode = MFI->getMode();
928  ProgInfo.IEEEMode = Mode.IEEE;
929 
930  // Make clamp modifier on NaN input returns 0.
931  ProgInfo.DX10Clamp = Mode.DX10Clamp;
932 
933  unsigned LDSAlignShift;
935  // LDS is allocated in 64 dword blocks.
936  LDSAlignShift = 8;
937  } else {
938  // LDS is allocated in 128 dword blocks.
939  LDSAlignShift = 9;
940  }
941 
942  unsigned LDSSpillSize =
943  MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
944 
945  ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
946  ProgInfo.LDSBlocks =
947  alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
948 
949  // Scratch is allocated in 256 dword blocks.
950  unsigned ScratchAlignShift = 10;
951  // We need to program the hardware with the amount of scratch memory that
952  // is used by the entire wave. ProgInfo.ScratchSize is the amount of
953  // scratch memory used per thread.
954  ProgInfo.ScratchBlocks =
955  alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
956  1ULL << ScratchAlignShift) >>
957  ScratchAlignShift;
958 
959  if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
960  ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
961  ProgInfo.MemOrdered = 1;
962  }
963 
964  ProgInfo.ComputePGMRSrc1 =
965  S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
966  S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
967  S_00B848_PRIORITY(ProgInfo.Priority) |
968  S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
969  S_00B848_PRIV(ProgInfo.Priv) |
970  S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
971  S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
972  S_00B848_IEEE_MODE(ProgInfo.IEEEMode) |
973  S_00B848_WGP_MODE(ProgInfo.WgpMode) |
975 
976  // 0 = X, 1 = XY, 2 = XYZ
977  unsigned TIDIGCompCnt = 0;
978  if (MFI->hasWorkItemIDZ())
979  TIDIGCompCnt = 2;
980  else if (MFI->hasWorkItemIDY())
981  TIDIGCompCnt = 1;
982 
983  ProgInfo.ComputePGMRSrc2 =
984  S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
985  S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
986  // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
988  S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
989  S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
990  S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
991  S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
992  S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
994  // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
995  S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
996  S_00B84C_EXCP_EN(0);
997 }
998 
999 static unsigned getRsrcReg(CallingConv::ID CallConv) {
1000  switch (CallConv) {
1001  default: LLVM_FALLTHROUGH;
1009  }
1010 }
1011 
1012 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
1013  const SIProgramInfo &CurrentProgramInfo) {
1015  unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
1016 
1018  OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
1019 
1020  OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4);
1021 
1022  OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
1023  OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4);
1024 
1025  OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
1026  OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1027 
1028  // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
1029  // 0" comment but I don't see a corresponding field in the register spec.
1030  } else {
1031  OutStreamer->EmitIntValue(RsrcReg, 4);
1032  OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1033  S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
1034  OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
1035  OutStreamer->EmitIntValue(
1036  S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1037  }
1038 
1041  OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4);
1042  OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
1043  OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4);
1044  OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
1045  OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
1046  }
1047 
1048  OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4);
1049  OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4);
1050  OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4);
1051  OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4);
1052 }
1053 
1054 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1055 // is AMDPAL. It stores each compute/SPI register setting and other PAL
1056 // metadata items into the PALMD::Metadata, combining with any provided by the
1057 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
1058 // is then written as a single block in the .note section.
1059 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
1060  const SIProgramInfo &CurrentProgramInfo) {
1062  auto CC = MF.getFunction().getCallingConv();
1063  auto MD = getTargetStreamer()->getPALMetadata();
1064 
1065  MD->setEntryPoint(CC, MF.getFunction().getName());
1066  MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1067  MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1069  MD->setRsrc1(CC, CurrentProgramInfo.ComputePGMRSrc1);
1070  MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
1071  } else {
1072  MD->setRsrc1(CC, S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1073  S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks));
1074  if (CurrentProgramInfo.ScratchBlocks > 0)
1075  MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
1076  }
1077  // ScratchSize is in bytes, 16 aligned.
1078  MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
1080  MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
1081  MD->setSpiPsInputEna(MFI->getPSInputEnable());
1082  MD->setSpiPsInputAddr(MFI->getPSInputAddr());
1083  }
1084 }
1085 
1086 // This is supposed to be log2(Size)
1088  switch (Size) {
1089  case 4:
1090  return AMD_ELEMENT_4_BYTES;
1091  case 8:
1092  return AMD_ELEMENT_8_BYTES;
1093  case 16:
1094  return AMD_ELEMENT_16_BYTES;
1095  default:
1096  llvm_unreachable("invalid private_element_size");
1097  }
1098 }
1099 
1100 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1101  const SIProgramInfo &CurrentProgramInfo,
1102  const MachineFunction &MF) const {
1103  const Function &F = MF.getFunction();
1106 
1108  const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1109 
1111 
1113  CurrentProgramInfo.ComputePGMRSrc1 |
1114  (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1116 
1117  if (CurrentProgramInfo.DynamicCallStack)
1119 
1122  getElementByteSizeValue(STM.getMaxPrivateElementSize()));
1123 
1124  if (MFI->hasPrivateSegmentBuffer()) {
1125  Out.code_properties |=
1127  }
1128 
1129  if (MFI->hasDispatchPtr())
1131 
1132  if (MFI->hasQueuePtr())
1134 
1135  if (MFI->hasKernargSegmentPtr())
1137 
1138  if (MFI->hasDispatchID())
1140 
1141  if (MFI->hasFlatScratchInit())
1143 
1144  if (MFI->hasDispatchPtr())
1146 
1147  if (STM.isXNACKEnabled())
1149 
1150  unsigned MaxKernArgAlign;
1151  Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1152  Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1153  Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1154  Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1155  Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1156 
1157  // These alignment values are specified in powers of two, so alignment =
1158  // 2^n. The minimum alignment is 2^4 = 16.
1159  Out.kernarg_segment_alignment = std::max<size_t>(4,
1160  countTrailingZeros(MaxKernArgAlign));
1161 }
1162 
1164  const char *ExtraCode, raw_ostream &O) {
1165  // First try the generic code, which knows about modifiers like 'c' and 'n'.
1166  if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1167  return false;
1168 
1169  if (ExtraCode && ExtraCode[0]) {
1170  if (ExtraCode[1] != 0)
1171  return true; // Unknown modifier.
1172 
1173  switch (ExtraCode[0]) {
1174  case 'r':
1175  break;
1176  default:
1177  return true;
1178  }
1179  }
1180 
1181  // TODO: Should be able to support other operand types like globals.
1182  const MachineOperand &MO = MI->getOperand(OpNo);
1183  if (MO.isReg()) {
1185  *MF->getSubtarget().getRegisterInfo());
1186  return false;
1187  }
1188 
1189  return true;
1190 }
virtual void EmitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:447
constexpr bool isUInt< 32 >(uint64_t x)
Definition: MathExtras.h:348
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:213
void EmitGlobalVariable(const GlobalVariable *GV) override
Emit the specified global variable to the .s file.
Interface definition for SIRegisterInfo.
Target & getTheGCNTarget()
The target for GCN GPUs.
#define S_00B848_VGPRS(x)
Definition: SIDefines.h:534
#define S_00B848_PRIV(x)
Definition: SIDefines.h:546
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
LLVMContext & Context
AMDGPU specific subclass of TargetSubtarget.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
SI Whole Quad Mode
#define FP_DENORM_MODE_SP(x)
Definition: SIDefines.h:588
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define R_00B228_SPI_SHADER_PGM_RSRC1_GS
Definition: SIDefines.h:485
#define G_00B84C_USER_SGPR(x)
Definition: SIDefines.h:498
const MCSubtargetInfo * getGlobalSTI() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:304
void EmitFunctionBodyEnd() override
Targets can override this to emit stuff after the last basic block in the function.
Target & getTheAMDGPUTarget()
The target which supports all AMD GPUs.
#define G_00B84C_TGID_Z_EN(x)
Definition: SIDefines.h:510
unsigned getReg() const
getReg - Returns the register number.
unsigned Reg
#define R_00B028_SPI_SHADER_PGM_RSRC1_PS
Definition: SIDefines.h:481
iterator_range< reg_iterator > reg_operands(unsigned Reg) const
virtual void EmitAmdhsaKernelDescriptor(const MCSubtargetInfo &STI, StringRef KernelName, const amdhsa::kernel_descriptor_t &KernelDescriptor, uint64_t NextVGPR, uint64_t NextSGPR, bool ReserveVCC, bool ReserveFlatScr, bool ReserveXNACK)=0
Instruction set architecture version.
Definition: TargetParser.h:135
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
#define S_00B84C_SCRATCH_EN(x)
Definition: SIDefines.h:494
const SIInstrInfo * getInstrInfo() const override
#define S_00B84C_TG_SIZE_EN(x)
Definition: SIDefines.h:512
#define S_00B848_DX10_CLAMP(x)
Definition: SIDefines.h:549
#define S_00B848_WGP_MODE(x)
Definition: SIDefines.h:558
uint32_t NumSGPRsForWavesPerEU
Definition: SIProgramInfo.h:49
unsigned const TargetRegisterInfo * TRI
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:684
#define G_00B84C_TGID_Y_EN(x)
Definition: SIDefines.h:507
Interface definition for R600RegisterInfo.
Calling convention used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
unsigned getMinNumSGPRs(unsigned WavesPerEU) const
#define R_0286CC_SPI_PS_INPUT_ENA
Definition: SIDefines.h:530
#define S_00B028_SGPRS(x)
Definition: SIDefines.h:491
AsmPrinter * createR600AsmPrinterPass(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer)
Track resource usage for kernels / entry functions.
Definition: SIProgramInfo.h:21
void setEntryPoint(unsigned CC, StringRef Name)
virtual void EmitAMDGPUSymbolType(StringRef SymbolName, unsigned Type)=0
const SIRegisterInfo & getRegisterInfo() const
Definition: SIInstrInfo.h:168
return AArch64::GPR64RegClass contains(Reg)
bool hasFP64Denormals() const
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0&#39;s from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:119
static amd_element_byte_size_t getElementByteSizeValue(unsigned Size)
#define S_00B848_MEM_ORDERED(x)
Definition: SIDefines.h:561
#define FP_DENORM_FLUSH_NONE
Definition: SIDefines.h:583
Calling convention used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
uint32_t code_properties
Code properties.
Definition: BitVector.h:937
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
static bool isFLAT(const MachineInstr &MI)
Definition: SIInstrInfo.h:485
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
const HexagonInstrInfo * TII
int getLocalMemorySize() const
AMD Kernel Code Object (amd_kernel_code_t).
static void printRegOperand(unsigned RegNo, raw_ostream &O, const MCRegisterInfo &MRI)
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
#define G_00B84C_TRAP_HANDLER(x)
Definition: SIDefines.h:501
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
AMDGPUAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:410
bool isTrapHandlerEnabled() const
#define FP_ROUND_MODE_SP(x)
Definition: SIDefines.h:577
Diagnostic information for stack size etc.
#define S_00B84C_TGID_Y_EN(x)
Definition: SIDefines.h:506
bool hasCodeObjectV3(const MCSubtargetInfo *STI)
Context object for machine code objects.
Definition: MCContext.h:62
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:273
#define S_00B848_FLOAT_MODE(x)
Definition: SIDefines.h:543
#define R_00B848_COMPUTE_PGM_RSRC1
Definition: SIDefines.h:533
uint8_t kernarg_segment_alignment
The maximum byte alignment of variables used by the kernel in the specified memory segment...
void EmitFunctionBody()
This method emits the body and trailer for a function.
virtual bool EmitCodeEnd()=0
unsigned getNumExtraSGPRs(const MCSubtargetInfo *STI, bool VCCUsed, bool FlatScrUsed, bool XNACKUsed)
unsigned getAddressableNumSGPRs() const
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, unsigned OperandName) const
Returns the operand named Op.
bool isGroupSegment(const GlobalValue *GV)
#define S_00B84C_TRAP_HANDLER(x)
Definition: SIDefines.h:500
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
uint64_t ComputePGMRSrc2
Definition: SIProgramInfo.h:41
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:199
uint64_t compute_pgm_resource_registers
Shader program settings for CS.
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool dumpCode() const
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
uint32_t NumVGPRsForWavesPerEU
Definition: SIProgramInfo.h:52
bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const override
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
bool hasFP32Denormals() const
#define S_00B848_IEEE_MODE(x)
Definition: SIDefines.h:555
bool isCompute(CallingConv::ID cc)
#define S_00B028_VGPRS(x)
Definition: SIDefines.h:490
static uint32_t getFPMode(const MachineFunction &F)
uint16_t wavefront_sgpr_count
Number of scalar registers used by a wavefront.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
unsigned const MachineRegisterInfo * MRI
bool isGFX10(const MCSubtargetInfo &STI)
AMDGPUPALMetadata * getPALMetadata()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
#define G_00B84C_TGID_X_EN(x)
Definition: SIDefines.h:504
#define S_00B84C_TIDIG_COMP_CNT(x)
Definition: SIDefines.h:515
#define FP_ROUND_MODE_DP(x)
Definition: SIDefines.h:578
Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:207
const GlobalValue * getGlobal() const
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
bool isEntryFunctionCC(CallingConv::ID CC)
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:437
void EmitEndOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the end of their file...
bool isCuModeEnabled() const
#define S_00B84C_EXCP_EN_MSB(x)
Definition: SIDefines.h:519
bool DX10Clamp
Used by the vector ALU to force DX10-style treatment of NaNs: when set, clamp NaN to zero; otherwise...
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Generation getGeneration() const
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
const Triple & getTargetTriple() const
#define R_00B02C_SPI_SHADER_PGM_RSRC2_PS
Definition: SIDefines.h:482
#define FP_DENORM_FLUSH_IN_FLUSH_OUT
Definition: SIDefines.h:580
#define S_00B84C_TGID_Z_EN(x)
Definition: SIDefines.h:509
The AMDGPU TargetMachine interface definition for hw codgen targets.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
#define R_00B328_SPI_SHADER_PGM_RSRC1_ES
Definition: SIDefines.h:486
#define S_00B84C_LDS_SIZE(x)
Definition: SIDefines.h:523
void EmitBasicBlockStart(const MachineBasicBlock &MBB) const override
Targets can override this to emit stuff at the start of a basic block.
#define R_SPILLED_SGPRS
Definition: SIDefines.h:606
virtual void EmitDirectiveHSACodeObjectISA(uint32_t Major, uint32_t Minor, uint32_t Stepping, StringRef VendorName, StringRef ArchName)=0
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:498
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
amd_element_byte_size_t
The values used to define the number of bytes to use for the swizzle element size.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
Definition: CallingConv.h:188
#define FP_ROUND_ROUND_TO_NEAREST
Definition: SIDefines.h:570
bool doesNotRecurse() const
Determine if the function is known not to recurse, directly or indirectly.
Definition: Function.h:569
#define S_00B84C_EXCP_EN(x)
Definition: SIDefines.h:526
void LLVMInitializeAMDGPUAsmPrinter()
IsaVersion getIsaVersion(StringRef GPU)
unsigned getWavefrontSize() const
#define R_00B428_SPI_SHADER_PGM_RSRC1_HS
Definition: SIDefines.h:487
AMDGPUTargetStreamer * getTargetStreamer() const
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:209
#define G_00B84C_TIDIG_COMP_CNT(x)
Definition: SIDefines.h:516
MCStreamer & getStreamer()
Definition: MCStreamer.h:91
std::vector< std::string > HexLines
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1173
#define R_00B128_SPI_SHADER_PGM_RSRC1_VS
Definition: SIDefines.h:484
uint64_t kernarg_segment_byte_size
The size in bytes of the kernarg segment that holds the values of the arguments to the kernel...
unsigned getTotalNumSGPRs(const MCSubtargetInfo *STI)
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:212
R600 Assembly printer class.
MachineOperand class - Representation of each machine instruction operand.
const MCSubtargetInfo * getMCSubtargetInfo() const
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
Calling convention used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
virtual void EmitAMDKernelCodeT(const amd_kernel_code_t &Header)=0
uint16_t workitem_vgpr_count
Number of vector registers used by each work-item.
bool hasSGPRInitBug() const
#define S_00B848_DEBUG_MODE(x)
Definition: SIDefines.h:552
#define FP_DENORM_MODE_DP(x)
Definition: SIDefines.h:589
#define S_0286E8_WAVESIZE(x)
Definition: SIDefines.h:595
const Function & getFunction() const
Return the LLVM function that this machine code represents.
#define S_00B84C_TGID_X_EN(x)
Definition: SIDefines.h:503
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
bool isPhysRegUsed(unsigned PhysReg) const
Return true if the specified register is modified or read in this function.
uint32_t workgroup_group_segment_byte_size
The amount of group segment memory required by a work-group in bytes.
#define AMD_HSA_BITS_SET(dst, mask, val)
amdgpu Simplify well known AMD library false FunctionCallee Callee
std::vector< std::string > DisasmLines
virtual void EmitDirectiveHSACodeObjectVersion(uint32_t Major, uint32_t Minor)=0
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:200
unsigned getNumVGPRBlocks(const MCSubtargetInfo *STI, unsigned NumVGPRs, Optional< bool > EnableWavefrontSize32)
void EmitFunctionEntryLabel() override
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
static AsmPrinter * createAMDGPUAsmPrinterPass(TargetMachine &tm, std::unique_ptr< MCStreamer > &&Streamer)
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
#define Success
Calling convention used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:215
virtual bool EmitISAVersion(StringRef IsaVersionString)=0
Provides AMDGPU specific target descriptions.
Representation of each machine instruction.
Definition: MachineInstr.h:63
void EmitFunctionBodyStart() override
Targets can override this to emit stuff before the first basic block in the function.
virtual void EmitDirectiveAMDGCNTarget(StringRef Target)=0
bool doFinalization(Module &M) override
Shut down the asmprinter.
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Interface definition for SIInstrInfo.
void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getNumSGPRBlocks(const MCSubtargetInfo *STI, unsigned NumSGPRs)
#define S_00B848_SGPRS(x)
Definition: SIDefines.h:537
virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const
Targets can override this to emit stuff at the start of a basic block.
bool hasXNACK(const MCSubtargetInfo &STI)
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
uint32_t workitem_private_segment_byte_size
The amount of memory required for the combined private, spill and arg segments for a work-item in byt...
#define S_00B84C_USER_SGPR(x)
Definition: SIDefines.h:497
#define I(x, y, z)
Definition: MD5.cpp:58
AMDGPU Assembly printer class.
#define R_00B860_COMPUTE_TMPRING_SIZE
Definition: SIDefines.h:591
Generic base class for all target subtargets.
bool isAmdHsaOrMesa(const Function &F) const
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
uint32_t Size
Definition: Profile.cpp:46
#define R_SPILLED_VGPRS
Definition: SIDefines.h:607
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, const SIInstrInfo &TII, unsigned Reg)
virtual void EmitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:740
bool isReg() const
isReg - Tests if this is a MO_Register operand.
unsigned getMinNumVGPRs(unsigned WavesPerEU) const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:227
static unsigned getRsrcReg(CallingConv::ID CallConv)
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
unsigned getMaxNumUserSGPRs() const
#define S_00B860_WAVESIZE(x)
Definition: SIDefines.h:592
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define R_00B84C_COMPUTE_PGM_RSRC2
Definition: SIDefines.h:493
#define S_00B848_PRIORITY(x)
Definition: SIDefines.h:540
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
void EmitStartOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the start of their fi...
uint64_t ComputePGMRSrc1
Definition: SIProgramInfo.h:35
#define R_0286E8_SPI_TMPRING_SIZE
Definition: SIDefines.h:594
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
void setAlignment(unsigned A)
setAlignment - Set the alignment (log2, not bytes) of the function.
unsigned getHWRegIndex(unsigned Reg) const
#define S_00B02C_EXTRA_LDS_SIZE(x)
Definition: SIDefines.h:483
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
static void RegisterAsmPrinter(Target &T, Target::AsmPrinterCtorTy Fn)
RegisterAsmPrinter - Register an AsmPrinter implementation for the given target.
IRTranslator LLVM IR MI
#define R_00B528_SPI_SHADER_PGM_RSRC1_LS
Definition: SIDefines.h:488
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
AMDGPU metadata definitions and in-memory representations.
#define R_0286D0_SPI_PS_INPUT_ADDR
Definition: SIDefines.h:531
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:415
void initDefaultAMDKernelCodeT(amd_kernel_code_t &Header, const MCSubtargetInfo *STI)
const uint64_t Version
Definition: InstrProf.h:984
Calling convention used for AMDPAL shader stage before geometry shader if geometry is in use...
Definition: CallingConv.h:220
MCCodeEmitter * getEmitterPtr() const
Definition: MCAssembler.h:288
SPIR_KERNEL - Calling convention for SPIR kernel functions.
Definition: CallingConv.h:136
void streamIsaVersion(const MCSubtargetInfo *STI, raw_ostream &Stream)
Streams isa version string for given subtarget STI into Stream.
iterator_range< arg_iterator > args()
Definition: Function.h:705
bool hasCodeObjectV3() const