LLVM 20.0.0git
SIMachineFunctionInfo.cpp
Go to the documentation of this file.
1//===- SIMachineFunctionInfo.cpp - SI Machine Function Info ---------------===//
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
10#include "AMDGPUSubtarget.h"
11#include "GCNSubtarget.h"
13#include "SIRegisterInfo.h"
21#include "llvm/IR/CallingConv.h"
23#include "llvm/IR/Function.h"
24#include <cassert>
25#include <optional>
26#include <vector>
27
28enum { MAX_LANES = 64 };
29
30using namespace llvm;
31
33 const SITargetLowering *TLI = STI->getTargetLowering();
34 return static_cast<const GCNTargetMachine &>(TLI->getTargetMachine());
35}
36
38 const GCNSubtarget *STI)
39 : AMDGPUMachineFunction(F, *STI), Mode(F, *STI), GWSResourcePSV(getTM(STI)),
40 UserSGPRInfo(F, *STI), WorkGroupIDX(false), WorkGroupIDY(false),
41 WorkGroupIDZ(false), WorkGroupInfo(false), LDSKernelId(false),
42 PrivateSegmentWaveByteOffset(false), WorkItemIDX(false),
43 WorkItemIDY(false), WorkItemIDZ(false), ImplicitArgPtr(false),
44 GITPtrHigh(0xffffffff), HighBitsOf32BitAddress(0) {
45 const GCNSubtarget &ST = *static_cast<const GCNSubtarget *>(STI);
46 FlatWorkGroupSizes = ST.getFlatWorkGroupSizes(F);
47 WavesPerEU = ST.getWavesPerEU(F);
48 MaxNumWorkGroups = ST.getMaxNumWorkGroups(F);
49 assert(MaxNumWorkGroups.size() == 3);
50
51 Occupancy = ST.computeOccupancy(F, getLDSSize());
52 CallingConv::ID CC = F.getCallingConv();
53
54 VRegFlags.reserve(1024);
55
56 const bool IsKernel = CC == CallingConv::AMDGPU_KERNEL ||
58
59 if (IsKernel) {
60 WorkGroupIDX = true;
61 WorkItemIDX = true;
62 } else if (CC == CallingConv::AMDGPU_PS) {
63 PSInputAddr = AMDGPU::getInitialPSInputAddr(F);
64 }
65
66 MayNeedAGPRs = ST.hasMAIInsts();
67
68 if (AMDGPU::isChainCC(CC)) {
69 // Chain functions don't receive an SP from their caller, but are free to
70 // set one up. For now, we can use s32 to match what amdgpu_gfx functions
71 // would use if called, but this can be revisited.
72 // FIXME: Only reserve this if we actually need it.
73 StackPtrOffsetReg = AMDGPU::SGPR32;
74
75 ScratchRSrcReg = AMDGPU::SGPR48_SGPR49_SGPR50_SGPR51;
76
77 ArgInfo.PrivateSegmentBuffer =
78 ArgDescriptor::createRegister(ScratchRSrcReg);
79
80 ImplicitArgPtr = false;
81 } else if (!isEntryFunction()) {
84
85 FrameOffsetReg = AMDGPU::SGPR33;
86 StackPtrOffsetReg = AMDGPU::SGPR32;
87
88 if (!ST.enableFlatScratch()) {
89 // Non-entry functions have no special inputs for now, other registers
90 // required for scratch access.
91 ScratchRSrcReg = AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3;
92
93 ArgInfo.PrivateSegmentBuffer =
94 ArgDescriptor::createRegister(ScratchRSrcReg);
95 }
96
97 if (!F.hasFnAttribute("amdgpu-no-implicitarg-ptr"))
98 ImplicitArgPtr = true;
99 } else {
100 ImplicitArgPtr = false;
101 MaxKernArgAlign = std::max(ST.getAlignmentForImplicitArgPtr(),
103
104 if (ST.hasGFX90AInsts() &&
105 ST.getMaxNumVGPRs(F) <= AMDGPU::VGPR_32RegClass.getNumRegs() &&
106 !mayUseAGPRs(F))
107 MayNeedAGPRs = false; // We will select all MAI with VGPR operands.
108 }
109
110 if (!AMDGPU::isGraphics(CC) ||
112 ST.hasArchitectedSGPRs())) {
113 if (IsKernel || !F.hasFnAttribute("amdgpu-no-workgroup-id-x"))
114 WorkGroupIDX = true;
115
116 if (!F.hasFnAttribute("amdgpu-no-workgroup-id-y"))
117 WorkGroupIDY = true;
118
119 if (!F.hasFnAttribute("amdgpu-no-workgroup-id-z"))
120 WorkGroupIDZ = true;
121 }
122
123 if (!AMDGPU::isGraphics(CC)) {
124 if (IsKernel || !F.hasFnAttribute("amdgpu-no-workitem-id-x"))
125 WorkItemIDX = true;
126
127 if (!F.hasFnAttribute("amdgpu-no-workitem-id-y") &&
128 ST.getMaxWorkitemID(F, 1) != 0)
129 WorkItemIDY = true;
130
131 if (!F.hasFnAttribute("amdgpu-no-workitem-id-z") &&
132 ST.getMaxWorkitemID(F, 2) != 0)
133 WorkItemIDZ = true;
134
135 if (!IsKernel && !F.hasFnAttribute("amdgpu-no-lds-kernel-id"))
136 LDSKernelId = true;
137 }
138
139 if (isEntryFunction()) {
140 // X, XY, and XYZ are the only supported combinations, so make sure Y is
141 // enabled if Z is.
142 if (WorkItemIDZ)
143 WorkItemIDY = true;
144
145 if (!ST.flatScratchIsArchitected()) {
146 PrivateSegmentWaveByteOffset = true;
147
148 // HS and GS always have the scratch wave offset in SGPR5 on GFX9.
149 if (ST.getGeneration() >= AMDGPUSubtarget::GFX9 &&
151 ArgInfo.PrivateSegmentWaveByteOffset =
152 ArgDescriptor::createRegister(AMDGPU::SGPR5);
153 }
154 }
155
156 Attribute A = F.getFnAttribute("amdgpu-git-ptr-high");
157 StringRef S = A.getValueAsString();
158 if (!S.empty())
159 S.consumeInteger(0, GITPtrHigh);
160
161 A = F.getFnAttribute("amdgpu-32bit-address-high-bits");
162 S = A.getValueAsString();
163 if (!S.empty())
164 S.consumeInteger(0, HighBitsOf32BitAddress);
165
166 // On GFX908, in order to guarantee copying between AGPRs, we need a scratch
167 // VGPR available at all times. For now, reserve highest available VGPR. After
168 // RA, shift it to the lowest available unused VGPR if the one exist.
169 if (ST.hasMAIInsts() && !ST.hasGFX90AInsts()) {
170 VGPRForAGPRCopy =
171 AMDGPU::VGPR_32RegClass.getRegister(ST.getMaxNumVGPRs(F) - 1);
172 }
173}
174
176 BumpPtrAllocator &Allocator, MachineFunction &DestMF,
178 const {
179 return DestMF.cloneInfo<SIMachineFunctionInfo>(*this);
180}
181
184 const GCNSubtarget& ST = MF.getSubtarget<GCNSubtarget>();
185 limitOccupancy(ST.getOccupancyWithLocalMemSize(getLDSSize(),
186 MF.getFunction()));
187}
188
190 const SIRegisterInfo &TRI) {
191 ArgInfo.PrivateSegmentBuffer =
192 ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
193 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SGPR_128RegClass));
194 NumUserSGPRs += 4;
195 return ArgInfo.PrivateSegmentBuffer.getRegister();
196}
197
199 ArgInfo.DispatchPtr = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
200 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
201 NumUserSGPRs += 2;
202 return ArgInfo.DispatchPtr.getRegister();
203}
204
206 ArgInfo.QueuePtr = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
207 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
208 NumUserSGPRs += 2;
209 return ArgInfo.QueuePtr.getRegister();
210}
211
213 ArgInfo.KernargSegmentPtr
214 = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
215 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
216 NumUserSGPRs += 2;
217 return ArgInfo.KernargSegmentPtr.getRegister();
218}
219
221 ArgInfo.DispatchID = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
222 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
223 NumUserSGPRs += 2;
224 return ArgInfo.DispatchID.getRegister();
225}
226
228 ArgInfo.FlatScratchInit = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
229 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
230 NumUserSGPRs += 2;
231 return ArgInfo.FlatScratchInit.getRegister();
232}
233
235 ArgInfo.PrivateSegmentSize = ArgDescriptor::createRegister(getNextUserSGPR());
236 NumUserSGPRs += 1;
237 return ArgInfo.PrivateSegmentSize.getRegister();
238}
239
241 ArgInfo.ImplicitBufferPtr = ArgDescriptor::createRegister(TRI.getMatchingSuperReg(
242 getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass));
243 NumUserSGPRs += 2;
244 return ArgInfo.ImplicitBufferPtr.getRegister();
245}
246
248 ArgInfo.LDSKernelId = ArgDescriptor::createRegister(getNextUserSGPR());
249 NumUserSGPRs += 1;
250 return ArgInfo.LDSKernelId.getRegister();
251}
252
254 const SIRegisterInfo &TRI, const TargetRegisterClass *RC,
255 unsigned AllocSizeDWord, int KernArgIdx, int PaddingSGPRs) {
256 assert(!ArgInfo.PreloadKernArgs.count(KernArgIdx) &&
257 "Preload kernel argument allocated twice.");
258 NumUserSGPRs += PaddingSGPRs;
259 // If the available register tuples are aligned with the kernarg to be
260 // preloaded use that register, otherwise we need to use a set of SGPRs and
261 // merge them.
262 Register PreloadReg =
263 TRI.getMatchingSuperReg(getNextUserSGPR(), AMDGPU::sub0, RC);
264 if (PreloadReg &&
265 (RC == &AMDGPU::SReg_32RegClass || RC == &AMDGPU::SReg_64RegClass)) {
266 ArgInfo.PreloadKernArgs[KernArgIdx].Regs.push_back(PreloadReg);
267 NumUserSGPRs += AllocSizeDWord;
268 } else {
269 for (unsigned I = 0; I < AllocSizeDWord; ++I) {
270 ArgInfo.PreloadKernArgs[KernArgIdx].Regs.push_back(getNextUserSGPR());
271 NumUserSGPRs++;
272 }
273 }
274
275 // Track the actual number of SGPRs that HW will preload to.
276 UserSGPRInfo.allocKernargPreloadSGPRs(AllocSizeDWord + PaddingSGPRs);
277 return &ArgInfo.PreloadKernArgs[KernArgIdx].Regs;
278}
279
281 uint64_t Size, Align Alignment) {
282 // Skip if it is an entry function or the register is already added.
283 if (isEntryFunction() || WWMSpills.count(VGPR))
284 return;
285
286 // Skip if this is a function with the amdgpu_cs_chain or
287 // amdgpu_cs_chain_preserve calling convention and this is a scratch register.
288 // We never need to allocate a spill for these because we don't even need to
289 // restore the inactive lanes for them (they're scratchier than the usual
290 // scratch registers).
292 return;
293
294 WWMSpills.insert(std::make_pair(
295 VGPR, MF.getFrameInfo().CreateSpillStackObject(Size, Alignment)));
296}
297
298// Separate out the callee-saved and scratch registers.
300 MachineFunction &MF,
301 SmallVectorImpl<std::pair<Register, int>> &CalleeSavedRegs,
302 SmallVectorImpl<std::pair<Register, int>> &ScratchRegs) const {
303 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
304 for (auto &Reg : WWMSpills) {
305 if (isCalleeSavedReg(CSRegs, Reg.first))
306 CalleeSavedRegs.push_back(Reg);
307 else
308 ScratchRegs.push_back(Reg);
309 }
310}
311
313 MCPhysReg Reg) const {
314 for (unsigned I = 0; CSRegs[I]; ++I) {
315 if (CSRegs[I] == Reg)
316 return true;
317 }
318
319 return false;
320}
321
323 MachineFunction &MF) {
324 const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
326 for (Register &Reg : SpillPhysVGPRs) {
327 Register NewReg =
328 TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass, MF);
329 if (!NewReg || NewReg >= Reg)
330 break;
331
332 MRI.replaceRegWith(Reg, NewReg);
333
334 // Update various tables with the new VGPR.
335 WWMReservedRegs.remove(Reg);
336 WWMReservedRegs.insert(NewReg);
337 WWMSpills.insert(std::make_pair(NewReg, WWMSpills[Reg]));
338 WWMSpills.erase(Reg);
339
340 for (MachineBasicBlock &MBB : MF) {
341 MBB.removeLiveIn(Reg);
343 }
344
345 Reg = NewReg;
346 }
347}
348
349bool SIMachineFunctionInfo::allocateVirtualVGPRForSGPRSpills(
350 MachineFunction &MF, int FI, unsigned LaneIndex) {
352 Register LaneVGPR;
353 if (!LaneIndex) {
354 LaneVGPR = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
355 SpillVGPRs.push_back(LaneVGPR);
356 } else {
357 LaneVGPR = SpillVGPRs.back();
358 }
359
360 SGPRSpillsToVirtualVGPRLanes[FI].emplace_back(LaneVGPR, LaneIndex);
361 return true;
362}
363
364bool SIMachineFunctionInfo::allocatePhysicalVGPRForSGPRSpills(
365 MachineFunction &MF, int FI, unsigned LaneIndex, bool IsPrologEpilog) {
367 const SIRegisterInfo *TRI = ST.getRegisterInfo();
369 Register LaneVGPR;
370 if (!LaneIndex) {
371 // Find the highest available register if called before RA to ensure the
372 // lowest registers are available for allocation. The LaneVGPR, in that
373 // case, will be shifted back to the lowest range after VGPR allocation.
374 LaneVGPR = TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass, MF,
375 !IsPrologEpilog);
376 if (LaneVGPR == AMDGPU::NoRegister) {
377 // We have no VGPRs left for spilling SGPRs. Reset because we will not
378 // partially spill the SGPR to VGPRs.
379 SGPRSpillsToPhysicalVGPRLanes.erase(FI);
380 return false;
381 }
382
383 allocateWWMSpill(MF, LaneVGPR);
384 reserveWWMRegister(LaneVGPR);
385 for (MachineBasicBlock &MBB : MF) {
386 MBB.addLiveIn(LaneVGPR);
388 }
389 SpillPhysVGPRs.push_back(LaneVGPR);
390 } else {
391 LaneVGPR = SpillPhysVGPRs.back();
392 }
393
394 SGPRSpillsToPhysicalVGPRLanes[FI].emplace_back(LaneVGPR, LaneIndex);
395 return true;
396}
397
399 MachineFunction &MF, int FI, bool SpillToPhysVGPRLane,
400 bool IsPrologEpilog) {
401 std::vector<SIRegisterInfo::SpilledReg> &SpillLanes =
402 SpillToPhysVGPRLane ? SGPRSpillsToPhysicalVGPRLanes[FI]
403 : SGPRSpillsToVirtualVGPRLanes[FI];
404
405 // This has already been allocated.
406 if (!SpillLanes.empty())
407 return true;
408
409 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
410 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
411 unsigned WaveSize = ST.getWavefrontSize();
412
413 unsigned Size = FrameInfo.getObjectSize(FI);
414 unsigned NumLanes = Size / 4;
415
416 if (NumLanes > WaveSize)
417 return false;
418
419 assert(Size >= 4 && "invalid sgpr spill size");
420 assert(ST.getRegisterInfo()->spillSGPRToVGPR() &&
421 "not spilling SGPRs to VGPRs");
422
423 unsigned &NumSpillLanes = SpillToPhysVGPRLane ? NumPhysicalVGPRSpillLanes
424 : NumVirtualVGPRSpillLanes;
425
426 for (unsigned I = 0; I < NumLanes; ++I, ++NumSpillLanes) {
427 unsigned LaneIndex = (NumSpillLanes % WaveSize);
428
429 bool Allocated = SpillToPhysVGPRLane
430 ? allocatePhysicalVGPRForSGPRSpills(MF, FI, LaneIndex,
431 IsPrologEpilog)
432 : allocateVirtualVGPRForSGPRSpills(MF, FI, LaneIndex);
433 if (!Allocated) {
434 NumSpillLanes -= I;
435 return false;
436 }
437 }
438
439 return true;
440}
441
442/// Reserve AGPRs or VGPRs to support spilling for FrameIndex \p FI.
443/// Either AGPR is spilled to VGPR to vice versa.
444/// Returns true if a \p FI can be eliminated completely.
446 int FI,
447 bool isAGPRtoVGPR) {
449 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
450 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
451
452 assert(ST.hasMAIInsts() && FrameInfo.isSpillSlotObjectIndex(FI));
453
454 auto &Spill = VGPRToAGPRSpills[FI];
455
456 // This has already been allocated.
457 if (!Spill.Lanes.empty())
458 return Spill.FullyAllocated;
459
460 unsigned Size = FrameInfo.getObjectSize(FI);
461 unsigned NumLanes = Size / 4;
462 Spill.Lanes.resize(NumLanes, AMDGPU::NoRegister);
463
464 const TargetRegisterClass &RC =
465 isAGPRtoVGPR ? AMDGPU::VGPR_32RegClass : AMDGPU::AGPR_32RegClass;
466 auto Regs = RC.getRegisters();
467
468 auto &SpillRegs = isAGPRtoVGPR ? SpillAGPR : SpillVGPR;
469 const SIRegisterInfo *TRI = ST.getRegisterInfo();
470 Spill.FullyAllocated = true;
471
472 // FIXME: Move allocation logic out of MachineFunctionInfo and initialize
473 // once.
474 BitVector OtherUsedRegs;
475 OtherUsedRegs.resize(TRI->getNumRegs());
476
477 const uint32_t *CSRMask =
478 TRI->getCallPreservedMask(MF, MF.getFunction().getCallingConv());
479 if (CSRMask)
480 OtherUsedRegs.setBitsInMask(CSRMask);
481
482 // TODO: Should include register tuples, but doesn't matter with current
483 // usage.
484 for (MCPhysReg Reg : SpillAGPR)
485 OtherUsedRegs.set(Reg);
486 for (MCPhysReg Reg : SpillVGPR)
487 OtherUsedRegs.set(Reg);
488
489 SmallVectorImpl<MCPhysReg>::const_iterator NextSpillReg = Regs.begin();
490 for (int I = NumLanes - 1; I >= 0; --I) {
491 NextSpillReg = std::find_if(
492 NextSpillReg, Regs.end(), [&MRI, &OtherUsedRegs](MCPhysReg Reg) {
493 return MRI.isAllocatable(Reg) && !MRI.isPhysRegUsed(Reg) &&
494 !OtherUsedRegs[Reg];
495 });
496
497 if (NextSpillReg == Regs.end()) { // Registers exhausted
498 Spill.FullyAllocated = false;
499 break;
500 }
501
502 OtherUsedRegs.set(*NextSpillReg);
503 SpillRegs.push_back(*NextSpillReg);
504 MRI.reserveReg(*NextSpillReg, TRI);
505 Spill.Lanes[I] = *NextSpillReg++;
506 }
507
508 return Spill.FullyAllocated;
509}
510
512 MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs) {
513 // Remove dead frame indices from function frame, however keep FP & BP since
514 // spills for them haven't been inserted yet. And also make sure to remove the
515 // frame indices from `SGPRSpillsToVirtualVGPRLanes` data structure,
516 // otherwise, it could result in an unexpected side effect and bug, in case of
517 // any re-mapping of freed frame indices by later pass(es) like "stack slot
518 // coloring".
519 for (auto &R : make_early_inc_range(SGPRSpillsToVirtualVGPRLanes)) {
520 MFI.RemoveStackObject(R.first);
521 SGPRSpillsToVirtualVGPRLanes.erase(R.first);
522 }
523
524 // Remove the dead frame indices of CSR SGPRs which are spilled to physical
525 // VGPR lanes during SILowerSGPRSpills pass.
526 if (!ResetSGPRSpillStackIDs) {
527 for (auto &R : make_early_inc_range(SGPRSpillsToPhysicalVGPRLanes)) {
528 MFI.RemoveStackObject(R.first);
529 SGPRSpillsToPhysicalVGPRLanes.erase(R.first);
530 }
531 }
532 bool HaveSGPRToMemory = false;
533
534 if (ResetSGPRSpillStackIDs) {
535 // All other SGPRs must be allocated on the default stack, so reset the
536 // stack ID.
537 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd(); I != E;
538 ++I) {
542 HaveSGPRToMemory = true;
543 }
544 }
545 }
546 }
547
548 for (auto &R : VGPRToAGPRSpills) {
549 if (R.second.IsDead)
550 MFI.RemoveStackObject(R.first);
551 }
552
553 return HaveSGPRToMemory;
554}
555
557 const SIRegisterInfo &TRI) {
558 if (ScavengeFI)
559 return *ScavengeFI;
560
561 ScavengeFI =
562 MFI.CreateStackObject(TRI.getSpillSize(AMDGPU::SGPR_32RegClass),
563 TRI.getSpillAlign(AMDGPU::SGPR_32RegClass), false);
564 return *ScavengeFI;
565}
566
567MCPhysReg SIMachineFunctionInfo::getNextUserSGPR() const {
568 assert(NumSystemSGPRs == 0 && "System SGPRs must be added after user SGPRs");
569 return AMDGPU::SGPR0 + NumUserSGPRs;
570}
571
572MCPhysReg SIMachineFunctionInfo::getNextSystemSGPR() const {
573 return AMDGPU::SGPR0 + NumUserSGPRs + NumSystemSGPRs;
574}
575
576void SIMachineFunctionInfo::MRI_NoteNewVirtualRegister(Register Reg) {
577 VRegFlags.grow(Reg);
578}
579
580void SIMachineFunctionInfo::MRI_NoteCloneVirtualRegister(Register NewReg,
581 Register SrcReg) {
582 VRegFlags.grow(NewReg);
583 VRegFlags[NewReg] = VRegFlags[SrcReg];
584}
585
588 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
589 if (!ST.isAmdPalOS())
590 return Register();
591 Register GitPtrLo = AMDGPU::SGPR0; // Low GIT address passed in
592 if (ST.hasMergedShaders()) {
593 switch (MF.getFunction().getCallingConv()) {
596 // Low GIT address is passed in s8 rather than s0 for an LS+HS or
597 // ES+GS merged shader on gfx9+.
598 GitPtrLo = AMDGPU::SGPR8;
599 return GitPtrLo;
600 default:
601 return GitPtrLo;
602 }
603 }
604 return GitPtrLo;
605}
606
608 const TargetRegisterInfo &TRI) {
610 {
612 OS << printReg(Reg, &TRI);
613 }
614 return Dest;
615}
616
617static std::optional<yaml::SIArgumentInfo>
619 const TargetRegisterInfo &TRI) {
621
622 auto convertArg = [&](std::optional<yaml::SIArgument> &A,
623 const ArgDescriptor &Arg) {
624 if (!Arg)
625 return false;
626
627 // Create a register or stack argument.
629 if (Arg.isRegister()) {
631 OS << printReg(Arg.getRegister(), &TRI);
632 } else
633 SA.StackOffset = Arg.getStackOffset();
634 // Check and update the optional mask.
635 if (Arg.isMasked())
636 SA.Mask = Arg.getMask();
637
638 A = SA;
639 return true;
640 };
641
642 // TODO: Need to serialize kernarg preloads.
643 bool Any = false;
644 Any |= convertArg(AI.PrivateSegmentBuffer, ArgInfo.PrivateSegmentBuffer);
645 Any |= convertArg(AI.DispatchPtr, ArgInfo.DispatchPtr);
646 Any |= convertArg(AI.QueuePtr, ArgInfo.QueuePtr);
647 Any |= convertArg(AI.KernargSegmentPtr, ArgInfo.KernargSegmentPtr);
648 Any |= convertArg(AI.DispatchID, ArgInfo.DispatchID);
649 Any |= convertArg(AI.FlatScratchInit, ArgInfo.FlatScratchInit);
650 Any |= convertArg(AI.LDSKernelId, ArgInfo.LDSKernelId);
651 Any |= convertArg(AI.PrivateSegmentSize, ArgInfo.PrivateSegmentSize);
652 Any |= convertArg(AI.WorkGroupIDX, ArgInfo.WorkGroupIDX);
653 Any |= convertArg(AI.WorkGroupIDY, ArgInfo.WorkGroupIDY);
654 Any |= convertArg(AI.WorkGroupIDZ, ArgInfo.WorkGroupIDZ);
655 Any |= convertArg(AI.WorkGroupInfo, ArgInfo.WorkGroupInfo);
656 Any |= convertArg(AI.PrivateSegmentWaveByteOffset,
657 ArgInfo.PrivateSegmentWaveByteOffset);
658 Any |= convertArg(AI.ImplicitArgPtr, ArgInfo.ImplicitArgPtr);
659 Any |= convertArg(AI.ImplicitBufferPtr, ArgInfo.ImplicitBufferPtr);
660 Any |= convertArg(AI.WorkItemIDX, ArgInfo.WorkItemIDX);
661 Any |= convertArg(AI.WorkItemIDY, ArgInfo.WorkItemIDY);
662 Any |= convertArg(AI.WorkItemIDZ, ArgInfo.WorkItemIDZ);
663
664 if (Any)
665 return AI;
666
667 return std::nullopt;
668}
669
672 const llvm::MachineFunction &MF)
673 : ExplicitKernArgSize(MFI.getExplicitKernArgSize()),
674 MaxKernArgAlign(MFI.getMaxKernArgAlign()), LDSSize(MFI.getLDSSize()),
675 GDSSize(MFI.getGDSSize()),
676 DynLDSAlign(MFI.getDynLDSAlign()), IsEntryFunction(MFI.isEntryFunction()),
677 NoSignedZerosFPMath(MFI.hasNoSignedZerosFPMath()),
678 MemoryBound(MFI.isMemoryBound()), WaveLimiter(MFI.needsWaveLimiter()),
679 HasSpilledSGPRs(MFI.hasSpilledSGPRs()),
680 HasSpilledVGPRs(MFI.hasSpilledVGPRs()),
681 HighBitsOf32BitAddress(MFI.get32BitAddressHighBits()),
682 Occupancy(MFI.getOccupancy()),
683 ScratchRSrcReg(regToString(MFI.getScratchRSrcReg(), TRI)),
684 FrameOffsetReg(regToString(MFI.getFrameOffsetReg(), TRI)),
685 StackPtrOffsetReg(regToString(MFI.getStackPtrOffsetReg(), TRI)),
686 BytesInStackArgArea(MFI.getBytesInStackArgArea()),
687 ReturnsVoid(MFI.returnsVoid()),
688 ArgInfo(convertArgumentInfo(MFI.getArgInfo(), TRI)),
689 PSInputAddr(MFI.getPSInputAddr()),
690 PSInputEnable(MFI.getPSInputEnable()),
691 Mode(MFI.getMode()) {
692 for (Register Reg : MFI.getWWMReservedRegs())
693 WWMReservedRegs.push_back(regToString(Reg, TRI));
694
695 if (MFI.getLongBranchReservedReg())
697 if (MFI.getVGPRForAGPRCopy())
699
700 if (MFI.getSGPRForEXECCopy())
702
703 auto SFI = MFI.getOptionalScavengeFI();
704 if (SFI)
706}
707
710}
711
713 const yaml::SIMachineFunctionInfo &YamlMFI, const MachineFunction &MF,
717 LDSSize = YamlMFI.LDSSize;
718 GDSSize = YamlMFI.GDSSize;
719 DynLDSAlign = YamlMFI.DynLDSAlign;
720 PSInputAddr = YamlMFI.PSInputAddr;
723 Occupancy = YamlMFI.Occupancy;
726 MemoryBound = YamlMFI.MemoryBound;
727 WaveLimiter = YamlMFI.WaveLimiter;
731 ReturnsVoid = YamlMFI.ReturnsVoid;
732
733 if (YamlMFI.ScavengeFI) {
734 auto FIOrErr = YamlMFI.ScavengeFI->getFI(MF.getFrameInfo());
735 if (!FIOrErr) {
736 // Create a diagnostic for a the frame index.
737 const MemoryBuffer &Buffer =
738 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
739
740 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1, 1,
741 SourceMgr::DK_Error, toString(FIOrErr.takeError()),
742 "", std::nullopt, std::nullopt);
743 SourceRange = YamlMFI.ScavengeFI->SourceRange;
744 return true;
745 }
746 ScavengeFI = *FIOrErr;
747 } else {
748 ScavengeFI = std::nullopt;
749 }
750 return false;
751}
752
754 return !F.hasFnAttribute("amdgpu-no-agpr");
755}
756
758 if (UsesAGPRs)
759 return *UsesAGPRs;
760
761 if (!mayNeedAGPRs()) {
762 UsesAGPRs = false;
763 return false;
764 }
765
767 MF.getFrameInfo().hasCalls()) {
768 UsesAGPRs = true;
769 return true;
770 }
771
772 const MachineRegisterInfo &MRI = MF.getRegInfo();
773
774 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
776 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
777 if (RC && SIRegisterInfo::isAGPRClass(RC)) {
778 UsesAGPRs = true;
779 return true;
780 }
781 if (!RC && !MRI.use_empty(Reg) && MRI.getType(Reg).isValid()) {
782 // Defer caching UsesAGPRs, function might not yet been regbank selected.
783 return true;
784 }
785 }
786
787 for (MCRegister Reg : AMDGPU::AGPR_32RegClass) {
788 if (MRI.isPhysRegUsed(Reg)) {
789 UsesAGPRs = true;
790 return true;
791 }
792 }
793
794 UsesAGPRs = false;
795 return false;
796}
unsigned const MachineRegisterInfo * MRI
Provides AMDGPU specific target descriptions.
Base class for AMDGPU specific classes of TargetSubtarget.
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
uint64_t Size
IO & YamlIO
Definition: ELFYAML.cpp:1308
AMD GCN specific subclass of TargetSubtarget.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
static std::optional< yaml::SIArgumentInfo > convertArgumentInfo(const AMDGPUFunctionArgInfo &ArgInfo, const TargetRegisterInfo &TRI)
static yaml::StringValue regToString(Register Reg, const TargetRegisterInfo &TRI)
Interface definition for SIRegisterInfo.
raw_pwrite_stream & OS
static const AMDGPUFunctionArgInfo FixedABIFunctionInfo
Definition: Any.h:28
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:341
BitVector & set()
Definition: BitVector.h:351
void setBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
setBitsInMask - Add '1' bits from Mask to this vector.
Definition: BitVector.h:707
void push_back(bool Val)
Definition: BitVector.h:466
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:281
const SITargetLowering * getTargetLowering() const override
Definition: GCNSubtarget.h:275
void allocKernargPreloadSGPRs(unsigned NumSGPRs)
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
void removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
bool hasCalls() const
Return true if the current function has any function calls.
int CreateSpillStackObject(uint64_t Size, Align Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
void setStackID(int ObjectIdx, uint8_t ID)
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
uint8_t getStackID(int ObjectIdx) const
int getObjectIndexBegin() const
Return the minimum frame object index.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * cloneInfo(const Ty &Old)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
size_type count(const KeyT &Key) const
Definition: MapVector.h:165
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition: MapVector.h:193
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:141
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:76
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
bool usesAGPRs(const MachineFunction &MF) const
bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI, const MachineFunction &MF, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange)
Register addPrivateSegmentSize(const SIRegisterInfo &TRI)
void allocateWWMSpill(MachineFunction &MF, Register VGPR, uint64_t Size=4, Align Alignment=Align(4))
Register addDispatchPtr(const SIRegisterInfo &TRI)
Register addFlatScratchInit(const SIRegisterInfo &TRI)
int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI)
Register addQueuePtr(const SIRegisterInfo &TRI)
SIMachineFunctionInfo(const SIMachineFunctionInfo &MFI)=default
Register getGITPtrLoReg(const MachineFunction &MF) const
bool allocateVGPRSpillToAGPR(MachineFunction &MF, int FI, bool isAGPRtoVGPR)
Reserve AGPRs or VGPRs to support spilling for FrameIndex FI.
void splitWWMSpillRegisters(MachineFunction &MF, SmallVectorImpl< std::pair< Register, int > > &CalleeSavedRegs, SmallVectorImpl< std::pair< Register, int > > &ScratchRegs) const
bool mayUseAGPRs(const Function &F) const
bool isCalleeSavedReg(const MCPhysReg *CSRegs, MCPhysReg Reg) const
void shiftSpillPhysVGPRsToLowestRange(MachineFunction &MF)
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
Register addKernargSegmentPtr(const SIRegisterInfo &TRI)
Register addDispatchID(const SIRegisterInfo &TRI)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
MachineFunctionInfo * clone(BumpPtrAllocator &Allocator, MachineFunction &DestMF, const DenseMap< MachineBasicBlock *, MachineBasicBlock * > &Src2DstMBB) const override
Make a functionally equivalent copy of this MachineFunctionInfo in MF.
bool checkIndexInPrologEpilogSGPRSpills(int FI) const
Register addPrivateSegmentBuffer(const SIRegisterInfo &TRI)
const ReservedRegSet & getWWMReservedRegs() const
std::optional< int > getOptionalScavengeFI() const
Register addImplicitBufferPtr(const SIRegisterInfo &TRI)
void limitOccupancy(const MachineFunction &MF)
SmallVectorImpl< MCRegister > * addPreloadedKernArg(const SIRegisterInfo &TRI, const TargetRegisterClass *RC, unsigned AllocSizeDWord, int KernArgIdx, int PaddingSGPRs)
static bool isChainScratchRegister(Register VGPR)
static bool isAGPRClass(const TargetRegisterClass *RC)
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:281
Represents a location in source code.
Definition: SMLoc.h:23
Represents a range in source code.
Definition: SMLoc.h:48
bool remove(const value_type &X)
Remove an item from the set vector.
Definition: SetVector.h:188
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:591
unsigned getMainFileID() const
Definition: SourceMgr.h:132
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool consumeInteger(unsigned Radix, T &Result)
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:484
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
const TargetMachine & getTargetMachine() const
ArrayRef< MCPhysReg > getRegisters() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
bool isEntryFunctionCC(CallingConv::ID CC)
bool isChainCC(CallingConv::ID CC)
unsigned getInitialPSInputAddr(const Function &F)
bool isGraphics(CallingConv::ID cc)
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AMDGPU_Gfx
Used for AMD graphics targets.
Definition: CallingConv.h:232
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ SPIR_KERNEL
Used for SPIR kernel functions.
Definition: CallingConv.h:144
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition: MCRegister.h:21
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
Helper struct shared between Function Specialization and SCCP Solver.
Definition: SCCPSolver.h:41
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
A serializaable representation of a reference to a stack object or fixed stack object.
std::optional< SIArgument > PrivateSegmentWaveByteOffset
std::optional< SIArgument > WorkGroupIDY
std::optional< SIArgument > FlatScratchInit
std::optional< SIArgument > DispatchPtr
std::optional< SIArgument > DispatchID
std::optional< SIArgument > WorkItemIDY
std::optional< SIArgument > WorkGroupIDX
std::optional< SIArgument > ImplicitArgPtr
std::optional< SIArgument > QueuePtr
std::optional< SIArgument > WorkGroupInfo
std::optional< SIArgument > LDSKernelId
std::optional< SIArgument > ImplicitBufferPtr
std::optional< SIArgument > WorkItemIDX
std::optional< SIArgument > KernargSegmentPtr
std::optional< SIArgument > WorkItemIDZ
std::optional< SIArgument > PrivateSegmentSize
std::optional< SIArgument > PrivateSegmentBuffer
std::optional< SIArgument > WorkGroupIDZ
std::optional< unsigned > Mask
static SIArgument createArgument(bool IsReg)
SmallVector< StringValue > WWMReservedRegs
void mappingImpl(yaml::IO &YamlIO) override
std::optional< FrameIndex > ScavengeFI
A wrapper around std::string which contains a source range that's being set during parsing.