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