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 // We need to tell the runtime some amount ahead of time if we don't know the 53 // true stack size. Assume a smaller number if this is only due to dynamic / 54 // non-entry block allocas. 55 static cl::opt<uint32_t> AssumedStackSizeForExternalCall( 56 "amdgpu-assume-external-call-stack-size", 57 cl::desc("Assumed stack use of any external call (in bytes)"), 58 cl::Hidden, 59 cl::init(16384)); 60 61 static cl::opt<uint32_t> AssumedStackSizeForDynamicSizeObjects( 62 "amdgpu-assume-dynamic-stack-object-size", 63 cl::desc("Assumed extra stack use if there are any " 64 "variable sized objects (in bytes)"), 65 cl::Hidden, 66 cl::init(4096)); 67 68 // This should get the default rounding mode from the kernel. We just set the 69 // default here, but this could change if the OpenCL rounding mode pragmas are 70 // used. 71 // 72 // The denormal mode here should match what is reported by the OpenCL runtime 73 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but 74 // can also be override to flush with the -cl-denorms-are-zero compiler flag. 75 // 76 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double 77 // precision, and leaves single precision to flush all and does not report 78 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports 79 // CL_FP_DENORM for both. 80 // 81 // FIXME: It seems some instructions do not support single precision denormals 82 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32, 83 // and sin_f32, cos_f32 on most parts). 84 85 // We want to use these instructions, and using fp32 denormals also causes 86 // instructions to run at the double precision rate for the device so it's 87 // probably best to just report no single precision denormals. 88 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) { 89 return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) | 90 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) | 91 FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) | 92 FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue()); 93 } 94 95 static AsmPrinter * 96 createAMDGPUAsmPrinterPass(TargetMachine &tm, 97 std::unique_ptr<MCStreamer> &&Streamer) { 98 return new AMDGPUAsmPrinter(tm, std::move(Streamer)); 99 } 100 101 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() { 102 TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(), 103 llvm::createR600AsmPrinterPass); 104 TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(), 105 createAMDGPUAsmPrinterPass); 106 } 107 108 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, 109 std::unique_ptr<MCStreamer> Streamer) 110 : AsmPrinter(TM, std::move(Streamer)) { 111 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 112 if (isHsaAbiVersion2(getGlobalSTI())) { 113 HSAMetadataStream.reset(new MetadataStreamerV2()); 114 } else { 115 HSAMetadataStream.reset(new MetadataStreamerV3()); 116 } 117 } 118 } 119 120 StringRef AMDGPUAsmPrinter::getPassName() const { 121 return "AMDGPU Assembly Printer"; 122 } 123 124 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const { 125 return TM.getMCSubtargetInfo(); 126 } 127 128 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const { 129 if (!OutStreamer) 130 return nullptr; 131 return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer()); 132 } 133 134 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) { 135 if (isHsaAbiVersion3(getGlobalSTI())) { 136 std::string ExpectedTarget; 137 raw_string_ostream ExpectedTargetOS(ExpectedTarget); 138 IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS); 139 140 getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget); 141 } 142 143 if (TM.getTargetTriple().getOS() != Triple::AMDHSA && 144 TM.getTargetTriple().getOS() != Triple::AMDPAL) 145 return; 146 147 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 148 HSAMetadataStream->begin(M); 149 150 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) 151 getTargetStreamer()->getPALMetadata()->readFromIR(M); 152 153 if (isHsaAbiVersion3(getGlobalSTI())) 154 return; 155 156 // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2. 157 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 158 getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1); 159 160 // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2. 161 IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU()); 162 getTargetStreamer()->EmitDirectiveHSACodeObjectISA( 163 Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU"); 164 } 165 166 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) { 167 // Following code requires TargetStreamer to be present. 168 if (!getTargetStreamer()) 169 return; 170 171 if (TM.getTargetTriple().getOS() != Triple::AMDHSA || 172 isHsaAbiVersion2(getGlobalSTI())) { 173 // Emit ISA Version (NT_AMD_AMDGPU_ISA). 174 std::string ISAVersionString; 175 raw_string_ostream ISAVersionStream(ISAVersionString); 176 IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream); 177 getTargetStreamer()->EmitISAVersion(ISAVersionStream.str()); 178 } 179 180 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA). 181 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 182 HSAMetadataStream->end(); 183 bool Success = HSAMetadataStream->emitTo(*getTargetStreamer()); 184 (void)Success; 185 assert(Success && "Malformed HSA Metadata"); 186 } 187 } 188 189 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough( 190 const MachineBasicBlock *MBB) const { 191 if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) 192 return false; 193 194 if (MBB->empty()) 195 return true; 196 197 // If this is a block implementing a long branch, an expression relative to 198 // the start of the block is needed. to the start of the block. 199 // XXX - Is there a smarter way to check this? 200 return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64); 201 } 202 203 void AMDGPUAsmPrinter::emitFunctionBodyStart() { 204 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 205 if (!MFI.isEntryFunction()) 206 return; 207 208 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 209 const Function &F = MF->getFunction(); 210 if ((STM.isMesaKernel(F) || isHsaAbiVersion2(getGlobalSTI())) && 211 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 212 F.getCallingConv() == CallingConv::SPIR_KERNEL)) { 213 amd_kernel_code_t KernelCode; 214 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 215 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 216 } 217 218 if (STM.isAmdHsaOS()) 219 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo); 220 } 221 222 void AMDGPUAsmPrinter::emitFunctionBodyEnd() { 223 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 224 if (!MFI.isEntryFunction()) 225 return; 226 227 if (TM.getTargetTriple().getOS() != Triple::AMDHSA || 228 isHsaAbiVersion2(getGlobalSTI())) 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(Align(64)); 244 245 const MCSubtargetInfo &STI = MF->getSubtarget(); 246 247 SmallString<128> KernelName; 248 getNameWithPrefix(KernelName, &MF->getFunction()); 249 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 250 STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo), 251 CurrentProgramInfo.NumVGPRsForWavesPerEU, 252 CurrentProgramInfo.NumSGPRsForWavesPerEU - 253 IsaInfo::getNumExtraSGPRs(&STI, 254 CurrentProgramInfo.VCCUsed, 255 CurrentProgramInfo.FlatUsed), 256 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed, 257 hasXNACK(STI)); 258 259 Streamer.PopSection(); 260 } 261 262 void AMDGPUAsmPrinter::emitFunctionEntryLabel() { 263 if (TM.getTargetTriple().getOS() == Triple::AMDHSA && 264 isHsaAbiVersion3(getGlobalSTI())) { 265 AsmPrinter::emitFunctionEntryLabel(); 266 return; 267 } 268 269 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 270 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 271 if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) { 272 SmallString<128> SymbolName; 273 getNameWithPrefix(SymbolName, &MF->getFunction()), 274 getTargetStreamer()->EmitAMDGPUSymbolType( 275 SymbolName, ELF::STT_AMDGPU_HSA_KERNEL); 276 } 277 if (DumpCodeInstEmitter) { 278 // Disassemble function name label to text. 279 DisasmLines.push_back(MF->getName().str() + ":"); 280 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 281 HexLines.push_back(""); 282 } 283 284 AsmPrinter::emitFunctionEntryLabel(); 285 } 286 287 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 288 if (DumpCodeInstEmitter && !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 if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 301 if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) { 302 OutContext.reportError({}, 303 Twine(GV->getName()) + 304 ": unsupported initializer for address space"); 305 return; 306 } 307 308 // LDS variables aren't emitted in HSA or PAL yet. 309 const Triple::OSType OS = TM.getTargetTriple().getOS(); 310 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 311 return; 312 313 MCSymbol *GVSym = getSymbol(GV); 314 315 GVSym->redefineIfPossible(); 316 if (GVSym->isDefined() || GVSym->isVariable()) 317 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 318 "' is already defined"); 319 320 const DataLayout &DL = GV->getParent()->getDataLayout(); 321 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 322 Align Alignment = GV->getAlign().getValueOr(Align(4)); 323 324 emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration()); 325 emitLinkage(GV, GVSym); 326 if (auto TS = getTargetStreamer()) 327 TS->emitAMDGPULDS(GVSym, Size, Alignment); 328 return; 329 } 330 331 AsmPrinter::emitGlobalVariable(GV); 332 } 333 334 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 335 CallGraphResourceInfo.clear(); 336 337 // Pad with s_code_end to help tools and guard against instruction prefetch 338 // causing stale data in caches. Arguably this should be done by the linker, 339 // which is why this isn't done for Mesa. 340 const MCSubtargetInfo &STI = *getGlobalSTI(); 341 if (AMDGPU::isGFX10Plus(STI) && 342 (STI.getTargetTriple().getOS() == Triple::AMDHSA || 343 STI.getTargetTriple().getOS() == Triple::AMDPAL)) { 344 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 345 getTargetStreamer()->EmitCodeEnd(); 346 } 347 348 return AsmPrinter::doFinalization(M); 349 } 350 351 // Print comments that apply to both callable functions and entry points. 352 void AMDGPUAsmPrinter::emitCommonFunctionComments( 353 uint32_t NumVGPR, 354 Optional<uint32_t> NumAGPR, 355 uint32_t TotalNumVGPR, 356 uint32_t NumSGPR, 357 uint64_t ScratchSize, 358 uint64_t CodeSize, 359 const AMDGPUMachineFunction *MFI) { 360 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false); 361 OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false); 362 OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false); 363 if (NumAGPR) { 364 OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false); 365 OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR), 366 false); 367 } 368 OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false); 369 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()), 370 false); 371 } 372 373 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties( 374 const MachineFunction &MF) const { 375 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 376 uint16_t KernelCodeProperties = 0; 377 378 if (MFI.hasPrivateSegmentBuffer()) { 379 KernelCodeProperties |= 380 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 381 } 382 if (MFI.hasDispatchPtr()) { 383 KernelCodeProperties |= 384 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 385 } 386 if (MFI.hasQueuePtr()) { 387 KernelCodeProperties |= 388 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 389 } 390 if (MFI.hasKernargSegmentPtr()) { 391 KernelCodeProperties |= 392 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 393 } 394 if (MFI.hasDispatchID()) { 395 KernelCodeProperties |= 396 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 397 } 398 if (MFI.hasFlatScratchInit()) { 399 KernelCodeProperties |= 400 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 401 } 402 if (MF.getSubtarget<GCNSubtarget>().isWave32()) { 403 KernelCodeProperties |= 404 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32; 405 } 406 407 return KernelCodeProperties; 408 } 409 410 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 411 const MachineFunction &MF, 412 const SIProgramInfo &PI) const { 413 amdhsa::kernel_descriptor_t KernelDescriptor; 414 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 415 416 assert(isUInt<32>(PI.ScratchSize)); 417 assert(isUInt<32>(PI.getComputePGMRSrc1())); 418 assert(isUInt<32>(PI.ComputePGMRSrc2)); 419 420 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 421 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 422 KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1(); 423 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 424 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 425 426 return KernelDescriptor; 427 } 428 429 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 430 CurrentProgramInfo = SIProgramInfo(); 431 432 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 433 434 // The starting address of all shader programs must be 256 bytes aligned. 435 // Regular functions just need the basic required instruction alignment. 436 MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4)); 437 438 SetupMachineFunction(MF); 439 440 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 441 MCContext &Context = getObjFileLowering().getContext(); 442 // FIXME: This should be an explicit check for Mesa. 443 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 444 MCSectionELF *ConfigSection = 445 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 446 OutStreamer->SwitchSection(ConfigSection); 447 } 448 449 if (MFI->isModuleEntryFunction()) { 450 getSIProgramInfo(CurrentProgramInfo, MF); 451 } else { 452 auto I = CallGraphResourceInfo.insert( 453 std::make_pair(&MF.getFunction(), SIFunctionResourceInfo())); 454 SIFunctionResourceInfo &Info = I.first->second; 455 assert(I.second && "should only be called once per function"); 456 Info = analyzeResourceUsage(MF); 457 } 458 459 if (STM.isAmdPalOS()) { 460 if (MFI->isEntryFunction()) 461 EmitPALMetadata(MF, CurrentProgramInfo); 462 else if (MFI->isModuleEntryFunction()) 463 emitPALFunctionMetadata(MF); 464 } else if (!STM.isAmdHsaOS()) { 465 EmitProgramInfoSI(MF, CurrentProgramInfo); 466 } 467 468 DumpCodeInstEmitter = nullptr; 469 if (STM.dumpCode()) { 470 // For -dumpcode, get the assembler out of the streamer, even if it does 471 // not really want to let us have it. This only works with -filetype=obj. 472 bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing(); 473 OutStreamer->setUseAssemblerInfoForParsing(true); 474 MCAssembler *Assembler = OutStreamer->getAssemblerPtr(); 475 OutStreamer->setUseAssemblerInfoForParsing(SaveFlag); 476 if (Assembler) 477 DumpCodeInstEmitter = Assembler->getEmitterPtr(); 478 } 479 480 DisasmLines.clear(); 481 HexLines.clear(); 482 DisasmLineMaxLen = 0; 483 484 emitFunctionBody(); 485 486 if (isVerbose()) { 487 MCSectionELF *CommentSection = 488 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 489 OutStreamer->SwitchSection(CommentSection); 490 491 if (!MFI->isEntryFunction()) { 492 OutStreamer->emitRawComment(" Function info:", false); 493 SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()]; 494 emitCommonFunctionComments( 495 Info.NumVGPR, 496 STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(), 497 Info.getTotalNumVGPRs(STM), 498 Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()), 499 Info.PrivateSegmentSize, 500 getFunctionCodeSize(MF), MFI); 501 return false; 502 } 503 504 OutStreamer->emitRawComment(" Kernel info:", false); 505 emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR, 506 STM.hasMAIInsts() 507 ? CurrentProgramInfo.NumAccVGPR 508 : Optional<uint32_t>(), 509 CurrentProgramInfo.NumVGPR, 510 CurrentProgramInfo.NumSGPR, 511 CurrentProgramInfo.ScratchSize, 512 getFunctionCodeSize(MF), MFI); 513 514 OutStreamer->emitRawComment( 515 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 516 OutStreamer->emitRawComment( 517 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 518 OutStreamer->emitRawComment( 519 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 520 " bytes/workgroup (compile time only)", false); 521 522 OutStreamer->emitRawComment( 523 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 524 OutStreamer->emitRawComment( 525 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 526 527 OutStreamer->emitRawComment( 528 " NumSGPRsForWavesPerEU: " + 529 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 530 OutStreamer->emitRawComment( 531 " NumVGPRsForWavesPerEU: " + 532 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 533 534 OutStreamer->emitRawComment( 535 " Occupancy: " + 536 Twine(CurrentProgramInfo.Occupancy), false); 537 538 OutStreamer->emitRawComment( 539 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 540 541 OutStreamer->emitRawComment( 542 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 543 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 544 OutStreamer->emitRawComment( 545 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 546 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 547 OutStreamer->emitRawComment( 548 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 549 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 550 OutStreamer->emitRawComment( 551 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 552 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 553 OutStreamer->emitRawComment( 554 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 555 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 556 OutStreamer->emitRawComment( 557 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 558 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 559 false); 560 } 561 562 if (DumpCodeInstEmitter) { 563 564 OutStreamer->SwitchSection( 565 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0)); 566 567 for (size_t i = 0; i < DisasmLines.size(); ++i) { 568 std::string Comment = "\n"; 569 if (!HexLines[i].empty()) { 570 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 571 Comment += " ; " + HexLines[i] + "\n"; 572 } 573 574 OutStreamer->emitBytes(StringRef(DisasmLines[i])); 575 OutStreamer->emitBytes(StringRef(Comment)); 576 } 577 } 578 579 return false; 580 } 581 582 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 583 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 584 const SIInstrInfo *TII = STM.getInstrInfo(); 585 586 uint64_t CodeSize = 0; 587 588 for (const MachineBasicBlock &MBB : MF) { 589 for (const MachineInstr &MI : MBB) { 590 // TODO: CodeSize should account for multiple functions. 591 592 // TODO: Should we count size of debug info? 593 if (MI.isDebugInstr()) 594 continue; 595 596 CodeSize += TII->getInstSizeInBytes(MI); 597 } 598 } 599 600 return CodeSize; 601 } 602 603 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 604 const SIInstrInfo &TII, 605 unsigned Reg) { 606 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 607 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 608 return true; 609 } 610 611 return false; 612 } 613 614 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 615 const GCNSubtarget &ST) const { 616 return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST, 617 UsesVCC, UsesFlatScratch); 618 } 619 620 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumVGPRs( 621 const GCNSubtarget &ST) const { 622 return std::max(NumVGPR, NumAGPR); 623 } 624 625 static const Function *getCalleeFunction(const MachineOperand &Op) { 626 if (Op.isImm()) { 627 assert(Op.getImm() == 0); 628 return nullptr; 629 } 630 631 return cast<Function>(Op.getGlobal()); 632 } 633 634 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 635 const MachineFunction &MF) const { 636 SIFunctionResourceInfo Info; 637 638 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 639 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 640 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 641 const MachineRegisterInfo &MRI = MF.getRegInfo(); 642 const SIInstrInfo *TII = ST.getInstrInfo(); 643 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 644 645 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 646 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 647 648 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 649 // instructions aren't used to access the scratch buffer. Inline assembly may 650 // need it though. 651 // 652 // If we only have implicit uses of flat_scr on flat instructions, it is not 653 // really needed. 654 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 655 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 656 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 657 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 658 Info.UsesFlatScratch = false; 659 } 660 661 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 662 663 // Assume a big number if there are any unknown sized objects. 664 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 665 if (Info.HasDynamicallySizedStack) 666 Info.PrivateSegmentSize += AssumedStackSizeForDynamicSizeObjects; 667 668 if (MFI->isStackRealigned()) 669 Info.PrivateSegmentSize += FrameInfo.getMaxAlign().value(); 670 671 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 672 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 673 674 // If there are no calls, MachineRegisterInfo can tell us the used register 675 // count easily. 676 // A tail call isn't considered a call for MachineFrameInfo's purposes. 677 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 678 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 679 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 680 if (MRI.isPhysRegUsed(Reg)) { 681 HighestVGPRReg = Reg; 682 break; 683 } 684 } 685 686 if (ST.hasMAIInsts()) { 687 MCPhysReg HighestAGPRReg = AMDGPU::NoRegister; 688 for (MCPhysReg Reg : reverse(AMDGPU::AGPR_32RegClass.getRegisters())) { 689 if (MRI.isPhysRegUsed(Reg)) { 690 HighestAGPRReg = Reg; 691 break; 692 } 693 } 694 Info.NumAGPR = HighestAGPRReg == AMDGPU::NoRegister ? 0 : 695 TRI.getHWRegIndex(HighestAGPRReg) + 1; 696 } 697 698 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 699 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 700 if (MRI.isPhysRegUsed(Reg)) { 701 HighestSGPRReg = Reg; 702 break; 703 } 704 } 705 706 // We found the maximum register index. They start at 0, so add one to get the 707 // number of registers. 708 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 709 TRI.getHWRegIndex(HighestVGPRReg) + 1; 710 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 711 TRI.getHWRegIndex(HighestSGPRReg) + 1; 712 713 return Info; 714 } 715 716 int32_t MaxVGPR = -1; 717 int32_t MaxAGPR = -1; 718 int32_t MaxSGPR = -1; 719 uint64_t CalleeFrameSize = 0; 720 721 for (const MachineBasicBlock &MBB : MF) { 722 for (const MachineInstr &MI : MBB) { 723 // TODO: Check regmasks? Do they occur anywhere except calls? 724 for (const MachineOperand &MO : MI.operands()) { 725 unsigned Width = 0; 726 bool IsSGPR = false; 727 bool IsAGPR = false; 728 729 if (!MO.isReg()) 730 continue; 731 732 Register Reg = MO.getReg(); 733 switch (Reg) { 734 case AMDGPU::EXEC: 735 case AMDGPU::EXEC_LO: 736 case AMDGPU::EXEC_HI: 737 case AMDGPU::SCC: 738 case AMDGPU::M0: 739 case AMDGPU::SRC_SHARED_BASE: 740 case AMDGPU::SRC_SHARED_LIMIT: 741 case AMDGPU::SRC_PRIVATE_BASE: 742 case AMDGPU::SRC_PRIVATE_LIMIT: 743 case AMDGPU::SGPR_NULL: 744 case AMDGPU::MODE: 745 continue; 746 747 case AMDGPU::SRC_POPS_EXITING_WAVE_ID: 748 llvm_unreachable("src_pops_exiting_wave_id should not be used"); 749 750 case AMDGPU::NoRegister: 751 assert(MI.isDebugInstr() && "Instruction uses invalid noreg register"); 752 continue; 753 754 case AMDGPU::VCC: 755 case AMDGPU::VCC_LO: 756 case AMDGPU::VCC_HI: 757 case AMDGPU::VCC_LO_LO16: 758 case AMDGPU::VCC_LO_HI16: 759 case AMDGPU::VCC_HI_LO16: 760 case AMDGPU::VCC_HI_HI16: 761 Info.UsesVCC = true; 762 continue; 763 764 case AMDGPU::FLAT_SCR: 765 case AMDGPU::FLAT_SCR_LO: 766 case AMDGPU::FLAT_SCR_HI: 767 continue; 768 769 case AMDGPU::XNACK_MASK: 770 case AMDGPU::XNACK_MASK_LO: 771 case AMDGPU::XNACK_MASK_HI: 772 llvm_unreachable("xnack_mask registers should not be used"); 773 774 case AMDGPU::LDS_DIRECT: 775 llvm_unreachable("lds_direct register should not be used"); 776 777 case AMDGPU::TBA: 778 case AMDGPU::TBA_LO: 779 case AMDGPU::TBA_HI: 780 case AMDGPU::TMA: 781 case AMDGPU::TMA_LO: 782 case AMDGPU::TMA_HI: 783 llvm_unreachable("trap handler registers should not be used"); 784 785 case AMDGPU::SRC_VCCZ: 786 llvm_unreachable("src_vccz register should not be used"); 787 788 case AMDGPU::SRC_EXECZ: 789 llvm_unreachable("src_execz register should not be used"); 790 791 case AMDGPU::SRC_SCC: 792 llvm_unreachable("src_scc register should not be used"); 793 794 default: 795 break; 796 } 797 798 if (AMDGPU::SReg_32RegClass.contains(Reg) || 799 AMDGPU::SReg_LO16RegClass.contains(Reg) || 800 AMDGPU::SGPR_HI16RegClass.contains(Reg)) { 801 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 802 "trap handler registers should not be used"); 803 IsSGPR = true; 804 Width = 1; 805 } else if (AMDGPU::VGPR_32RegClass.contains(Reg) || 806 AMDGPU::VGPR_LO16RegClass.contains(Reg) || 807 AMDGPU::VGPR_HI16RegClass.contains(Reg)) { 808 IsSGPR = false; 809 Width = 1; 810 } else if (AMDGPU::AGPR_32RegClass.contains(Reg) || 811 AMDGPU::AGPR_LO16RegClass.contains(Reg)) { 812 IsSGPR = false; 813 IsAGPR = true; 814 Width = 1; 815 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 816 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 817 "trap handler registers should not be used"); 818 IsSGPR = true; 819 Width = 2; 820 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 821 IsSGPR = false; 822 Width = 2; 823 } else if (AMDGPU::AReg_64RegClass.contains(Reg)) { 824 IsSGPR = false; 825 IsAGPR = true; 826 Width = 2; 827 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 828 IsSGPR = false; 829 Width = 3; 830 } else if (AMDGPU::SReg_96RegClass.contains(Reg)) { 831 IsSGPR = true; 832 Width = 3; 833 } else if (AMDGPU::AReg_96RegClass.contains(Reg)) { 834 IsSGPR = false; 835 IsAGPR = true; 836 Width = 3; 837 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 838 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 839 "trap handler registers should not be used"); 840 IsSGPR = true; 841 Width = 4; 842 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 843 IsSGPR = false; 844 Width = 4; 845 } else if (AMDGPU::AReg_128RegClass.contains(Reg)) { 846 IsSGPR = false; 847 IsAGPR = true; 848 Width = 4; 849 } else if (AMDGPU::VReg_160RegClass.contains(Reg)) { 850 IsSGPR = false; 851 Width = 5; 852 } else if (AMDGPU::SReg_160RegClass.contains(Reg)) { 853 IsSGPR = true; 854 Width = 5; 855 } else if (AMDGPU::AReg_160RegClass.contains(Reg)) { 856 IsSGPR = false; 857 IsAGPR = true; 858 Width = 5; 859 } else if (AMDGPU::VReg_192RegClass.contains(Reg)) { 860 IsSGPR = false; 861 Width = 6; 862 } else if (AMDGPU::SReg_192RegClass.contains(Reg)) { 863 IsSGPR = true; 864 Width = 6; 865 } else if (AMDGPU::AReg_192RegClass.contains(Reg)) { 866 IsSGPR = false; 867 IsAGPR = true; 868 Width = 6; 869 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 870 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 871 "trap handler registers should not be used"); 872 IsSGPR = true; 873 Width = 8; 874 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 875 IsSGPR = false; 876 Width = 8; 877 } else if (AMDGPU::AReg_256RegClass.contains(Reg)) { 878 IsSGPR = false; 879 IsAGPR = true; 880 Width = 8; 881 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 882 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 883 "trap handler registers should not be used"); 884 IsSGPR = true; 885 Width = 16; 886 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 887 IsSGPR = false; 888 Width = 16; 889 } else if (AMDGPU::AReg_512RegClass.contains(Reg)) { 890 IsSGPR = false; 891 IsAGPR = true; 892 Width = 16; 893 } else if (AMDGPU::SReg_1024RegClass.contains(Reg)) { 894 IsSGPR = true; 895 Width = 32; 896 } else if (AMDGPU::VReg_1024RegClass.contains(Reg)) { 897 IsSGPR = false; 898 Width = 32; 899 } else if (AMDGPU::AReg_1024RegClass.contains(Reg)) { 900 IsSGPR = false; 901 IsAGPR = true; 902 Width = 32; 903 } else { 904 llvm_unreachable("Unknown register class"); 905 } 906 unsigned HWReg = TRI.getHWRegIndex(Reg); 907 int MaxUsed = HWReg + Width - 1; 908 if (IsSGPR) { 909 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 910 } else if (IsAGPR) { 911 MaxAGPR = MaxUsed > MaxAGPR ? MaxUsed : MaxAGPR; 912 } else { 913 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 914 } 915 } 916 917 if (MI.isCall()) { 918 // Pseudo used just to encode the underlying global. Is there a better 919 // way to track this? 920 921 const MachineOperand *CalleeOp 922 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 923 924 const Function *Callee = getCalleeFunction(*CalleeOp); 925 DenseMap<const Function *, SIFunctionResourceInfo>::const_iterator I = 926 CallGraphResourceInfo.end(); 927 bool IsExternal = !Callee || Callee->isDeclaration(); 928 if (!IsExternal) 929 I = CallGraphResourceInfo.find(Callee); 930 931 if (IsExternal || I == CallGraphResourceInfo.end()) { 932 // Avoid crashing on undefined behavior with an illegal call to a 933 // kernel. If a callsite's calling convention doesn't match the 934 // function's, it's undefined behavior. If the callsite calling 935 // convention does match, that would have errored earlier. 936 // FIXME: The verifier shouldn't allow this. 937 if (!IsExternal && 938 AMDGPU::isEntryFunctionCC(Callee->getCallingConv())) 939 report_fatal_error("invalid call to entry function"); 940 941 // If this is a call to an external function, we can't do much. Make 942 // conservative guesses. 943 944 // 48 SGPRs - vcc, - flat_scr, -xnack 945 int MaxSGPRGuess = 946 47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace()); 947 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 948 MaxVGPR = std::max(MaxVGPR, 23); 949 MaxAGPR = std::max(MaxAGPR, 23); 950 951 CalleeFrameSize = std::max(CalleeFrameSize, 952 static_cast<uint64_t>(AssumedStackSizeForExternalCall)); 953 954 Info.UsesVCC = true; 955 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 956 Info.HasDynamicallySizedStack = true; 957 } else { 958 // We force CodeGen to run in SCC order, so the callee's register 959 // usage etc. should be the cumulative usage of all callees. 960 961 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 962 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 963 MaxAGPR = std::max(I->second.NumAGPR - 1, MaxAGPR); 964 CalleeFrameSize 965 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 966 Info.UsesVCC |= I->second.UsesVCC; 967 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 968 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 969 Info.HasRecursion |= I->second.HasRecursion; 970 } 971 972 // FIXME: Call site could have norecurse on it 973 if (!Callee || !Callee->doesNotRecurse()) 974 Info.HasRecursion = true; 975 } 976 } 977 } 978 979 Info.NumExplicitSGPR = MaxSGPR + 1; 980 Info.NumVGPR = MaxVGPR + 1; 981 Info.NumAGPR = MaxAGPR + 1; 982 Info.PrivateSegmentSize += CalleeFrameSize; 983 984 return Info; 985 } 986 987 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 988 const MachineFunction &MF) { 989 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 990 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 991 992 ProgInfo.NumArchVGPR = Info.NumVGPR; 993 ProgInfo.NumAccVGPR = Info.NumAGPR; 994 ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM); 995 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 996 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 997 ProgInfo.VCCUsed = Info.UsesVCC; 998 ProgInfo.FlatUsed = Info.UsesFlatScratch; 999 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 1000 1001 const uint64_t MaxScratchPerWorkitem = 1002 GCNSubtarget::MaxWaveScratchSize / STM.getWavefrontSize(); 1003 if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) { 1004 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 1005 ProgInfo.ScratchSize, DS_Error); 1006 MF.getFunction().getContext().diagnose(DiagStackSize); 1007 } 1008 1009 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1010 1011 // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are 1012 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 1013 // unified. 1014 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 1015 &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed); 1016 1017 // Check the addressable register limit before we add ExtraSGPRs. 1018 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 1019 !STM.hasSGPRInitBug()) { 1020 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 1021 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 1022 // This can happen due to a compiler bug or when using inline asm. 1023 LLVMContext &Ctx = MF.getFunction().getContext(); 1024 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 1025 "addressable scalar registers", 1026 ProgInfo.NumSGPR, DS_Error, 1027 DK_ResourceLimit, 1028 MaxAddressableNumSGPRs); 1029 Ctx.diagnose(Diag); 1030 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 1031 } 1032 } 1033 1034 // Account for extra SGPRs and VGPRs reserved for debugger use. 1035 ProgInfo.NumSGPR += ExtraSGPRs; 1036 1037 const Function &F = MF.getFunction(); 1038 1039 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 1040 // dispatch registers are function args. 1041 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 1042 1043 if (isShader(F.getCallingConv())) { 1044 // FIXME: We should be using the number of registers determined during 1045 // calling convention lowering to legalize the types. 1046 const DataLayout &DL = F.getParent()->getDataLayout(); 1047 for (auto &Arg : F.args()) { 1048 unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32; 1049 if (Arg.hasAttribute(Attribute::InReg)) 1050 WaveDispatchNumSGPR += NumRegs; 1051 else 1052 WaveDispatchNumVGPR += NumRegs; 1053 } 1054 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 1055 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 1056 } 1057 1058 // Adjust number of registers used to meet default/requested minimum/maximum 1059 // number of waves per execution unit request. 1060 ProgInfo.NumSGPRsForWavesPerEU = std::max( 1061 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 1062 ProgInfo.NumVGPRsForWavesPerEU = std::max( 1063 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 1064 1065 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 1066 STM.hasSGPRInitBug()) { 1067 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 1068 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 1069 // This can happen due to a compiler bug or when using inline asm to use 1070 // the registers which are usually reserved for vcc etc. 1071 LLVMContext &Ctx = MF.getFunction().getContext(); 1072 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 1073 "scalar registers", 1074 ProgInfo.NumSGPR, DS_Error, 1075 DK_ResourceLimit, 1076 MaxAddressableNumSGPRs); 1077 Ctx.diagnose(Diag); 1078 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 1079 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 1080 } 1081 } 1082 1083 if (STM.hasSGPRInitBug()) { 1084 ProgInfo.NumSGPR = 1085 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 1086 ProgInfo.NumSGPRsForWavesPerEU = 1087 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 1088 } 1089 1090 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 1091 LLVMContext &Ctx = MF.getFunction().getContext(); 1092 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 1093 MFI->getNumUserSGPRs(), DS_Error); 1094 Ctx.diagnose(Diag); 1095 } 1096 1097 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 1098 LLVMContext &Ctx = MF.getFunction().getContext(); 1099 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 1100 MFI->getLDSSize(), DS_Error); 1101 Ctx.diagnose(Diag); 1102 } 1103 1104 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 1105 &STM, ProgInfo.NumSGPRsForWavesPerEU); 1106 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 1107 &STM, ProgInfo.NumVGPRsForWavesPerEU); 1108 1109 const SIModeRegisterDefaults Mode = MFI->getMode(); 1110 1111 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 1112 // register. 1113 ProgInfo.FloatMode = getFPMode(Mode); 1114 1115 ProgInfo.IEEEMode = Mode.IEEE; 1116 1117 // Make clamp modifier on NaN input returns 0. 1118 ProgInfo.DX10Clamp = Mode.DX10Clamp; 1119 1120 unsigned LDSAlignShift; 1121 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 1122 // LDS is allocated in 64 dword blocks. 1123 LDSAlignShift = 8; 1124 } else { 1125 // LDS is allocated in 128 dword blocks. 1126 LDSAlignShift = 9; 1127 } 1128 1129 unsigned LDSSpillSize = 1130 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 1131 1132 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 1133 ProgInfo.LDSBlocks = 1134 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 1135 1136 // Scratch is allocated in 256 dword blocks. 1137 unsigned ScratchAlignShift = 10; 1138 // We need to program the hardware with the amount of scratch memory that 1139 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 1140 // scratch memory used per thread. 1141 ProgInfo.ScratchBlocks = 1142 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 1143 1ULL << ScratchAlignShift) >> 1144 ScratchAlignShift; 1145 1146 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) { 1147 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1; 1148 ProgInfo.MemOrdered = 1; 1149 } 1150 1151 // 0 = X, 1 = XY, 2 = XYZ 1152 unsigned TIDIGCompCnt = 0; 1153 if (MFI->hasWorkItemIDZ()) 1154 TIDIGCompCnt = 2; 1155 else if (MFI->hasWorkItemIDY()) 1156 TIDIGCompCnt = 1; 1157 1158 ProgInfo.ComputePGMRSrc2 = 1159 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 1160 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 1161 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 1162 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 1163 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 1164 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 1165 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 1166 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 1167 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 1168 S_00B84C_EXCP_EN_MSB(0) | 1169 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 1170 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 1171 S_00B84C_EXCP_EN(0); 1172 1173 ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize, 1174 ProgInfo.NumSGPRsForWavesPerEU, 1175 ProgInfo.NumVGPRsForWavesPerEU); 1176 } 1177 1178 static unsigned getRsrcReg(CallingConv::ID CallConv) { 1179 switch (CallConv) { 1180 default: LLVM_FALLTHROUGH; 1181 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 1182 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 1183 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 1184 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 1185 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 1186 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 1187 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 1188 } 1189 } 1190 1191 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1192 const SIProgramInfo &CurrentProgramInfo) { 1193 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1194 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1195 1196 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1197 OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1); 1198 1199 OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1()); 1200 1201 OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2); 1202 OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2); 1203 1204 OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE); 1205 OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks)); 1206 1207 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1208 // 0" comment but I don't see a corresponding field in the register spec. 1209 } else { 1210 OutStreamer->emitInt32(RsrcReg); 1211 OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1212 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1213 OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE); 1214 OutStreamer->emitIntValue( 1215 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1216 } 1217 1218 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1219 OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS); 1220 OutStreamer->emitInt32( 1221 S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1222 OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA); 1223 OutStreamer->emitInt32(MFI->getPSInputEnable()); 1224 OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR); 1225 OutStreamer->emitInt32(MFI->getPSInputAddr()); 1226 } 1227 1228 OutStreamer->emitInt32(R_SPILLED_SGPRS); 1229 OutStreamer->emitInt32(MFI->getNumSpilledSGPRs()); 1230 OutStreamer->emitInt32(R_SPILLED_VGPRS); 1231 OutStreamer->emitInt32(MFI->getNumSpilledVGPRs()); 1232 } 1233 1234 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1235 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1236 // metadata items into the PALMD::Metadata, combining with any provided by the 1237 // frontend as LLVM metadata. Once all functions are written, the PAL metadata 1238 // is then written as a single block in the .note section. 1239 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1240 const SIProgramInfo &CurrentProgramInfo) { 1241 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1242 auto CC = MF.getFunction().getCallingConv(); 1243 auto MD = getTargetStreamer()->getPALMetadata(); 1244 1245 MD->setEntryPoint(CC, MF.getFunction().getName()); 1246 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU); 1247 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU); 1248 MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC)); 1249 if (AMDGPU::isCompute(CC)) { 1250 MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2); 1251 } else { 1252 if (CurrentProgramInfo.ScratchBlocks > 0) 1253 MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1)); 1254 } 1255 // ScratchSize is in bytes, 16 aligned. 1256 MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16)); 1257 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1258 MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1259 MD->setSpiPsInputEna(MFI->getPSInputEnable()); 1260 MD->setSpiPsInputAddr(MFI->getPSInputAddr()); 1261 } 1262 1263 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1264 if (STM.isWave32()) 1265 MD->setWave32(MF.getFunction().getCallingConv()); 1266 } 1267 1268 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) { 1269 auto *MD = getTargetStreamer()->getPALMetadata(); 1270 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1271 MD->setFunctionScratchSize(MF, MFI.getStackSize()); 1272 // Set compute registers 1273 MD->setRsrc1(CallingConv::AMDGPU_CS, 1274 CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS)); 1275 MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2); 1276 } 1277 1278 // This is supposed to be log2(Size) 1279 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1280 switch (Size) { 1281 case 4: 1282 return AMD_ELEMENT_4_BYTES; 1283 case 8: 1284 return AMD_ELEMENT_8_BYTES; 1285 case 16: 1286 return AMD_ELEMENT_16_BYTES; 1287 default: 1288 llvm_unreachable("invalid private_element_size"); 1289 } 1290 } 1291 1292 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1293 const SIProgramInfo &CurrentProgramInfo, 1294 const MachineFunction &MF) const { 1295 const Function &F = MF.getFunction(); 1296 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 1297 F.getCallingConv() == CallingConv::SPIR_KERNEL); 1298 1299 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1300 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1301 1302 AMDGPU::initDefaultAMDKernelCodeT(Out, &STM); 1303 1304 Out.compute_pgm_resource_registers = 1305 CurrentProgramInfo.getComputePGMRSrc1() | 1306 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1307 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64; 1308 1309 if (CurrentProgramInfo.DynamicCallStack) 1310 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1311 1312 AMD_HSA_BITS_SET(Out.code_properties, 1313 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1314 getElementByteSizeValue(STM.getMaxPrivateElementSize(true))); 1315 1316 if (MFI->hasPrivateSegmentBuffer()) { 1317 Out.code_properties |= 1318 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1319 } 1320 1321 if (MFI->hasDispatchPtr()) 1322 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1323 1324 if (MFI->hasQueuePtr()) 1325 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1326 1327 if (MFI->hasKernargSegmentPtr()) 1328 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1329 1330 if (MFI->hasDispatchID()) 1331 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1332 1333 if (MFI->hasFlatScratchInit()) 1334 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1335 1336 if (MFI->hasDispatchPtr()) 1337 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1338 1339 if (STM.isXNACKEnabled()) 1340 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1341 1342 Align MaxKernArgAlign; 1343 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1344 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1345 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1346 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1347 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1348 1349 // kernarg_segment_alignment is specified as log of the alignment. 1350 // The minimum alignment is 16. 1351 Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign)); 1352 } 1353 1354 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1355 const char *ExtraCode, raw_ostream &O) { 1356 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1357 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O)) 1358 return false; 1359 1360 if (ExtraCode && ExtraCode[0]) { 1361 if (ExtraCode[1] != 0) 1362 return true; // Unknown modifier. 1363 1364 switch (ExtraCode[0]) { 1365 case 'r': 1366 break; 1367 default: 1368 return true; 1369 } 1370 } 1371 1372 // TODO: Should be able to support other operand types like globals. 1373 const MachineOperand &MO = MI->getOperand(OpNo); 1374 if (MO.isReg()) { 1375 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1376 *MF->getSubtarget().getRegisterInfo()); 1377 return false; 1378 } else if (MO.isImm()) { 1379 int64_t Val = MO.getImm(); 1380 if (AMDGPU::isInlinableIntLiteral(Val)) { 1381 O << Val; 1382 } else if (isUInt<16>(Val)) { 1383 O << format("0x%" PRIx16, static_cast<uint16_t>(Val)); 1384 } else if (isUInt<32>(Val)) { 1385 O << format("0x%" PRIx32, static_cast<uint32_t>(Val)); 1386 } else { 1387 O << format("0x%" PRIx64, static_cast<uint64_t>(Val)); 1388 } 1389 return false; 1390 } 1391 return true; 1392 } 1393