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 "InstPrinter/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(getSTI())) 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::getSTI() 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(getSTI())) { 124 std::string ExpectedTarget; 125 raw_string_ostream ExpectedTargetOS(ExpectedTarget); 126 IsaInfo::streamIsaVersion(getSTI(), 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 readPALMetadata(M); 140 141 if (IsaInfo::hasCodeObjectV3(getSTI())) 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(getSTI()->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(getSTI())) { 160 // Emit ISA Version (NT_AMD_AMDGPU_ISA). 161 std::string ISAVersionString; 162 raw_string_ostream ISAVersionStream(ISAVersionString); 163 IsaInfo::streamIsaVersion(getSTI(), 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 if (!IsaInfo::hasCodeObjectV3(getSTI())) { 176 // Emit PAL Metadata (NT_AMD_AMDGPU_PAL_METADATA). 177 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) { 178 // Copy the PAL metadata from the map where we collected it into a vector, 179 // then write it as a .note. 180 PALMD::Metadata PALMetadataVector; 181 for (auto i : PALMetadataMap) { 182 PALMetadataVector.push_back(i.first); 183 PALMetadataVector.push_back(i.second); 184 } 185 getTargetStreamer()->EmitPALMetadata(PALMetadataVector); 186 } 187 } 188 } 189 190 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough( 191 const MachineBasicBlock *MBB) const { 192 if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) 193 return false; 194 195 if (MBB->empty()) 196 return true; 197 198 // If this is a block implementing a long branch, an expression relative to 199 // the start of the block is needed. to the start of the block. 200 // XXX - Is there a smarter way to check this? 201 return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64); 202 } 203 204 void AMDGPUAsmPrinter::EmitFunctionBodyStart() { 205 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 206 if (!MFI.isEntryFunction()) 207 return; 208 209 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 210 const Function &F = MF->getFunction(); 211 if (!STM.hasCodeObjectV3() && STM.isAmdHsaOrMesa(F) && 212 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 213 F.getCallingConv() == CallingConv::SPIR_KERNEL)) { 214 amd_kernel_code_t KernelCode; 215 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 216 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 217 } 218 219 if (STM.isAmdHsaOS()) 220 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo); 221 } 222 223 void AMDGPUAsmPrinter::EmitFunctionBodyEnd() { 224 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 225 if (!MFI.isEntryFunction()) 226 return; 227 if (!IsaInfo::hasCodeObjectV3(getSTI()) || 228 TM.getTargetTriple().getOS() != Triple::AMDHSA) 229 return; 230 231 auto &Streamer = getTargetStreamer()->getStreamer(); 232 auto &Context = Streamer.getContext(); 233 auto &ObjectFileInfo = *Context.getObjectFileInfo(); 234 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection(); 235 236 Streamer.PushSection(); 237 Streamer.SwitchSection(&ReadOnlySection); 238 239 // CP microcode requires the kernel descriptor to be allocated on 64 byte 240 // alignment. 241 Streamer.EmitValueToAlignment(64, 0, 1, 0); 242 if (ReadOnlySection.getAlignment() < 64) 243 ReadOnlySection.setAlignment(64); 244 245 SmallString<128> KernelName; 246 getNameWithPrefix(KernelName, &MF->getFunction()); 247 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 248 *getSTI(), KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo), 249 CurrentProgramInfo.NumVGPRsForWavesPerEU, 250 CurrentProgramInfo.NumSGPRsForWavesPerEU - 251 IsaInfo::getNumExtraSGPRs(getSTI(), 252 CurrentProgramInfo.VCCUsed, 253 CurrentProgramInfo.FlatUsed), 254 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed, 255 hasXNACK(*getSTI())); 256 257 Streamer.PopSection(); 258 } 259 260 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() { 261 if (IsaInfo::hasCodeObjectV3(getSTI()) && 262 TM.getTargetTriple().getOS() == Triple::AMDHSA) { 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 const GCNSubtarget &STI = MF->getSubtarget<GCNSubtarget>(); 276 if (STI.dumpCode()) { 277 // Disassemble function name label to text. 278 DisasmLines.push_back(MF->getName().str() + ":"); 279 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 280 HexLines.push_back(""); 281 } 282 283 AsmPrinter::EmitFunctionEntryLabel(); 284 } 285 286 void AMDGPUAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 287 const GCNSubtarget &STI = MBB.getParent()->getSubtarget<GCNSubtarget>(); 288 if (STI.dumpCode() && !isBlockOnlyReachableByFallthrough(&MBB)) { 289 // Write a line for the basic block label if it is not only fallthrough. 290 DisasmLines.push_back( 291 (Twine("BB") + Twine(getFunctionNumber()) 292 + "_" + Twine(MBB.getNumber()) + ":").str()); 293 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 294 HexLines.push_back(""); 295 } 296 AsmPrinter::EmitBasicBlockStart(MBB); 297 } 298 299 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 300 301 // Group segment variables aren't emitted in HSA. 302 if (AMDGPU::isGroupSegment(GV)) 303 return; 304 305 AsmPrinter::EmitGlobalVariable(GV); 306 } 307 308 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 309 CallGraphResourceInfo.clear(); 310 return AsmPrinter::doFinalization(M); 311 } 312 313 // For the amdpal OS type, read the amdgpu.pal.metadata supplied by the 314 // frontend into our PALMetadataMap, ready for per-function modification. It 315 // is a NamedMD containing an MDTuple containing a number of MDNodes each of 316 // which is an integer value, and each two integer values forms a key=value 317 // pair that we store as PALMetadataMap[key]=value in the map. 318 void AMDGPUAsmPrinter::readPALMetadata(Module &M) { 319 auto NamedMD = M.getNamedMetadata("amdgpu.pal.metadata"); 320 if (!NamedMD || !NamedMD->getNumOperands()) 321 return; 322 auto Tuple = dyn_cast<MDTuple>(NamedMD->getOperand(0)); 323 if (!Tuple) 324 return; 325 for (unsigned I = 0, E = Tuple->getNumOperands() & -2; I != E; I += 2) { 326 auto Key = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I)); 327 auto Val = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I + 1)); 328 if (!Key || !Val) 329 continue; 330 PALMetadataMap[Key->getZExtValue()] = Val->getZExtValue(); 331 } 332 } 333 334 // Print comments that apply to both callable functions and entry points. 335 void AMDGPUAsmPrinter::emitCommonFunctionComments( 336 uint32_t NumVGPR, 337 uint32_t NumSGPR, 338 uint64_t ScratchSize, 339 uint64_t CodeSize, 340 const AMDGPUMachineFunction *MFI) { 341 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false); 342 OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false); 343 OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false); 344 OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false); 345 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()), 346 false); 347 } 348 349 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties( 350 const MachineFunction &MF) const { 351 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 352 uint16_t KernelCodeProperties = 0; 353 354 if (MFI.hasPrivateSegmentBuffer()) { 355 KernelCodeProperties |= 356 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 357 } 358 if (MFI.hasDispatchPtr()) { 359 KernelCodeProperties |= 360 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 361 } 362 if (MFI.hasQueuePtr()) { 363 KernelCodeProperties |= 364 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 365 } 366 if (MFI.hasKernargSegmentPtr()) { 367 KernelCodeProperties |= 368 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 369 } 370 if (MFI.hasDispatchID()) { 371 KernelCodeProperties |= 372 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 373 } 374 if (MFI.hasFlatScratchInit()) { 375 KernelCodeProperties |= 376 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 377 } 378 379 return KernelCodeProperties; 380 } 381 382 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 383 const MachineFunction &MF, 384 const SIProgramInfo &PI) const { 385 amdhsa::kernel_descriptor_t KernelDescriptor; 386 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 387 388 assert(isUInt<32>(PI.ScratchSize)); 389 assert(isUInt<32>(PI.ComputePGMRSrc1)); 390 assert(isUInt<32>(PI.ComputePGMRSrc2)); 391 392 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 393 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 394 KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1; 395 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 396 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 397 398 return KernelDescriptor; 399 } 400 401 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 402 CurrentProgramInfo = SIProgramInfo(); 403 404 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 405 406 // The starting address of all shader programs must be 256 bytes aligned. 407 // Regular functions just need the basic required instruction alignment. 408 MF.setAlignment(MFI->isEntryFunction() ? 8 : 2); 409 410 SetupMachineFunction(MF); 411 412 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 413 MCContext &Context = getObjFileLowering().getContext(); 414 // FIXME: This should be an explicit check for Mesa. 415 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 416 MCSectionELF *ConfigSection = 417 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 418 OutStreamer->SwitchSection(ConfigSection); 419 } 420 421 if (MFI->isEntryFunction()) { 422 getSIProgramInfo(CurrentProgramInfo, MF); 423 } else { 424 auto I = CallGraphResourceInfo.insert( 425 std::make_pair(&MF.getFunction(), SIFunctionResourceInfo())); 426 SIFunctionResourceInfo &Info = I.first->second; 427 assert(I.second && "should only be called once per function"); 428 Info = analyzeResourceUsage(MF); 429 } 430 431 if (STM.isAmdPalOS()) 432 EmitPALMetadata(MF, CurrentProgramInfo); 433 else if (!STM.isAmdHsaOS()) { 434 EmitProgramInfoSI(MF, CurrentProgramInfo); 435 } 436 437 DisasmLines.clear(); 438 HexLines.clear(); 439 DisasmLineMaxLen = 0; 440 441 EmitFunctionBody(); 442 443 if (isVerbose()) { 444 MCSectionELF *CommentSection = 445 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 446 OutStreamer->SwitchSection(CommentSection); 447 448 if (!MFI->isEntryFunction()) { 449 OutStreamer->emitRawComment(" Function info:", false); 450 SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()]; 451 emitCommonFunctionComments( 452 Info.NumVGPR, 453 Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()), 454 Info.PrivateSegmentSize, 455 getFunctionCodeSize(MF), MFI); 456 return false; 457 } 458 459 OutStreamer->emitRawComment(" Kernel info:", false); 460 emitCommonFunctionComments(CurrentProgramInfo.NumVGPR, 461 CurrentProgramInfo.NumSGPR, 462 CurrentProgramInfo.ScratchSize, 463 getFunctionCodeSize(MF), MFI); 464 465 OutStreamer->emitRawComment( 466 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 467 OutStreamer->emitRawComment( 468 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 469 OutStreamer->emitRawComment( 470 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 471 " bytes/workgroup (compile time only)", false); 472 473 OutStreamer->emitRawComment( 474 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 475 OutStreamer->emitRawComment( 476 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 477 478 OutStreamer->emitRawComment( 479 " NumSGPRsForWavesPerEU: " + 480 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 481 OutStreamer->emitRawComment( 482 " NumVGPRsForWavesPerEU: " + 483 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 484 485 OutStreamer->emitRawComment( 486 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 487 488 if (MF.getSubtarget<GCNSubtarget>().debuggerEmitPrologue()) { 489 OutStreamer->emitRawComment( 490 " DebuggerWavefrontPrivateSegmentOffsetSGPR: s" + 491 Twine(CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false); 492 OutStreamer->emitRawComment( 493 " DebuggerPrivateSegmentBufferSGPR: s" + 494 Twine(CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR), false); 495 } 496 497 OutStreamer->emitRawComment( 498 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 499 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 500 OutStreamer->emitRawComment( 501 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 502 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 503 OutStreamer->emitRawComment( 504 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 505 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 506 OutStreamer->emitRawComment( 507 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 508 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 509 OutStreamer->emitRawComment( 510 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 511 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 512 OutStreamer->emitRawComment( 513 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 514 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 515 false); 516 } 517 518 if (STM.dumpCode()) { 519 520 OutStreamer->SwitchSection( 521 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0)); 522 523 for (size_t i = 0; i < DisasmLines.size(); ++i) { 524 std::string Comment = "\n"; 525 if (!HexLines[i].empty()) { 526 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 527 Comment += " ; " + HexLines[i] + "\n"; 528 } 529 530 OutStreamer->EmitBytes(StringRef(DisasmLines[i])); 531 OutStreamer->EmitBytes(StringRef(Comment)); 532 } 533 } 534 535 return false; 536 } 537 538 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 539 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 540 const SIInstrInfo *TII = STM.getInstrInfo(); 541 542 uint64_t CodeSize = 0; 543 544 for (const MachineBasicBlock &MBB : MF) { 545 for (const MachineInstr &MI : MBB) { 546 // TODO: CodeSize should account for multiple functions. 547 548 // TODO: Should we count size of debug info? 549 if (MI.isDebugInstr()) 550 continue; 551 552 CodeSize += TII->getInstSizeInBytes(MI); 553 } 554 } 555 556 return CodeSize; 557 } 558 559 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 560 const SIInstrInfo &TII, 561 unsigned Reg) { 562 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 563 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 564 return true; 565 } 566 567 return false; 568 } 569 570 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 571 const GCNSubtarget &ST) const { 572 return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST, 573 UsesVCC, UsesFlatScratch); 574 } 575 576 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 577 const MachineFunction &MF) const { 578 SIFunctionResourceInfo Info; 579 580 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 581 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 582 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 583 const MachineRegisterInfo &MRI = MF.getRegInfo(); 584 const SIInstrInfo *TII = ST.getInstrInfo(); 585 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 586 587 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 588 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 589 590 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 591 // instructions aren't used to access the scratch buffer. Inline assembly may 592 // need it though. 593 // 594 // If we only have implicit uses of flat_scr on flat instructions, it is not 595 // really needed. 596 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 597 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 598 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 599 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 600 Info.UsesFlatScratch = false; 601 } 602 603 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 604 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 605 if (MFI->isStackRealigned()) 606 Info.PrivateSegmentSize += FrameInfo.getMaxAlignment(); 607 608 609 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 610 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 611 612 // If there are no calls, MachineRegisterInfo can tell us the used register 613 // count easily. 614 // A tail call isn't considered a call for MachineFrameInfo's purposes. 615 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 616 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 617 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 618 if (MRI.isPhysRegUsed(Reg)) { 619 HighestVGPRReg = Reg; 620 break; 621 } 622 } 623 624 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 625 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 626 if (MRI.isPhysRegUsed(Reg)) { 627 HighestSGPRReg = Reg; 628 break; 629 } 630 } 631 632 // We found the maximum register index. They start at 0, so add one to get the 633 // number of registers. 634 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 635 TRI.getHWRegIndex(HighestVGPRReg) + 1; 636 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 637 TRI.getHWRegIndex(HighestSGPRReg) + 1; 638 639 return Info; 640 } 641 642 int32_t MaxVGPR = -1; 643 int32_t MaxSGPR = -1; 644 uint64_t CalleeFrameSize = 0; 645 646 for (const MachineBasicBlock &MBB : MF) { 647 for (const MachineInstr &MI : MBB) { 648 // TODO: Check regmasks? Do they occur anywhere except calls? 649 for (const MachineOperand &MO : MI.operands()) { 650 unsigned Width = 0; 651 bool IsSGPR = false; 652 653 if (!MO.isReg()) 654 continue; 655 656 unsigned Reg = MO.getReg(); 657 switch (Reg) { 658 case AMDGPU::EXEC: 659 case AMDGPU::EXEC_LO: 660 case AMDGPU::EXEC_HI: 661 case AMDGPU::SCC: 662 case AMDGPU::M0: 663 case AMDGPU::SRC_SHARED_BASE: 664 case AMDGPU::SRC_SHARED_LIMIT: 665 case AMDGPU::SRC_PRIVATE_BASE: 666 case AMDGPU::SRC_PRIVATE_LIMIT: 667 continue; 668 669 case AMDGPU::NoRegister: 670 assert(MI.isDebugInstr()); 671 continue; 672 673 case AMDGPU::VCC: 674 case AMDGPU::VCC_LO: 675 case AMDGPU::VCC_HI: 676 Info.UsesVCC = true; 677 continue; 678 679 case AMDGPU::FLAT_SCR: 680 case AMDGPU::FLAT_SCR_LO: 681 case AMDGPU::FLAT_SCR_HI: 682 continue; 683 684 case AMDGPU::XNACK_MASK: 685 case AMDGPU::XNACK_MASK_LO: 686 case AMDGPU::XNACK_MASK_HI: 687 llvm_unreachable("xnack_mask registers should not be used"); 688 689 case AMDGPU::LDS_DIRECT: 690 llvm_unreachable("lds_direct register should not be used"); 691 692 case AMDGPU::TBA: 693 case AMDGPU::TBA_LO: 694 case AMDGPU::TBA_HI: 695 case AMDGPU::TMA: 696 case AMDGPU::TMA_LO: 697 case AMDGPU::TMA_HI: 698 llvm_unreachable("trap handler registers should not be used"); 699 700 default: 701 break; 702 } 703 704 if (AMDGPU::SReg_32RegClass.contains(Reg)) { 705 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 706 "trap handler registers should not be used"); 707 IsSGPR = true; 708 Width = 1; 709 } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) { 710 IsSGPR = false; 711 Width = 1; 712 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 713 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 714 "trap handler registers should not be used"); 715 IsSGPR = true; 716 Width = 2; 717 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 718 IsSGPR = false; 719 Width = 2; 720 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 721 IsSGPR = false; 722 Width = 3; 723 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 724 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 725 "trap handler registers should not be used"); 726 IsSGPR = true; 727 Width = 4; 728 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 729 IsSGPR = false; 730 Width = 4; 731 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 732 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 733 "trap handler registers should not be used"); 734 IsSGPR = true; 735 Width = 8; 736 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 737 IsSGPR = false; 738 Width = 8; 739 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 740 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 741 "trap handler registers should not be used"); 742 IsSGPR = true; 743 Width = 16; 744 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 745 IsSGPR = false; 746 Width = 16; 747 } else { 748 llvm_unreachable("Unknown register class"); 749 } 750 unsigned HWReg = TRI.getHWRegIndex(Reg); 751 int MaxUsed = HWReg + Width - 1; 752 if (IsSGPR) { 753 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 754 } else { 755 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 756 } 757 } 758 759 if (MI.isCall()) { 760 // Pseudo used just to encode the underlying global. Is there a better 761 // way to track this? 762 763 const MachineOperand *CalleeOp 764 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 765 const Function *Callee = cast<Function>(CalleeOp->getGlobal()); 766 if (Callee->isDeclaration()) { 767 // If this is a call to an external function, we can't do much. Make 768 // conservative guesses. 769 770 // 48 SGPRs - vcc, - flat_scr, -xnack 771 int MaxSGPRGuess = 772 47 - IsaInfo::getNumExtraSGPRs(getSTI(), true, 773 ST.hasFlatAddressSpace()); 774 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 775 MaxVGPR = std::max(MaxVGPR, 23); 776 777 CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384)); 778 Info.UsesVCC = true; 779 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 780 Info.HasDynamicallySizedStack = true; 781 } else { 782 // We force CodeGen to run in SCC order, so the callee's register 783 // usage etc. should be the cumulative usage of all callees. 784 auto I = CallGraphResourceInfo.find(Callee); 785 assert(I != CallGraphResourceInfo.end() && 786 "callee should have been handled before caller"); 787 788 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 789 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 790 CalleeFrameSize 791 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 792 Info.UsesVCC |= I->second.UsesVCC; 793 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 794 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 795 Info.HasRecursion |= I->second.HasRecursion; 796 } 797 798 if (!Callee->doesNotRecurse()) 799 Info.HasRecursion = true; 800 } 801 } 802 } 803 804 Info.NumExplicitSGPR = MaxSGPR + 1; 805 Info.NumVGPR = MaxVGPR + 1; 806 Info.PrivateSegmentSize += CalleeFrameSize; 807 808 return Info; 809 } 810 811 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 812 const MachineFunction &MF) { 813 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 814 815 ProgInfo.NumVGPR = Info.NumVGPR; 816 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 817 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 818 ProgInfo.VCCUsed = Info.UsesVCC; 819 ProgInfo.FlatUsed = Info.UsesFlatScratch; 820 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 821 822 if (!isUInt<32>(ProgInfo.ScratchSize)) { 823 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 824 ProgInfo.ScratchSize, DS_Error); 825 MF.getFunction().getContext().diagnose(DiagStackSize); 826 } 827 828 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 829 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 830 const SIInstrInfo *TII = STM.getInstrInfo(); 831 const SIRegisterInfo *RI = &TII->getRegisterInfo(); 832 833 // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are 834 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 835 // unified. 836 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 837 getSTI(), ProgInfo.VCCUsed, ProgInfo.FlatUsed); 838 839 // Check the addressable register limit before we add ExtraSGPRs. 840 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 841 !STM.hasSGPRInitBug()) { 842 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 843 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 844 // This can happen due to a compiler bug or when using inline asm. 845 LLVMContext &Ctx = MF.getFunction().getContext(); 846 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 847 "addressable scalar registers", 848 ProgInfo.NumSGPR, DS_Error, 849 DK_ResourceLimit, 850 MaxAddressableNumSGPRs); 851 Ctx.diagnose(Diag); 852 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 853 } 854 } 855 856 // Account for extra SGPRs and VGPRs reserved for debugger use. 857 ProgInfo.NumSGPR += ExtraSGPRs; 858 859 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 860 // dispatch registers are function args. 861 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 862 for (auto &Arg : MF.getFunction().args()) { 863 unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32; 864 if (Arg.hasAttribute(Attribute::InReg)) 865 WaveDispatchNumSGPR += NumRegs; 866 else 867 WaveDispatchNumVGPR += NumRegs; 868 } 869 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 870 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 871 872 // Adjust number of registers used to meet default/requested minimum/maximum 873 // number of waves per execution unit request. 874 ProgInfo.NumSGPRsForWavesPerEU = std::max( 875 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 876 ProgInfo.NumVGPRsForWavesPerEU = std::max( 877 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 878 879 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 880 STM.hasSGPRInitBug()) { 881 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 882 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 883 // This can happen due to a compiler bug or when using inline asm to use 884 // the registers which are usually reserved for vcc etc. 885 LLVMContext &Ctx = MF.getFunction().getContext(); 886 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 887 "scalar registers", 888 ProgInfo.NumSGPR, DS_Error, 889 DK_ResourceLimit, 890 MaxAddressableNumSGPRs); 891 Ctx.diagnose(Diag); 892 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 893 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 894 } 895 } 896 897 if (STM.hasSGPRInitBug()) { 898 ProgInfo.NumSGPR = 899 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 900 ProgInfo.NumSGPRsForWavesPerEU = 901 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 902 } 903 904 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 905 LLVMContext &Ctx = MF.getFunction().getContext(); 906 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 907 MFI->getNumUserSGPRs(), DS_Error); 908 Ctx.diagnose(Diag); 909 } 910 911 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 912 LLVMContext &Ctx = MF.getFunction().getContext(); 913 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 914 MFI->getLDSSize(), DS_Error); 915 Ctx.diagnose(Diag); 916 } 917 918 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 919 &STM, ProgInfo.NumSGPRsForWavesPerEU); 920 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 921 &STM, ProgInfo.NumVGPRsForWavesPerEU); 922 923 // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and 924 // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue" 925 // attribute was requested. 926 if (STM.debuggerEmitPrologue()) { 927 ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR = 928 RI->getHWRegIndex(MFI->getScratchWaveOffsetReg()); 929 ProgInfo.DebuggerPrivateSegmentBufferSGPR = 930 RI->getHWRegIndex(MFI->getScratchRSrcReg()); 931 } 932 933 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 934 // register. 935 ProgInfo.FloatMode = getFPMode(MF); 936 937 ProgInfo.IEEEMode = STM.enableIEEEBit(MF); 938 939 // Make clamp modifier on NaN input returns 0. 940 ProgInfo.DX10Clamp = STM.enableDX10Clamp(); 941 942 unsigned LDSAlignShift; 943 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 944 // LDS is allocated in 64 dword blocks. 945 LDSAlignShift = 8; 946 } else { 947 // LDS is allocated in 128 dword blocks. 948 LDSAlignShift = 9; 949 } 950 951 unsigned LDSSpillSize = 952 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 953 954 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 955 ProgInfo.LDSBlocks = 956 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 957 958 // Scratch is allocated in 256 dword blocks. 959 unsigned ScratchAlignShift = 10; 960 // We need to program the hardware with the amount of scratch memory that 961 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 962 // scratch memory used per thread. 963 ProgInfo.ScratchBlocks = 964 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 965 1ULL << ScratchAlignShift) >> 966 ScratchAlignShift; 967 968 ProgInfo.ComputePGMRSrc1 = 969 S_00B848_VGPRS(ProgInfo.VGPRBlocks) | 970 S_00B848_SGPRS(ProgInfo.SGPRBlocks) | 971 S_00B848_PRIORITY(ProgInfo.Priority) | 972 S_00B848_FLOAT_MODE(ProgInfo.FloatMode) | 973 S_00B848_PRIV(ProgInfo.Priv) | 974 S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) | 975 S_00B848_DEBUG_MODE(ProgInfo.DebugMode) | 976 S_00B848_IEEE_MODE(ProgInfo.IEEEMode); 977 978 // 0 = X, 1 = XY, 2 = XYZ 979 unsigned TIDIGCompCnt = 0; 980 if (MFI->hasWorkItemIDZ()) 981 TIDIGCompCnt = 2; 982 else if (MFI->hasWorkItemIDY()) 983 TIDIGCompCnt = 1; 984 985 ProgInfo.ComputePGMRSrc2 = 986 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 987 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 988 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 989 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 990 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 991 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 992 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 993 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 994 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 995 S_00B84C_EXCP_EN_MSB(0) | 996 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 997 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 998 S_00B84C_EXCP_EN(0); 999 } 1000 1001 static unsigned getRsrcReg(CallingConv::ID CallConv) { 1002 switch (CallConv) { 1003 default: LLVM_FALLTHROUGH; 1004 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 1005 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 1006 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 1007 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 1008 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 1009 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 1010 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 1011 } 1012 } 1013 1014 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1015 const SIProgramInfo &CurrentProgramInfo) { 1016 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1017 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1018 1019 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1020 OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4); 1021 1022 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4); 1023 1024 OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); 1025 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4); 1026 1027 OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4); 1028 OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1029 1030 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1031 // 0" comment but I don't see a corresponding field in the register spec. 1032 } else { 1033 OutStreamer->EmitIntValue(RsrcReg, 4); 1034 OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1035 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1036 OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4); 1037 OutStreamer->EmitIntValue( 1038 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1039 } 1040 1041 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1042 OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); 1043 OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4); 1044 OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); 1045 OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4); 1046 OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4); 1047 OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4); 1048 } 1049 1050 OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4); 1051 OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4); 1052 OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4); 1053 OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4); 1054 } 1055 1056 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1057 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1058 // metadata items into the PALMetadataMap, combining with any provided by the 1059 // frontend as LLVM metadata. Once all functions are written, PALMetadataMap is 1060 // then written as a single block in the .note section. 1061 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1062 const SIProgramInfo &CurrentProgramInfo) { 1063 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1064 // Given the calling convention, calculate the register number for rsrc1. In 1065 // principle the register number could change in future hardware, but we know 1066 // it is the same for gfx6-9 (except that LS and ES don't exist on gfx9), so 1067 // we can use the same fixed value that .AMDGPU.config has for Mesa. Note 1068 // that we use a register number rather than a byte offset, so we need to 1069 // divide by 4. 1070 unsigned Rsrc1Reg = getRsrcReg(MF.getFunction().getCallingConv()) / 4; 1071 unsigned Rsrc2Reg = Rsrc1Reg + 1; 1072 // Also calculate the PAL metadata key for *S_SCRATCH_SIZE. It can be used 1073 // with a constant offset to access any non-register shader-specific PAL 1074 // metadata key. 1075 unsigned ScratchSizeKey = PALMD::Key::CS_SCRATCH_SIZE; 1076 switch (MF.getFunction().getCallingConv()) { 1077 case CallingConv::AMDGPU_PS: 1078 ScratchSizeKey = PALMD::Key::PS_SCRATCH_SIZE; 1079 break; 1080 case CallingConv::AMDGPU_VS: 1081 ScratchSizeKey = PALMD::Key::VS_SCRATCH_SIZE; 1082 break; 1083 case CallingConv::AMDGPU_GS: 1084 ScratchSizeKey = PALMD::Key::GS_SCRATCH_SIZE; 1085 break; 1086 case CallingConv::AMDGPU_ES: 1087 ScratchSizeKey = PALMD::Key::ES_SCRATCH_SIZE; 1088 break; 1089 case CallingConv::AMDGPU_HS: 1090 ScratchSizeKey = PALMD::Key::HS_SCRATCH_SIZE; 1091 break; 1092 case CallingConv::AMDGPU_LS: 1093 ScratchSizeKey = PALMD::Key::LS_SCRATCH_SIZE; 1094 break; 1095 } 1096 unsigned NumUsedVgprsKey = ScratchSizeKey + 1097 PALMD::Key::VS_NUM_USED_VGPRS - PALMD::Key::VS_SCRATCH_SIZE; 1098 unsigned NumUsedSgprsKey = ScratchSizeKey + 1099 PALMD::Key::VS_NUM_USED_SGPRS - PALMD::Key::VS_SCRATCH_SIZE; 1100 PALMetadataMap[NumUsedVgprsKey] = CurrentProgramInfo.NumVGPRsForWavesPerEU; 1101 PALMetadataMap[NumUsedSgprsKey] = CurrentProgramInfo.NumSGPRsForWavesPerEU; 1102 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1103 PALMetadataMap[Rsrc1Reg] |= CurrentProgramInfo.ComputePGMRSrc1; 1104 PALMetadataMap[Rsrc2Reg] |= CurrentProgramInfo.ComputePGMRSrc2; 1105 // ScratchSize is in bytes, 16 aligned. 1106 PALMetadataMap[ScratchSizeKey] |= 1107 alignTo(CurrentProgramInfo.ScratchSize, 16); 1108 } else { 1109 PALMetadataMap[Rsrc1Reg] |= S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1110 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks); 1111 if (CurrentProgramInfo.ScratchBlocks > 0) 1112 PALMetadataMap[Rsrc2Reg] |= S_00B84C_SCRATCH_EN(1); 1113 // ScratchSize is in bytes, 16 aligned. 1114 PALMetadataMap[ScratchSizeKey] |= 1115 alignTo(CurrentProgramInfo.ScratchSize, 16); 1116 } 1117 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1118 PALMetadataMap[Rsrc2Reg] |= 1119 S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks); 1120 PALMetadataMap[R_0286CC_SPI_PS_INPUT_ENA / 4] |= MFI->getPSInputEnable(); 1121 PALMetadataMap[R_0286D0_SPI_PS_INPUT_ADDR / 4] |= MFI->getPSInputAddr(); 1122 } 1123 } 1124 1125 // This is supposed to be log2(Size) 1126 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1127 switch (Size) { 1128 case 4: 1129 return AMD_ELEMENT_4_BYTES; 1130 case 8: 1131 return AMD_ELEMENT_8_BYTES; 1132 case 16: 1133 return AMD_ELEMENT_16_BYTES; 1134 default: 1135 llvm_unreachable("invalid private_element_size"); 1136 } 1137 } 1138 1139 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1140 const SIProgramInfo &CurrentProgramInfo, 1141 const MachineFunction &MF) const { 1142 const Function &F = MF.getFunction(); 1143 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 1144 F.getCallingConv() == CallingConv::SPIR_KERNEL); 1145 1146 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1147 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1148 1149 AMDGPU::initDefaultAMDKernelCodeT(Out, getSTI()); 1150 1151 Out.compute_pgm_resource_registers = 1152 CurrentProgramInfo.ComputePGMRSrc1 | 1153 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1154 Out.code_properties = AMD_CODE_PROPERTY_IS_PTR64; 1155 1156 if (CurrentProgramInfo.DynamicCallStack) 1157 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1158 1159 AMD_HSA_BITS_SET(Out.code_properties, 1160 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1161 getElementByteSizeValue(STM.getMaxPrivateElementSize())); 1162 1163 if (MFI->hasPrivateSegmentBuffer()) { 1164 Out.code_properties |= 1165 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1166 } 1167 1168 if (MFI->hasDispatchPtr()) 1169 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1170 1171 if (MFI->hasQueuePtr()) 1172 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1173 1174 if (MFI->hasKernargSegmentPtr()) 1175 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1176 1177 if (MFI->hasDispatchID()) 1178 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1179 1180 if (MFI->hasFlatScratchInit()) 1181 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1182 1183 if (MFI->hasDispatchPtr()) 1184 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1185 1186 if (STM.debuggerSupported()) 1187 Out.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED; 1188 1189 if (STM.isXNACKEnabled()) 1190 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1191 1192 unsigned MaxKernArgAlign; 1193 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1194 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1195 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1196 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1197 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1198 1199 // These alignment values are specified in powers of two, so alignment = 1200 // 2^n. The minimum alignment is 2^4 = 16. 1201 Out.kernarg_segment_alignment = std::max((size_t)4, 1202 countTrailingZeros(MaxKernArgAlign)); 1203 1204 if (STM.debuggerEmitPrologue()) { 1205 Out.debug_wavefront_private_segment_offset_sgpr = 1206 CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR; 1207 Out.debug_private_segment_buffer_sgpr = 1208 CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR; 1209 } 1210 } 1211 1212 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1213 unsigned AsmVariant, 1214 const char *ExtraCode, raw_ostream &O) { 1215 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1216 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O)) 1217 return false; 1218 1219 if (ExtraCode && ExtraCode[0]) { 1220 if (ExtraCode[1] != 0) 1221 return true; // Unknown modifier. 1222 1223 switch (ExtraCode[0]) { 1224 case 'r': 1225 break; 1226 default: 1227 return true; 1228 } 1229 } 1230 1231 // TODO: Should be able to support other operand types like globals. 1232 const MachineOperand &MO = MI->getOperand(OpNo); 1233 if (MO.isReg()) { 1234 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1235 *MF->getSubtarget().getRegisterInfo()); 1236 return false; 1237 } 1238 1239 return true; 1240 } 1241