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