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:SCRATCH_EN: " + 543 Twine(G_00B84C_SCRATCH_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 544 OutStreamer->emitRawComment( 545 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 546 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 547 OutStreamer->emitRawComment( 548 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 549 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 550 OutStreamer->emitRawComment( 551 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 552 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 553 OutStreamer->emitRawComment( 554 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 555 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 556 OutStreamer->emitRawComment( 557 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 558 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 559 OutStreamer->emitRawComment( 560 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 561 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 562 false); 563 } 564 565 if (DumpCodeInstEmitter) { 566 567 OutStreamer->SwitchSection( 568 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0)); 569 570 for (size_t i = 0; i < DisasmLines.size(); ++i) { 571 std::string Comment = "\n"; 572 if (!HexLines[i].empty()) { 573 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 574 Comment += " ; " + HexLines[i] + "\n"; 575 } 576 577 OutStreamer->emitBytes(StringRef(DisasmLines[i])); 578 OutStreamer->emitBytes(StringRef(Comment)); 579 } 580 } 581 582 return false; 583 } 584 585 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 586 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 587 const SIInstrInfo *TII = STM.getInstrInfo(); 588 589 uint64_t CodeSize = 0; 590 591 for (const MachineBasicBlock &MBB : MF) { 592 for (const MachineInstr &MI : MBB) { 593 // TODO: CodeSize should account for multiple functions. 594 595 // TODO: Should we count size of debug info? 596 if (MI.isDebugInstr()) 597 continue; 598 599 CodeSize += TII->getInstSizeInBytes(MI); 600 } 601 } 602 603 return CodeSize; 604 } 605 606 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 607 const SIInstrInfo &TII, 608 unsigned Reg) { 609 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 610 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 611 return true; 612 } 613 614 return false; 615 } 616 617 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 618 const GCNSubtarget &ST) const { 619 return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST, 620 UsesVCC, UsesFlatScratch); 621 } 622 623 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumVGPRs( 624 const GCNSubtarget &ST) const { 625 return std::max(NumVGPR, NumAGPR); 626 } 627 628 static const Function *getCalleeFunction(const MachineOperand &Op) { 629 if (Op.isImm()) { 630 assert(Op.getImm() == 0); 631 return nullptr; 632 } 633 634 return cast<Function>(Op.getGlobal()); 635 } 636 637 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 638 const MachineFunction &MF) const { 639 SIFunctionResourceInfo Info; 640 641 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 642 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 643 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 644 const MachineRegisterInfo &MRI = MF.getRegInfo(); 645 const SIInstrInfo *TII = ST.getInstrInfo(); 646 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 647 648 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 649 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 650 651 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 652 // instructions aren't used to access the scratch buffer. Inline assembly may 653 // need it though. 654 // 655 // If we only have implicit uses of flat_scr on flat instructions, it is not 656 // really needed. 657 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 658 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 659 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 660 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 661 Info.UsesFlatScratch = false; 662 } 663 664 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 665 666 // Assume a big number if there are any unknown sized objects. 667 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 668 if (Info.HasDynamicallySizedStack) 669 Info.PrivateSegmentSize += AssumedStackSizeForDynamicSizeObjects; 670 671 if (MFI->isStackRealigned()) 672 Info.PrivateSegmentSize += FrameInfo.getMaxAlign().value(); 673 674 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 675 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 676 677 // If there are no calls, MachineRegisterInfo can tell us the used register 678 // count easily. 679 // A tail call isn't considered a call for MachineFrameInfo's purposes. 680 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 681 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 682 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 683 if (MRI.isPhysRegUsed(Reg)) { 684 HighestVGPRReg = Reg; 685 break; 686 } 687 } 688 689 if (ST.hasMAIInsts()) { 690 MCPhysReg HighestAGPRReg = AMDGPU::NoRegister; 691 for (MCPhysReg Reg : reverse(AMDGPU::AGPR_32RegClass.getRegisters())) { 692 if (MRI.isPhysRegUsed(Reg)) { 693 HighestAGPRReg = Reg; 694 break; 695 } 696 } 697 Info.NumAGPR = HighestAGPRReg == AMDGPU::NoRegister ? 0 : 698 TRI.getHWRegIndex(HighestAGPRReg) + 1; 699 } 700 701 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 702 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 703 if (MRI.isPhysRegUsed(Reg)) { 704 HighestSGPRReg = Reg; 705 break; 706 } 707 } 708 709 // We found the maximum register index. They start at 0, so add one to get the 710 // number of registers. 711 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 712 TRI.getHWRegIndex(HighestVGPRReg) + 1; 713 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 714 TRI.getHWRegIndex(HighestSGPRReg) + 1; 715 716 return Info; 717 } 718 719 int32_t MaxVGPR = -1; 720 int32_t MaxAGPR = -1; 721 int32_t MaxSGPR = -1; 722 uint64_t CalleeFrameSize = 0; 723 724 for (const MachineBasicBlock &MBB : MF) { 725 for (const MachineInstr &MI : MBB) { 726 // TODO: Check regmasks? Do they occur anywhere except calls? 727 for (const MachineOperand &MO : MI.operands()) { 728 unsigned Width = 0; 729 bool IsSGPR = false; 730 bool IsAGPR = false; 731 732 if (!MO.isReg()) 733 continue; 734 735 Register Reg = MO.getReg(); 736 switch (Reg) { 737 case AMDGPU::EXEC: 738 case AMDGPU::EXEC_LO: 739 case AMDGPU::EXEC_HI: 740 case AMDGPU::SCC: 741 case AMDGPU::M0: 742 case AMDGPU::SRC_SHARED_BASE: 743 case AMDGPU::SRC_SHARED_LIMIT: 744 case AMDGPU::SRC_PRIVATE_BASE: 745 case AMDGPU::SRC_PRIVATE_LIMIT: 746 case AMDGPU::SGPR_NULL: 747 case AMDGPU::MODE: 748 continue; 749 750 case AMDGPU::SRC_POPS_EXITING_WAVE_ID: 751 llvm_unreachable("src_pops_exiting_wave_id should not be used"); 752 753 case AMDGPU::NoRegister: 754 assert(MI.isDebugInstr() && "Instruction uses invalid noreg register"); 755 continue; 756 757 case AMDGPU::VCC: 758 case AMDGPU::VCC_LO: 759 case AMDGPU::VCC_HI: 760 case AMDGPU::VCC_LO_LO16: 761 case AMDGPU::VCC_LO_HI16: 762 case AMDGPU::VCC_HI_LO16: 763 case AMDGPU::VCC_HI_HI16: 764 Info.UsesVCC = true; 765 continue; 766 767 case AMDGPU::FLAT_SCR: 768 case AMDGPU::FLAT_SCR_LO: 769 case AMDGPU::FLAT_SCR_HI: 770 continue; 771 772 case AMDGPU::XNACK_MASK: 773 case AMDGPU::XNACK_MASK_LO: 774 case AMDGPU::XNACK_MASK_HI: 775 llvm_unreachable("xnack_mask registers should not be used"); 776 777 case AMDGPU::LDS_DIRECT: 778 llvm_unreachable("lds_direct register should not be used"); 779 780 case AMDGPU::TBA: 781 case AMDGPU::TBA_LO: 782 case AMDGPU::TBA_HI: 783 case AMDGPU::TMA: 784 case AMDGPU::TMA_LO: 785 case AMDGPU::TMA_HI: 786 llvm_unreachable("trap handler registers should not be used"); 787 788 case AMDGPU::SRC_VCCZ: 789 llvm_unreachable("src_vccz register should not be used"); 790 791 case AMDGPU::SRC_EXECZ: 792 llvm_unreachable("src_execz register should not be used"); 793 794 case AMDGPU::SRC_SCC: 795 llvm_unreachable("src_scc register should not be used"); 796 797 default: 798 break; 799 } 800 801 if (AMDGPU::SReg_32RegClass.contains(Reg) || 802 AMDGPU::SReg_LO16RegClass.contains(Reg) || 803 AMDGPU::SGPR_HI16RegClass.contains(Reg)) { 804 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 805 "trap handler registers should not be used"); 806 IsSGPR = true; 807 Width = 1; 808 } else if (AMDGPU::VGPR_32RegClass.contains(Reg) || 809 AMDGPU::VGPR_LO16RegClass.contains(Reg) || 810 AMDGPU::VGPR_HI16RegClass.contains(Reg)) { 811 IsSGPR = false; 812 Width = 1; 813 } else if (AMDGPU::AGPR_32RegClass.contains(Reg) || 814 AMDGPU::AGPR_LO16RegClass.contains(Reg)) { 815 IsSGPR = false; 816 IsAGPR = true; 817 Width = 1; 818 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 819 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 820 "trap handler registers should not be used"); 821 IsSGPR = true; 822 Width = 2; 823 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 824 IsSGPR = false; 825 Width = 2; 826 } else if (AMDGPU::AReg_64RegClass.contains(Reg)) { 827 IsSGPR = false; 828 IsAGPR = true; 829 Width = 2; 830 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 831 IsSGPR = false; 832 Width = 3; 833 } else if (AMDGPU::SReg_96RegClass.contains(Reg)) { 834 IsSGPR = true; 835 Width = 3; 836 } else if (AMDGPU::AReg_96RegClass.contains(Reg)) { 837 IsSGPR = false; 838 IsAGPR = true; 839 Width = 3; 840 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 841 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 842 "trap handler registers should not be used"); 843 IsSGPR = true; 844 Width = 4; 845 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 846 IsSGPR = false; 847 Width = 4; 848 } else if (AMDGPU::AReg_128RegClass.contains(Reg)) { 849 IsSGPR = false; 850 IsAGPR = true; 851 Width = 4; 852 } else if (AMDGPU::VReg_160RegClass.contains(Reg)) { 853 IsSGPR = false; 854 Width = 5; 855 } else if (AMDGPU::SReg_160RegClass.contains(Reg)) { 856 IsSGPR = true; 857 Width = 5; 858 } else if (AMDGPU::AReg_160RegClass.contains(Reg)) { 859 IsSGPR = false; 860 IsAGPR = true; 861 Width = 5; 862 } else if (AMDGPU::VReg_192RegClass.contains(Reg)) { 863 IsSGPR = false; 864 Width = 6; 865 } else if (AMDGPU::SReg_192RegClass.contains(Reg)) { 866 IsSGPR = true; 867 Width = 6; 868 } else if (AMDGPU::AReg_192RegClass.contains(Reg)) { 869 IsSGPR = false; 870 IsAGPR = true; 871 Width = 6; 872 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 873 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 874 "trap handler registers should not be used"); 875 IsSGPR = true; 876 Width = 8; 877 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 878 IsSGPR = false; 879 Width = 8; 880 } else if (AMDGPU::AReg_256RegClass.contains(Reg)) { 881 IsSGPR = false; 882 IsAGPR = true; 883 Width = 8; 884 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 885 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 886 "trap handler registers should not be used"); 887 IsSGPR = true; 888 Width = 16; 889 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 890 IsSGPR = false; 891 Width = 16; 892 } else if (AMDGPU::AReg_512RegClass.contains(Reg)) { 893 IsSGPR = false; 894 IsAGPR = true; 895 Width = 16; 896 } else if (AMDGPU::SReg_1024RegClass.contains(Reg)) { 897 IsSGPR = true; 898 Width = 32; 899 } else if (AMDGPU::VReg_1024RegClass.contains(Reg)) { 900 IsSGPR = false; 901 Width = 32; 902 } else if (AMDGPU::AReg_1024RegClass.contains(Reg)) { 903 IsSGPR = false; 904 IsAGPR = true; 905 Width = 32; 906 } else { 907 llvm_unreachable("Unknown register class"); 908 } 909 unsigned HWReg = TRI.getHWRegIndex(Reg); 910 int MaxUsed = HWReg + Width - 1; 911 if (IsSGPR) { 912 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 913 } else if (IsAGPR) { 914 MaxAGPR = MaxUsed > MaxAGPR ? MaxUsed : MaxAGPR; 915 } else { 916 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 917 } 918 } 919 920 if (MI.isCall()) { 921 // Pseudo used just to encode the underlying global. Is there a better 922 // way to track this? 923 924 const MachineOperand *CalleeOp 925 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 926 927 const Function *Callee = getCalleeFunction(*CalleeOp); 928 DenseMap<const Function *, SIFunctionResourceInfo>::const_iterator I = 929 CallGraphResourceInfo.end(); 930 bool IsExternal = !Callee || Callee->isDeclaration(); 931 if (!IsExternal) 932 I = CallGraphResourceInfo.find(Callee); 933 934 if (IsExternal || I == CallGraphResourceInfo.end()) { 935 // Avoid crashing on undefined behavior with an illegal call to a 936 // kernel. If a callsite's calling convention doesn't match the 937 // function's, it's undefined behavior. If the callsite calling 938 // convention does match, that would have errored earlier. 939 // FIXME: The verifier shouldn't allow this. 940 if (!IsExternal && 941 AMDGPU::isEntryFunctionCC(Callee->getCallingConv())) 942 report_fatal_error("invalid call to entry function"); 943 944 // If this is a call to an external function, we can't do much. Make 945 // conservative guesses. 946 947 // 48 SGPRs - vcc, - flat_scr, -xnack 948 int MaxSGPRGuess = 949 47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace()); 950 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 951 MaxVGPR = std::max(MaxVGPR, 23); 952 MaxAGPR = std::max(MaxAGPR, 23); 953 954 CalleeFrameSize = std::max(CalleeFrameSize, 955 static_cast<uint64_t>(AssumedStackSizeForExternalCall)); 956 957 Info.UsesVCC = true; 958 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 959 Info.HasDynamicallySizedStack = true; 960 } else { 961 // We force CodeGen to run in SCC order, so the callee's register 962 // usage etc. should be the cumulative usage of all callees. 963 964 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 965 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 966 MaxAGPR = std::max(I->second.NumAGPR - 1, MaxAGPR); 967 CalleeFrameSize 968 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 969 Info.UsesVCC |= I->second.UsesVCC; 970 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 971 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 972 Info.HasRecursion |= I->second.HasRecursion; 973 } 974 975 // FIXME: Call site could have norecurse on it 976 if (!Callee || !Callee->doesNotRecurse()) 977 Info.HasRecursion = true; 978 } 979 } 980 } 981 982 Info.NumExplicitSGPR = MaxSGPR + 1; 983 Info.NumVGPR = MaxVGPR + 1; 984 Info.NumAGPR = MaxAGPR + 1; 985 Info.PrivateSegmentSize += CalleeFrameSize; 986 987 return Info; 988 } 989 990 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 991 const MachineFunction &MF) { 992 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 993 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 994 995 ProgInfo.NumArchVGPR = Info.NumVGPR; 996 ProgInfo.NumAccVGPR = Info.NumAGPR; 997 ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM); 998 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 999 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 1000 ProgInfo.VCCUsed = Info.UsesVCC; 1001 ProgInfo.FlatUsed = Info.UsesFlatScratch; 1002 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 1003 1004 const uint64_t MaxScratchPerWorkitem = 1005 GCNSubtarget::MaxWaveScratchSize / STM.getWavefrontSize(); 1006 if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) { 1007 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 1008 ProgInfo.ScratchSize, DS_Error); 1009 MF.getFunction().getContext().diagnose(DiagStackSize); 1010 } 1011 1012 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1013 1014 // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are 1015 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 1016 // unified. 1017 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 1018 &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed); 1019 1020 // Check the addressable register limit before we add ExtraSGPRs. 1021 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 1022 !STM.hasSGPRInitBug()) { 1023 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 1024 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 1025 // This can happen due to a compiler bug or when using inline asm. 1026 LLVMContext &Ctx = MF.getFunction().getContext(); 1027 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 1028 "addressable scalar registers", 1029 ProgInfo.NumSGPR, DS_Error, 1030 DK_ResourceLimit, 1031 MaxAddressableNumSGPRs); 1032 Ctx.diagnose(Diag); 1033 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 1034 } 1035 } 1036 1037 // Account for extra SGPRs and VGPRs reserved for debugger use. 1038 ProgInfo.NumSGPR += ExtraSGPRs; 1039 1040 const Function &F = MF.getFunction(); 1041 1042 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 1043 // dispatch registers are function args. 1044 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 1045 1046 if (isShader(F.getCallingConv())) { 1047 // FIXME: We should be using the number of registers determined during 1048 // calling convention lowering to legalize the types. 1049 const DataLayout &DL = F.getParent()->getDataLayout(); 1050 for (auto &Arg : F.args()) { 1051 unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32; 1052 if (Arg.hasAttribute(Attribute::InReg)) 1053 WaveDispatchNumSGPR += NumRegs; 1054 else 1055 WaveDispatchNumVGPR += NumRegs; 1056 } 1057 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 1058 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 1059 } 1060 1061 // Adjust number of registers used to meet default/requested minimum/maximum 1062 // number of waves per execution unit request. 1063 ProgInfo.NumSGPRsForWavesPerEU = std::max( 1064 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 1065 ProgInfo.NumVGPRsForWavesPerEU = std::max( 1066 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 1067 1068 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 1069 STM.hasSGPRInitBug()) { 1070 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 1071 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 1072 // This can happen due to a compiler bug or when using inline asm to use 1073 // the registers which are usually reserved for vcc etc. 1074 LLVMContext &Ctx = MF.getFunction().getContext(); 1075 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 1076 "scalar registers", 1077 ProgInfo.NumSGPR, DS_Error, 1078 DK_ResourceLimit, 1079 MaxAddressableNumSGPRs); 1080 Ctx.diagnose(Diag); 1081 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 1082 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 1083 } 1084 } 1085 1086 if (STM.hasSGPRInitBug()) { 1087 ProgInfo.NumSGPR = 1088 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 1089 ProgInfo.NumSGPRsForWavesPerEU = 1090 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 1091 } 1092 1093 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 1094 LLVMContext &Ctx = MF.getFunction().getContext(); 1095 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 1096 MFI->getNumUserSGPRs(), DS_Error); 1097 Ctx.diagnose(Diag); 1098 } 1099 1100 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 1101 LLVMContext &Ctx = MF.getFunction().getContext(); 1102 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 1103 MFI->getLDSSize(), DS_Error); 1104 Ctx.diagnose(Diag); 1105 } 1106 1107 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 1108 &STM, ProgInfo.NumSGPRsForWavesPerEU); 1109 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 1110 &STM, ProgInfo.NumVGPRsForWavesPerEU); 1111 1112 const SIModeRegisterDefaults Mode = MFI->getMode(); 1113 1114 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 1115 // register. 1116 ProgInfo.FloatMode = getFPMode(Mode); 1117 1118 ProgInfo.IEEEMode = Mode.IEEE; 1119 1120 // Make clamp modifier on NaN input returns 0. 1121 ProgInfo.DX10Clamp = Mode.DX10Clamp; 1122 1123 unsigned LDSAlignShift; 1124 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 1125 // LDS is allocated in 64 dword blocks. 1126 LDSAlignShift = 8; 1127 } else { 1128 // LDS is allocated in 128 dword blocks. 1129 LDSAlignShift = 9; 1130 } 1131 1132 unsigned LDSSpillSize = 1133 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 1134 1135 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 1136 ProgInfo.LDSBlocks = 1137 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 1138 1139 // Scratch is allocated in 256 dword blocks. 1140 unsigned ScratchAlignShift = 10; 1141 // We need to program the hardware with the amount of scratch memory that 1142 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 1143 // scratch memory used per thread. 1144 ProgInfo.ScratchBlocks = 1145 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 1146 1ULL << ScratchAlignShift) >> 1147 ScratchAlignShift; 1148 1149 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) { 1150 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1; 1151 ProgInfo.MemOrdered = 1; 1152 } 1153 1154 // 0 = X, 1 = XY, 2 = XYZ 1155 unsigned TIDIGCompCnt = 0; 1156 if (MFI->hasWorkItemIDZ()) 1157 TIDIGCompCnt = 2; 1158 else if (MFI->hasWorkItemIDY()) 1159 TIDIGCompCnt = 1; 1160 1161 ProgInfo.ComputePGMRSrc2 = 1162 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 1163 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 1164 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 1165 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 1166 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 1167 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 1168 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 1169 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 1170 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 1171 S_00B84C_EXCP_EN_MSB(0) | 1172 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 1173 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 1174 S_00B84C_EXCP_EN(0); 1175 1176 ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize, 1177 ProgInfo.NumSGPRsForWavesPerEU, 1178 ProgInfo.NumVGPRsForWavesPerEU); 1179 } 1180 1181 static unsigned getRsrcReg(CallingConv::ID CallConv) { 1182 switch (CallConv) { 1183 default: LLVM_FALLTHROUGH; 1184 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 1185 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 1186 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 1187 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 1188 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 1189 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 1190 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 1191 } 1192 } 1193 1194 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1195 const SIProgramInfo &CurrentProgramInfo) { 1196 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1197 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1198 1199 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1200 OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1); 1201 1202 OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1()); 1203 1204 OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2); 1205 OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2); 1206 1207 OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE); 1208 OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks)); 1209 1210 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1211 // 0" comment but I don't see a corresponding field in the register spec. 1212 } else { 1213 OutStreamer->emitInt32(RsrcReg); 1214 OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1215 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1216 OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE); 1217 OutStreamer->emitIntValue( 1218 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1219 } 1220 1221 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1222 OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS); 1223 OutStreamer->emitInt32( 1224 S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1225 OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA); 1226 OutStreamer->emitInt32(MFI->getPSInputEnable()); 1227 OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR); 1228 OutStreamer->emitInt32(MFI->getPSInputAddr()); 1229 } 1230 1231 OutStreamer->emitInt32(R_SPILLED_SGPRS); 1232 OutStreamer->emitInt32(MFI->getNumSpilledSGPRs()); 1233 OutStreamer->emitInt32(R_SPILLED_VGPRS); 1234 OutStreamer->emitInt32(MFI->getNumSpilledVGPRs()); 1235 } 1236 1237 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1238 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1239 // metadata items into the PALMD::Metadata, combining with any provided by the 1240 // frontend as LLVM metadata. Once all functions are written, the PAL metadata 1241 // is then written as a single block in the .note section. 1242 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1243 const SIProgramInfo &CurrentProgramInfo) { 1244 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1245 auto CC = MF.getFunction().getCallingConv(); 1246 auto MD = getTargetStreamer()->getPALMetadata(); 1247 1248 MD->setEntryPoint(CC, MF.getFunction().getName()); 1249 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU); 1250 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU); 1251 MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC)); 1252 if (AMDGPU::isCompute(CC)) { 1253 MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2); 1254 } else { 1255 if (CurrentProgramInfo.ScratchBlocks > 0) 1256 MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1)); 1257 } 1258 // ScratchSize is in bytes, 16 aligned. 1259 MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16)); 1260 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1261 MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1262 MD->setSpiPsInputEna(MFI->getPSInputEnable()); 1263 MD->setSpiPsInputAddr(MFI->getPSInputAddr()); 1264 } 1265 1266 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1267 if (STM.isWave32()) 1268 MD->setWave32(MF.getFunction().getCallingConv()); 1269 } 1270 1271 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) { 1272 auto *MD = getTargetStreamer()->getPALMetadata(); 1273 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1274 MD->setFunctionScratchSize(MF, MFI.getStackSize()); 1275 // Set compute registers 1276 MD->setRsrc1(CallingConv::AMDGPU_CS, 1277 CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS)); 1278 MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2); 1279 } 1280 1281 // This is supposed to be log2(Size) 1282 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1283 switch (Size) { 1284 case 4: 1285 return AMD_ELEMENT_4_BYTES; 1286 case 8: 1287 return AMD_ELEMENT_8_BYTES; 1288 case 16: 1289 return AMD_ELEMENT_16_BYTES; 1290 default: 1291 llvm_unreachable("invalid private_element_size"); 1292 } 1293 } 1294 1295 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1296 const SIProgramInfo &CurrentProgramInfo, 1297 const MachineFunction &MF) const { 1298 const Function &F = MF.getFunction(); 1299 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 1300 F.getCallingConv() == CallingConv::SPIR_KERNEL); 1301 1302 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1303 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1304 1305 AMDGPU::initDefaultAMDKernelCodeT(Out, &STM); 1306 1307 Out.compute_pgm_resource_registers = 1308 CurrentProgramInfo.getComputePGMRSrc1() | 1309 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1310 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64; 1311 1312 if (CurrentProgramInfo.DynamicCallStack) 1313 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1314 1315 AMD_HSA_BITS_SET(Out.code_properties, 1316 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1317 getElementByteSizeValue(STM.getMaxPrivateElementSize(true))); 1318 1319 if (MFI->hasPrivateSegmentBuffer()) { 1320 Out.code_properties |= 1321 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1322 } 1323 1324 if (MFI->hasDispatchPtr()) 1325 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1326 1327 if (MFI->hasQueuePtr()) 1328 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1329 1330 if (MFI->hasKernargSegmentPtr()) 1331 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1332 1333 if (MFI->hasDispatchID()) 1334 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1335 1336 if (MFI->hasFlatScratchInit()) 1337 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1338 1339 if (MFI->hasDispatchPtr()) 1340 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1341 1342 if (STM.isXNACKEnabled()) 1343 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1344 1345 Align MaxKernArgAlign; 1346 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1347 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1348 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1349 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1350 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1351 1352 // kernarg_segment_alignment is specified as log of the alignment. 1353 // The minimum alignment is 16. 1354 Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign)); 1355 } 1356 1357 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1358 const char *ExtraCode, raw_ostream &O) { 1359 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1360 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O)) 1361 return false; 1362 1363 if (ExtraCode && ExtraCode[0]) { 1364 if (ExtraCode[1] != 0) 1365 return true; // Unknown modifier. 1366 1367 switch (ExtraCode[0]) { 1368 case 'r': 1369 break; 1370 default: 1371 return true; 1372 } 1373 } 1374 1375 // TODO: Should be able to support other operand types like globals. 1376 const MachineOperand &MO = MI->getOperand(OpNo); 1377 if (MO.isReg()) { 1378 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1379 *MF->getSubtarget().getRegisterInfo()); 1380 return false; 1381 } else if (MO.isImm()) { 1382 int64_t Val = MO.getImm(); 1383 if (AMDGPU::isInlinableIntLiteral(Val)) { 1384 O << Val; 1385 } else if (isUInt<16>(Val)) { 1386 O << format("0x%" PRIx16, static_cast<uint16_t>(Val)); 1387 } else if (isUInt<32>(Val)) { 1388 O << format("0x%" PRIx32, static_cast<uint32_t>(Val)); 1389 } else { 1390 O << format("0x%" PRIx64, static_cast<uint64_t>(Val)); 1391 } 1392 return false; 1393 } 1394 return true; 1395 } 1396