1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// 11 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary 12 /// code. When passed an MCAsmStreamer it prints assembly and when passed 13 /// an MCObjectStreamer it outputs binary code. 14 // 15 //===----------------------------------------------------------------------===// 16 // 17 18 #include "AMDGPUAsmPrinter.h" 19 #include "AMDGPU.h" 20 #include "AMDGPUHSAMetadataStreamer.h" 21 #include "AMDGPUResourceUsageAnalysis.h" 22 #include "AMDKernelCodeT.h" 23 #include "GCNSubtarget.h" 24 #include "MCTargetDesc/AMDGPUInstPrinter.h" 25 #include "MCTargetDesc/AMDGPUTargetStreamer.h" 26 #include "R600AsmPrinter.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "TargetInfo/AMDGPUTargetInfo.h" 29 #include "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/MC/MCAssembler.h" 32 #include "llvm/MC/MCContext.h" 33 #include "llvm/MC/MCSectionELF.h" 34 #include "llvm/MC/MCStreamer.h" 35 #include "llvm/Support/AMDHSAKernelDescriptor.h" 36 #include "llvm/Support/TargetRegistry.h" 37 #include "llvm/Target/TargetLoweringObjectFile.h" 38 #include "llvm/Target/TargetMachine.h" 39 40 using namespace llvm; 41 using namespace llvm::AMDGPU; 42 43 // This should get the default rounding mode from the kernel. We just set the 44 // default here, but this could change if the OpenCL rounding mode pragmas are 45 // used. 46 // 47 // The denormal mode here should match what is reported by the OpenCL runtime 48 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but 49 // can also be override to flush with the -cl-denorms-are-zero compiler flag. 50 // 51 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double 52 // precision, and leaves single precision to flush all and does not report 53 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports 54 // CL_FP_DENORM for both. 55 // 56 // FIXME: It seems some instructions do not support single precision denormals 57 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32, 58 // and sin_f32, cos_f32 on most parts). 59 60 // We want to use these instructions, and using fp32 denormals also causes 61 // instructions to run at the double precision rate for the device so it's 62 // probably best to just report no single precision denormals. 63 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) { 64 return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) | 65 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) | 66 FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) | 67 FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue()); 68 } 69 70 static AsmPrinter * 71 createAMDGPUAsmPrinterPass(TargetMachine &tm, 72 std::unique_ptr<MCStreamer> &&Streamer) { 73 return new AMDGPUAsmPrinter(tm, std::move(Streamer)); 74 } 75 76 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() { 77 TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(), 78 llvm::createR600AsmPrinterPass); 79 TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(), 80 createAMDGPUAsmPrinterPass); 81 } 82 83 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, 84 std::unique_ptr<MCStreamer> Streamer) 85 : AsmPrinter(TM, std::move(Streamer)) { 86 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 87 if (isHsaAbiVersion2(getGlobalSTI())) { 88 HSAMetadataStream.reset(new HSAMD::MetadataStreamerV2()); 89 } else if (isHsaAbiVersion3(getGlobalSTI())) { 90 HSAMetadataStream.reset(new HSAMD::MetadataStreamerV3()); 91 } else { 92 HSAMetadataStream.reset(new HSAMD::MetadataStreamerV4()); 93 } 94 } 95 } 96 97 StringRef AMDGPUAsmPrinter::getPassName() const { 98 return "AMDGPU Assembly Printer"; 99 } 100 101 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const { 102 return TM.getMCSubtargetInfo(); 103 } 104 105 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const { 106 if (!OutStreamer) 107 return nullptr; 108 return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer()); 109 } 110 111 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) { 112 // TODO: Which one is called first, emitStartOfAsmFile or 113 // emitFunctionBodyStart? 114 if (getTargetStreamer() && !getTargetStreamer()->getTargetID()) 115 initializeTargetID(M); 116 117 if (TM.getTargetTriple().getOS() != Triple::AMDHSA && 118 TM.getTargetTriple().getOS() != Triple::AMDPAL) 119 return; 120 121 if (isHsaAbiVersion3Or4(getGlobalSTI())) 122 getTargetStreamer()->EmitDirectiveAMDGCNTarget(); 123 124 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 125 HSAMetadataStream->begin(M, *getTargetStreamer()->getTargetID()); 126 127 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) 128 getTargetStreamer()->getPALMetadata()->readFromIR(M); 129 130 if (isHsaAbiVersion3Or4(getGlobalSTI())) 131 return; 132 133 // HSA emits NT_AMD_HSA_CODE_OBJECT_VERSION for code objects v2. 134 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 135 getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1); 136 137 // HSA and PAL emit NT_AMD_HSA_ISA_VERSION for code objects v2. 138 IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU()); 139 getTargetStreamer()->EmitDirectiveHSACodeObjectISAV2( 140 Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU"); 141 } 142 143 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) { 144 // Following code requires TargetStreamer to be present. 145 if (!getTargetStreamer()) 146 return; 147 148 if (TM.getTargetTriple().getOS() != Triple::AMDHSA || 149 isHsaAbiVersion2(getGlobalSTI())) 150 getTargetStreamer()->EmitISAVersion(); 151 152 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA). 153 // Emit HSA Metadata (NT_AMD_HSA_METADATA). 154 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 155 HSAMetadataStream->end(); 156 bool Success = HSAMetadataStream->emitTo(*getTargetStreamer()); 157 (void)Success; 158 assert(Success && "Malformed HSA Metadata"); 159 } 160 } 161 162 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough( 163 const MachineBasicBlock *MBB) const { 164 if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) 165 return false; 166 167 if (MBB->empty()) 168 return true; 169 170 // If this is a block implementing a long branch, an expression relative to 171 // the start of the block is needed. to the start of the block. 172 // XXX - Is there a smarter way to check this? 173 return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64); 174 } 175 176 void AMDGPUAsmPrinter::emitFunctionBodyStart() { 177 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 178 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 179 const Function &F = MF->getFunction(); 180 181 // TODO: Which one is called first, emitStartOfAsmFile or 182 // emitFunctionBodyStart? 183 if (getTargetStreamer() && !getTargetStreamer()->getTargetID()) 184 initializeTargetID(*F.getParent()); 185 186 const auto &FunctionTargetID = STM.getTargetID(); 187 // Make sure function's xnack settings are compatible with module's 188 // xnack settings. 189 if (FunctionTargetID.isXnackSupported() && 190 FunctionTargetID.getXnackSetting() != IsaInfo::TargetIDSetting::Any && 191 FunctionTargetID.getXnackSetting() != getTargetStreamer()->getTargetID()->getXnackSetting()) { 192 OutContext.reportError({}, "xnack setting of '" + Twine(MF->getName()) + 193 "' function does not match module xnack setting"); 194 return; 195 } 196 // Make sure function's sramecc settings are compatible with module's 197 // sramecc settings. 198 if (FunctionTargetID.isSramEccSupported() && 199 FunctionTargetID.getSramEccSetting() != IsaInfo::TargetIDSetting::Any && 200 FunctionTargetID.getSramEccSetting() != getTargetStreamer()->getTargetID()->getSramEccSetting()) { 201 OutContext.reportError({}, "sramecc setting of '" + Twine(MF->getName()) + 202 "' function does not match module sramecc setting"); 203 return; 204 } 205 206 if (!MFI.isEntryFunction()) 207 return; 208 209 if ((STM.isMesaKernel(F) || isHsaAbiVersion2(getGlobalSTI())) && 210 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 211 F.getCallingConv() == CallingConv::SPIR_KERNEL)) { 212 amd_kernel_code_t KernelCode; 213 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 214 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 215 } 216 217 if (STM.isAmdHsaOS()) 218 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo); 219 } 220 221 void AMDGPUAsmPrinter::emitFunctionBodyEnd() { 222 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 223 if (!MFI.isEntryFunction()) 224 return; 225 226 if (TM.getTargetTriple().getOS() != Triple::AMDHSA || 227 isHsaAbiVersion2(getGlobalSTI())) 228 return; 229 230 auto &Streamer = getTargetStreamer()->getStreamer(); 231 auto &Context = Streamer.getContext(); 232 auto &ObjectFileInfo = *Context.getObjectFileInfo(); 233 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection(); 234 235 Streamer.PushSection(); 236 Streamer.SwitchSection(&ReadOnlySection); 237 238 // CP microcode requires the kernel descriptor to be allocated on 64 byte 239 // alignment. 240 Streamer.emitValueToAlignment(64, 0, 1, 0); 241 if (ReadOnlySection.getAlignment() < 64) 242 ReadOnlySection.setAlignment(Align(64)); 243 244 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 245 246 SmallString<128> KernelName; 247 getNameWithPrefix(KernelName, &MF->getFunction()); 248 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 249 STM, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo), 250 CurrentProgramInfo.NumVGPRsForWavesPerEU, 251 CurrentProgramInfo.NumSGPRsForWavesPerEU - 252 IsaInfo::getNumExtraSGPRs(&STM, 253 CurrentProgramInfo.VCCUsed, 254 CurrentProgramInfo.FlatUsed), 255 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed); 256 257 Streamer.PopSection(); 258 } 259 260 void AMDGPUAsmPrinter::emitFunctionEntryLabel() { 261 if (TM.getTargetTriple().getOS() == Triple::AMDHSA && 262 isHsaAbiVersion3Or4(getGlobalSTI())) { 263 AsmPrinter::emitFunctionEntryLabel(); 264 return; 265 } 266 267 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 268 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 269 if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) { 270 SmallString<128> SymbolName; 271 getNameWithPrefix(SymbolName, &MF->getFunction()), 272 getTargetStreamer()->EmitAMDGPUSymbolType( 273 SymbolName, ELF::STT_AMDGPU_HSA_KERNEL); 274 } 275 if (DumpCodeInstEmitter) { 276 // Disassemble function name label to text. 277 DisasmLines.push_back(MF->getName().str() + ":"); 278 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 279 HexLines.push_back(""); 280 } 281 282 AsmPrinter::emitFunctionEntryLabel(); 283 } 284 285 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 286 if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) { 287 // Write a line for the basic block label if it is not only fallthrough. 288 DisasmLines.push_back( 289 (Twine("BB") + Twine(getFunctionNumber()) 290 + "_" + Twine(MBB.getNumber()) + ":").str()); 291 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 292 HexLines.push_back(""); 293 } 294 AsmPrinter::emitBasicBlockStart(MBB); 295 } 296 297 void AMDGPUAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 298 if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 299 if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) { 300 OutContext.reportError({}, 301 Twine(GV->getName()) + 302 ": unsupported initializer for address space"); 303 return; 304 } 305 306 // LDS variables aren't emitted in HSA or PAL yet. 307 const Triple::OSType OS = TM.getTargetTriple().getOS(); 308 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 309 return; 310 311 MCSymbol *GVSym = getSymbol(GV); 312 313 GVSym->redefineIfPossible(); 314 if (GVSym->isDefined() || GVSym->isVariable()) 315 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 316 "' is already defined"); 317 318 const DataLayout &DL = GV->getParent()->getDataLayout(); 319 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 320 Align Alignment = GV->getAlign().getValueOr(Align(4)); 321 322 emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration()); 323 emitLinkage(GV, GVSym); 324 if (auto TS = getTargetStreamer()) 325 TS->emitAMDGPULDS(GVSym, Size, Alignment); 326 return; 327 } 328 329 AsmPrinter::emitGlobalVariable(GV); 330 } 331 332 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 333 // Pad with s_code_end to help tools and guard against instruction prefetch 334 // causing stale data in caches. Arguably this should be done by the linker, 335 // which is why this isn't done for Mesa. 336 const MCSubtargetInfo &STI = *getGlobalSTI(); 337 if ((AMDGPU::isGFX10Plus(STI) || AMDGPU::isGFX90A(STI)) && 338 (STI.getTargetTriple().getOS() == Triple::AMDHSA || 339 STI.getTargetTriple().getOS() == Triple::AMDPAL)) { 340 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 341 getTargetStreamer()->EmitCodeEnd(STI); 342 } 343 344 return AsmPrinter::doFinalization(M); 345 } 346 347 // Print comments that apply to both callable functions and entry points. 348 void AMDGPUAsmPrinter::emitCommonFunctionComments( 349 uint32_t NumVGPR, 350 Optional<uint32_t> NumAGPR, 351 uint32_t TotalNumVGPR, 352 uint32_t NumSGPR, 353 uint64_t ScratchSize, 354 uint64_t CodeSize, 355 const AMDGPUMachineFunction *MFI) { 356 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false); 357 OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false); 358 OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false); 359 if (NumAGPR) { 360 OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false); 361 OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR), 362 false); 363 } 364 OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false); 365 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()), 366 false); 367 } 368 369 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties( 370 const MachineFunction &MF) const { 371 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 372 uint16_t KernelCodeProperties = 0; 373 374 if (MFI.hasPrivateSegmentBuffer()) { 375 KernelCodeProperties |= 376 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 377 } 378 if (MFI.hasDispatchPtr()) { 379 KernelCodeProperties |= 380 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 381 } 382 if (MFI.hasQueuePtr()) { 383 KernelCodeProperties |= 384 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 385 } 386 if (MFI.hasKernargSegmentPtr()) { 387 KernelCodeProperties |= 388 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 389 } 390 if (MFI.hasDispatchID()) { 391 KernelCodeProperties |= 392 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 393 } 394 if (MFI.hasFlatScratchInit()) { 395 KernelCodeProperties |= 396 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 397 } 398 if (MF.getSubtarget<GCNSubtarget>().isWave32()) { 399 KernelCodeProperties |= 400 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32; 401 } 402 403 return KernelCodeProperties; 404 } 405 406 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 407 const MachineFunction &MF, 408 const SIProgramInfo &PI) const { 409 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 410 const Function &F = MF.getFunction(); 411 412 amdhsa::kernel_descriptor_t KernelDescriptor; 413 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 414 415 assert(isUInt<32>(PI.ScratchSize)); 416 assert(isUInt<32>(PI.getComputePGMRSrc1())); 417 assert(isUInt<32>(PI.ComputePGMRSrc2)); 418 419 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 420 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 421 422 Align MaxKernArgAlign; 423 KernelDescriptor.kernarg_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 424 425 KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1(); 426 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 427 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 428 429 assert(STM.hasGFX90AInsts() || CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0); 430 if (STM.hasGFX90AInsts()) 431 KernelDescriptor.compute_pgm_rsrc3 = 432 CurrentProgramInfo.ComputePGMRSrc3GFX90A; 433 434 return KernelDescriptor; 435 } 436 437 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 438 ResourceUsage = &getAnalysis<AMDGPUResourceUsageAnalysis>(); 439 CurrentProgramInfo = SIProgramInfo(); 440 441 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 442 443 // The starting address of all shader programs must be 256 bytes aligned. 444 // Regular functions just need the basic required instruction alignment. 445 MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4)); 446 447 SetupMachineFunction(MF); 448 449 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 450 MCContext &Context = getObjFileLowering().getContext(); 451 // FIXME: This should be an explicit check for Mesa. 452 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 453 MCSectionELF *ConfigSection = 454 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 455 OutStreamer->SwitchSection(ConfigSection); 456 } 457 458 if (MFI->isModuleEntryFunction()) { 459 getSIProgramInfo(CurrentProgramInfo, MF); 460 } 461 462 if (STM.isAmdPalOS()) { 463 if (MFI->isEntryFunction()) 464 EmitPALMetadata(MF, CurrentProgramInfo); 465 else if (MFI->isModuleEntryFunction()) 466 emitPALFunctionMetadata(MF); 467 } else if (!STM.isAmdHsaOS()) { 468 EmitProgramInfoSI(MF, CurrentProgramInfo); 469 } 470 471 DumpCodeInstEmitter = nullptr; 472 if (STM.dumpCode()) { 473 // For -dumpcode, get the assembler out of the streamer, even if it does 474 // not really want to let us have it. This only works with -filetype=obj. 475 bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing(); 476 OutStreamer->setUseAssemblerInfoForParsing(true); 477 MCAssembler *Assembler = OutStreamer->getAssemblerPtr(); 478 OutStreamer->setUseAssemblerInfoForParsing(SaveFlag); 479 if (Assembler) 480 DumpCodeInstEmitter = Assembler->getEmitterPtr(); 481 } 482 483 DisasmLines.clear(); 484 HexLines.clear(); 485 DisasmLineMaxLen = 0; 486 487 emitFunctionBody(); 488 489 if (isVerbose()) { 490 MCSectionELF *CommentSection = 491 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 492 OutStreamer->SwitchSection(CommentSection); 493 494 if (!MFI->isEntryFunction()) { 495 OutStreamer->emitRawComment(" Function info:", false); 496 const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info = 497 ResourceUsage->getResourceInfo(&MF.getFunction()); 498 emitCommonFunctionComments( 499 Info.NumVGPR, 500 STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(), 501 Info.getTotalNumVGPRs(STM), 502 Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()), 503 Info.PrivateSegmentSize, 504 getFunctionCodeSize(MF), MFI); 505 return false; 506 } 507 508 OutStreamer->emitRawComment(" Kernel info:", false); 509 emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR, 510 STM.hasMAIInsts() 511 ? CurrentProgramInfo.NumAccVGPR 512 : Optional<uint32_t>(), 513 CurrentProgramInfo.NumVGPR, 514 CurrentProgramInfo.NumSGPR, 515 CurrentProgramInfo.ScratchSize, 516 getFunctionCodeSize(MF), MFI); 517 518 OutStreamer->emitRawComment( 519 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 520 OutStreamer->emitRawComment( 521 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 522 OutStreamer->emitRawComment( 523 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 524 " bytes/workgroup (compile time only)", false); 525 526 OutStreamer->emitRawComment( 527 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 528 OutStreamer->emitRawComment( 529 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 530 531 OutStreamer->emitRawComment( 532 " NumSGPRsForWavesPerEU: " + 533 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 534 OutStreamer->emitRawComment( 535 " NumVGPRsForWavesPerEU: " + 536 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 537 538 if (STM.hasGFX90AInsts()) 539 OutStreamer->emitRawComment( 540 " AccumOffset: " + 541 Twine((CurrentProgramInfo.AccumOffset + 1) * 4), false); 542 543 OutStreamer->emitRawComment( 544 " Occupancy: " + 545 Twine(CurrentProgramInfo.Occupancy), false); 546 547 OutStreamer->emitRawComment( 548 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 549 550 OutStreamer->emitRawComment( 551 " COMPUTE_PGM_RSRC2:SCRATCH_EN: " + 552 Twine(G_00B84C_SCRATCH_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 553 OutStreamer->emitRawComment( 554 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 555 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 556 OutStreamer->emitRawComment( 557 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 558 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 559 OutStreamer->emitRawComment( 560 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 561 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 562 OutStreamer->emitRawComment( 563 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 564 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 565 OutStreamer->emitRawComment( 566 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 567 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 568 OutStreamer->emitRawComment( 569 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 570 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 571 false); 572 573 assert(STM.hasGFX90AInsts() || 574 CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0); 575 if (STM.hasGFX90AInsts()) { 576 OutStreamer->emitRawComment( 577 " COMPUTE_PGM_RSRC3_GFX90A:ACCUM_OFFSET: " + 578 Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A, 579 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET))), 580 false); 581 OutStreamer->emitRawComment( 582 " COMPUTE_PGM_RSRC3_GFX90A:TG_SPLIT: " + 583 Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A, 584 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT))), 585 false); 586 } 587 } 588 589 if (DumpCodeInstEmitter) { 590 591 OutStreamer->SwitchSection( 592 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0)); 593 594 for (size_t i = 0; i < DisasmLines.size(); ++i) { 595 std::string Comment = "\n"; 596 if (!HexLines[i].empty()) { 597 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 598 Comment += " ; " + HexLines[i] + "\n"; 599 } 600 601 OutStreamer->emitBytes(StringRef(DisasmLines[i])); 602 OutStreamer->emitBytes(StringRef(Comment)); 603 } 604 } 605 606 return false; 607 } 608 609 // TODO: Fold this into emitFunctionBodyStart. 610 void AMDGPUAsmPrinter::initializeTargetID(const Module &M) { 611 // In the beginning all features are either 'Any' or 'NotSupported', 612 // depending on global target features. This will cover empty modules. 613 getTargetStreamer()->initializeTargetID( 614 *getGlobalSTI(), getGlobalSTI()->getFeatureString()); 615 616 // If module is empty, we are done. 617 if (M.empty()) 618 return; 619 620 // If module is not empty, need to find first 'Off' or 'On' feature 621 // setting per feature from functions in module. 622 for (auto &F : M) { 623 auto &TSTargetID = getTargetStreamer()->getTargetID(); 624 if ((!TSTargetID->isXnackSupported() || TSTargetID->isXnackOnOrOff()) && 625 (!TSTargetID->isSramEccSupported() || TSTargetID->isSramEccOnOrOff())) 626 break; 627 628 const GCNSubtarget &STM = TM.getSubtarget<GCNSubtarget>(F); 629 const IsaInfo::AMDGPUTargetID &STMTargetID = STM.getTargetID(); 630 if (TSTargetID->isXnackSupported()) 631 if (TSTargetID->getXnackSetting() == IsaInfo::TargetIDSetting::Any) 632 TSTargetID->setXnackSetting(STMTargetID.getXnackSetting()); 633 if (TSTargetID->isSramEccSupported()) 634 if (TSTargetID->getSramEccSetting() == IsaInfo::TargetIDSetting::Any) 635 TSTargetID->setSramEccSetting(STMTargetID.getSramEccSetting()); 636 } 637 } 638 639 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 640 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 641 const SIInstrInfo *TII = STM.getInstrInfo(); 642 643 uint64_t CodeSize = 0; 644 645 for (const MachineBasicBlock &MBB : MF) { 646 for (const MachineInstr &MI : MBB) { 647 // TODO: CodeSize should account for multiple functions. 648 649 // TODO: Should we count size of debug info? 650 if (MI.isDebugInstr()) 651 continue; 652 653 CodeSize += TII->getInstSizeInBytes(MI); 654 } 655 } 656 657 return CodeSize; 658 } 659 660 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 661 const MachineFunction &MF) { 662 const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info = 663 ResourceUsage->getResourceInfo(&MF.getFunction()); 664 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 665 666 ProgInfo.NumArchVGPR = Info.NumVGPR; 667 ProgInfo.NumAccVGPR = Info.NumAGPR; 668 ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM); 669 ProgInfo.AccumOffset = alignTo(std::max(1, Info.NumVGPR), 4) / 4 - 1; 670 ProgInfo.TgSplit = STM.isTgSplitEnabled(); 671 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 672 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 673 ProgInfo.VCCUsed = Info.UsesVCC; 674 ProgInfo.FlatUsed = Info.UsesFlatScratch; 675 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 676 677 const uint64_t MaxScratchPerWorkitem = 678 GCNSubtarget::MaxWaveScratchSize / STM.getWavefrontSize(); 679 if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) { 680 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 681 ProgInfo.ScratchSize, 682 MaxScratchPerWorkitem, DS_Error); 683 MF.getFunction().getContext().diagnose(DiagStackSize); 684 } 685 686 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 687 688 // The calculations related to SGPR/VGPR blocks are 689 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 690 // unified. 691 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 692 &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed); 693 694 // Check the addressable register limit before we add ExtraSGPRs. 695 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 696 !STM.hasSGPRInitBug()) { 697 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 698 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 699 // This can happen due to a compiler bug or when using inline asm. 700 LLVMContext &Ctx = MF.getFunction().getContext(); 701 DiagnosticInfoResourceLimit Diag( 702 MF.getFunction(), "addressable scalar registers", ProgInfo.NumSGPR, 703 MaxAddressableNumSGPRs, DS_Error, DK_ResourceLimit); 704 Ctx.diagnose(Diag); 705 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 706 } 707 } 708 709 // Account for extra SGPRs and VGPRs reserved for debugger use. 710 ProgInfo.NumSGPR += ExtraSGPRs; 711 712 const Function &F = MF.getFunction(); 713 714 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 715 // dispatch registers are function args. 716 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 717 718 if (isShader(F.getCallingConv())) { 719 // FIXME: We should be using the number of registers determined during 720 // calling convention lowering to legalize the types. 721 const DataLayout &DL = F.getParent()->getDataLayout(); 722 for (auto &Arg : F.args()) { 723 unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32; 724 if (Arg.hasAttribute(Attribute::InReg)) 725 WaveDispatchNumSGPR += NumRegs; 726 else 727 WaveDispatchNumVGPR += NumRegs; 728 } 729 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 730 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 731 } 732 733 // Adjust number of registers used to meet default/requested minimum/maximum 734 // number of waves per execution unit request. 735 ProgInfo.NumSGPRsForWavesPerEU = std::max( 736 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 737 ProgInfo.NumVGPRsForWavesPerEU = std::max( 738 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 739 740 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 741 STM.hasSGPRInitBug()) { 742 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 743 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 744 // This can happen due to a compiler bug or when using inline asm to use 745 // the registers which are usually reserved for vcc etc. 746 LLVMContext &Ctx = MF.getFunction().getContext(); 747 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "scalar registers", 748 ProgInfo.NumSGPR, MaxAddressableNumSGPRs, 749 DS_Error, DK_ResourceLimit); 750 Ctx.diagnose(Diag); 751 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 752 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 753 } 754 } 755 756 if (STM.hasSGPRInitBug()) { 757 ProgInfo.NumSGPR = 758 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 759 ProgInfo.NumSGPRsForWavesPerEU = 760 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 761 } 762 763 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 764 LLVMContext &Ctx = MF.getFunction().getContext(); 765 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 766 MFI->getNumUserSGPRs(), 767 STM.getMaxNumUserSGPRs(), DS_Error); 768 Ctx.diagnose(Diag); 769 } 770 771 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 772 LLVMContext &Ctx = MF.getFunction().getContext(); 773 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 774 MFI->getLDSSize(), 775 STM.getLocalMemorySize(), DS_Error); 776 Ctx.diagnose(Diag); 777 } 778 779 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 780 &STM, ProgInfo.NumSGPRsForWavesPerEU); 781 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 782 &STM, ProgInfo.NumVGPRsForWavesPerEU); 783 784 const SIModeRegisterDefaults Mode = MFI->getMode(); 785 786 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 787 // register. 788 ProgInfo.FloatMode = getFPMode(Mode); 789 790 ProgInfo.IEEEMode = Mode.IEEE; 791 792 // Make clamp modifier on NaN input returns 0. 793 ProgInfo.DX10Clamp = Mode.DX10Clamp; 794 795 unsigned LDSAlignShift; 796 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 797 // LDS is allocated in 64 dword blocks. 798 LDSAlignShift = 8; 799 } else { 800 // LDS is allocated in 128 dword blocks. 801 LDSAlignShift = 9; 802 } 803 804 unsigned LDSSpillSize = 805 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 806 807 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 808 ProgInfo.LDSBlocks = 809 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 810 811 // Scratch is allocated in 256 dword blocks. 812 unsigned ScratchAlignShift = 10; 813 // We need to program the hardware with the amount of scratch memory that 814 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 815 // scratch memory used per thread. 816 ProgInfo.ScratchBlocks = 817 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 818 1ULL << ScratchAlignShift) >> 819 ScratchAlignShift; 820 821 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) { 822 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1; 823 ProgInfo.MemOrdered = 1; 824 } 825 826 // 0 = X, 1 = XY, 2 = XYZ 827 unsigned TIDIGCompCnt = 0; 828 if (MFI->hasWorkItemIDZ()) 829 TIDIGCompCnt = 2; 830 else if (MFI->hasWorkItemIDY()) 831 TIDIGCompCnt = 1; 832 833 ProgInfo.ComputePGMRSrc2 = 834 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 835 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 836 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 837 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 838 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 839 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 840 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 841 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 842 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 843 S_00B84C_EXCP_EN_MSB(0) | 844 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 845 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 846 S_00B84C_EXCP_EN(0); 847 848 if (STM.hasGFX90AInsts()) { 849 AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A, 850 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET, 851 ProgInfo.AccumOffset); 852 AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A, 853 amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT, 854 ProgInfo.TgSplit); 855 } 856 857 ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize, 858 ProgInfo.NumSGPRsForWavesPerEU, 859 ProgInfo.NumVGPRsForWavesPerEU); 860 } 861 862 static unsigned getRsrcReg(CallingConv::ID CallConv) { 863 switch (CallConv) { 864 default: LLVM_FALLTHROUGH; 865 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 866 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 867 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 868 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 869 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 870 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 871 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 872 } 873 } 874 875 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 876 const SIProgramInfo &CurrentProgramInfo) { 877 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 878 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 879 880 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 881 OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1); 882 883 OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1()); 884 885 OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2); 886 OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2); 887 888 OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE); 889 OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks)); 890 891 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 892 // 0" comment but I don't see a corresponding field in the register spec. 893 } else { 894 OutStreamer->emitInt32(RsrcReg); 895 OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 896 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 897 OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE); 898 OutStreamer->emitIntValue( 899 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 900 } 901 902 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 903 OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS); 904 OutStreamer->emitInt32( 905 S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 906 OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA); 907 OutStreamer->emitInt32(MFI->getPSInputEnable()); 908 OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR); 909 OutStreamer->emitInt32(MFI->getPSInputAddr()); 910 } 911 912 OutStreamer->emitInt32(R_SPILLED_SGPRS); 913 OutStreamer->emitInt32(MFI->getNumSpilledSGPRs()); 914 OutStreamer->emitInt32(R_SPILLED_VGPRS); 915 OutStreamer->emitInt32(MFI->getNumSpilledVGPRs()); 916 } 917 918 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 919 // is AMDPAL. It stores each compute/SPI register setting and other PAL 920 // metadata items into the PALMD::Metadata, combining with any provided by the 921 // frontend as LLVM metadata. Once all functions are written, the PAL metadata 922 // is then written as a single block in the .note section. 923 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 924 const SIProgramInfo &CurrentProgramInfo) { 925 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 926 auto CC = MF.getFunction().getCallingConv(); 927 auto MD = getTargetStreamer()->getPALMetadata(); 928 929 MD->setEntryPoint(CC, MF.getFunction().getName()); 930 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU); 931 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU); 932 MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC)); 933 if (AMDGPU::isCompute(CC)) { 934 MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2); 935 } else { 936 if (CurrentProgramInfo.ScratchBlocks > 0) 937 MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1)); 938 } 939 // ScratchSize is in bytes, 16 aligned. 940 MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16)); 941 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 942 MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 943 MD->setSpiPsInputEna(MFI->getPSInputEnable()); 944 MD->setSpiPsInputAddr(MFI->getPSInputAddr()); 945 } 946 947 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 948 if (STM.isWave32()) 949 MD->setWave32(MF.getFunction().getCallingConv()); 950 } 951 952 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) { 953 auto *MD = getTargetStreamer()->getPALMetadata(); 954 const MachineFrameInfo &MFI = MF.getFrameInfo(); 955 MD->setFunctionScratchSize(MF, MFI.getStackSize()); 956 957 // Set compute registers 958 MD->setRsrc1(CallingConv::AMDGPU_CS, 959 CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS)); 960 MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2); 961 962 // Set optional info 963 MD->setFunctionLdsSize(MF, CurrentProgramInfo.LDSSize); 964 MD->setFunctionNumUsedVgprs(MF, CurrentProgramInfo.NumVGPRsForWavesPerEU); 965 MD->setFunctionNumUsedSgprs(MF, CurrentProgramInfo.NumSGPRsForWavesPerEU); 966 } 967 968 // This is supposed to be log2(Size) 969 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 970 switch (Size) { 971 case 4: 972 return AMD_ELEMENT_4_BYTES; 973 case 8: 974 return AMD_ELEMENT_8_BYTES; 975 case 16: 976 return AMD_ELEMENT_16_BYTES; 977 default: 978 llvm_unreachable("invalid private_element_size"); 979 } 980 } 981 982 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 983 const SIProgramInfo &CurrentProgramInfo, 984 const MachineFunction &MF) const { 985 const Function &F = MF.getFunction(); 986 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 987 F.getCallingConv() == CallingConv::SPIR_KERNEL); 988 989 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 990 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 991 992 AMDGPU::initDefaultAMDKernelCodeT(Out, &STM); 993 994 Out.compute_pgm_resource_registers = 995 CurrentProgramInfo.getComputePGMRSrc1() | 996 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 997 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64; 998 999 if (CurrentProgramInfo.DynamicCallStack) 1000 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1001 1002 AMD_HSA_BITS_SET(Out.code_properties, 1003 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1004 getElementByteSizeValue(STM.getMaxPrivateElementSize(true))); 1005 1006 if (MFI->hasPrivateSegmentBuffer()) { 1007 Out.code_properties |= 1008 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1009 } 1010 1011 if (MFI->hasDispatchPtr()) 1012 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1013 1014 if (MFI->hasQueuePtr()) 1015 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1016 1017 if (MFI->hasKernargSegmentPtr()) 1018 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1019 1020 if (MFI->hasDispatchID()) 1021 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1022 1023 if (MFI->hasFlatScratchInit()) 1024 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1025 1026 if (MFI->hasDispatchPtr()) 1027 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1028 1029 if (STM.isXNACKEnabled()) 1030 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1031 1032 Align MaxKernArgAlign; 1033 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1034 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1035 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1036 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1037 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1038 1039 // kernarg_segment_alignment is specified as log of the alignment. 1040 // The minimum alignment is 16. 1041 Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign)); 1042 } 1043 1044 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1045 const char *ExtraCode, raw_ostream &O) { 1046 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1047 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O)) 1048 return false; 1049 1050 if (ExtraCode && ExtraCode[0]) { 1051 if (ExtraCode[1] != 0) 1052 return true; // Unknown modifier. 1053 1054 switch (ExtraCode[0]) { 1055 case 'r': 1056 break; 1057 default: 1058 return true; 1059 } 1060 } 1061 1062 // TODO: Should be able to support other operand types like globals. 1063 const MachineOperand &MO = MI->getOperand(OpNo); 1064 if (MO.isReg()) { 1065 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1066 *MF->getSubtarget().getRegisterInfo()); 1067 return false; 1068 } else if (MO.isImm()) { 1069 int64_t Val = MO.getImm(); 1070 if (AMDGPU::isInlinableIntLiteral(Val)) { 1071 O << Val; 1072 } else if (isUInt<16>(Val)) { 1073 O << format("0x%" PRIx16, static_cast<uint16_t>(Val)); 1074 } else if (isUInt<32>(Val)) { 1075 O << format("0x%" PRIx32, static_cast<uint32_t>(Val)); 1076 } else { 1077 O << format("0x%" PRIx64, static_cast<uint64_t>(Val)); 1078 } 1079 return false; 1080 } 1081 return true; 1082 } 1083 1084 void AMDGPUAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 1085 AU.addRequired<AMDGPUResourceUsageAnalysis>(); 1086 AU.addPreserved<AMDGPUResourceUsageAnalysis>(); 1087 AsmPrinter::getAnalysisUsage(AU); 1088 } 1089