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