1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// 11 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary 12 /// code. When passed an MCAsmStreamer it prints assembly and when passed 13 /// an MCObjectStreamer it outputs binary code. 14 // 15 //===----------------------------------------------------------------------===// 16 // 17 18 #include "AMDGPUAsmPrinter.h" 19 #include "AMDGPU.h" 20 #include "AMDGPUSubtarget.h" 21 #include "AMDGPUTargetMachine.h" 22 #include "MCTargetDesc/AMDGPUInstPrinter.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "MCTargetDesc/AMDGPUTargetStreamer.h" 25 #include "R600AsmPrinter.h" 26 #include "R600Defines.h" 27 #include "R600MachineFunctionInfo.h" 28 #include "R600RegisterInfo.h" 29 #include "SIDefines.h" 30 #include "SIInstrInfo.h" 31 #include "SIMachineFunctionInfo.h" 32 #include "SIRegisterInfo.h" 33 #include "TargetInfo/AMDGPUTargetInfo.h" 34 #include "Utils/AMDGPUBaseInfo.h" 35 #include "llvm/BinaryFormat/ELF.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/IR/DiagnosticInfo.h" 38 #include "llvm/MC/MCAssembler.h" 39 #include "llvm/MC/MCContext.h" 40 #include "llvm/MC/MCSectionELF.h" 41 #include "llvm/MC/MCStreamer.h" 42 #include "llvm/Support/AMDGPUMetadata.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/TargetParser.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Target/TargetLoweringObjectFile.h" 47 48 using namespace llvm; 49 using namespace llvm::AMDGPU; 50 using namespace llvm::AMDGPU::HSAMD; 51 52 // TODO: This should get the default rounding mode from the kernel. We just set 53 // the default here, but this could change if the OpenCL rounding mode pragmas 54 // are used. 55 // 56 // The denormal mode here should match what is reported by the OpenCL runtime 57 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but 58 // can also be override to flush with the -cl-denorms-are-zero compiler flag. 59 // 60 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double 61 // precision, and leaves single precision to flush all and does not report 62 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports 63 // CL_FP_DENORM for both. 64 // 65 // FIXME: It seems some instructions do not support single precision denormals 66 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32, 67 // and sin_f32, cos_f32 on most parts). 68 69 // We want to use these instructions, and using fp32 denormals also causes 70 // instructions to run at the double precision rate for the device so it's 71 // probably best to just report no single precision denormals. 72 static uint32_t getFPMode(const MachineFunction &F) { 73 const GCNSubtarget& ST = F.getSubtarget<GCNSubtarget>(); 74 // TODO: Is there any real use for the flush in only / flush out only modes? 75 76 uint32_t FP32Denormals = 77 ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 78 79 uint32_t FP64Denormals = 80 ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 81 82 return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) | 83 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) | 84 FP_DENORM_MODE_SP(FP32Denormals) | 85 FP_DENORM_MODE_DP(FP64Denormals); 86 } 87 88 static AsmPrinter * 89 createAMDGPUAsmPrinterPass(TargetMachine &tm, 90 std::unique_ptr<MCStreamer> &&Streamer) { 91 return new AMDGPUAsmPrinter(tm, std::move(Streamer)); 92 } 93 94 extern "C" void LLVMInitializeAMDGPUAsmPrinter() { 95 TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(), 96 llvm::createR600AsmPrinterPass); 97 TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(), 98 createAMDGPUAsmPrinterPass); 99 } 100 101 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, 102 std::unique_ptr<MCStreamer> Streamer) 103 : AsmPrinter(TM, std::move(Streamer)) { 104 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) 105 HSAMetadataStream.reset(new MetadataStreamerV3()); 106 else 107 HSAMetadataStream.reset(new MetadataStreamerV2()); 108 } 109 110 StringRef AMDGPUAsmPrinter::getPassName() const { 111 return "AMDGPU Assembly Printer"; 112 } 113 114 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const { 115 return TM.getMCSubtargetInfo(); 116 } 117 118 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const { 119 if (!OutStreamer) 120 return nullptr; 121 return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer()); 122 } 123 124 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) { 125 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) { 126 std::string ExpectedTarget; 127 raw_string_ostream ExpectedTargetOS(ExpectedTarget); 128 IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS); 129 130 getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget); 131 } 132 133 if (TM.getTargetTriple().getOS() != Triple::AMDHSA && 134 TM.getTargetTriple().getOS() != Triple::AMDPAL) 135 return; 136 137 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 138 HSAMetadataStream->begin(M); 139 140 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) 141 getTargetStreamer()->getPALMetadata()->readFromIR(M); 142 143 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) 144 return; 145 146 // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2. 147 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 148 getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1); 149 150 // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2. 151 IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU()); 152 getTargetStreamer()->EmitDirectiveHSACodeObjectISA( 153 Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU"); 154 } 155 156 void AMDGPUAsmPrinter::EmitEndOfAsmFile(Module &M) { 157 // Following code requires TargetStreamer to be present. 158 if (!getTargetStreamer()) 159 return; 160 161 if (!IsaInfo::hasCodeObjectV3(getGlobalSTI())) { 162 // Emit ISA Version (NT_AMD_AMDGPU_ISA). 163 std::string ISAVersionString; 164 raw_string_ostream ISAVersionStream(ISAVersionString); 165 IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream); 166 getTargetStreamer()->EmitISAVersion(ISAVersionStream.str()); 167 } 168 169 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA). 170 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 171 HSAMetadataStream->end(); 172 bool Success = HSAMetadataStream->emitTo(*getTargetStreamer()); 173 (void)Success; 174 assert(Success && "Malformed HSA Metadata"); 175 } 176 } 177 178 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough( 179 const MachineBasicBlock *MBB) const { 180 if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) 181 return false; 182 183 if (MBB->empty()) 184 return true; 185 186 // If this is a block implementing a long branch, an expression relative to 187 // the start of the block is needed. to the start of the block. 188 // XXX - Is there a smarter way to check this? 189 return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64); 190 } 191 192 void AMDGPUAsmPrinter::EmitFunctionBodyStart() { 193 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 194 if (!MFI.isEntryFunction()) 195 return; 196 197 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 198 const Function &F = MF->getFunction(); 199 if (!STM.hasCodeObjectV3() && STM.isAmdHsaOrMesa(F) && 200 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 201 F.getCallingConv() == CallingConv::SPIR_KERNEL)) { 202 amd_kernel_code_t KernelCode; 203 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 204 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 205 } 206 207 if (STM.isAmdHsaOS()) 208 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo); 209 210 DumpCodeInstEmitter = nullptr; 211 if (STM.dumpCode()) { 212 // For -dumpcode, get the assembler out of the streamer, even if it does 213 // not really want to let us have it. This only works with -filetype=obj. 214 bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing(); 215 OutStreamer->setUseAssemblerInfoForParsing(true); 216 MCAssembler *Assembler = OutStreamer->getAssemblerPtr(); 217 OutStreamer->setUseAssemblerInfoForParsing(SaveFlag); 218 if (Assembler) 219 DumpCodeInstEmitter = Assembler->getEmitterPtr(); 220 } 221 } 222 223 void AMDGPUAsmPrinter::EmitFunctionBodyEnd() { 224 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 225 if (!MFI.isEntryFunction()) 226 return; 227 228 if (!IsaInfo::hasCodeObjectV3(getGlobalSTI()) || 229 TM.getTargetTriple().getOS() != Triple::AMDHSA) 230 return; 231 232 auto &Streamer = getTargetStreamer()->getStreamer(); 233 auto &Context = Streamer.getContext(); 234 auto &ObjectFileInfo = *Context.getObjectFileInfo(); 235 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection(); 236 237 Streamer.PushSection(); 238 Streamer.SwitchSection(&ReadOnlySection); 239 240 // CP microcode requires the kernel descriptor to be allocated on 64 byte 241 // alignment. 242 Streamer.EmitValueToAlignment(64, 0, 1, 0); 243 if (ReadOnlySection.getAlignment() < 64) 244 ReadOnlySection.setAlignment(64); 245 246 const MCSubtargetInfo &STI = MF->getSubtarget(); 247 248 SmallString<128> KernelName; 249 getNameWithPrefix(KernelName, &MF->getFunction()); 250 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 251 STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo), 252 CurrentProgramInfo.NumVGPRsForWavesPerEU, 253 CurrentProgramInfo.NumSGPRsForWavesPerEU - 254 IsaInfo::getNumExtraSGPRs(&STI, 255 CurrentProgramInfo.VCCUsed, 256 CurrentProgramInfo.FlatUsed), 257 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed, 258 hasXNACK(STI)); 259 260 Streamer.PopSection(); 261 } 262 263 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() { 264 if (IsaInfo::hasCodeObjectV3(getGlobalSTI()) && 265 TM.getTargetTriple().getOS() == Triple::AMDHSA) { 266 AsmPrinter::EmitFunctionEntryLabel(); 267 return; 268 } 269 270 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 271 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 272 if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) { 273 SmallString<128> SymbolName; 274 getNameWithPrefix(SymbolName, &MF->getFunction()), 275 getTargetStreamer()->EmitAMDGPUSymbolType( 276 SymbolName, ELF::STT_AMDGPU_HSA_KERNEL); 277 } 278 if (DumpCodeInstEmitter) { 279 // Disassemble function name label to text. 280 DisasmLines.push_back(MF->getName().str() + ":"); 281 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 282 HexLines.push_back(""); 283 } 284 285 AsmPrinter::EmitFunctionEntryLabel(); 286 } 287 288 void AMDGPUAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 289 if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) { 290 // Write a line for the basic block label if it is not only fallthrough. 291 DisasmLines.push_back( 292 (Twine("BB") + Twine(getFunctionNumber()) 293 + "_" + Twine(MBB.getNumber()) + ":").str()); 294 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 295 HexLines.push_back(""); 296 } 297 AsmPrinter::EmitBasicBlockStart(MBB); 298 } 299 300 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 301 302 // Group segment variables aren't emitted in HSA. 303 if (AMDGPU::isGroupSegment(GV)) 304 return; 305 306 AsmPrinter::EmitGlobalVariable(GV); 307 } 308 309 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 310 CallGraphResourceInfo.clear(); 311 312 if (AMDGPU::isGFX10(*getGlobalSTI())) { 313 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 314 getTargetStreamer()->EmitCodeEnd(); 315 } 316 317 return AsmPrinter::doFinalization(M); 318 } 319 320 // Print comments that apply to both callable functions and entry points. 321 void AMDGPUAsmPrinter::emitCommonFunctionComments( 322 uint32_t NumVGPR, 323 uint32_t NumSGPR, 324 uint64_t ScratchSize, 325 uint64_t CodeSize, 326 const AMDGPUMachineFunction *MFI) { 327 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false); 328 OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false); 329 OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false); 330 OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false); 331 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()), 332 false); 333 } 334 335 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties( 336 const MachineFunction &MF) const { 337 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 338 uint16_t KernelCodeProperties = 0; 339 340 if (MFI.hasPrivateSegmentBuffer()) { 341 KernelCodeProperties |= 342 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 343 } 344 if (MFI.hasDispatchPtr()) { 345 KernelCodeProperties |= 346 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 347 } 348 if (MFI.hasQueuePtr()) { 349 KernelCodeProperties |= 350 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 351 } 352 if (MFI.hasKernargSegmentPtr()) { 353 KernelCodeProperties |= 354 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 355 } 356 if (MFI.hasDispatchID()) { 357 KernelCodeProperties |= 358 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 359 } 360 if (MFI.hasFlatScratchInit()) { 361 KernelCodeProperties |= 362 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 363 } 364 365 return KernelCodeProperties; 366 } 367 368 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 369 const MachineFunction &MF, 370 const SIProgramInfo &PI) const { 371 amdhsa::kernel_descriptor_t KernelDescriptor; 372 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 373 374 assert(isUInt<32>(PI.ScratchSize)); 375 assert(isUInt<32>(PI.ComputePGMRSrc1)); 376 assert(isUInt<32>(PI.ComputePGMRSrc2)); 377 378 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 379 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 380 KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1; 381 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 382 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 383 384 return KernelDescriptor; 385 } 386 387 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 388 CurrentProgramInfo = SIProgramInfo(); 389 390 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 391 392 // The starting address of all shader programs must be 256 bytes aligned. 393 // Regular functions just need the basic required instruction alignment. 394 MF.setAlignment(MFI->isEntryFunction() ? 8 : 2); 395 396 SetupMachineFunction(MF); 397 398 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 399 MCContext &Context = getObjFileLowering().getContext(); 400 // FIXME: This should be an explicit check for Mesa. 401 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 402 MCSectionELF *ConfigSection = 403 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 404 OutStreamer->SwitchSection(ConfigSection); 405 } 406 407 if (MFI->isEntryFunction()) { 408 getSIProgramInfo(CurrentProgramInfo, MF); 409 } else { 410 auto I = CallGraphResourceInfo.insert( 411 std::make_pair(&MF.getFunction(), SIFunctionResourceInfo())); 412 SIFunctionResourceInfo &Info = I.first->second; 413 assert(I.second && "should only be called once per function"); 414 Info = analyzeResourceUsage(MF); 415 } 416 417 if (STM.isAmdPalOS()) 418 EmitPALMetadata(MF, CurrentProgramInfo); 419 else if (!STM.isAmdHsaOS()) { 420 EmitProgramInfoSI(MF, CurrentProgramInfo); 421 } 422 423 DisasmLines.clear(); 424 HexLines.clear(); 425 DisasmLineMaxLen = 0; 426 427 EmitFunctionBody(); 428 429 if (isVerbose()) { 430 MCSectionELF *CommentSection = 431 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 432 OutStreamer->SwitchSection(CommentSection); 433 434 if (!MFI->isEntryFunction()) { 435 OutStreamer->emitRawComment(" Function info:", false); 436 SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()]; 437 emitCommonFunctionComments( 438 Info.NumVGPR, 439 Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()), 440 Info.PrivateSegmentSize, 441 getFunctionCodeSize(MF), MFI); 442 return false; 443 } 444 445 OutStreamer->emitRawComment(" Kernel info:", false); 446 emitCommonFunctionComments(CurrentProgramInfo.NumVGPR, 447 CurrentProgramInfo.NumSGPR, 448 CurrentProgramInfo.ScratchSize, 449 getFunctionCodeSize(MF), MFI); 450 451 OutStreamer->emitRawComment( 452 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 453 OutStreamer->emitRawComment( 454 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 455 OutStreamer->emitRawComment( 456 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 457 " bytes/workgroup (compile time only)", false); 458 459 OutStreamer->emitRawComment( 460 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 461 OutStreamer->emitRawComment( 462 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 463 464 OutStreamer->emitRawComment( 465 " NumSGPRsForWavesPerEU: " + 466 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 467 OutStreamer->emitRawComment( 468 " NumVGPRsForWavesPerEU: " + 469 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 470 471 OutStreamer->emitRawComment( 472 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 473 474 OutStreamer->emitRawComment( 475 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 476 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 477 OutStreamer->emitRawComment( 478 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 479 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 480 OutStreamer->emitRawComment( 481 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 482 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 483 OutStreamer->emitRawComment( 484 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 485 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 486 OutStreamer->emitRawComment( 487 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 488 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 489 OutStreamer->emitRawComment( 490 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 491 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 492 false); 493 } 494 495 if (DumpCodeInstEmitter) { 496 497 OutStreamer->SwitchSection( 498 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0)); 499 500 for (size_t i = 0; i < DisasmLines.size(); ++i) { 501 std::string Comment = "\n"; 502 if (!HexLines[i].empty()) { 503 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 504 Comment += " ; " + HexLines[i] + "\n"; 505 } 506 507 OutStreamer->EmitBytes(StringRef(DisasmLines[i])); 508 OutStreamer->EmitBytes(StringRef(Comment)); 509 } 510 } 511 512 return false; 513 } 514 515 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 516 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 517 const SIInstrInfo *TII = STM.getInstrInfo(); 518 519 uint64_t CodeSize = 0; 520 521 for (const MachineBasicBlock &MBB : MF) { 522 for (const MachineInstr &MI : MBB) { 523 // TODO: CodeSize should account for multiple functions. 524 525 // TODO: Should we count size of debug info? 526 if (MI.isDebugInstr()) 527 continue; 528 529 CodeSize += TII->getInstSizeInBytes(MI); 530 } 531 } 532 533 return CodeSize; 534 } 535 536 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 537 const SIInstrInfo &TII, 538 unsigned Reg) { 539 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 540 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 541 return true; 542 } 543 544 return false; 545 } 546 547 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 548 const GCNSubtarget &ST) const { 549 return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST, 550 UsesVCC, UsesFlatScratch); 551 } 552 553 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 554 const MachineFunction &MF) const { 555 SIFunctionResourceInfo Info; 556 557 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 558 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 559 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 560 const MachineRegisterInfo &MRI = MF.getRegInfo(); 561 const SIInstrInfo *TII = ST.getInstrInfo(); 562 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 563 564 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 565 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 566 567 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 568 // instructions aren't used to access the scratch buffer. Inline assembly may 569 // need it though. 570 // 571 // If we only have implicit uses of flat_scr on flat instructions, it is not 572 // really needed. 573 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 574 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 575 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 576 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 577 Info.UsesFlatScratch = false; 578 } 579 580 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 581 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 582 if (MFI->isStackRealigned()) 583 Info.PrivateSegmentSize += FrameInfo.getMaxAlignment(); 584 585 586 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 587 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 588 589 // If there are no calls, MachineRegisterInfo can tell us the used register 590 // count easily. 591 // A tail call isn't considered a call for MachineFrameInfo's purposes. 592 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 593 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 594 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 595 if (MRI.isPhysRegUsed(Reg)) { 596 HighestVGPRReg = Reg; 597 break; 598 } 599 } 600 601 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 602 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 603 if (MRI.isPhysRegUsed(Reg)) { 604 HighestSGPRReg = Reg; 605 break; 606 } 607 } 608 609 // We found the maximum register index. They start at 0, so add one to get the 610 // number of registers. 611 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 612 TRI.getHWRegIndex(HighestVGPRReg) + 1; 613 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 614 TRI.getHWRegIndex(HighestSGPRReg) + 1; 615 616 return Info; 617 } 618 619 int32_t MaxVGPR = -1; 620 int32_t MaxSGPR = -1; 621 uint64_t CalleeFrameSize = 0; 622 623 for (const MachineBasicBlock &MBB : MF) { 624 for (const MachineInstr &MI : MBB) { 625 // TODO: Check regmasks? Do they occur anywhere except calls? 626 for (const MachineOperand &MO : MI.operands()) { 627 unsigned Width = 0; 628 bool IsSGPR = false; 629 630 if (!MO.isReg()) 631 continue; 632 633 unsigned Reg = MO.getReg(); 634 switch (Reg) { 635 case AMDGPU::EXEC: 636 case AMDGPU::EXEC_LO: 637 case AMDGPU::EXEC_HI: 638 case AMDGPU::SCC: 639 case AMDGPU::M0: 640 case AMDGPU::SRC_SHARED_BASE: 641 case AMDGPU::SRC_SHARED_LIMIT: 642 case AMDGPU::SRC_PRIVATE_BASE: 643 case AMDGPU::SRC_PRIVATE_LIMIT: 644 case AMDGPU::SGPR_NULL: 645 continue; 646 647 case AMDGPU::SRC_POPS_EXITING_WAVE_ID: 648 llvm_unreachable("src_pops_exiting_wave_id should not be used"); 649 650 case AMDGPU::NoRegister: 651 assert(MI.isDebugInstr()); 652 continue; 653 654 case AMDGPU::VCC: 655 case AMDGPU::VCC_LO: 656 case AMDGPU::VCC_HI: 657 Info.UsesVCC = true; 658 continue; 659 660 case AMDGPU::FLAT_SCR: 661 case AMDGPU::FLAT_SCR_LO: 662 case AMDGPU::FLAT_SCR_HI: 663 continue; 664 665 case AMDGPU::XNACK_MASK: 666 case AMDGPU::XNACK_MASK_LO: 667 case AMDGPU::XNACK_MASK_HI: 668 llvm_unreachable("xnack_mask registers should not be used"); 669 670 case AMDGPU::LDS_DIRECT: 671 llvm_unreachable("lds_direct register should not be used"); 672 673 case AMDGPU::TBA: 674 case AMDGPU::TBA_LO: 675 case AMDGPU::TBA_HI: 676 case AMDGPU::TMA: 677 case AMDGPU::TMA_LO: 678 case AMDGPU::TMA_HI: 679 llvm_unreachable("trap handler registers should not be used"); 680 681 default: 682 break; 683 } 684 685 if (AMDGPU::SReg_32RegClass.contains(Reg)) { 686 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 687 "trap handler registers should not be used"); 688 IsSGPR = true; 689 Width = 1; 690 } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) { 691 IsSGPR = false; 692 Width = 1; 693 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 694 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 695 "trap handler registers should not be used"); 696 IsSGPR = true; 697 Width = 2; 698 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 699 IsSGPR = false; 700 Width = 2; 701 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 702 IsSGPR = false; 703 Width = 3; 704 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 705 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 706 "trap handler registers should not be used"); 707 IsSGPR = true; 708 Width = 4; 709 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 710 IsSGPR = false; 711 Width = 4; 712 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 713 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 714 "trap handler registers should not be used"); 715 IsSGPR = true; 716 Width = 8; 717 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 718 IsSGPR = false; 719 Width = 8; 720 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 721 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 722 "trap handler registers should not be used"); 723 IsSGPR = true; 724 Width = 16; 725 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 726 IsSGPR = false; 727 Width = 16; 728 } else if (AMDGPU::SReg_96RegClass.contains(Reg)) { 729 IsSGPR = true; 730 Width = 3; 731 } else { 732 llvm_unreachable("Unknown register class"); 733 } 734 unsigned HWReg = TRI.getHWRegIndex(Reg); 735 int MaxUsed = HWReg + Width - 1; 736 if (IsSGPR) { 737 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 738 } else { 739 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 740 } 741 } 742 743 if (MI.isCall()) { 744 // Pseudo used just to encode the underlying global. Is there a better 745 // way to track this? 746 747 const MachineOperand *CalleeOp 748 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 749 const Function *Callee = cast<Function>(CalleeOp->getGlobal()); 750 if (Callee->isDeclaration()) { 751 // If this is a call to an external function, we can't do much. Make 752 // conservative guesses. 753 754 // 48 SGPRs - vcc, - flat_scr, -xnack 755 int MaxSGPRGuess = 756 47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace()); 757 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 758 MaxVGPR = std::max(MaxVGPR, 23); 759 760 CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384)); 761 Info.UsesVCC = true; 762 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 763 Info.HasDynamicallySizedStack = true; 764 } else { 765 // We force CodeGen to run in SCC order, so the callee's register 766 // usage etc. should be the cumulative usage of all callees. 767 768 auto I = CallGraphResourceInfo.find(Callee); 769 if (I == CallGraphResourceInfo.end()) { 770 // Avoid crashing on undefined behavior with an illegal call to a 771 // kernel. If a callsite's calling convention doesn't match the 772 // function's, it's undefined behavior. If the callsite calling 773 // convention does match, that would have errored earlier. 774 // FIXME: The verifier shouldn't allow this. 775 if (AMDGPU::isEntryFunctionCC(Callee->getCallingConv())) 776 report_fatal_error("invalid call to entry function"); 777 778 llvm_unreachable("callee should have been handled before caller"); 779 } 780 781 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 782 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 783 CalleeFrameSize 784 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 785 Info.UsesVCC |= I->second.UsesVCC; 786 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 787 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 788 Info.HasRecursion |= I->second.HasRecursion; 789 } 790 791 if (!Callee->doesNotRecurse()) 792 Info.HasRecursion = true; 793 } 794 } 795 } 796 797 Info.NumExplicitSGPR = MaxSGPR + 1; 798 Info.NumVGPR = MaxVGPR + 1; 799 Info.PrivateSegmentSize += CalleeFrameSize; 800 801 return Info; 802 } 803 804 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 805 const MachineFunction &MF) { 806 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 807 808 ProgInfo.NumVGPR = Info.NumVGPR; 809 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 810 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 811 ProgInfo.VCCUsed = Info.UsesVCC; 812 ProgInfo.FlatUsed = Info.UsesFlatScratch; 813 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 814 815 if (!isUInt<32>(ProgInfo.ScratchSize)) { 816 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 817 ProgInfo.ScratchSize, DS_Error); 818 MF.getFunction().getContext().diagnose(DiagStackSize); 819 } 820 821 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 822 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 823 824 // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are 825 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 826 // unified. 827 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 828 &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed); 829 830 // Check the addressable register limit before we add ExtraSGPRs. 831 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 832 !STM.hasSGPRInitBug()) { 833 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 834 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 835 // This can happen due to a compiler bug or when using inline asm. 836 LLVMContext &Ctx = MF.getFunction().getContext(); 837 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 838 "addressable scalar registers", 839 ProgInfo.NumSGPR, DS_Error, 840 DK_ResourceLimit, 841 MaxAddressableNumSGPRs); 842 Ctx.diagnose(Diag); 843 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 844 } 845 } 846 847 // Account for extra SGPRs and VGPRs reserved for debugger use. 848 ProgInfo.NumSGPR += ExtraSGPRs; 849 850 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 851 // dispatch registers are function args. 852 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 853 for (auto &Arg : MF.getFunction().args()) { 854 unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32; 855 if (Arg.hasAttribute(Attribute::InReg)) 856 WaveDispatchNumSGPR += NumRegs; 857 else 858 WaveDispatchNumVGPR += NumRegs; 859 } 860 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 861 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 862 863 // Adjust number of registers used to meet default/requested minimum/maximum 864 // number of waves per execution unit request. 865 ProgInfo.NumSGPRsForWavesPerEU = std::max( 866 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 867 ProgInfo.NumVGPRsForWavesPerEU = std::max( 868 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 869 870 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 871 STM.hasSGPRInitBug()) { 872 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 873 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 874 // This can happen due to a compiler bug or when using inline asm to use 875 // the registers which are usually reserved for vcc etc. 876 LLVMContext &Ctx = MF.getFunction().getContext(); 877 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 878 "scalar registers", 879 ProgInfo.NumSGPR, DS_Error, 880 DK_ResourceLimit, 881 MaxAddressableNumSGPRs); 882 Ctx.diagnose(Diag); 883 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 884 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 885 } 886 } 887 888 if (STM.hasSGPRInitBug()) { 889 ProgInfo.NumSGPR = 890 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 891 ProgInfo.NumSGPRsForWavesPerEU = 892 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 893 } 894 895 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 896 LLVMContext &Ctx = MF.getFunction().getContext(); 897 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 898 MFI->getNumUserSGPRs(), DS_Error); 899 Ctx.diagnose(Diag); 900 } 901 902 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 903 LLVMContext &Ctx = MF.getFunction().getContext(); 904 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 905 MFI->getLDSSize(), DS_Error); 906 Ctx.diagnose(Diag); 907 } 908 909 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 910 &STM, ProgInfo.NumSGPRsForWavesPerEU); 911 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 912 &STM, ProgInfo.NumVGPRsForWavesPerEU); 913 914 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 915 // register. 916 ProgInfo.FloatMode = getFPMode(MF); 917 918 const SIModeRegisterDefaults Mode = MFI->getMode(); 919 ProgInfo.IEEEMode = Mode.IEEE; 920 921 // Make clamp modifier on NaN input returns 0. 922 ProgInfo.DX10Clamp = Mode.DX10Clamp; 923 924 unsigned LDSAlignShift; 925 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 926 // LDS is allocated in 64 dword blocks. 927 LDSAlignShift = 8; 928 } else { 929 // LDS is allocated in 128 dword blocks. 930 LDSAlignShift = 9; 931 } 932 933 unsigned LDSSpillSize = 934 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 935 936 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 937 ProgInfo.LDSBlocks = 938 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 939 940 // Scratch is allocated in 256 dword blocks. 941 unsigned ScratchAlignShift = 10; 942 // We need to program the hardware with the amount of scratch memory that 943 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 944 // scratch memory used per thread. 945 ProgInfo.ScratchBlocks = 946 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 947 1ULL << ScratchAlignShift) >> 948 ScratchAlignShift; 949 950 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) { 951 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1; 952 ProgInfo.MemOrdered = 1; 953 } 954 955 ProgInfo.ComputePGMRSrc1 = 956 S_00B848_VGPRS(ProgInfo.VGPRBlocks) | 957 S_00B848_SGPRS(ProgInfo.SGPRBlocks) | 958 S_00B848_PRIORITY(ProgInfo.Priority) | 959 S_00B848_FLOAT_MODE(ProgInfo.FloatMode) | 960 S_00B848_PRIV(ProgInfo.Priv) | 961 S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) | 962 S_00B848_DEBUG_MODE(ProgInfo.DebugMode) | 963 S_00B848_IEEE_MODE(ProgInfo.IEEEMode) | 964 S_00B848_WGP_MODE(ProgInfo.WgpMode) | 965 S_00B848_MEM_ORDERED(ProgInfo.MemOrdered); 966 967 // 0 = X, 1 = XY, 2 = XYZ 968 unsigned TIDIGCompCnt = 0; 969 if (MFI->hasWorkItemIDZ()) 970 TIDIGCompCnt = 2; 971 else if (MFI->hasWorkItemIDY()) 972 TIDIGCompCnt = 1; 973 974 ProgInfo.ComputePGMRSrc2 = 975 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 976 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 977 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 978 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 979 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 980 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 981 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 982 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 983 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 984 S_00B84C_EXCP_EN_MSB(0) | 985 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 986 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 987 S_00B84C_EXCP_EN(0); 988 } 989 990 static unsigned getRsrcReg(CallingConv::ID CallConv) { 991 switch (CallConv) { 992 default: LLVM_FALLTHROUGH; 993 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 994 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 995 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 996 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 997 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 998 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 999 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 1000 } 1001 } 1002 1003 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1004 const SIProgramInfo &CurrentProgramInfo) { 1005 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1006 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1007 1008 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1009 OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4); 1010 1011 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4); 1012 1013 OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); 1014 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4); 1015 1016 OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4); 1017 OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1018 1019 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1020 // 0" comment but I don't see a corresponding field in the register spec. 1021 } else { 1022 OutStreamer->EmitIntValue(RsrcReg, 4); 1023 OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1024 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1025 OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4); 1026 OutStreamer->EmitIntValue( 1027 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1028 } 1029 1030 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1031 OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); 1032 OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4); 1033 OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); 1034 OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4); 1035 OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4); 1036 OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4); 1037 } 1038 1039 OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4); 1040 OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4); 1041 OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4); 1042 OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4); 1043 } 1044 1045 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1046 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1047 // metadata items into the PALMD::Metadata, combining with any provided by the 1048 // frontend as LLVM metadata. Once all functions are written, the PAL metadata 1049 // is then written as a single block in the .note section. 1050 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1051 const SIProgramInfo &CurrentProgramInfo) { 1052 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1053 auto CC = MF.getFunction().getCallingConv(); 1054 auto MD = getTargetStreamer()->getPALMetadata(); 1055 1056 MD->setEntryPoint(CC, MF.getFunction().getName()); 1057 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU); 1058 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU); 1059 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1060 MD->setRsrc1(CC, CurrentProgramInfo.ComputePGMRSrc1); 1061 MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2); 1062 } else { 1063 MD->setRsrc1(CC, S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1064 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks)); 1065 if (CurrentProgramInfo.ScratchBlocks > 0) 1066 MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1)); 1067 } 1068 // ScratchSize is in bytes, 16 aligned. 1069 MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16)); 1070 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1071 MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1072 MD->setSpiPsInputEna(MFI->getPSInputEnable()); 1073 MD->setSpiPsInputAddr(MFI->getPSInputAddr()); 1074 } 1075 } 1076 1077 // This is supposed to be log2(Size) 1078 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1079 switch (Size) { 1080 case 4: 1081 return AMD_ELEMENT_4_BYTES; 1082 case 8: 1083 return AMD_ELEMENT_8_BYTES; 1084 case 16: 1085 return AMD_ELEMENT_16_BYTES; 1086 default: 1087 llvm_unreachable("invalid private_element_size"); 1088 } 1089 } 1090 1091 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1092 const SIProgramInfo &CurrentProgramInfo, 1093 const MachineFunction &MF) const { 1094 const Function &F = MF.getFunction(); 1095 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 1096 F.getCallingConv() == CallingConv::SPIR_KERNEL); 1097 1098 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1099 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1100 1101 AMDGPU::initDefaultAMDKernelCodeT(Out, &STM); 1102 1103 Out.compute_pgm_resource_registers = 1104 CurrentProgramInfo.ComputePGMRSrc1 | 1105 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1106 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64; 1107 1108 if (CurrentProgramInfo.DynamicCallStack) 1109 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1110 1111 AMD_HSA_BITS_SET(Out.code_properties, 1112 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1113 getElementByteSizeValue(STM.getMaxPrivateElementSize())); 1114 1115 if (MFI->hasPrivateSegmentBuffer()) { 1116 Out.code_properties |= 1117 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1118 } 1119 1120 if (MFI->hasDispatchPtr()) 1121 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1122 1123 if (MFI->hasQueuePtr()) 1124 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1125 1126 if (MFI->hasKernargSegmentPtr()) 1127 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1128 1129 if (MFI->hasDispatchID()) 1130 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1131 1132 if (MFI->hasFlatScratchInit()) 1133 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1134 1135 if (MFI->hasDispatchPtr()) 1136 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1137 1138 if (STM.isXNACKEnabled()) 1139 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1140 1141 unsigned MaxKernArgAlign; 1142 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1143 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1144 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1145 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1146 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1147 1148 // These alignment values are specified in powers of two, so alignment = 1149 // 2^n. The minimum alignment is 2^4 = 16. 1150 Out.kernarg_segment_alignment = std::max((size_t)4, 1151 countTrailingZeros(MaxKernArgAlign)); 1152 } 1153 1154 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1155 const char *ExtraCode, raw_ostream &O) { 1156 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1157 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O)) 1158 return false; 1159 1160 if (ExtraCode && ExtraCode[0]) { 1161 if (ExtraCode[1] != 0) 1162 return true; // Unknown modifier. 1163 1164 switch (ExtraCode[0]) { 1165 case 'r': 1166 break; 1167 default: 1168 return true; 1169 } 1170 } 1171 1172 // TODO: Should be able to support other operand types like globals. 1173 const MachineOperand &MO = MI->getOperand(OpNo); 1174 if (MO.isReg()) { 1175 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1176 *MF->getSubtarget().getRegisterInfo()); 1177 return false; 1178 } 1179 1180 return true; 1181 } 1182