LLVM 24.0.0git
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"
23#include "AMDGPUTargetMachine.h"
24#include "GCNSubtarget.h"
29#include "R600AsmPrinter.h"
43#include "llvm/MC/MCAssembler.h"
44#include "llvm/MC/MCContext.h"
46#include "llvm/MC/MCStreamer.h"
47#include "llvm/MC/MCValue.h"
54
55using namespace llvm;
56using namespace llvm::AMDGPU;
57
58// This should get the default rounding mode from the kernel. We just set the
59// default here, but this could change if the OpenCL rounding mode pragmas are
60// used.
61//
62// The denormal mode here should match what is reported by the OpenCL runtime
63// for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
64// can also be override to flush with the -cl-denorms-are-zero compiler flag.
65//
66// AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
67// precision, and leaves single precision to flush all and does not report
68// CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
69// CL_FP_DENORM for both.
70//
71// FIXME: It seems some instructions do not support single precision denormals
72// regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
73// and sin_f32, cos_f32 on most parts).
74
75// We want to use these instructions, and using fp32 denormals also causes
76// instructions to run at the double precision rate for the device so it's
77// probably best to just report no single precision denormals.
84
85static AsmPrinter *
87 std::unique_ptr<MCStreamer> &&Streamer) {
88 return new AMDGPUAsmPrinter(tm, std::move(Streamer));
89}
90
100
101namespace {
102class AMDGPUAsmPrinterHandler : public AsmPrinterHandler {
103protected:
104 AMDGPUAsmPrinter *Asm;
105
106public:
107 AMDGPUAsmPrinterHandler(AMDGPUAsmPrinter *A) : Asm(A) {}
108
109 void beginFunction(const MachineFunction *MF) override {}
110
111 void endFunction(const MachineFunction *MF) override { Asm->endFunction(MF); }
112
113 void endModule() override {}
114};
115} // End anonymous namespace
116
118 std::unique_ptr<MCStreamer> Streamer)
120 assert(OutStreamer && "AsmPrinter constructed without streamer");
121 // AMDGPU describes a pointer's address space with its own attribute rather
122 // than DW_AT_address_class.
123 TypeAddressSpaceAttribute = dwarf::DW_AT_LLVM_address_space;
126 if (auto *ResourceUsageW =
128 return &ResourceUsageW->getResourceInfo();
129 return nullptr;
130 };
131}
132
134 return "AMDGPU Assembly Printer";
135}
136
138 return &TM.getMCSubtargetInfo();
139}
140
142 if (!OutStreamer)
143 return nullptr;
144 return static_cast<AMDGPUTargetStreamer *>(OutStreamer->getTargetStreamer());
145}
146
150
151void AMDGPUAsmPrinter::initTargetStreamer(Module &M) {
153
154 // TODO: Which one is called first, emitStartOfAsmFile or
155 // emitFunctionBodyStart?
156 if (getTargetStreamer() && !getTargetStreamer()->getTargetID())
157 initializeTargetID(M);
158
159 const Triple &TT = M.getTargetTriple();
160 if (TT.getOS() != Triple::AMDHSA && TT.getOS() != Triple::AMDPAL)
161 return;
162
164
165 if (TT.getOS() == Triple::AMDHSA) {
167 CodeObjectVersion);
168 HSAMetadataStream->begin(M, *getTargetStreamer()->getTargetID());
169 }
170
171 if (TT.getOS() == Triple::AMDPAL)
173}
174
176 // Init target streamer if it has not yet happened
178 initTargetStreamer(M);
179
180 const Triple &TT = M.getTargetTriple();
181 if (TT.getOS() != Triple::AMDHSA)
183
184 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
185 // Emit HSA Metadata (NT_AMD_HSA_METADATA).
186 if (TT.getOS() == Triple::AMDHSA) {
187 HSAMetadataStream->end();
188 bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
189 (void)Success;
190 assert(Success && "Malformed HSA Metadata");
191 }
192}
193
195 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
196 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
197 const Function &F = MF->getFunction();
198
199 // TODO: We're checking this late, would be nice to check it earlier.
200 if (STM.requiresCodeObjectV6() && CodeObjectVersion < AMDGPU::AMDHSA_COV6) {
202 STM.getCPU() + " is only available on code object version 6 or better");
203 }
204
205 // TODO: Which one is called first, emitStartOfAsmFile or
206 // emitFunctionBodyStart?
207 if (!getTargetStreamer()->getTargetID())
208 initializeTargetID(*F.getParent());
209
210 if (!MFI.isEntryFunction())
211 return;
212
213 if (STM.isMesaKernel(F) &&
214 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
215 F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
216 AMDGPUMCKernelCodeT KernelCode;
217 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
218 KernelCode.validate(&STM, MF->getContext());
220 }
221
222 if (STM.isAmdHsaOS())
223 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
224}
225
226/// Set bits in a kernel descriptor MCExpr field:
227/// return ((Dst & ~Mask) | (Value << Shift))
228static const MCExpr *setBits(const MCExpr *Dst, const MCExpr *Value,
229 uint32_t Mask, uint32_t Shift, MCContext &Ctx) {
230 const auto *Shft = MCConstantExpr::create(Shift, Ctx);
231 const auto *Msk = MCConstantExpr::create(Mask, Ctx);
232 Dst = MCBinaryExpr::createAnd(Dst, MCUnaryExpr::createNot(Msk, Ctx), Ctx);
234 Ctx);
235 return Dst;
236}
237
239 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
240 if (!MFI.isEntryFunction())
241 return;
242
243 assert(TM.getTargetTriple().getOS() == Triple::AMDHSA);
244
245 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
246 MCContext &Ctx = MF->getContext();
247
249 getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo);
250
251 // Compute inst_pref_size using MCExpr label subtraction for exact code
252 // size. At this point .Lfunc_end has been emitted (by the base AsmPrinter)
253 // right after the function code, so (Lfunc_end - func_sym) gives the
254 // exact function code size in bytes.
255 if (STM.hasInstPrefSize()) {
256 const MCExpr *CodeSizeExpr = MCBinaryExpr::createSub(
259
260 uint32_t Mask, Shift, Width, CacheLineSize;
261 STM.getInstPrefSizeArgs(Mask, Shift, Width, CacheLineSize);
262 const MCExpr *InstPrefSize =
263 AMDGPUMCExpr::createInstPrefSize(CodeSizeExpr, Ctx);
265 setBits(KD.compute_pgm_rsrc3, InstPrefSize, Mask, Shift, Ctx);
266 }
267
269 auto &Context = Streamer.getContext();
270 auto &ObjectFileInfo = *Context.getObjectFileInfo();
271 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
272
273 Streamer.pushSection();
274 Streamer.switchSection(&ReadOnlySection);
275
276 // CP microcode requires the kernel descriptor to be allocated on 64 byte
277 // alignment.
278 Streamer.emitValueToAlignment(Align(64), 0, 1, 0);
279 ReadOnlySection.ensureMinAlignment(Align(64));
280
281 SmallString<128> KernelName;
282 getNameWithPrefix(KernelName, &MF->getFunction());
284 STM, KernelName, KD, CurrentProgramInfo.NumVGPRsForWavesPerEU,
286 CurrentProgramInfo.NumSGPRsForWavesPerEU,
288 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed,
289 getTargetStreamer()->getTargetID()->isXnackOnOrAny(), Context),
290 Context),
291 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed);
292
293 Streamer.popSection();
294}
295
297 Register RegNo = MI->getOperand(0).getReg();
298
300 raw_svector_ostream OS(Str);
301 OS << "implicit-def: "
302 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
303
304 if (MI->getAsmPrinterFlags() & AMDGPU::SGPR_SPILL)
305 OS << " : SGPR spill to VGPR lane";
306
307 OutStreamer->AddComment(OS.str());
308 OutStreamer->addBlankLine();
309}
310
312 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
314 return;
315 }
316
317 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
318 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
319 if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
320 SmallString<128> SymbolName;
321 getNameWithPrefix(SymbolName, &MF->getFunction()),
324 }
325 if (DumpCodeInstEmitter) {
326 // Disassemble function name label to text.
327 DisasmLines.push_back(MF->getName().str() + ":");
328 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
329 HexLines.emplace_back("");
330 }
331
333}
334
336 if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
337 // Write a line for the basic block label if it is not only fallthrough.
338 DisasmLines.push_back((Twine("BB") + Twine(getFunctionNumber()) + "_" +
339 Twine(MBB.getNumber()) + ":")
340 .str());
341 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
342 HexLines.emplace_back("");
343 }
345}
346
349 if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
350 OutContext.reportError({},
351 Twine(GV->getName()) +
352 ": unsupported initializer for address space");
353 return;
354 }
355
356 const Triple::OSType OS = TM.getTargetTriple().getOS();
357 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) {
359 return;
360 // With object linking, LDS definitions should have been externalized
361 // by earlier passes (e.g. LDS lowering, named barrier lowering).
362 // Only declarations reach here, emitted as SHN_AMDGPU_LDS symbols
363 // so the linker can assign their offsets.
364 assert(GV->isDeclaration() &&
365 "LDS definitions should have been externalized when object "
366 "linking is enabled");
367 }
368
369 MCSymbol *GVSym = getSymbol(GV);
370
371 GVSym->redefineIfPossible();
372 if (GVSym->isDefined() || GVSym->isVariable())
373 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
374 "' is already defined");
375
376 const DataLayout &DL = GV->getDataLayout();
377 uint64_t Size = GV->getGlobalSize(DL);
378 Align Alignment = GV->getAlign().value_or(Align(4));
379
380 emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
381 emitLinkage(GV, GVSym);
382 auto *TS = getTargetStreamer();
383 TS->emitAMDGPULDS(GVSym, Size, Alignment);
384 return;
385 }
386
388}
389
391 const Triple &TT = M.getTargetTriple();
392 if (TT.getSubArch() == Triple::NoSubArch) {
393 Triple::SubArchType SubArch =
395 if (SubArch != Triple::NoSubArch) {
396 Triple Fixed(TT);
397 Fixed.setArch(Triple::amdgpu, SubArch);
398 M.getContext().diagnose(DiagnosticInfoGeneric(
399 "codegen with no subarch in the target triple is deprecated and will "
400 "become an error; use the target triple '" +
401 Fixed.str() + "' instead",
402 DS_Warning));
403 } else {
404 M.getContext().diagnose(DiagnosticInfoGeneric(
405 "codegen with no subarch in the target triple is deprecated and will "
406 "become an error",
407 DS_Warning));
408 }
409 }
410
411 CodeObjectVersion = AMDGPU::getAMDHSACodeObjectVersion(M);
412
413 if (TT.getOS() == Triple::AMDHSA) {
414 const AMDGPUOptions &CLOpts =
415 static_cast<const AMDGPUTargetMachine &>(TM).getCLOpts();
416 switch (CodeObjectVersion) {
418 HSAMetadataStream =
419 std::make_unique<HSAMD::MetadataStreamerMsgPackV4>(CLOpts);
420 break;
422 HSAMetadataStream =
423 std::make_unique<HSAMD::MetadataStreamerMsgPackV5>(CLOpts);
424 break;
426 HSAMetadataStream =
427 std::make_unique<HSAMD::MetadataStreamerMsgPackV6>(CLOpts);
428 break;
429 default:
430 reportFatalUsageError("unsupported code object version");
431 }
432
433 addAsmPrinterHandler(std::make_unique<AMDGPUAsmPrinterHandler>(this));
434 }
435
437}
438
439/// Mimics GCNSubtarget::computeOccupancy for MCExpr.
440///
441/// Remove dependency on GCNSubtarget and depend only only the necessary values
442/// for said occupancy computation. Should match computeOccupancy implementation
443/// without passing \p STM on.
444const AMDGPUMCExpr *createOccupancy(unsigned InitOcc, const MCExpr *NumSGPRs,
445 const MCExpr *NumVGPRs,
446 unsigned DynamicVGPRBlockSize,
447 const GCNSubtarget &STM, MCContext &Ctx) {
448 unsigned MaxWaves = STM.getMaxWavesPerEU();
449 unsigned Granule = IsaInfo::getVGPRAllocGranule(STM, DynamicVGPRBlockSize);
450 unsigned TargetTotalNumVGPRs = STM.getTotalNumVGPRs();
451
452 // Bake the per-function SGPR budget into the operands so the late-evaluated
453 // MCExpr stays arithmetic. The trap reservation in particular is implicit on
454 // amdhsa and lives on STM, not on the assembler's MCSubtargetInfo.
456 unsigned SGPRTotal = AMDGPU::getTotalNumSGPRs(Kind);
457 unsigned SGPRGranule = AMDGPU::getSGPRAllocGranule(Kind);
458 unsigned SGPRTrapReserve = STM.hasTrapHandler() ? IsaInfo::TRAP_NUM_SGPRS : 0;
459
460 auto CreateExpr = [&Ctx](unsigned Value) {
461 return MCConstantExpr::create(Value, Ctx);
462 };
463
464 // Zero SGPR count when SGPRs don't limit occupancy, so the MCExpr skips the
465 // SGPR term without having to test the generation itself.
466 const MCExpr *SGPRArg =
467 IsaInfo::isSGPROccupancyLimited(STM) ? NumSGPRs : CreateExpr(0);
468
470 {CreateExpr(MaxWaves), CreateExpr(Granule),
471 CreateExpr(TargetTotalNumVGPRs),
472 CreateExpr(InitOcc), CreateExpr(SGPRTotal),
473 CreateExpr(SGPRGranule),
474 CreateExpr(SGPRTrapReserve), SGPRArg, NumVGPRs},
475 Ctx);
476}
477
478// Diagnoses an "amdgpu-waves-per-eu" request that the final occupancy does not
479// meet. Returns true if a diagnostic was emitted.
481 const SIMachineFunctionInfo &MFI,
482 uint64_t Occupancy) {
483 const auto [MinWEU, MaxWEU] =
484 AMDGPU::getIntegerPairAttribute(F, "amdgpu-waves-per-eu", {0, 0}, true);
485 std::string Desired;
486 if (Occupancy < MinWEU) {
487 Desired = std::to_string(MinWEU);
488 } else if (MaxWEU != 0 && Occupancy > MaxWEU &&
489 MFI.getMaxWavesPerEU() > MaxWEU) {
490 // The requested maximum was not applied: a request whose minimum is below
491 // what the workgroup size requires is ignored in favor of the default
492 // range. An applied maximum always caps the effective maximum, so this
493 // does not fire when the occupancy merely exceeds a requested maximum that
494 // register usage cannot enforce.
495 Desired = "at most " + std::to_string(MaxWEU);
496 } else {
497 return false;
498 }
500 F, F.getSubprogram(),
501 "failed to meet occupancy target given by 'amdgpu-waves-per-eu' in '" +
502 F.getName() + "': desired occupancy was " + Desired +
503 ", final occupancy is " + Twine(Occupancy));
504 F.getContext().diagnose(Diag);
505 return true;
506}
507
508void AMDGPUAsmPrinter::validateMCResourceInfo(Function &F) {
509 if (F.isDeclaration() || !AMDGPU::isModuleEntryFunctionCC(F.getCallingConv()))
510 return;
511
513 const GCNSubtarget &STM = TM.getSubtarget<GCNSubtarget>(F);
514 MCSymbol *FnSym = TM.getSymbol(&F);
515
516 auto TryGetMCExprValue = [](const MCExpr *Value, uint64_t &Res) -> bool {
517 int64_t Val;
518 if (Value->evaluateAsAbsolute(Val)) {
519 Res = Val;
520 return true;
521 }
522 return false;
523 };
524
525 const uint64_t MaxScratchPerWorkitem =
527 MCSymbol *ScratchSizeSymbol =
528 RI.getSymbol(FnSym->getName(), RIK::RIK_PrivateSegSize, OutContext);
529 uint64_t ScratchSize;
530 if (ScratchSizeSymbol->isVariable() &&
531 TryGetMCExprValue(ScratchSizeSymbol->getVariableValue(), ScratchSize) &&
532 ScratchSize > MaxScratchPerWorkitem) {
533 DiagnosticInfoStackSize DiagStackSize(F, ScratchSize, MaxScratchPerWorkitem,
534 DS_Error);
535 F.getContext().diagnose(DiagStackSize);
536 }
537
538 // Validate addressable scalar registers (i.e., prior to added implicit
539 // SGPRs).
540 MCSymbol *NumSGPRSymbol =
541 RI.getSymbol(FnSym->getName(), RIK::RIK_NumSGPR, OutContext);
543 !STM.hasSGPRInitBug()) {
544 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
545 uint64_t NumSgpr;
546 if (NumSGPRSymbol->isVariable() &&
547 TryGetMCExprValue(NumSGPRSymbol->getVariableValue(), NumSgpr) &&
548 NumSgpr > MaxAddressableNumSGPRs) {
549 F.getContext().diagnose(DiagnosticInfoResourceLimit(
550 F, "addressable scalar registers", NumSgpr, MaxAddressableNumSGPRs,
552 return;
553 }
554 }
555
556 MCSymbol *VCCUsedSymbol =
557 RI.getSymbol(FnSym->getName(), RIK::RIK_UsesVCC, OutContext);
558 MCSymbol *FlatUsedSymbol =
559 RI.getSymbol(FnSym->getName(), RIK::RIK_UsesFlatScratch, OutContext);
560 uint64_t VCCUsed, FlatUsed, NumSgpr;
561
562 if (NumSGPRSymbol->isVariable() && VCCUsedSymbol->isVariable() &&
563 FlatUsedSymbol->isVariable() &&
564 TryGetMCExprValue(NumSGPRSymbol->getVariableValue(), NumSgpr) &&
565 TryGetMCExprValue(VCCUsedSymbol->getVariableValue(), VCCUsed) &&
566 TryGetMCExprValue(FlatUsedSymbol->getVariableValue(), FlatUsed)) {
567
568 // Recomputes NumSgprs + implicit SGPRs but all symbols should now be
569 // resolvable.
570 NumSgpr += IsaInfo::getNumExtraSGPRs(
571 STM, VCCUsed, FlatUsed,
572 getTargetStreamer()->getTargetID()->isXnackOnOrAny());
574 STM.hasSGPRInitBug()) {
575 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
576 if (NumSgpr > MaxAddressableNumSGPRs) {
577 F.getContext().diagnose(DiagnosticInfoResourceLimit(
578 F, "scalar registers", NumSgpr, MaxAddressableNumSGPRs, DS_Error,
580 return;
581 }
582 }
583
584 MCSymbol *NumVgprSymbol =
585 RI.getSymbol(FnSym->getName(), RIK::RIK_NumVGPR, OutContext);
586 MCSymbol *NumAgprSymbol =
587 RI.getSymbol(FnSym->getName(), RIK::RIK_NumAGPR, OutContext);
588 uint64_t NumVgpr, NumAgpr;
589
590 MachineModuleInfo &MMI = *GetMMI();
591 MachineFunction *MF = MMI.getMachineFunction(F);
592 if (MF && NumVgprSymbol->isVariable() && NumAgprSymbol->isVariable() &&
593 TryGetMCExprValue(NumVgprSymbol->getVariableValue(), NumVgpr) &&
594 TryGetMCExprValue(NumAgprSymbol->getVariableValue(), NumAgpr)) {
595 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
596 unsigned MaxWaves = MFI.getMaxWavesPerEU();
597 uint64_t TotalNumVgpr =
598 getTotalNumVGPRs(STM.hasGFX90AInsts(), static_cast<uint32_t>(NumAgpr),
599 static_cast<uint32_t>(NumVgpr));
600 uint64_t NumVGPRsForWavesPerEU =
601 std::max({TotalNumVgpr, (uint64_t)1,
603 MaxWaves, MFI.getDynamicVGPRBlockSize())});
604 uint64_t NumSGPRsForWavesPerEU = std::max(
605 {NumSgpr, (uint64_t)1, (uint64_t)STM.getMinNumSGPRs(MaxWaves)});
606 const MCExpr *OccupancyExpr = createOccupancy(
607 STM.getOccupancyWithWorkGroupSizes(*MF).second,
608 MCConstantExpr::create(NumSGPRsForWavesPerEU, OutContext),
609 MCConstantExpr::create(NumVGPRsForWavesPerEU, OutContext),
611 uint64_t Occupancy;
612 if (TryGetMCExprValue(OccupancyExpr, Occupancy) &&
613 diagnoseUnmetWavesPerEU(F, MFI, Occupancy))
614 return;
615 }
616 }
617}
618
619static void appendTypeEncoding(std::string &Enc, Type *Ty, const DataLayout &DL,
620 bool IsReturnType) {
621 if (Ty->isVoidTy()) {
622 Enc += 'v';
623 return;
624 }
625 uint64_t Bits = DL.getTypeSizeInBits(Ty);
626 // Zero-sized non-void types (e.g. `{}` or `[0 x i8]`) consume no ABI
627 // registers. For returns, emit the same no-result marker as void so the
628 // parameter encoding still has an explicit return-type prefix.
629 if (Bits == 0) {
630 if (IsReturnType)
631 Enc += 'v';
632 return;
633 }
634 if (Bits <= 32)
635 Enc += 'i';
636 else if (Bits <= 64)
637 Enc += 'l';
638 else
639 Enc.append(divideCeil(Bits, 32), 'i');
640}
641
642static std::string computeTypeId(const FunctionType *FTy,
643 const DataLayout &DL) {
644 std::string Enc;
645 appendTypeEncoding(Enc, FTy->getReturnType(), DL, /*IsReturnType=*/true);
646 for (Type *ParamTy : FTy->params())
647 appendTypeEncoding(Enc, ParamTy, DL, /*IsReturnType=*/false);
648 return Enc;
649}
650
651void AMDGPUAsmPrinter::collectCallEdge(const MachineInstr &MI) {
653 return;
654 const SIInstrInfo *TII = MF->getSubtarget<GCNSubtarget>().getInstrInfo();
655 const MachineOperand *Callee =
656 TII->getNamedOperand(MI, AMDGPU::OpName::callee);
657 if (!Callee || !Callee->isGlobal())
658 return;
659 DirectCallEdges.insert(
660 {getSymbol(&MF->getFunction()), getSymbol(Callee->getGlobal())});
661}
662
663void AMDGPUAsmPrinter::emitAMDGPUInfo(Module &M) {
665 return;
666
667 const NamedMDNode *LDSMD = M.getNamedMetadata("amdgpu.lds.uses");
668 bool HasLDSUses = LDSMD && LDSMD->getNumOperands() > 0;
669
670 const NamedMDNode *BarMD = M.getNamedMetadata("amdgpu.named_barrier.uses");
671 bool HasNamedBarriers = BarMD && BarMD->getNumOperands() > 0;
672
673 // Collect address-taken functions (with type IDs) and indirect call sites.
674 DenseMap<const Function *, std::string> AddrTakenTypeIds;
675 using IndirectCallInfo = std::pair<const Function *, std::string>;
677
678 for (const Function &F : M) {
679 bool IsKernel = AMDGPU::isKernel(F.getCallingConv());
680
681 if (!IsKernel && F.hasAddressTaken(/*PutOffender=*/nullptr,
682 /*IgnoreCallbackUses=*/false,
683 /*IgnoreAssumeLikeCalls=*/true,
684 /*IgnoreLLVMUsed=*/true)) {
685 AddrTakenTypeIds[&F] =
686 computeTypeId(F.getFunctionType(), M.getDataLayout());
687 }
688
689 if (F.isDeclaration())
690 continue;
691
692 StringSet<> SeenTypeIds;
693 for (const BasicBlock &BB : F) {
694 for (const Instruction &I : BB) {
695 const auto *CB = dyn_cast<CallBase>(&I);
696 if (!CB || !CB->isIndirectCall())
697 continue;
698 std::string TId =
699 computeTypeId(CB->getFunctionType(), M.getDataLayout());
700 if (SeenTypeIds.insert(TId).second)
701 IndirectCalls.push_back({&F, std::move(TId)});
702 }
703 }
704 }
705
706 if (FunctionInfos.empty() && DirectCallEdges.empty() && !HasLDSUses &&
707 !HasNamedBarriers && AddrTakenTypeIds.empty() && IndirectCalls.empty())
708 return;
709
710 AMDGPU::InfoSectionData Data;
711 Data.Funcs = std::move(FunctionInfos);
712
713 for (auto &[F, TypeId] : AddrTakenTypeIds) {
714 MCSymbol *Sym = getSymbol(F);
715 Data.TypeIds.push_back({Sym, TypeId});
716 }
717
718 for (auto &[CallerSym, CalleeSym] : DirectCallEdges)
719 Data.Calls.push_back({CallerSym, CalleeSym});
720 DirectCallEdges.clear();
721
722 if (HasLDSUses) {
723 for (const MDNode *N : LDSMD->operands()) {
724 auto *Func = mdconst::extract<Function>(N->getOperand(0));
725 auto *LdsVar = mdconst::extract<GlobalVariable>(N->getOperand(1));
726 Data.Uses.push_back({getSymbol(Func), getSymbol(LdsVar)});
727 }
728 }
729
730 if (HasNamedBarriers) {
731 for (const MDNode *N : BarMD->operands()) {
732 auto *BarVar = mdconst::extract<GlobalVariable>(N->getOperand(0));
733 MCSymbol *BarSym = getSymbol(BarVar);
734 for (unsigned I = 1, E = N->getNumOperands(); I < E; ++I) {
735 auto *Func = mdconst::extract<Function>(N->getOperand(I));
736 Data.Uses.push_back({getSymbol(Func), BarSym});
737 }
738 }
739 }
740
741 for (auto &[Caller, Enc] : IndirectCalls) {
742 MCSymbol *CallerSym = getSymbol(Caller);
743 Data.IndirectCalls.push_back({CallerSym, Enc});
744 }
745
747}
748
750 const Triple &TT = M.getTargetTriple();
751
752 // Pad with s_code_end to help tools and guard against instruction prefetch
753 // causing stale data in caches. Arguably this should be done by the linker,
754 // which is why this isn't done for Mesa.
755 // Don't do it if there is no code.
756 const MCSubtargetInfo &STI = *getGlobalSTI();
757 if ((AMDGPU::isGFX10Plus(STI) || AMDGPU::isGFX90A(STI)) &&
758 (TT.getOS() == Triple::AMDHSA || TT.getOS() == Triple::AMDPAL)) {
760 if (TextSect->hasInstructions()) {
761 OutStreamer->switchSection(TextSect);
763 }
764 }
765
766 // Emit the unified .amdgpu.info section (per-function resources, call graph,
767 // LDS/named-barrier use edges, indirect calls, and address-taken type IDs).
768 emitAMDGPUInfo(M);
769
770 // Assign expressions which can only be resolved when all other functions are
771 // known.
772 RI.finalize(OutContext);
773
774 // Switch section and emit all GPR maximums within the processed module.
775 OutStreamer->pushSection();
776 MCSectionELF *MaxGPRSection =
777 OutContext.getELFSection(".AMDGPU.gpr_maximums", ELF::SHT_PROGBITS, 0);
778 OutStreamer->switchSection(MaxGPRSection);
780 RI.getMaxVGPRSymbol(OutContext), RI.getMaxAGPRSymbol(OutContext),
781 RI.getMaxSGPRSymbol(OutContext), RI.getMaxNamedBarrierSymbol(OutContext));
782 OutStreamer->popSection();
783
784 // In the object-linking pipeline per-function resource MCExprs reference
785 // external callee symbols that cannot be evaluated here, so cross-TU limit
786 // checks would silently no-op for every non-leaf function. Defer resource
787 // sanity checking to the linker, which re-validates against the aggregated
788 // call graph in the combined .amdgpu.info metadata.
790 for (Function &F : M.functions())
791 validateMCResourceInfo(F);
792 }
793
794 RI.reset();
795
797}
798
799SmallString<128> AMDGPUAsmPrinter::getMCExprStr(const MCExpr *Value) {
801 raw_svector_ostream OSS(Str);
803 auto &Context = Streamer.getContext();
804 const MCExpr *New = foldAMDGPUMCExpr(Value, Context);
805 printAMDGPUMCExpr(New, OSS, &MAI);
806 return Str;
807}
808
809// Print comments that apply to both callable functions and entry points.
810void AMDGPUAsmPrinter::emitCommonFunctionComments(
811 const MCExpr *NumVGPR, const MCExpr *NumAGPR, const MCExpr *TotalNumVGPR,
812 const MCExpr *NumSGPR, const MCExpr *ScratchSize, uint64_t CodeSize,
813 const AMDGPUMachineFunctionInfo *MFI) {
814 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
815 OutStreamer->emitRawComment(" TotalNumSgprs: " + getMCExprStr(NumSGPR),
816 false);
817 OutStreamer->emitRawComment(" NumVgprs: " + getMCExprStr(NumVGPR), false);
818 if (NumAGPR && TotalNumVGPR) {
819 OutStreamer->emitRawComment(" NumAgprs: " + getMCExprStr(NumAGPR), false);
820 OutStreamer->emitRawComment(" TotalNumVgprs: " + getMCExprStr(TotalNumVGPR),
821 false);
822 }
823 OutStreamer->emitRawComment(" ScratchSize: " + getMCExprStr(ScratchSize),
824 false);
825 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
826 false);
827}
828
829const MCExpr *AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
830 const MachineFunction &MF) const {
831 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
832 MCContext &Ctx = MF.getContext();
833 uint16_t KernelCodeProperties = 0;
834 const GCNUserSGPRUsageInfo &UserSGPRInfo = MFI.getUserSGPRInfo();
835
836 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
837 KernelCodeProperties |=
838 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
839 }
840 if (UserSGPRInfo.hasDispatchPtr()) {
841 KernelCodeProperties |=
842 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
843 }
844 if (UserSGPRInfo.hasQueuePtr()) {
845 KernelCodeProperties |= amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
846 }
847 if (UserSGPRInfo.hasKernargSegmentPtr()) {
848 KernelCodeProperties |=
849 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
850 }
851 if (UserSGPRInfo.hasDispatchID()) {
852 KernelCodeProperties |=
853 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
854 }
855 if (UserSGPRInfo.hasFlatScratchInit()) {
856 KernelCodeProperties |=
857 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
858 }
859 if (UserSGPRInfo.hasPrivateSegmentSize()) {
860 KernelCodeProperties |=
861 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE;
862 }
863 if (MF.getSubtarget<GCNSubtarget>().isWave32()) {
864 KernelCodeProperties |=
865 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
866 }
867
868 const MCExpr *KernelCodePropExpr =
869 MCConstantExpr::create(KernelCodeProperties, Ctx);
870 // The dynamic-stack bit is reserved in code objects before V5.
871 if (CodeObjectVersion < AMDGPU::AMDHSA_COV5)
872 return KernelCodePropExpr;
873
874 // CurrentProgramInfo.DynamicCallStack is a MCExpr and could be
875 // un-evaluatable at this point so it cannot be conditionally checked here.
876 // Instead, we'll directly shift the possibly unknown MCExpr into its place
877 // and bitwise-or it into KernelCodeProperties.
878 const MCExpr *OrValue = MCConstantExpr::create(
879 amdhsa::KERNEL_CODE_PROPERTY_USES_DYNAMIC_STACK_SHIFT, Ctx);
880 OrValue = MCBinaryExpr::createShl(CurrentProgramInfo.DynamicCallStack,
881 OrValue, Ctx);
882 KernelCodePropExpr = MCBinaryExpr::createOr(KernelCodePropExpr, OrValue, Ctx);
883
884 return KernelCodePropExpr;
885}
886
887MCKernelDescriptor
888AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(const MachineFunction &MF,
889 const SIProgramInfo &PI) const {
890 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
891 const Function &F = MF.getFunction();
892 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
893 MCContext &Ctx = MF.getContext();
894
895 MCKernelDescriptor KernelDescriptor;
896
897 KernelDescriptor.group_segment_fixed_size =
899 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
900
901 Align MaxKernArgAlign;
902 KernelDescriptor.kernarg_size = MCConstantExpr::create(
903 STM.getKernArgSegmentSize(F, MaxKernArgAlign), Ctx);
904
905 KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1(STM, Ctx);
906 KernelDescriptor.compute_pgm_rsrc2 = PI.getComputePGMRSrc2(STM, Ctx);
907 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
908
909 int64_t PGM_Rsrc3 = 1;
910 bool EvaluatableRsrc3 =
911 CurrentProgramInfo.ComputePGMRSrc3->evaluateAsAbsolute(PGM_Rsrc3);
912 (void)PGM_Rsrc3;
913 (void)EvaluatableRsrc3;
915 STM.hasGFX90AInsts() || STM.hasGFX1250Insts() || !EvaluatableRsrc3 ||
916 static_cast<uint64_t>(PGM_Rsrc3) == 0);
917 KernelDescriptor.compute_pgm_rsrc3 = CurrentProgramInfo.ComputePGMRSrc3;
918
919 KernelDescriptor.kernarg_preload = MCConstantExpr::create(
920 AMDGPU::hasKernargPreload(STM) ? Info->getNumKernargPreloadedSGPRs() : 0,
921 Ctx);
922
923 return KernelDescriptor;
924}
925
927 // Init target streamer lazily on the first function so that previous passes
928 // can set metadata.
930 initTargetStreamer(*MF.getFunction().getParent());
931
932 ResourceUsage = GetResourceUsage(MF);
933 CurrentProgramInfo.reset(MF);
934
935 const AMDGPUMachineFunctionInfo *MFI =
936 MF.getInfo<AMDGPUMachineFunctionInfo>();
937 MCContext &Ctx = MF.getContext();
938
939 // The starting address of all shader programs must be 256 bytes aligned.
940 // Regular functions just need the basic required instruction alignment.
941 MF.ensureAlignment(MFI->isEntryFunction() ? Align(256) : Align(4));
942
944
945 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
947 // FIXME: This should be an explicit check for Mesa.
948 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
949 MCSectionELF *ConfigSection =
950 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
951 OutStreamer->switchSection(ConfigSection);
952 }
953
954 RI.gatherResourceInfo(MF, *ResourceUsage, OutContext);
955
958 *ResourceUsage;
959 FunctionInfos.push_back(
960 {/*NumSGPR=*/static_cast<uint32_t>(RU.NumExplicitSGPR),
961 /*NumArchVGPR=*/static_cast<uint32_t>(RU.NumVGPR),
962 /*NumAccVGPR=*/static_cast<uint32_t>(RU.NumAGPR),
963 /*PrivateSegmentSize=*/static_cast<uint32_t>(RU.PrivateSegmentSize),
964 /*UsesVCC=*/RU.UsesVCC,
965 /*UsesFlatScratch=*/RU.UsesFlatScratch,
966 /*HasDynStack=*/RU.HasDynamicallySizedStack,
967 /*Sym=*/getSymbol(&MF.getFunction())});
968 }
969
970 if (MFI->isModuleEntryFunction()) {
971 getSIProgramInfo(CurrentProgramInfo, MF);
972 }
973
974 if (STM.isAmdPalOS()) {
975 if (MFI->isEntryFunction())
976 EmitPALMetadata(MF, CurrentProgramInfo);
977 else if (MFI->isModuleEntryFunction())
978 emitPALFunctionMetadata(MF);
979 } else if (!STM.isAmdHsaOS()) {
980 EmitProgramInfoSI(MF, CurrentProgramInfo);
981 }
982
983 DumpCodeInstEmitter = nullptr;
984 if (STM.dumpCode()) {
985 // For -dumpcode, get the assembler out of the streamer. This only works
986 // with -filetype=obj.
987 MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
988 if (Assembler)
989 DumpCodeInstEmitter = Assembler->getEmitterPtr();
990 }
991
992 DisasmLines.clear();
993 HexLines.clear();
995
997
998 emitResourceUsageRemarks(MF, CurrentProgramInfo, MFI->isModuleEntryFunction(),
999 STM.hasMAIInsts());
1000
1001 {
1004 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_NumVGPR, OutContext),
1005 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_NumAGPR, OutContext),
1006 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_NumSGPR, OutContext),
1007 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_NumNamedBarrier,
1008 OutContext),
1009 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_PrivateSegSize,
1010 OutContext),
1011 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_UsesVCC, OutContext),
1012 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_UsesFlatScratch,
1013 OutContext),
1014 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_HasDynSizedStack,
1015 OutContext),
1016 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_HasRecursion,
1017 OutContext),
1018 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_HasIndirectCall,
1019 OutContext));
1020 }
1021
1022 // Emit _dvgpr$ symbol when appropriate.
1023 emitDVgprSymbol(MF);
1024
1025 if (isVerbose()) {
1026 MCSectionELF *CommentSection =
1027 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
1028 OutStreamer->switchSection(CommentSection);
1029
1030 if (!MFI->isEntryFunction()) {
1032 OutStreamer->emitRawComment(" Function info:", false);
1033
1034 emitCommonFunctionComments(
1035 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_NumVGPR, OutContext)
1036 ->getVariableValue(),
1037 STM.hasMAIInsts() ? RI.getSymbol(CurrentFnSym->getName(),
1038 RIK::RIK_NumAGPR, OutContext)
1039 ->getVariableValue()
1040 : nullptr,
1041 RI.createTotalNumVGPRs(MF, Ctx),
1042 RI.createTotalNumSGPRs(
1043 MF,
1044 MF.getSubtarget<GCNSubtarget>().getTargetID().isXnackOnOrAny(),
1045 Ctx),
1046 RI.getSymbol(CurrentFnSym->getName(), RIK::RIK_PrivateSegSize,
1047 OutContext)
1048 ->getVariableValue(),
1049 CurrentProgramInfo.getFunctionCodeSize(MF), MFI);
1050 return false;
1051 }
1052
1053 OutStreamer->emitRawComment(" Kernel info:", false);
1054 emitCommonFunctionComments(
1055 CurrentProgramInfo.NumArchVGPR,
1056 STM.hasMAIInsts() ? CurrentProgramInfo.NumAccVGPR : nullptr,
1057 CurrentProgramInfo.NumVGPR, CurrentProgramInfo.NumSGPR,
1058 CurrentProgramInfo.ScratchSize,
1059 CurrentProgramInfo.getFunctionCodeSize(MF), MFI);
1060
1061 OutStreamer->emitRawComment(
1062 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
1063 OutStreamer->emitRawComment(
1064 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
1065 OutStreamer->emitRawComment(
1066 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
1067 " bytes/workgroup (compile time only)",
1068 false);
1069
1070 OutStreamer->emitRawComment(
1071 " SGPRBlocks: " + getMCExprStr(CurrentProgramInfo.SGPRBlocks), false);
1072
1073 OutStreamer->emitRawComment(
1074 " VGPRBlocks: " + getMCExprStr(CurrentProgramInfo.VGPRBlocks), false);
1075
1076 OutStreamer->emitRawComment(
1077 " NumSGPRsForWavesPerEU: " +
1078 getMCExprStr(CurrentProgramInfo.NumSGPRsForWavesPerEU),
1079 false);
1080 OutStreamer->emitRawComment(
1081 " NumVGPRsForWavesPerEU: " +
1082 getMCExprStr(CurrentProgramInfo.NumVGPRsForWavesPerEU),
1083 false);
1084
1085 if (STM.hasGFX90AInsts()) {
1086 const MCExpr *AdjustedAccum = MCBinaryExpr::createAdd(
1087 CurrentProgramInfo.AccumOffset, MCConstantExpr::create(1, Ctx), Ctx);
1088 AdjustedAccum = MCBinaryExpr::createMul(
1089 AdjustedAccum, MCConstantExpr::create(4, Ctx), Ctx);
1090 OutStreamer->emitRawComment(
1091 " AccumOffset: " + getMCExprStr(AdjustedAccum), false);
1092 }
1093
1094 if (STM.hasGFX1250Insts())
1095 OutStreamer->emitRawComment(
1096 " NamedBarCnt: " + getMCExprStr(CurrentProgramInfo.NamedBarCnt),
1097 false);
1098
1099 OutStreamer->emitRawComment(
1100 " Occupancy: " + getMCExprStr(CurrentProgramInfo.Occupancy), false);
1101
1102 OutStreamer->emitRawComment(
1103 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
1104
1105 OutStreamer->emitRawComment(
1106 " COMPUTE_PGM_RSRC2:SCRATCH_EN: " +
1107 getMCExprStr(CurrentProgramInfo.ScratchEnable),
1108 false);
1109 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:USER_SGPR: " +
1110 Twine(CurrentProgramInfo.UserSGPR),
1111 false);
1112 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
1113 Twine(CurrentProgramInfo.TrapHandlerEnable),
1114 false);
1115 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_X_EN: " +
1116 Twine(CurrentProgramInfo.TGIdXEnable),
1117 false);
1118 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
1119 Twine(CurrentProgramInfo.TGIdYEnable),
1120 false);
1121 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
1122 Twine(CurrentProgramInfo.TGIdZEnable),
1123 false);
1124 OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
1125 Twine(CurrentProgramInfo.TIdIGCompCount),
1126 false);
1127
1128 [[maybe_unused]] int64_t PGMRSrc3;
1130 STM.hasGFX90AInsts() || STM.hasGFX1250Insts() ||
1131 (CurrentProgramInfo.ComputePGMRSrc3->evaluateAsAbsolute(PGMRSrc3) &&
1132 static_cast<uint64_t>(PGMRSrc3) == 0));
1133 if (STM.hasGFX90AInsts()) {
1134 OutStreamer->emitRawComment(
1135 " COMPUTE_PGM_RSRC3_GFX90A:ACCUM_OFFSET: " +
1136 getMCExprStr(MCKernelDescriptor::bits_get(
1137 CurrentProgramInfo.ComputePGMRSrc3,
1138 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET_SHIFT,
1139 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET, Ctx)),
1140 false);
1141 OutStreamer->emitRawComment(
1142 " COMPUTE_PGM_RSRC3_GFX90A:TG_SPLIT: " +
1143 getMCExprStr(MCKernelDescriptor::bits_get(
1144 CurrentProgramInfo.ComputePGMRSrc3,
1145 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT_SHIFT,
1146 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT, Ctx)),
1147 false);
1148 }
1149 }
1150
1151 if (DumpCodeInstEmitter) {
1152
1153 OutStreamer->switchSection(
1154 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0));
1155
1156 for (size_t i = 0; i < DisasmLines.size(); ++i) {
1157 std::string Comment = "\n";
1158 if (!HexLines[i].empty()) {
1159 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
1160 Comment += " ; " + HexLines[i] + "\n";
1161 }
1162
1163 OutStreamer->emitBytes(StringRef(DisasmLines[i]));
1164 OutStreamer->emitBytes(StringRef(Comment));
1165 }
1166 }
1167
1168 return false;
1169}
1170
1171// When appropriate, add a _dvgpr$ symbol, with the value of the function
1172// symbol, plus an offset encoding one less than the number of VGPR blocks used
1173// by the function in bits 5..3 of the symbol value. A "VGPR block" can be
1174// either 16 VGPRs (for a max of 128), or 32 VGPRs (for a max of 256). This is
1175// used by a front-end to have functions that are chained rather than called,
1176// and a dispatcher that dynamically resizes the VGPR count before dispatching
1177// to a function.
1178void AMDGPUAsmPrinter::emitDVgprSymbol(MachineFunction &MF) {
1180 if (MFI.isDynamicVGPREnabled() &&
1182 MCContext &Ctx = MF.getContext();
1183 unsigned BlockSize = MFI.getDynamicVGPRBlockSize();
1184
1185 const MCExpr *EncodedBlocks;
1186 MCValue NumVGPRs;
1187 if (CurrentProgramInfo.NumVGPRsForWavesPerEU->evaluateAsRelocatable(
1188 NumVGPRs, nullptr) &&
1189 NumVGPRs.isAbsolute()) {
1190
1191 // Calculate number of VGPR blocks.
1192 // Treat 0 VGPRs as 1 VGPR to avoid underflowing.
1193 unsigned NumBlocks =
1194 divideCeil(std::max(unsigned(NumVGPRs.getConstant()), 1U), BlockSize);
1195
1196 if (NumBlocks > AMDGPU::IsaInfo::MaxDynamicVGPRBlocks) {
1198 {}, "DVGPR block count " + Twine(NumBlocks) +
1199 " exceeds maximum of " +
1201 " for __dvgpr$ symbol for '" +
1202 Twine(CurrentFnSym->getName()) + "'");
1203 return;
1204 }
1205 unsigned EncodedNumBlocks = (NumBlocks - 1) << 3;
1206 EncodedBlocks = MCConstantExpr::create(EncodedNumBlocks, Ctx);
1207 } else {
1208 // Value not yet available so build a symbolic MCExpr:
1209 // ((alignTo(max(NumVGPRs, 1), BlockSize) / BlockSize - 1) << 3
1210 const MCExpr *One = MCConstantExpr::create(1, Ctx);
1211 const MCExpr *BlockSizeConst = MCConstantExpr::create(BlockSize, Ctx);
1212 const MCExpr *MaxVGPRs = AMDGPUMCExpr::createMax(
1213 {CurrentProgramInfo.NumVGPRsForWavesPerEU, One}, Ctx);
1214 const MCExpr *NumBlocks = MCBinaryExpr::createDiv(
1215 AMDGPUMCExpr::createAlignTo(MaxVGPRs, BlockSizeConst, Ctx),
1216 BlockSizeConst, Ctx);
1217 EncodedBlocks =
1219 MCConstantExpr::create(3, Ctx), Ctx);
1220 }
1221
1222 // Add to function symbol to create _dvgpr$ symbol.
1223 const MCExpr *DVgprFuncVal = MCBinaryExpr::createAdd(
1224 MCSymbolRefExpr::create(CurrentFnSym, Ctx), EncodedBlocks, Ctx);
1225 MCSymbol *DVgprFuncSym =
1226 Ctx.getOrCreateSymbol(Twine("_dvgpr$") + CurrentFnSym->getName());
1227 OutStreamer->emitAssignment(DVgprFuncSym, DVgprFuncVal);
1228 emitVisibility(DVgprFuncSym, MF.getFunction().getVisibility());
1229 emitLinkage(&MF.getFunction(), DVgprFuncSym);
1230 }
1231}
1232
1233// TODO: Fold this into emitFunctionBodyStart.
1234void AMDGPUAsmPrinter::initializeTargetID(const Module &M) {
1236
1237 auto &TSTargetID = getTargetStreamer()->getTargetID();
1238
1239 // Error if -mattr specified xnack or sramecc.
1240 // TODO: Remove this when subtarget features removed.
1241 StringRef FeatureString = getGlobalSTI()->getFeatureString();
1242 if (FeatureString.contains("xnack")) {
1243 M.getContext().diagnose(DiagnosticInfoGeneric(
1244 "xnack/sramecc should be specified via module flags. "
1245 "Use module flag 'amdgpu.xnack' instead of subtarget feature",
1246 DS_Error));
1247 }
1248 if (FeatureString.contains("sramecc")) {
1249 M.getContext().diagnose(DiagnosticInfoGeneric(
1250 "xnack/sramecc should be specified via module flags. "
1251 "Use module flag 'amdgpu.sramecc' instead of subtarget feature",
1252 DS_Error));
1253 }
1254
1255 // Apply xnack/sramecc settings from module flags.
1256 const auto &GCNTM = static_cast<const GCNTargetMachine &>(TM);
1257 if (getGlobalSTI()->getFeatureBits().test(AMDGPU::FeatureXNACKOnOffModes)) {
1258 AMDGPU::TargetIDSetting Setting =
1259 GCNTM.getTargetIDSettingFromModuleFlag(M, "amdgpu.xnack");
1260 if (Setting != AMDGPU::TargetIDSetting::Any)
1261 TSTargetID->setXnackSetting(Setting);
1262 }
1263
1264 if (getGlobalSTI()->getFeatureBits().test(AMDGPU::FeatureSRAMECCOnOffModes)) {
1265 AMDGPU::TargetIDSetting Setting =
1266 GCNTM.getTargetIDSettingFromModuleFlag(M, "amdgpu.sramecc");
1267 if (Setting != AMDGPU::TargetIDSetting::Any)
1268 TSTargetID->setSramEccSetting(Setting);
1269 }
1270}
1271
1272// AccumOffset computed for the MCExpr equivalent of:
1273// alignTo(std::max(1, NumVGPR), 4) / 4 - 1;
1274static const MCExpr *computeAccumOffset(const MCExpr *NumVGPR, MCContext &Ctx) {
1275 const MCExpr *ConstFour = MCConstantExpr::create(4, Ctx);
1276 const MCExpr *ConstOne = MCConstantExpr::create(1, Ctx);
1277
1278 // Can't be lower than 1 for subsequent alignTo.
1279 const MCExpr *MaximumTaken =
1280 AMDGPUMCExpr::createMax({ConstOne, NumVGPR}, Ctx);
1281
1282 // Practically, it's computing divideCeil(MaximumTaken, 4).
1283 const MCExpr *DivCeil = MCBinaryExpr::createDiv(
1284 AMDGPUMCExpr::createAlignTo(MaximumTaken, ConstFour, Ctx), ConstFour,
1285 Ctx);
1286
1287 return MCBinaryExpr::createSub(DivCeil, ConstOne, Ctx);
1288}
1289
1290static unsigned getLDSEncodingGranule(const GCNSubtarget &ST) {
1291 unsigned Granule =
1292 AMDGPU::getLDSEncodingGranule(ST.getTargetID().getGPUKind());
1293 // The legacy generic targets have no encoding granularity feature. Preserve
1294 // the default used for code generation when no GPU is specified.
1295 return Granule ? Granule : 256;
1296}
1297
1298void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
1299 const MachineFunction &MF) {
1300 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1301 MCContext &Ctx = MF.getContext();
1302
1303 auto CreateExpr = [&Ctx](int64_t Value) {
1304 return MCConstantExpr::create(Value, Ctx);
1305 };
1306
1307 auto TryGetMCExprValue = [](const MCExpr *Value, uint64_t &Res) -> bool {
1308 int64_t Val;
1309 if (Value->evaluateAsAbsolute(Val)) {
1310 Res = Val;
1311 return true;
1312 }
1313 return false;
1314 };
1315
1316 auto GetSymRefExpr =
1317 [&](MCResourceInfo::ResourceInfoKind RIK) -> const MCExpr * {
1318 MCSymbol *Sym = RI.getSymbol(CurrentFnSym->getName(), RIK, OutContext);
1319 return MCSymbolRefExpr::create(Sym, Ctx);
1320 };
1321
1323 ProgInfo.NumArchVGPR = GetSymRefExpr(RIK::RIK_NumVGPR);
1324 ProgInfo.NumAccVGPR = GetSymRefExpr(RIK::RIK_NumAGPR);
1326 ProgInfo.NumAccVGPR, ProgInfo.NumArchVGPR, Ctx);
1327
1328 ProgInfo.AccumOffset = computeAccumOffset(ProgInfo.NumArchVGPR, Ctx);
1329 ProgInfo.TgSplit =
1330 STM.hasTgSplitSupport() && AMDGPU::isTgSplitEnabled(MF.getFunction());
1331 ProgInfo.NumSGPR = GetSymRefExpr(RIK::RIK_NumSGPR);
1332 ProgInfo.ScratchSize = GetSymRefExpr(RIK::RIK_PrivateSegSize);
1333 ProgInfo.VCCUsed = GetSymRefExpr(RIK::RIK_UsesVCC);
1334 ProgInfo.FlatUsed = GetSymRefExpr(RIK::RIK_UsesFlatScratch);
1335 ProgInfo.DynamicCallStack =
1336 MCBinaryExpr::createOr(GetSymRefExpr(RIK::RIK_HasDynSizedStack),
1337 GetSymRefExpr(RIK::RIK_HasRecursion), Ctx);
1338
1339 const MCExpr *BarBlkConst = MCConstantExpr::create(4, Ctx);
1340 const MCExpr *AlignToBlk = AMDGPUMCExpr::createAlignTo(
1341 GetSymRefExpr(RIK::RIK_NumNamedBarrier), BarBlkConst, Ctx);
1342 ProgInfo.NamedBarCnt = MCBinaryExpr::createDiv(AlignToBlk, BarBlkConst, Ctx);
1343
1344 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1345
1346 // The calculations related to SGPR/VGPR blocks are
1347 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
1348 // unified.
1349 const MCExpr *ExtraSGPRs = AMDGPUMCExpr::createExtraSGPRs(
1350 ProgInfo.VCCUsed, ProgInfo.FlatUsed,
1351 getTargetStreamer()->getTargetID()->isXnackOnOrAny(), Ctx);
1352
1353 // Check the addressable register limit before we add ExtraSGPRs.
1355 !STM.hasSGPRInitBug()) {
1356 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1357 uint64_t NumSgpr;
1358 if (TryGetMCExprValue(ProgInfo.NumSGPR, NumSgpr) &&
1359 NumSgpr > MaxAddressableNumSGPRs) {
1360 // This can happen due to a compiler bug or when using inline asm.
1361 LLVMContext &Ctx = MF.getFunction().getContext();
1362 Ctx.diagnose(DiagnosticInfoResourceLimit(
1363 MF.getFunction(), "addressable scalar registers", NumSgpr,
1364 MaxAddressableNumSGPRs, DS_Error, DK_ResourceLimit));
1365 ProgInfo.NumSGPR = CreateExpr(MaxAddressableNumSGPRs - 1);
1366 }
1367 }
1368
1369 // Account for extra SGPRs and VGPRs reserved for debugger use.
1370 ProgInfo.NumSGPR = MCBinaryExpr::createAdd(ProgInfo.NumSGPR, ExtraSGPRs, Ctx);
1371
1372 const Function &F = MF.getFunction();
1373
1374 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
1375 // dispatch registers as function args.
1376 unsigned WaveDispatchNumSGPR = MFI->getNumWaveDispatchSGPRs(),
1377 WaveDispatchNumVGPR = MFI->getNumWaveDispatchVGPRs();
1378
1379 if (WaveDispatchNumSGPR) {
1381 {ProgInfo.NumSGPR,
1382 MCBinaryExpr::createAdd(CreateExpr(WaveDispatchNumSGPR), ExtraSGPRs,
1383 Ctx)},
1384 Ctx);
1385 }
1386
1387 if (WaveDispatchNumVGPR) {
1389 {ProgInfo.NumArchVGPR, CreateExpr(WaveDispatchNumVGPR)}, Ctx);
1390
1392 ProgInfo.NumAccVGPR, ProgInfo.NumArchVGPR, Ctx);
1393 }
1394
1395 // Adjust number of registers used to meet default/requested minimum/maximum
1396 // number of waves per execution unit request.
1397 unsigned MaxWaves = MFI->getMaxWavesPerEU();
1398 ProgInfo.NumSGPRsForWavesPerEU =
1399 AMDGPUMCExpr::createMax({ProgInfo.NumSGPR, CreateExpr(1ul),
1400 CreateExpr(STM.getMinNumSGPRs(MaxWaves))},
1401 Ctx);
1402 ProgInfo.NumVGPRsForWavesPerEU =
1403 AMDGPUMCExpr::createMax({ProgInfo.NumVGPR, CreateExpr(1ul),
1404 CreateExpr(STM.getMinNumVGPRs(
1405 MaxWaves, MFI->getDynamicVGPRBlockSize()))},
1406 Ctx);
1407
1409 STM.hasSGPRInitBug()) {
1410 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1411 uint64_t NumSgpr;
1412 if (TryGetMCExprValue(ProgInfo.NumSGPR, NumSgpr) &&
1413 NumSgpr > MaxAddressableNumSGPRs) {
1414 // This can happen due to a compiler bug or when using inline asm to use
1415 // the registers which are usually reserved for vcc etc.
1416 LLVMContext &Ctx = MF.getFunction().getContext();
1417 Ctx.diagnose(DiagnosticInfoResourceLimit(
1418 MF.getFunction(), "scalar registers", NumSgpr, MaxAddressableNumSGPRs,
1420 ProgInfo.NumSGPR = CreateExpr(MaxAddressableNumSGPRs);
1421 ProgInfo.NumSGPRsForWavesPerEU = CreateExpr(MaxAddressableNumSGPRs);
1422 }
1423 }
1424
1425 if (STM.hasSGPRInitBug()) {
1426 ProgInfo.NumSGPR =
1428 ProgInfo.NumSGPRsForWavesPerEU =
1430 }
1431
1432 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
1433 LLVMContext &Ctx = MF.getFunction().getContext();
1434 Ctx.diagnose(DiagnosticInfoResourceLimit(
1435 MF.getFunction(), "user SGPRs", MFI->getNumUserSGPRs(),
1437 }
1438
1439 if (MFI->getLDSSize() > STM.getAddressableLocalMemorySize()) {
1440 LLVMContext &Ctx = MF.getFunction().getContext();
1441 Ctx.diagnose(DiagnosticInfoResourceLimit(
1442 MF.getFunction(), "local memory", MFI->getLDSSize(),
1444 }
1445
1446 // When dynamic VGPRs are enabled, entry functions are launched with a single
1447 // VGPR block. The register allocator enforces this constraint, but we also
1448 // need to catch explicit physical registers in inline asm and wave dispatch
1449 // VGPR arguments.
1450 if (MFI->isDynamicVGPREnabled() &&
1451 AMDGPU::isEntryFunctionCC(F.getCallingConv())) {
1452 unsigned BlockSize = MFI->getDynamicVGPRBlockSize();
1453 uint64_t NumVgpr;
1454 if (TryGetMCExprValue(ProgInfo.NumVGPRsForWavesPerEU, NumVgpr) &&
1455 NumVgpr > BlockSize) {
1456 LLVMContext &Ctx = F.getContext();
1457 Ctx.diagnose(DiagnosticInfoResourceLimit(
1458 F, "dynamic VGPR entry point vector registers", NumVgpr, BlockSize,
1460 }
1461 }
1462
1463 // The MCExpr equivalent of getNumSGPRBlocks/getNumVGPRBlocks:
1464 // (alignTo(max(1u, NumGPR), GPREncodingGranule) / GPREncodingGranule) - 1
1465 auto GetNumGPRBlocks = [&CreateExpr, &Ctx](const MCExpr *NumGPR,
1466 unsigned Granule) {
1467 const MCExpr *OneConst = CreateExpr(1ul);
1468 const MCExpr *GranuleConst = CreateExpr(Granule);
1469 const MCExpr *MaxNumGPR = AMDGPUMCExpr::createMax({NumGPR, OneConst}, Ctx);
1470 const MCExpr *AlignToGPR =
1471 AMDGPUMCExpr::createAlignTo(MaxNumGPR, GranuleConst, Ctx);
1472 const MCExpr *DivGPR =
1473 MCBinaryExpr::createDiv(AlignToGPR, GranuleConst, Ctx);
1474 const MCExpr *SubGPR = MCBinaryExpr::createSub(DivGPR, OneConst, Ctx);
1475 return SubGPR;
1476 };
1477 // GFX10+ will always allocate 128 SGPRs and this field must be 0
1479 ProgInfo.SGPRBlocks = CreateExpr(0ul);
1480 } else {
1481 ProgInfo.SGPRBlocks = GetNumGPRBlocks(ProgInfo.NumSGPRsForWavesPerEU,
1483 }
1484 ProgInfo.VGPRBlocks = GetNumGPRBlocks(ProgInfo.NumVGPRsForWavesPerEU,
1486
1487 const SIModeRegisterDefaults Mode = MFI->getMode();
1488
1489 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
1490 // register.
1491 ProgInfo.FloatMode = getFPMode(Mode);
1492
1493 ProgInfo.IEEEMode = Mode.IEEE;
1494
1495 // Make clamp modifier on NaN input returns 0.
1496 ProgInfo.DX10Clamp = Mode.DX10Clamp;
1497 ProgInfo.SGPRSpill = MFI->getNumSpilledSGPRs();
1498 ProgInfo.VGPRSpill = MFI->getNumSpilledVGPRs();
1499
1500 ProgInfo.LDSSize = MFI->getLDSSize();
1501
1502 unsigned LDSGranularityBytes = getLDSEncodingGranule(STM);
1503 ProgInfo.LDSBlocks =
1504 alignTo(ProgInfo.LDSSize, LDSGranularityBytes) / LDSGranularityBytes;
1505
1506 // The MCExpr equivalent of divideCeil.
1507 auto DivideCeil = [&Ctx](const MCExpr *Numerator, const MCExpr *Denominator) {
1508 const MCExpr *Ceil =
1509 AMDGPUMCExpr::createAlignTo(Numerator, Denominator, Ctx);
1510 return MCBinaryExpr::createDiv(Ceil, Denominator, Ctx);
1511 };
1512
1513 // Scratch is allocated in 64-dword or 256-dword blocks.
1514 unsigned ScratchAlignShift =
1515 STM.getGeneration() >= AMDGPUSubtarget::GFX11 ? 8 : 10;
1516 // We need to program the hardware with the amount of scratch memory that
1517 // is used by the entire wave. ProgInfo.ScratchSize is the amount of
1518 // scratch memory used per thread.
1519 ProgInfo.ScratchBlocks = DivideCeil(
1521 CreateExpr(STM.getWavefrontSize()), Ctx),
1522 CreateExpr(1ULL << ScratchAlignShift));
1523
1524 if (STM.hasSupportsWGP()) {
1525 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
1526 }
1527
1528 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
1529 ProgInfo.MemOrdered = 1;
1530 ProgInfo.FwdProgress = !F.hasFnAttribute("amdgpu-no-fwd-progress");
1531 }
1532
1533 // 0 = X, 1 = XY, 2 = XYZ
1534 unsigned TIDIGCompCnt = 0;
1535 if (MFI->hasWorkItemIDZ())
1536 TIDIGCompCnt = 2;
1537 else if (MFI->hasWorkItemIDY())
1538 TIDIGCompCnt = 1;
1539
1540 // The private segment wave byte offset is the last of the system SGPRs. We
1541 // initially assumed it was allocated, and may have used it. It shouldn't harm
1542 // anything to disable it if we know the stack isn't used here. We may still
1543 // have emitted code reading it to initialize scratch, but if that's unused
1544 // reading garbage should be OK.
1547 MCConstantExpr::create(0, Ctx), Ctx),
1548 ProgInfo.DynamicCallStack, Ctx);
1549
1550 ProgInfo.UserSGPR = MFI->getNumUserSGPRs();
1551 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
1552 ProgInfo.TrapHandlerEnable = STM.isAmdHsaOS() ? 0 : STM.hasTrapHandler();
1553 ProgInfo.TGIdXEnable = MFI->hasWorkGroupIDX();
1554 ProgInfo.TGIdYEnable = MFI->hasWorkGroupIDY();
1555 ProgInfo.TGIdZEnable = MFI->hasWorkGroupIDZ();
1556 ProgInfo.TGSizeEnable = MFI->hasWorkGroupInfo();
1557 ProgInfo.TIdIGCompCount = TIDIGCompCnt;
1558 ProgInfo.EXCPEnMSB = 0;
1559 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
1560 ProgInfo.LdsSize = STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks;
1561 ProgInfo.EXCPEnable = 0;
1562
1563 if (STM.hasGFX90AInsts()) {
1564 ProgInfo.ComputePGMRSrc3 =
1565 setBits(ProgInfo.ComputePGMRSrc3, ProgInfo.AccumOffset,
1566 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
1567 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET_SHIFT, Ctx);
1568 ProgInfo.ComputePGMRSrc3 =
1569 setBits(ProgInfo.ComputePGMRSrc3, CreateExpr(ProgInfo.TgSplit),
1570 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
1571 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT_SHIFT, Ctx);
1572 }
1573
1574 if (STM.hasGFX1250Insts())
1575 ProgInfo.ComputePGMRSrc3 =
1576 setBits(ProgInfo.ComputePGMRSrc3, ProgInfo.NamedBarCnt,
1577 amdhsa::COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT,
1578 amdhsa::COMPUTE_PGM_RSRC3_GFX125_NAMED_BAR_CNT_SHIFT, Ctx);
1579
1580 ProgInfo.Occupancy = createOccupancy(
1583 MFI->getDynamicVGPRBlockSize(), STM, Ctx);
1584
1585 uint64_t Occupancy;
1586 if (TryGetMCExprValue(ProgInfo.Occupancy, Occupancy))
1587 diagnoseUnmetWavesPerEU(F, *MFI, Occupancy);
1588}
1589
1590static unsigned getRsrcReg(CallingConv::ID CallConv) {
1591 switch (CallConv) {
1592 default:
1593 [[fallthrough]];
1608 }
1609}
1610
1611void AMDGPUAsmPrinter::EmitProgramInfoSI(
1612 const MachineFunction &MF, const SIProgramInfo &CurrentProgramInfo) {
1613 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1614 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1615 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
1616 MCContext &Ctx = MF.getContext();
1617
1618 // (((Value) & Mask) << Shift)
1619 auto SetBits = [&Ctx](const MCExpr *Value, uint32_t Mask, uint32_t Shift) {
1620 const MCExpr *msk = MCConstantExpr::create(Mask, Ctx);
1621 const MCExpr *shft = MCConstantExpr::create(Shift, Ctx);
1623 shft, Ctx);
1624 };
1625
1626 auto EmitResolvedOrExpr = [this](const MCExpr *Value, unsigned Size) {
1627 int64_t Val;
1628 if (Value->evaluateAsAbsolute(Val))
1629 OutStreamer->emitIntValue(static_cast<uint64_t>(Val), Size);
1630 else
1631 OutStreamer->emitValue(Value, Size);
1632 };
1633
1634 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1636
1637 EmitResolvedOrExpr(CurrentProgramInfo.getComputePGMRSrc1(STM, Ctx),
1638 /*Size=*/4);
1639
1641 EmitResolvedOrExpr(CurrentProgramInfo.getComputePGMRSrc2(STM, Ctx),
1642 /*Size=*/4);
1643
1645
1646 // Sets bits according to S_0286E8_WAVESIZE_* mask and shift values for the
1647 // appropriate generation.
1648 if (STM.getGeneration() >= AMDGPUSubtarget::GFX12) {
1649 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1650 /*Mask=*/0x3FFFF, /*Shift=*/12),
1651 /*Size=*/4);
1652 } else if (STM.getGeneration() == AMDGPUSubtarget::GFX11) {
1653 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1654 /*Mask=*/0x7FFF, /*Shift=*/12),
1655 /*Size=*/4);
1656 } else {
1657 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1658 /*Mask=*/0x1FFF, /*Shift=*/12),
1659 /*Size=*/4);
1660 }
1661
1662 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
1663 // 0" comment but I don't see a corresponding field in the register spec.
1664 } else {
1665 OutStreamer->emitInt32(RsrcReg);
1666
1667 const MCExpr *GPRBlocks = MCBinaryExpr::createOr(
1668 SetBits(CurrentProgramInfo.VGPRBlocks, /*Mask=*/0x3F, /*Shift=*/0),
1669 SetBits(CurrentProgramInfo.SGPRBlocks, /*Mask=*/0x0F, /*Shift=*/6),
1670 MF.getContext());
1671 EmitResolvedOrExpr(GPRBlocks, /*Size=*/4);
1673
1674 // Sets bits according to S_0286E8_WAVESIZE_* mask and shift values for the
1675 // appropriate generation.
1676 if (STM.getGeneration() >= AMDGPUSubtarget::GFX12) {
1677 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1678 /*Mask=*/0x3FFFF, /*Shift=*/12),
1679 /*Size=*/4);
1680 } else if (STM.getGeneration() == AMDGPUSubtarget::GFX11) {
1681 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1682 /*Mask=*/0x7FFF, /*Shift=*/12),
1683 /*Size=*/4);
1684 } else {
1685 EmitResolvedOrExpr(SetBits(CurrentProgramInfo.ScratchBlocks,
1686 /*Mask=*/0x1FFF, /*Shift=*/12),
1687 /*Size=*/4);
1688 }
1689 }
1690
1691 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1693 unsigned ExtraLDSSize = STM.getGeneration() >= AMDGPUSubtarget::GFX11
1694 ? divideCeil(CurrentProgramInfo.LDSBlocks, 2)
1695 : CurrentProgramInfo.LDSBlocks;
1696 OutStreamer->emitInt32(S_00B02C_EXTRA_LDS_SIZE(ExtraLDSSize));
1698 OutStreamer->emitInt32(MFI->getPSInputEnable());
1700 OutStreamer->emitInt32(MFI->getPSInputAddr());
1701 }
1702
1703 OutStreamer->emitInt32(R_SPILLED_SGPRS);
1704 OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
1705 OutStreamer->emitInt32(R_SPILLED_VGPRS);
1706 OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
1707}
1708
1709// Helper function to add common PAL Metadata 3.0+
1711 const SIProgramInfo &CurrentProgramInfo,
1712 CallingConv::ID CC, const GCNSubtarget &ST,
1713 unsigned DynamicVGPRBlockSize) {
1714 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode))
1715 MD->setHwStage(CC, ".ieee_mode", (bool)CurrentProgramInfo.IEEEMode);
1716
1717 MD->setHwStage(CC, ".wgp_mode", (bool)CurrentProgramInfo.WgpMode);
1718 MD->setHwStage(CC, ".mem_ordered", (bool)CurrentProgramInfo.MemOrdered);
1719 MD->setHwStage(CC, ".forward_progress", (bool)CurrentProgramInfo.FwdProgress);
1720
1721 if (AMDGPU::isCompute(CC)) {
1722 MD->setHwStage(CC, ".trap_present",
1723 (bool)CurrentProgramInfo.TrapHandlerEnable);
1724 MD->setHwStage(CC, ".excp_en", CurrentProgramInfo.EXCPEnable);
1725
1726 if (DynamicVGPRBlockSize != 0)
1727 MD->setComputeRegisters(".dynamic_vgpr_en", true);
1728 }
1729
1731 CC, ".lds_size",
1732 (unsigned)(CurrentProgramInfo.LdsSize * getLDSEncodingGranule(ST)));
1733}
1734
1735// This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1736// is AMDPAL. It stores each compute/SPI register setting and other PAL
1737// metadata items into the PALMD::Metadata, combining with any provided by the
1738// frontend as LLVM metadata. Once all functions are written, the PAL metadata
1739// is then written as a single block in the .note section.
1740void AMDGPUAsmPrinter::EmitPALMetadata(
1741 const MachineFunction &MF, const SIProgramInfo &CurrentProgramInfo) {
1742 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1743 auto CC = MF.getFunction().getCallingConv();
1744 auto *MD = getTargetStreamer()->getPALMetadata();
1745 auto &Ctx = MF.getContext();
1746
1747 MD->setEntryPoint(CC, MF.getFunction().getName());
1748 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU, Ctx);
1749
1750 // For targets that support dynamic VGPRs, set the number of saved dynamic
1751 // VGPRs (if any) in the PAL metadata.
1752 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1753 if (MFI->isDynamicVGPREnabled() &&
1755 MD->setHwStage(CC, ".dynamic_vgpr_saved_count",
1757
1758 // Only set AGPRs for supported devices
1759 if (STM.hasMAIInsts()) {
1760 MD->setNumUsedAgprs(CC, CurrentProgramInfo.NumAccVGPR);
1761 }
1762
1763 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU, Ctx);
1764 if (MD->getPALMajorVersion() < 3) {
1765 MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC, STM, Ctx), Ctx);
1766 if (AMDGPU::isCompute(CC)) {
1767 MD->setRsrc2(CC, CurrentProgramInfo.getComputePGMRSrc2(STM, Ctx), Ctx);
1768 } else {
1769 const MCExpr *HasScratchBlocks =
1770 MCBinaryExpr::createGT(CurrentProgramInfo.ScratchBlocks,
1771 MCConstantExpr::create(0, Ctx), Ctx);
1772 auto [Shift, Mask] = getShiftMask(C_00B84C_SCRATCH_EN);
1773 MD->setRsrc2(CC, maskShiftSet(HasScratchBlocks, Mask, Shift, Ctx), Ctx);
1774 }
1775 } else {
1776 MD->setHwStage(CC, ".debug_mode", (bool)CurrentProgramInfo.DebugMode);
1777 MD->setHwStage(CC, ".scratch_en", msgpack::Type::Boolean,
1778 CurrentProgramInfo.ScratchEnable);
1779 EmitPALMetadataCommon(MD, CurrentProgramInfo, CC, STM,
1781 }
1782
1783 // ScratchSize is in bytes, 16 aligned.
1784 MD->setScratchSize(
1785 CC,
1786 AMDGPUMCExpr::createAlignTo(CurrentProgramInfo.ScratchSize,
1787 MCConstantExpr::create(16, Ctx), Ctx),
1788 Ctx);
1789
1790 MD->setBackendStackSize(CC, CurrentProgramInfo.ScratchSize);
1791
1792 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1793 unsigned ExtraLDSSize = STM.getGeneration() >= AMDGPUSubtarget::GFX11
1794 ? divideCeil(CurrentProgramInfo.LDSBlocks, 2)
1795 : CurrentProgramInfo.LDSBlocks;
1796 if (MD->getPALMajorVersion() < 3) {
1797 MD->setRsrc2(
1798 CC,
1800 Ctx);
1801 MD->setSpiPsInputEna(MFI->getPSInputEnable());
1802 MD->setSpiPsInputAddr(MFI->getPSInputAddr());
1803 } else {
1804 // Graphics registers
1805 const unsigned ExtraLdsDwGranularity =
1806 STM.getGeneration() >= AMDGPUSubtarget::GFX11 ? 256 : 128;
1807 MD->setGraphicsRegisters(
1808 ".ps_extra_lds_size",
1809 (unsigned)(ExtraLDSSize * ExtraLdsDwGranularity * sizeof(uint32_t)));
1810
1811 // Set PsInputEna and PsInputAddr .spi_ps_input_ena and .spi_ps_input_addr
1812 static StringLiteral const PsInputFields[] = {
1813 ".persp_sample_ena", ".persp_center_ena",
1814 ".persp_centroid_ena", ".persp_pull_model_ena",
1815 ".linear_sample_ena", ".linear_center_ena",
1816 ".linear_centroid_ena", ".line_stipple_tex_ena",
1817 ".pos_x_float_ena", ".pos_y_float_ena",
1818 ".pos_z_float_ena", ".pos_w_float_ena",
1819 ".front_face_ena", ".ancillary_ena",
1820 ".sample_coverage_ena", ".pos_fixed_pt_ena"};
1821 unsigned PSInputEna = MFI->getPSInputEnable();
1822 unsigned PSInputAddr = MFI->getPSInputAddr();
1823 for (auto [Idx, Field] : enumerate(PsInputFields)) {
1824 MD->setGraphicsRegisters(".spi_ps_input_ena", Field,
1825 (bool)((PSInputEna >> Idx) & 1));
1826 MD->setGraphicsRegisters(".spi_ps_input_addr", Field,
1827 (bool)((PSInputAddr >> Idx) & 1));
1828 }
1829 }
1830 }
1831
1832 // For version 3 and above the wave front size is already set in the metadata
1833 if (MD->getPALMajorVersion() < 3 && STM.isWave32())
1834 MD->setWave32(MF.getFunction().getCallingConv());
1835}
1836
1837void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) {
1838 auto *MD = getTargetStreamer()->getPALMetadata();
1839 const MachineFrameInfo &MFI = MF.getFrameInfo();
1840 StringRef FnName = MF.getFunction().getName();
1841 MD->setFunctionStackFrameSize(FnName, MFI.getStackSize());
1842 MD->setFunctionBackendStackSize(FnName, CurrentProgramInfo.ScratchSize);
1843 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1844 MCContext &Ctx = MF.getContext();
1845
1846 if (MD->getPALMajorVersion() < 3) {
1847 // Set compute registers
1848 MD->setRsrc1(
1850 CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS, ST, Ctx), Ctx);
1851 MD->setRsrc2(CallingConv::AMDGPU_CS,
1852 CurrentProgramInfo.getComputePGMRSrc2(ST, Ctx), Ctx);
1853 } else {
1855 MD, CurrentProgramInfo, CallingConv::AMDGPU_CS, ST,
1856 MF.getInfo<SIMachineFunctionInfo>()->getDynamicVGPRBlockSize());
1857 }
1858
1859 // Set optional info
1860 MD->setFunctionLdsSize(FnName, CurrentProgramInfo.LDSSize);
1861 MD->setFunctionNumUsedVgprs(FnName, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1862 MD->setFunctionNumUsedSgprs(FnName, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1863}
1864
1865// This is supposed to be log2(Size)
1867 switch (Size) {
1868 case 4:
1869 return AMD_ELEMENT_4_BYTES;
1870 case 8:
1871 return AMD_ELEMENT_8_BYTES;
1872 case 16:
1873 return AMD_ELEMENT_16_BYTES;
1874 default:
1875 llvm_unreachable("invalid private_element_size");
1876 }
1877}
1878
1879void AMDGPUAsmPrinter::getAmdKernelCode(AMDGPUMCKernelCodeT &Out,
1880 const SIProgramInfo &CurrentProgramInfo,
1881 const MachineFunction &MF) const {
1882 const Function &F = MF.getFunction();
1883 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
1884 F.getCallingConv() == CallingConv::SPIR_KERNEL);
1885
1886 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1887 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1888 MCContext &Ctx = MF.getContext();
1889
1890 Out.initDefault(STM, Ctx, /*InitMCExpr=*/false);
1891
1892 Out.compute_pgm_resource1_registers =
1893 CurrentProgramInfo.getComputePGMRSrc1(STM, Ctx);
1894 Out.compute_pgm_resource2_registers =
1895 CurrentProgramInfo.getComputePGMRSrc2(STM, Ctx);
1896 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
1897
1898 Out.is_dynamic_callstack = CurrentProgramInfo.DynamicCallStack;
1899
1901 getElementByteSizeValue(STM.getMaxPrivateElementSize(true)));
1902
1903 const GCNUserSGPRUsageInfo &UserSGPRInfo = MFI->getUserSGPRInfo();
1904 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
1906 }
1907
1908 if (UserSGPRInfo.hasDispatchPtr())
1910
1911 if (UserSGPRInfo.hasQueuePtr())
1913
1914 if (UserSGPRInfo.hasKernargSegmentPtr())
1916
1917 if (UserSGPRInfo.hasDispatchID())
1919
1920 if (UserSGPRInfo.hasFlatScratchInit())
1922
1923 if (UserSGPRInfo.hasPrivateSegmentSize())
1925
1926 if (STM.isXNACKEnabled())
1927 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1928
1929 Align MaxKernArgAlign;
1930 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1931 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1932 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1933 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1934 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1935
1936 // kernarg_segment_alignment is specified as log of the alignment.
1937 // The minimum alignment is 16.
1938 // FIXME: The metadata treats the minimum as 4?
1939 Out.kernarg_segment_alignment =
1940 static_cast<uint8_t>(Log2(std::max(Align(16), MaxKernArgAlign)));
1941}
1942
1944 const char *ExtraCode, raw_ostream &O) {
1945 // First try the generic code, which knows about modifiers like 'c' and 'n'.
1946 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1947 return false;
1948
1949 if (ExtraCode && ExtraCode[0]) {
1950 if (ExtraCode[1] != 0)
1951 return true; // Unknown modifier.
1952
1953 switch (ExtraCode[0]) {
1954 case 'r':
1955 break;
1956 default:
1957 return true;
1958 }
1959 }
1960
1961 // TODO: Should be able to support other operand types like globals.
1962 const MachineOperand &MO = MI->getOperand(OpNo);
1963 if (MO.isReg()) {
1965 *MF->getSubtarget().getRegisterInfo());
1966 return false;
1967 }
1968 if (MO.isImm()) {
1969 int64_t Val = MO.getImm();
1971 O << Val;
1972 } else if (isUInt<16>(Val)) {
1973 O << format("0x%" PRIx16, static_cast<uint16_t>(Val));
1974 } else if (isUInt<32>(Val)) {
1975 O << format("0x%" PRIx32, static_cast<uint32_t>(Val));
1976 } else {
1977 O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1978 }
1979 return false;
1980 }
1981 return true;
1982}
1983
1985 unsigned OpNo,
1986 const char *ExtraCode,
1987 raw_ostream &OS) {
1988 const MachineOperand &MO = MI->getOperand(OpNo);
1990 *MF->getSubtarget().getRegisterInfo());
1991 return false;
1992}
1993
2001
2002void AMDGPUAsmPrinter::emitResourceUsageRemarks(
2003 const MachineFunction &MF, const SIProgramInfo &CurrentProgramInfo,
2004 bool isModuleEntryFunction, bool hasMAIInsts) {
2005 if (!ORE)
2006 return;
2007
2008 const char *Name = "kernel-resource-usage";
2009 const char *Indent = " ";
2010
2011 // If the remark is not specifically enabled, do not output to yaml
2013 if (!Ctx.getDiagHandlerPtr()->isAnalysisRemarkEnabled(Name))
2014 return;
2015
2016 // Currently non-kernel functions have no resources to emit.
2018 return;
2019
2020 auto EmitResourceUsageRemark = [&](StringRef RemarkName,
2021 StringRef RemarkLabel, auto Argument) {
2022 // Add an indent for every line besides the line with the kernel name. This
2023 // makes it easier to tell which resource usage go with which kernel since
2024 // the kernel name will always be displayed first.
2025 std::string LabelStr = RemarkLabel.str() + ": ";
2026 if (RemarkName != "FunctionName")
2027 LabelStr = Indent + LabelStr;
2028
2029 ORE->emit([&]() {
2030 return MachineOptimizationRemarkAnalysis(Name, RemarkName,
2032 &MF.front())
2033 << LabelStr << ore::NV(RemarkName, Argument);
2034 });
2035 };
2036
2037 // FIXME: Formatting here is pretty nasty because clang does not accept
2038 // newlines from diagnostics. This forces us to emit multiple diagnostic
2039 // remarks to simulate newlines. If and when clang does accept newlines, this
2040 // formatting should be aggregated into one remark with newlines to avoid
2041 // printing multiple diagnostic location and diag opts.
2042 EmitResourceUsageRemark("FunctionName", "Function Name",
2043 MF.getFunction().getName());
2044 EmitResourceUsageRemark("NumSGPR", "TotalSGPRs",
2045 getMCExprStr(CurrentProgramInfo.NumSGPR));
2046 EmitResourceUsageRemark("NumVGPR", "VGPRs",
2047 getMCExprStr(CurrentProgramInfo.NumArchVGPR));
2048 if (hasMAIInsts) {
2049 EmitResourceUsageRemark("NumAGPR", "AGPRs",
2050 getMCExprStr(CurrentProgramInfo.NumAccVGPR));
2051 }
2052 EmitResourceUsageRemark("ScratchSize", "ScratchSize [bytes/lane]",
2053 getMCExprStr(CurrentProgramInfo.ScratchSize));
2054 int64_t DynStack;
2055 bool DynStackEvaluatable =
2056 CurrentProgramInfo.DynamicCallStack->evaluateAsAbsolute(DynStack);
2057 StringRef DynamicStackStr =
2058 DynStackEvaluatable && DynStack ? "True" : "False";
2059 EmitResourceUsageRemark("DynamicStack", "Dynamic Stack", DynamicStackStr);
2060 EmitResourceUsageRemark("Occupancy", "Occupancy [waves/SIMD]",
2061 getMCExprStr(CurrentProgramInfo.Occupancy));
2062 EmitResourceUsageRemark("SGPRSpill", "SGPRs Spill",
2063 CurrentProgramInfo.SGPRSpill);
2064 EmitResourceUsageRemark("VGPRSpill", "VGPRs Spill",
2065 CurrentProgramInfo.VGPRSpill);
2066 if (isModuleEntryFunction)
2067 EmitResourceUsageRemark("BytesLDS", "LDS Size [bytes/block]",
2068 CurrentProgramInfo.LDSSize);
2069}
2070
2080
2096
2105
2106char AMDGPUAsmPrinter::ID = 0;
2107
2108INITIALIZE_PASS(AMDGPUAsmPrinter, "amdgpu-asm-printer",
2109 "AMDGPU Assembly Printer", false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static void EmitPALMetadataCommon(AMDGPUPALMetadata *MD, const SIProgramInfo &CurrentProgramInfo, CallingConv::ID CC, const GCNSubtarget &ST, unsigned DynamicVGPRBlockSize)
const AMDGPUMCExpr * createOccupancy(unsigned InitOcc, const MCExpr *NumSGPRs, const MCExpr *NumVGPRs, unsigned DynamicVGPRBlockSize, const GCNSubtarget &STM, MCContext &Ctx)
Mimics GCNSubtarget::computeOccupancy for MCExpr.
static unsigned getRsrcReg(CallingConv::ID CallConv)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUAsmPrinter()
static amd_element_byte_size_t getElementByteSizeValue(unsigned Size)
static const MCExpr * setBits(const MCExpr *Dst, const MCExpr *Value, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
Set bits in a kernel descriptor MCExpr field: return ((Dst & ~Mask) | (Value << Shift))
static uint32_t getFPMode(SIModeRegisterDefaults Mode)
static bool diagnoseUnmetWavesPerEU(const Function &F, const SIMachineFunctionInfo &MFI, uint64_t Occupancy)
static std::string computeTypeId(const FunctionType *FTy, const DataLayout &DL)
static const MCExpr * computeAccumOffset(const MCExpr *NumVGPR, MCContext &Ctx)
static void appendTypeEncoding(std::string &Enc, Type *Ty, const DataLayout &DL, bool IsReturnType)
static AsmPrinter * createAMDGPUAsmPrinterPass(TargetMachine &tm, std::unique_ptr< MCStreamer > &&Streamer)
AMDGPU Assembly printer class.
uint64_t uint64_t
AMDGPU HSA Metadata Streamer.
AMDHSA kernel descriptor MCExpr struct for use in MC layer.
MC infrastructure to propagate the function level resource usage info.
Analyzes how many registers and other resources are used by functions.
The AMDGPU TargetMachine interface definition for hw codegen targets.
AMDHSA kernel descriptor definitions.
MC layer struct for AMDGPUMCKernelCodeT, provides MCExpr functionality where required.
amd_element_byte_size_t
The values used to define the number of bytes to use for the swizzle element size.
@ AMD_ELEMENT_8_BYTES
@ AMD_ELEMENT_16_BYTES
@ AMD_ELEMENT_4_BYTES
#define AMD_HSA_BITS_SET(dst, mask, val)
@ AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID
@ AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE
@ AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR
@ AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR
@ AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE
@ AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER
@ AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR
@ AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED
@ AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT
@ AMD_CODE_PROPERTY_IS_PTR64
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
AMD GCN specific subclass of TargetSubtarget.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
modulo schedule test
OptimizedStructLayoutField Field
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
R600 Assembly printer class.
RISCVCC::CondCode CC
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
#define R_00B028_SPI_SHADER_PGM_RSRC1_PS
Definition SIDefines.h:1394
#define R_0286E8_SPI_TMPRING_SIZE
Definition SIDefines.h:1536
#define FP_ROUND_MODE_DP(x)
Definition SIDefines.h:1518
#define C_00B84C_SCRATCH_EN
Definition SIDefines.h:1430
#define FP_ROUND_ROUND_TO_NEAREST
Definition SIDefines.h:1510
#define R_0286D0_SPI_PS_INPUT_ADDR
Definition SIDefines.h:1469
#define R_00B860_COMPUTE_TMPRING_SIZE
Definition SIDefines.h:1531
#define R_00B428_SPI_SHADER_PGM_RSRC1_HS
Definition SIDefines.h:1417
#define R_00B328_SPI_SHADER_PGM_RSRC1_ES
Definition SIDefines.h:1416
#define R_00B528_SPI_SHADER_PGM_RSRC1_LS
Definition SIDefines.h:1425
#define R_0286CC_SPI_PS_INPUT_ENA
Definition SIDefines.h:1468
#define R_00B128_SPI_SHADER_PGM_RSRC1_VS
Definition SIDefines.h:1403
#define FP_DENORM_MODE_DP(x)
Definition SIDefines.h:1529
#define R_00B848_COMPUTE_PGM_RSRC1
Definition SIDefines.h:1471
#define R_SPILLED_SGPRS
Definition SIDefines.h:1550
#define FP_ROUND_MODE_SP(x)
Definition SIDefines.h:1517
#define FP_DENORM_MODE_SP(x)
Definition SIDefines.h:1528
#define R_00B228_SPI_SHADER_PGM_RSRC1_GS
Definition SIDefines.h:1408
#define R_SPILLED_VGPRS
Definition SIDefines.h:1551
#define S_00B02C_EXTRA_LDS_SIZE(x)
Definition SIDefines.h:1402
#define R_00B84C_COMPUTE_PGM_RSRC2
Definition SIDefines.h:1427
#define R_00B02C_SPI_SHADER_PGM_RSRC2_PS
Definition SIDefines.h:1401
std::unique_ptr< MCStreamer > && Streamer
static const int BlockSize
Definition TarWriter.cpp:33
static cl::opt< unsigned > CacheLineSize("cache-line-size", cl::init(0), cl::Hidden, cl::desc("Use this to override the target cache line size when " "specified by the user."))
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void emitFunctionEntryLabel() override
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
const MCSubtargetInfo * getGlobalSTI() const
void emitImplicitDef(const MachineInstr *MI) const override
Targets can override this to customize the output of IMPLICIT_DEF instructions in verbose mode.
std::vector< std::string > DisasmLines
std::function< const AMDGPUResourceUsageAnalysisImpl::SIFunctionResourceInfo *(MachineFunction &)> GetResourceUsage
void emitStartOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the start of their fi...
void endFunction(const MachineFunction *MF)
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
std::vector< std::string > HexLines
void emitGlobalVariable(const GlobalVariable *GV) override
Emit the specified global variable to the .s file.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
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.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
void emitEndOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the end of their file...
AMDGPUAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
void emitFunctionBodyStart() override
Targets can override this to emit stuff before the first basic block in the function.
void emitBasicBlockStart(const MachineBasicBlock &MBB) override
Targets can override this to emit stuff at the start of a basic block.
AMDGPUTargetStreamer * getTargetStreamer() const
static void printRegOperand(MCRegister Reg, raw_ostream &O, const MCRegisterInfo &MRI)
AMDGPU target specific MCExpr operations.
static const AMDGPUMCExpr * createInstPrefSize(const MCExpr *CodeSizeBytes, MCContext &Ctx)
Create an expression for instruction prefetch size computation: min(divideCeil(CodeSizeBytes,...
static const AMDGPUMCExpr * createMax(ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static const AMDGPUMCExpr * createTotalNumVGPR(const MCExpr *NumAGPR, const MCExpr *NumVGPR, MCContext &Ctx)
static const AMDGPUMCExpr * create(VariantKind Kind, ArrayRef< const MCExpr * > Args, MCContext &Ctx)
static const AMDGPUMCExpr * createExtraSGPRs(const MCExpr *VCCUsed, const MCExpr *FlatScrUsed, bool XNACKUsed, MCContext &Ctx)
Allow delayed MCExpr resolve of ExtraSGPRs (in case VCCUsed or FlatScrUsed are unresolvable but neede...
static const AMDGPUMCExpr * createAlignTo(const MCExpr *Value, const MCExpr *Align, MCContext &Ctx)
void setHwStage(unsigned CC, StringRef field, unsigned Val)
void updateHwStageMaximum(unsigned CC, StringRef field, unsigned Val)
void setComputeRegisters(StringRef field, unsigned Val)
std::pair< unsigned, unsigned > getOccupancyWithWorkGroupSizes(uint32_t LDSBytes, const Function &F) const
Subtarget's minimum/maximum occupancy, in number of waves per EU, that can be achieved when the only ...
unsigned getAddressableLocalMemorySize() const
Return the maximum number of bytes of LDS that can be allocated to a single workgroup.
unsigned getKernArgSegmentSize(const Function &F, Align &MaxAlign) const
unsigned getWavefrontSize() const
virtual void EmitAmdhsaKernelDescriptor(const MCSubtargetInfo &STI, StringRef KernelName, const AMDGPU::MCKernelDescriptor &KernelDescriptor, const MCExpr *NextVGPR, const MCExpr *NextSGPR, const MCExpr *ReserveVCC, const MCExpr *ReserveFlatScr)
virtual void emitAMDGPUInfo(const AMDGPU::InfoSectionData &Data)
AMDGPUPALMetadata * getPALMetadata()
void initializeTargetID(const MCSubtargetInfo &STI, bool ApplyFeatureString=false)
virtual void EmitDirectiveAMDHSACodeObjectVersion(unsigned COV)
virtual void EmitMCResourceInfo(const MCSymbol *NumVGPR, const MCSymbol *NumAGPR, const MCSymbol *NumExplicitSGPR, const MCSymbol *NumNamedBarrier, const MCSymbol *PrivateSegmentSize, const MCSymbol *UsesVCC, const MCSymbol *UsesFlatScratch, const MCSymbol *HasDynamicallySizedStack, const MCSymbol *HasRecursion, const MCSymbol *HasIndirectCall)
virtual bool EmitCodeEnd(const MCSubtargetInfo &STI)
virtual void EmitAMDGPUSymbolType(StringRef SymbolName, unsigned Type)
const std::optional< AMDGPU::TargetID > & getTargetID() const
void emitDirectiveAMDGCNTargetOnce()
Emit the .amdgcn_target directive unless it has already been emitted to this streamer.
virtual void EmitAMDKernelCodeT(AMDGPU::AMDGPUMCKernelCodeT &Header)
virtual void EmitMCResourceMaximums(const MCSymbol *MaxVGPR, const MCSymbol *MaxAGPR, const MCSymbol *MaxSGPR, const MCSymbol *MaxNamedBarrier)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Collects and handles AsmPrinter objects required to build debug or EH information.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:93
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
MCSymbol * getSymbol(const GlobalValue *GV) const
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
dwarf::Attribute TypeAddressSpaceAttribute
The attribute used for a pointer type's DWARF address space.
Definition AsmPrinter.h:299
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:96
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:111
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
void emitFunctionBody()
This method emits the body and trailer for a function.
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
unsigned getFunctionNumber() const
Return a unique ID for the current function.
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition AsmPrinter.h:126
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer, char &ID=AsmPrinter::ID)
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition AsmPrinter.h:133
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:114
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:103
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
void emitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition AsmPrinter.h:478
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:108
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:99
std::function< MachineModuleInfo *()> GetMMI
Definition AsmPrinter.h:181
bool isVerbose() const
Return true if assembly output should contain comments.
Definition AsmPrinter.h:335
MCSymbol * getFunctionEnd() const
Definition AsmPrinter.h:345
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
void addAsmPrinterHandler(std::unique_ptr< AsmPrinterHandler > Handler)
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.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool empty() const
Definition DenseMap.h:716
Diagnostic information for optimization failures.
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
unsigned getMinNumSGPRs(unsigned WavesPerEU) const
unsigned getTotalNumVGPRs() const
unsigned getMinNumVGPRs(unsigned WavesPerEU, unsigned DynamicVGPRBlockSize) const
bool hasInstPrefSize() const
bool isCuModeEnabled() const
const AMDGPU::TargetID & getTargetID() const
bool isWave32() const
void getInstPrefSizeArgs(uint32_t &Mask, uint32_t &Shift, uint32_t &Width, uint32_t &CacheLineSize) const
unsigned getMaxNumUserSGPRs() const
unsigned getMaxWavesPerEU() const
Generation getGeneration() const
unsigned getAddressableNumSGPRs() const
unsigned getMaxWaveScratchSize() const
bool hasPrivateSegmentBuffer() const
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
unsigned getAddressSpace() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
MCCodeEmitter * getEmitterPtr() const
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:339
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:344
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:404
static const MCBinaryExpr * createLOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:374
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:394
static const MCBinaryExpr * createGT(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:359
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:349
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:409
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:424
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:84
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:31
LLVM_ABI bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm) const
Try to evaluate the expression to a relocatable value, i.e.
Definition MCExpr.cpp:450
MCSection * getTextSection() const
MCContext & getContext() const
This represents a section on linux, lots of unix variants and some bare metal systems.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:577
bool hasInstructions() const
Definition MCSection.h:673
Generic base class for all target subtargets.
StringRef getFeatureString() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition MCSymbol.h:267
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition MCSymbol.h:212
const MCExpr * getVariableValue() const
Get the expression of the variable symbol.
Definition MCSymbol.h:270
MCStreamer & getStreamer()
Definition MCStreamer.h:102
static const MCUnaryExpr * createNot(const MCExpr *Expr, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:269
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
Diagnostic information for optimization analysis remarks.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
GCNUserSGPRUsageInfo & getUserSGPRInfo()
SIModeRegisterDefaults getMode() const
unsigned getScratchReservedForDynamicVGPRs() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:438
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:41
Primary interface to the complete machine description for the target machine.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool isSGPROccupancyLimited(const MCSubtargetInfo &STI)
unsigned getVGPREncodingGranule(const MCSubtargetInfo &STI, std::optional< bool > EnableWavefrontSize32)
static constexpr unsigned MaxDynamicVGPRBlocks
Maximum number of VGPR blocks that can be allocated in dynamic VGPR mode.
unsigned getSGPREncodingGranule(const MCSubtargetInfo &STI)
unsigned getNumExtraSGPRs(const MCSubtargetInfo &STI, bool VCCUsed, bool FlatScrUsed, bool XNACKUsed)
unsigned getVGPRAllocGranule(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
LLVM_ABI unsigned getLDSEncodingGranule(GPUKind AK)
void printAMDGPUMCExpr(const MCExpr *Expr, raw_ostream &OS, const MCAsmInfo *MAI)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
LLVM_ABI unsigned getTotalNumVGPRs(GPUKind AK, bool IsWave32)
LLVM_ABI unsigned getTotalNumSGPRs(GPUKind AK)
const MCExpr * maskShiftSet(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
Provided with the MCExpr * Val, uint32 Mask and Shift, will return the masked and left shifted,...
unsigned getAMDHSACodeObjectVersion(const Module &M)
bool isTgSplitEnabled(const Function &F)
GPUKind
GPU kinds supported by the AMDGPU target.
bool isGFX90A(const MCSubtargetInfo &STI)
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
LLVM_ABI unsigned getSGPRAllocGranule(GPUKind AK)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isCompute(CallingConv::ID CC)
bool hasMAIInsts(const MCSubtargetInfo &STI)
LLVM_ABI Triple::SubArchType getSubArch(GPUKind AK)
LLVM_READNONE bool isInlinableIntLiteral(int64_t Literal)
Is this literal inlinable, and not one of the values intended for floating point values.
LLVM_ABI GPUKind parseArchAMDGCN(StringRef CPU)
const MCExpr * foldAMDGPUMCExpr(const MCExpr *Expr, MCContext &Ctx)
bool isGFX10Plus(const MCSubtargetInfo &STI)
constexpr std::pair< unsigned, unsigned > getShiftMask(unsigned Value)
Deduce the least significant bit aligned shift and mask values for a binary Complement Value (as they...
unsigned hasKernargPreload(const MCSubtargetInfo &STI)
std::pair< unsigned, unsigned > getIntegerPairAttribute(const Function &F, StringRef Name, std::pair< unsigned, unsigned > Default, bool OnlyFirstRequired)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ STT_AMDGPU_HSA_KERNEL
Definition ELF.h:1286
@ SHT_PROGBITS
Definition ELF.h:996
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Target & getTheR600Target()
The target for R600 GPUs.
@ DK_ResourceLimit
AsmPrinter * createR600AsmPrinterPass(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
@ Success
The lock was released successfully.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
Target & getTheGCNTarget()
The target for GCN GPUs.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
Target & getTheGCNLegacyTarget()
The target for GCN GPUs, registered under the legacy "amdgcn" architecture name for use with -march.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
AMDGPUResourceUsageAnalysisImpl::SIFunctionResourceInfo FunctionResourceInfo
void validate(const MCSubtargetInfo *STI, MCContext &Ctx)
static const MCExpr * bits_get(const MCExpr *Src, uint32_t Shift, uint32_t Mask, MCContext &Ctx)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Track resource usage for kernels / entry functions.
const MCExpr * NumSGPR
const MCExpr * NumArchVGPR
const MCExpr * VGPRBlocks
const MCExpr * ScratchBlocks
const MCExpr * ComputePGMRSrc3
const MCExpr * getComputePGMRSrc1(const GCNSubtarget &ST, MCContext &Ctx) const
Compute the value of the ComputePGMRsrc1 register.
const MCExpr * VCCUsed
const MCExpr * FlatUsed
const MCExpr * NamedBarCnt
const MCExpr * ScratchEnable
const MCExpr * AccumOffset
const MCExpr * NumAccVGPR
const MCExpr * DynamicCallStack
const MCExpr * SGPRBlocks
const MCExpr * NumVGPRsForWavesPerEU
const MCExpr * NumVGPR
const MCExpr * Occupancy
const MCExpr * ScratchSize
const MCExpr * NumSGPRsForWavesPerEU
const MCExpr * getComputePGMRSrc2(const GCNSubtarget &ST, MCContext &Ctx) const
Compute the value of the ComputePGMRsrc2 register.
static void RegisterAsmPrinter(Target &T, Target::AsmPrinterCtorTy Fn)
RegisterAsmPrinter - Register an AsmPrinter implementation for the given target.