LLVM 24.0.0git
SIFrameLowering.cpp
Go to the documentation of this file.
1//===----------------------- SIFrameLowering.cpp --------------------------===//
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#include "SIFrameLowering.h"
10#include "AMDGPULaneMaskUtils.h"
11#include "GCNSubtarget.h"
14#include "SISpillUtils.h"
20#include "llvm/Support/LEB128.h"
22
23using namespace llvm;
24
25#define DEBUG_TYPE "frame-info"
26
28 "amdgpu-spill-vgpr-to-agpr",
29 cl::desc("Enable spilling VGPRs to AGPRs"),
31 cl::init(true));
32
33static constexpr unsigned SGPRBitSize = 32;
34static constexpr unsigned SGPRByteSize = SGPRBitSize / 8;
35static constexpr unsigned VGPRLaneBitSize = 32;
36
37// The DWARF register numbers of vcc_lo and vcc_hi (VCC_32_LO and VCC_32_HI) are
38// only defined in wave32. In wave64 both halves are described as part of
39// VCC_64.
40static bool isWave64VCCHalf(const GCNSubtarget &ST, MCRegister Reg) {
41 return ST.isWave64() && (Reg == AMDGPU::VCC_LO || Reg == AMDGPU::VCC_HI);
42}
43
44// Find a register matching \p RC from \p LiveUnits which is unused and
45// available throughout the function. On failure, returns AMDGPU::NoRegister.
46// TODO: Rewrite the loop here to iterate over MCRegUnits instead of
47// MCRegisters. This should reduce the number of iterations and avoid redundant
48// checking.
50 const LiveRegUnits &LiveUnits,
51 const TargetRegisterClass &RC) {
52 for (MCRegister Reg : RC) {
53 if (!MRI.isPhysRegUsed(Reg) && LiveUnits.available(Reg) &&
54 !MRI.isReserved(Reg))
55 return Reg;
56 }
57 return MCRegister();
58}
59
60static void encodeDwarfRegisterLocation(int DwarfReg, raw_ostream &OS) {
61 assert(DwarfReg >= 0);
62 if (DwarfReg < 32) {
63 OS << uint8_t(dwarf::DW_OP_reg0 + DwarfReg);
64 } else {
65 OS << uint8_t(dwarf::DW_OP_regx);
66 encodeULEB128(DwarfReg, OS);
67 }
68}
69
71 int64_t DwarfStackPtrReg) {
72 assert(ST.hasFlatScratchEnabled());
73
74 // When flat scratch is enabled, the stack pointer is an address in the
75 // private_lane DWARF address space (i.e. swizzled), but in order to
76 // accurately and efficiently describe things like masked spills of vector
77 // registers we want to define the CFA to be an address in the private_wave
78 // DWARF address space (i.e. unswizzled). To achieve this we scale the stack
79 // pointer by the wavefront size, implemented as (SP << wave_size_log2).
80 const unsigned WavefrontSizeLog2 = ST.getWavefrontSizeLog2();
81 assert(WavefrontSizeLog2 < 32);
82
85 encodeDwarfRegisterLocation(DwarfStackPtrReg, OSBlock);
86 OSBlock << uint8_t(dwarf::DW_OP_deref_size) << uint8_t(SGPRByteSize)
87 << uint8_t(dwarf::DW_OP_lit0 + WavefrontSizeLog2)
88 << uint8_t(dwarf::DW_OP_shl)
89 << uint8_t(dwarf::DW_OP_lit0 +
90 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave)
91 << uint8_t(dwarf::DW_OP_LLVM_user)
92 << uint8_t(dwarf::DW_OP_LLVM_form_aspace_address);
93
94 SmallString<20> CFIInst;
95 raw_svector_ostream OSCFIInst(CFIInst);
96 OSCFIInst << uint8_t(dwarf::DW_CFA_def_cfa_expression);
97 encodeULEB128(Block.size(), OSCFIInst);
98 OSCFIInst << Block;
99
100 return MCCFIInstruction::createEscape(nullptr, OSCFIInst.str());
101}
102
103void SIFrameLowering::emitDefCFA(MachineBasicBlock &MBB,
105 DebugLoc const &DL, MCRegister StackPtrReg,
106 bool AspaceAlreadyDefined,
107 MachineInstr::MIFlag Flags) const {
109 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
110 const SIRegisterInfo *TRI = ST.getRegisterInfo();
111
112 int64_t DwarfStackPtrReg = TRI->getDwarfRegNum(StackPtrReg, false);
113 MCCFIInstruction CFIInst =
114 ST.hasFlatScratchEnabled()
115 ? createScaledCFAInPrivateWave(ST, DwarfStackPtrReg)
116 : (AspaceAlreadyDefined
117 ? MCCFIInstruction::createLLVMDefAspaceCfa(
118 nullptr, DwarfStackPtrReg, 0,
119 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave, SMLoc())
120 : MCCFIInstruction::createDefCfaRegister(nullptr,
121 DwarfStackPtrReg));
122 buildCFI(MBB, MBBI, DL, CFIInst, Flags);
123}
124
125// Find a scratch register that we can use in the prologue. We avoid using
126// callee-save registers since they may appear to be free when this is called
127// from canUseAsPrologue (during shrink wrapping), but then no longer be free
128// when this is called from emitPrologue.
131 const TargetRegisterClass &RC, bool Unused = false) {
132 // Mark callee saved registers as used so we will not choose them.
133 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
134 for (unsigned i = 0; CSRegs[i]; ++i)
135 LiveUnits.addReg(CSRegs[i]);
136
137 // We are looking for a register that can be used throughout the entire
138 // function, so any use is unacceptable.
139 if (Unused)
140 return findUnusedRegister(MRI, LiveUnits, RC);
141
142 for (MCRegister Reg : RC) {
143 if (LiveUnits.available(Reg) && !MRI.isReserved(Reg))
144 return Reg;
145 }
146
147 return MCRegister();
148}
149
150/// Query target location for spilling SGPRs
151/// \p IncludeScratchCopy : Also look for free scratch SGPRs
153 MachineFunction &MF, LiveRegUnits &LiveUnits, Register SGPR,
154 const TargetRegisterClass &RC = AMDGPU::SReg_32_XM0_XEXECRegClass,
155 bool IncludeScratchCopy = true) {
157 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
158
159 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
160 const SIRegisterInfo *TRI = ST.getRegisterInfo();
161 unsigned Size = TRI->getSpillSize(RC);
162 Align Alignment = TRI->getSpillAlign(RC);
163
164 // We need to save and restore the given SGPR.
165
166 Register ScratchSGPR;
167 // 1: Try to save the given register into an unused scratch SGPR. The
168 // LiveUnits should have all the callee saved registers marked as used. For
169 // certain cases we skip copy to scratch SGPR.
170 if (IncludeScratchCopy)
171 ScratchSGPR = findUnusedRegister(MF.getRegInfo(), LiveUnits, RC);
172
173 if (!ScratchSGPR) {
174 int FI = FrameInfo.CreateStackObject(Size, Alignment, true, nullptr,
176
177 if (TRI->spillSGPRToVGPR() &&
178 MFI->allocateSGPRSpillToVGPRLane(MF, FI, /*SpillToPhysVGPRLane=*/true,
179 /*IsPrologEpilog=*/true)) {
180 // 2: There's no free lane to spill, and no free register to save the
181 // SGPR, so we're forced to take another VGPR to use for the spill.
185
186 LLVM_DEBUG(auto Spill = MFI->getSGPRSpillToPhysicalVGPRLanes(FI).front();
187 dbgs() << printReg(SGPR, TRI) << " requires fallback spill to "
188 << printReg(Spill.VGPR, TRI) << ':' << Spill.Lane
189 << '\n';);
190 } else {
191 // Remove dead <FI> index
193 // 3: If all else fails, spill the register to memory.
194 FI = FrameInfo.CreateSpillStackObject(Size, Alignment);
196 SGPR,
198 LLVM_DEBUG(dbgs() << "Reserved FI " << FI << " for spilling "
199 << printReg(SGPR, TRI) << '\n');
200 }
201 } else {
205 LiveUnits.addReg(ScratchSGPR);
206 LLVM_DEBUG(dbgs() << "Saving " << printReg(SGPR, TRI) << " with copy to "
207 << printReg(ScratchSGPR, TRI) << '\n');
208 }
209}
210
211// We need to specially emit stack operations here because a different frame
212// register is used than in the rest of the function, as getFrameRegister would
213// use.
214static void buildPrologSpill(const GCNSubtarget &ST, const SIRegisterInfo &TRI,
215 const SIMachineFunctionInfo &FuncInfo,
216 LiveRegUnits &LiveUnits, MachineFunction &MF,
219 Register SpillReg, int FI, Register FrameReg,
220 int64_t DwordOff = 0) {
221 unsigned Opc = ST.hasFlatScratchEnabled() ? AMDGPU::SCRATCH_STORE_DWORD_SADDR
222 : AMDGPU::BUFFER_STORE_DWORD_OFFSET;
223
224 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
227 PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FI),
228 FrameInfo.getObjectAlign(FI));
229 LiveUnits.addReg(SpillReg);
230 bool IsKill = !MBB.isLiveIn(SpillReg);
231 TRI.buildSpillLoadStore(MBB, I, DL, Opc, FI, SpillReg, IsKill, FrameReg,
232 DwordOff, MMO, nullptr, &LiveUnits);
233 if (IsKill)
234 LiveUnits.removeReg(SpillReg);
235}
236
237static void buildEpilogRestore(const GCNSubtarget &ST,
238 const SIRegisterInfo &TRI,
239 const SIMachineFunctionInfo &FuncInfo,
240 LiveRegUnits &LiveUnits, MachineFunction &MF,
243 const DebugLoc &DL, Register SpillReg, int FI,
244 Register FrameReg, int64_t DwordOff = 0) {
245 unsigned Opc = ST.hasFlatScratchEnabled() ? AMDGPU::SCRATCH_LOAD_DWORD_SADDR
246 : AMDGPU::BUFFER_LOAD_DWORD_OFFSET;
247
248 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
251 PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FI),
252 FrameInfo.getObjectAlign(FI));
253 TRI.buildSpillLoadStore(MBB, I, DL, Opc, FI, SpillReg, false, FrameReg,
254 DwordOff, MMO, nullptr, &LiveUnits);
255}
256
258 const DebugLoc &DL, const SIInstrInfo *TII,
259 Register TargetReg) {
260 MachineFunction *MF = MBB.getParent();
262 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
263 const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
264 Register TargetLo = TRI->getSubReg(TargetReg, AMDGPU::sub0);
265 Register TargetHi = TRI->getSubReg(TargetReg, AMDGPU::sub1);
266
267 if (MFI->getGITPtrHigh() != 0xffffffff) {
268 BuildMI(MBB, I, DL, SMovB32, TargetHi)
269 .addImm(MFI->getGITPtrHigh())
270 .addReg(TargetReg, RegState::ImplicitDefine);
271 } else {
272 const MCInstrDesc &GetPC64 = TII->get(AMDGPU::S_GETPC_B64_pseudo);
273 BuildMI(MBB, I, DL, GetPC64, TargetReg);
274 }
275 Register GitPtrLo = MFI->getGITPtrLoReg(*MF);
276 MF->getRegInfo().addLiveIn(GitPtrLo);
277 MBB.addLiveIn(GitPtrLo);
278 BuildMI(MBB, I, DL, SMovB32, TargetLo)
279 .addReg(GitPtrLo);
280}
281
282static void initLiveUnits(LiveRegUnits &LiveUnits, const SIRegisterInfo &TRI,
283 const SIMachineFunctionInfo *FuncInfo,
285 MachineBasicBlock::iterator MBBI, bool IsProlog) {
286 if (LiveUnits.empty()) {
287 LiveUnits.init(TRI);
288 if (IsProlog) {
289 LiveUnits.addLiveIns(MBB);
290 } else {
291 // In epilog.
292 LiveUnits.addLiveOuts(MBB);
293 LiveUnits.stepBackward(*MBBI);
294 }
295 }
296}
297
298namespace llvm {
299
300// SpillBuilder to save/restore special SGPR spills like the one needed for FP,
301// BP, etc. These spills are delayed until the current function's frame is
302// finalized. For a given register, the builder uses the
303// PrologEpilogSGPRSaveRestoreInfo to decide the spill method.
307 MachineFunction &MF;
308 const GCNSubtarget &ST;
309 MachineFrameInfo &MFI;
310 SIMachineFunctionInfo *FuncInfo;
311 const SIInstrInfo *TII;
312 const SIRegisterInfo &TRI;
313 const MCRegisterInfo *MCRI;
314 const SIFrameLowering *TFI;
315 Register SuperReg;
317 LiveRegUnits &LiveUnits;
318 const DebugLoc &DL;
319 Register FrameReg;
320 ArrayRef<int16_t> SplitParts;
321 unsigned NumSubRegs;
322 unsigned EltSize = 4;
323 bool IsFramePtrPrologSpill;
324 bool NeedsFrameMoves;
325
326 static bool isExec(Register Reg) {
327 return Reg == AMDGPU::EXEC_LO || Reg == AMDGPU::EXEC;
328 }
329
330 /// If this builder requires SuperReg-based CFI, which is emitted after all
331 /// SubRegs are actually spilled, return the Register which should be used
332 /// as input to getDwarfRegNum. Otherwise, CFI should be generated per-SubReg.
333 ///
334 /// Note: Most spills handled by this builder generate CFI after each
335 /// SubReg spill, as each SubReg maps directly to a CFI register via
336 /// getDwarfRegNum(SubReg, false). All other cases currently currently
337 /// correspond to the SuperReg directly.
338 MCRegister getCFISuperReg() const {
339 if (IsFramePtrPrologSpill)
340 return FuncInfo->getFrameOffsetReg();
341 // FIXME: CFI for EXEC needs a fix by accurately computing the spill
342 // offset for both the low and high components.
343 if (isExec(SuperReg))
344 return AMDGPU::EXEC;
345 return {};
346 }
347
348 void saveToMemory(const int FI) const {
349 MachineRegisterInfo &MRI = MF.getRegInfo();
350 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
351 assert(!MFI.isDeadObjectIndex(FI));
352
353 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MI, /*IsProlog*/ true);
354
356 MRI, LiveUnits, AMDGPU::VGPR_32RegClass);
357 if (!TmpVGPR)
358 report_fatal_error("failed to find free scratch register");
359
360 auto BuildCFI = [&](Register Reg) {
361 TFI->buildCFI(MBB, MI, DL,
363 nullptr, MCRI->getDwarfRegNum(Reg, false),
364 MFI.getObjectOffset(FI) * ST.getWavefrontSize()));
365 };
366 MCRegister CFISuperReg = getCFISuperReg();
367 for (unsigned I = 0, DwordOff = 0; I < NumSubRegs; ++I) {
368 Register SubReg = NumSubRegs == 1
369 ? SuperReg
370 : Register(TRI.getSubReg(SuperReg, SplitParts[I]));
371 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), TmpVGPR)
372 .addReg(SubReg);
373
374 buildPrologSpill(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MI, DL, TmpVGPR,
375 FI, FrameReg, DwordOff);
376 if (NeedsFrameMoves && !CFISuperReg)
377 BuildCFI(SubReg);
378 DwordOff += 4;
379 }
380 if (NeedsFrameMoves && CFISuperReg)
381 BuildCFI(CFISuperReg);
382 }
383
384 void saveToVGPRLane(const int FI) const {
385 assert(!MFI.isDeadObjectIndex(FI));
386
387 assert(MFI.getStackID(FI) == TargetStackID::SGPRSpill);
389 FuncInfo->getSGPRSpillToPhysicalVGPRLanes(FI);
390 assert(Spill.size() == NumSubRegs);
391
392 MCRegister CFISuperReg = getCFISuperReg();
393 for (unsigned I = 0; I < NumSubRegs; ++I) {
394 Register SubReg = NumSubRegs == 1
395 ? SuperReg
396 : Register(TRI.getSubReg(SuperReg, SplitParts[I]));
397 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_SPILL_S32_TO_VGPR),
398 Spill[I].VGPR)
399 .addReg(SubReg)
400 .addImm(Spill[I].Lane)
401 .addReg(Spill[I].VGPR, RegState::Undef);
402 if (NeedsFrameMoves && !CFISuperReg)
403 TFI->buildCFIForSGPRToVGPRSpill(MBB, MI, DL, SubReg, Spill[I].VGPR,
404 Spill[I].Lane);
405 }
406 if (NeedsFrameMoves && CFISuperReg)
407 TFI->buildCFIForSGPRToVGPRSpill(MBB, MI, DL, CFISuperReg, Spill);
408 }
409
410 void copyToScratchSGPR(Register DstReg) const {
411 BuildMI(MBB, MI, DL, TII->get(AMDGPU::COPY), DstReg)
412 .addReg(SuperReg)
414 if (NeedsFrameMoves) {
415 MCRegister CFISuperReg = getCFISuperReg();
416 if (!CFISuperReg)
417 CFISuperReg = SuperReg;
418 if (isWave64VCCHalf(ST, DstReg)) {
419 assert(NumSubRegs == 1 && "Expected a 32-bit SGPR");
420 TFI->buildCFIForSGPRToVCCHalfCopy(MBB, MI, DL, CFISuperReg, DstReg);
421 } else {
422 TFI->buildCFIForSRegToSRegSpill(MBB, MI, DL, CFISuperReg, DstReg);
423 }
424 }
425 }
426
427 void restoreFromMemory(const int FI) {
428 MachineRegisterInfo &MRI = MF.getRegInfo();
429 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
430
431 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MI, /*IsProlog*/ false);
433 MRI, LiveUnits, AMDGPU::VGPR_32RegClass);
434 if (!TmpVGPR)
435 report_fatal_error("failed to find free scratch register");
436
437 for (unsigned I = 0, DwordOff = 0; I < NumSubRegs; ++I) {
438 MCRegister SubReg = NumSubRegs == 1
439 ? SuperReg.asMCReg()
440 : TRI.getSubReg(SuperReg, SplitParts[I]);
441
442 buildEpilogRestore(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MI, DL,
443 TmpVGPR, FI, FrameReg, DwordOff);
444 assert(SubReg.isPhysical());
445
446 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), SubReg)
447 .addReg(TmpVGPR, RegState::Kill);
448 DwordOff += 4;
449 }
450 }
451
452 void restoreFromVGPRLane(const int FI) {
453 assert(MFI.getStackID(FI) == TargetStackID::SGPRSpill);
455 FuncInfo->getSGPRSpillToPhysicalVGPRLanes(FI);
456 assert(Spill.size() == NumSubRegs);
457
458 for (unsigned I = 0; I < NumSubRegs; ++I) {
459 MCRegister SubReg = NumSubRegs == 1
460 ? SuperReg.asMCReg()
461 : TRI.getSubReg(SuperReg, SplitParts[I]);
462 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_RESTORE_S32_FROM_VGPR), SubReg)
463 .addReg(Spill[I].VGPR)
464 .addImm(Spill[I].Lane);
465 }
466 }
467
468 void copyFromScratchSGPR(Register SrcReg) const {
469 BuildMI(MBB, MI, DL, TII->get(AMDGPU::COPY), SuperReg)
470 .addReg(SrcReg)
472 }
473
474public:
479 const DebugLoc &DL, const SIInstrInfo *TII,
480 const SIRegisterInfo &TRI,
481 LiveRegUnits &LiveUnits, Register FrameReg,
482 bool IsFramePtrPrologSpill = false)
483 : MI(MI), MBB(MBB), MF(*MBB.getParent()),
484 ST(MF.getSubtarget<GCNSubtarget>()), MFI(MF.getFrameInfo()),
485 FuncInfo(MF.getInfo<SIMachineFunctionInfo>()), TII(TII), TRI(TRI),
486 MCRI(MF.getContext().getRegisterInfo()), TFI(ST.getFrameLowering()),
487 SuperReg(Reg), SI(SI), LiveUnits(LiveUnits), DL(DL), FrameReg(FrameReg),
488 IsFramePtrPrologSpill(IsFramePtrPrologSpill),
489 NeedsFrameMoves(MF.needsFrameMoves()) {
490 const TargetRegisterClass *RC = TRI.getPhysRegBaseClass(SuperReg);
491 SplitParts = TRI.getRegSplitParts(RC, EltSize);
492 NumSubRegs = SplitParts.empty() ? 1 : SplitParts.size();
493
494 assert(SuperReg != AMDGPU::M0 && "m0 should never spill");
495 }
496
497 void save() {
498 switch (SI.getKind()) {
500 return saveToMemory(SI.getIndex());
502 return saveToVGPRLane(SI.getIndex());
504 return copyToScratchSGPR(SI.getReg());
505 }
506 }
507
508 void restore() {
509 switch (SI.getKind()) {
511 return restoreFromMemory(SI.getIndex());
513 return restoreFromVGPRLane(SI.getIndex());
515 return copyFromScratchSGPR(SI.getReg());
516 }
517 }
518};
519
520} // namespace llvm
521
522// Emit flat scratch setup code, assuming `MFI->hasFlatScratchInit()`
523void SIFrameLowering::emitEntryFunctionFlatScratchInit(
525 const DebugLoc &DL, Register ScratchWaveOffsetReg) const {
526 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
527 const SIInstrInfo *TII = ST.getInstrInfo();
528 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
529 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
530
531 // We don't need this if we only have spills since there is no user facing
532 // scratch.
533
534 // TODO: If we know we don't have flat instructions earlier, we can omit
535 // this from the input registers.
536 //
537 // TODO: We only need to know if we access scratch space through a flat
538 // pointer. Because we only detect if flat instructions are used at all,
539 // this will be used more often than necessary on VI.
540
541 Register FlatScrInitLo;
542 Register FlatScrInitHi;
543
544 if (ST.isAmdPalOS()) {
545 // Extract the scratch offset from the descriptor in the GIT
546 LiveRegUnits LiveUnits;
547 LiveUnits.init(*TRI);
548 LiveUnits.addLiveIns(MBB);
549
550 // Find unused reg to load flat scratch init into
551 MachineRegisterInfo &MRI = MF.getRegInfo();
552 Register FlatScrInit = AMDGPU::NoRegister;
553 ArrayRef<MCPhysReg> AllSGPR64s = TRI->getAllSGPR64(MF);
554 unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 1) / 2;
555 AllSGPR64s = AllSGPR64s.slice(
556 std::min(static_cast<unsigned>(AllSGPR64s.size()), NumPreloaded));
557 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
558 for (MCPhysReg Reg : AllSGPR64s) {
559 if (LiveUnits.available(Reg) && !MRI.isReserved(Reg) &&
560 MRI.isAllocatable(Reg) && !TRI->isSubRegisterEq(Reg, GITPtrLoReg)) {
561 FlatScrInit = Reg;
562 break;
563 }
564 }
565 assert(FlatScrInit && "Failed to find free register for scratch init");
566
567 FlatScrInitLo = TRI->getSubReg(FlatScrInit, AMDGPU::sub0);
568 FlatScrInitHi = TRI->getSubReg(FlatScrInit, AMDGPU::sub1);
569
570 buildGitPtr(MBB, I, DL, TII, FlatScrInit);
571
572 // We now have the GIT ptr - now get the scratch descriptor from the entry
573 // at offset 0 (or offset 16 for a compute shader).
574 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
575 const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
576 auto *MMO = MF.getMachineMemOperand(
577 PtrInfo,
580 8, Align(4));
581 unsigned Offset =
583 const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
584 unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
585 BuildMI(MBB, I, DL, LoadDwordX2, FlatScrInit)
586 .addReg(FlatScrInit)
587 .addImm(EncodedOffset) // offset
588 .addImm(0) // cpol
589 .addMemOperand(MMO);
590
591 // Mask the offset in [47:0] of the descriptor
592 const MCInstrDesc &SAndB32 = TII->get(AMDGPU::S_AND_B32);
593 auto And = BuildMI(MBB, I, DL, SAndB32, FlatScrInitHi)
594 .addReg(FlatScrInitHi)
595 .addImm(0xffff);
596 And->getOperand(3).setIsDead(); // Mark SCC as dead.
597 } else {
598 Register FlatScratchInitReg =
600 assert(FlatScratchInitReg);
601
602 MachineRegisterInfo &MRI = MF.getRegInfo();
603 MRI.addLiveIn(FlatScratchInitReg);
604 MBB.addLiveIn(FlatScratchInitReg);
605
606 FlatScrInitLo = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub0);
607 FlatScrInitHi = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub1);
608 }
609
610 // Do a 64-bit pointer add.
611 if (ST.flatScratchIsPointer()) {
612 if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
613 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), FlatScrInitLo)
614 .addReg(FlatScrInitLo)
615 .addReg(ScratchWaveOffsetReg);
616 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32),
617 FlatScrInitHi)
618 .addReg(FlatScrInitHi)
619 .addImm(0);
620 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
621
622 using namespace AMDGPU::Hwreg;
623 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32))
624 .addReg(FlatScrInitLo)
625 .addImm(int16_t(HwregEncoding::encode(ID_FLAT_SCR_LO, 0, 32)));
626 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32))
627 .addReg(FlatScrInitHi)
628 .addImm(int16_t(HwregEncoding::encode(ID_FLAT_SCR_HI, 0, 32)));
629 return;
630 }
631
632 // For GFX9.
633 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), AMDGPU::FLAT_SCR_LO)
634 .addReg(FlatScrInitLo)
635 .addReg(ScratchWaveOffsetReg);
636 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32),
637 AMDGPU::FLAT_SCR_HI)
638 .addReg(FlatScrInitHi)
639 .addImm(0);
640 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
641
642 return;
643 }
644
645 assert(ST.getGeneration() < AMDGPUSubtarget::GFX9);
646
647 // Copy the size in bytes.
648 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::FLAT_SCR_LO)
649 .addReg(FlatScrInitHi, RegState::Kill);
650
651 // Add wave offset in bytes to private base offset.
652 // See comment in AMDKernelCodeT.h for enable_sgpr_flat_scratch_init.
653 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), FlatScrInitLo)
654 .addReg(FlatScrInitLo)
655 .addReg(ScratchWaveOffsetReg);
656
657 // Convert offset to 256-byte units.
658 auto LShr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_LSHR_B32),
659 AMDGPU::FLAT_SCR_HI)
660 .addReg(FlatScrInitLo, RegState::Kill)
661 .addImm(8);
662 LShr->getOperand(3).setIsDead(); // Mark SCC as dead.
663}
664
665// Note SGPRSpill stack IDs should only be used for SGPR spilling to VGPRs, not
666// memory. They should have been removed by now.
668 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
669 I != E; ++I) {
670 if (!MFI.isDeadObjectIndex(I))
671 return false;
672 }
673
674 return true;
675}
676
677// Shift down registers reserved for the scratch RSRC.
678Register SIFrameLowering::getEntryFunctionReservedScratchRsrcReg(
679 MachineFunction &MF) const {
680
681 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
682 const SIInstrInfo *TII = ST.getInstrInfo();
683 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
684 MachineRegisterInfo &MRI = MF.getRegInfo();
685 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
686
687 assert(MFI->isEntryFunction());
688
689 Register ScratchRsrcReg = MFI->getScratchRSrcReg();
690
691 if (!ScratchRsrcReg || (!MRI.isPhysRegUsed(ScratchRsrcReg) &&
693 return Register();
694
695 if (ST.hasSGPRInitBug() ||
696 ScratchRsrcReg != TRI->reservedPrivateSegmentBufferReg(MF))
697 return ScratchRsrcReg;
698
699 // We reserved the last registers for this. Shift it down to the end of those
700 // which were actually used.
701 //
702 // FIXME: It might be safer to use a pseudoregister before replacement.
703
704 // FIXME: We should be able to eliminate unused input registers. We only
705 // cannot do this for the resources required for scratch access. For now we
706 // skip over user SGPRs and may leave unused holes.
707
708 unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 3) / 4;
709 ArrayRef<MCPhysReg> AllSGPR128s = TRI->getAllSGPR128(MF);
710 AllSGPR128s = AllSGPR128s.slice(std::min(static_cast<unsigned>(AllSGPR128s.size()), NumPreloaded));
711
712 // Skip the last N reserved elements because they should have already been
713 // reserved for VCC etc.
714 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
715 for (MCPhysReg Reg : AllSGPR128s) {
716 // Pick the first unallocated one. Make sure we don't clobber the other
717 // reserved input we needed. Also for PAL, make sure we don't clobber
718 // the GIT pointer passed in SGPR0 or SGPR8.
720 (!GITPtrLoReg || !TRI->isSubRegisterEq(Reg, GITPtrLoReg))) {
721 MRI.replaceRegWith(ScratchRsrcReg, Reg);
724 return Reg;
725 }
726 }
727
728 return ScratchRsrcReg;
729}
730
731static unsigned getScratchScaleFactor(const GCNSubtarget &ST) {
732 return ST.hasFlatScratchEnabled() ? 1 : ST.getWavefrontSize();
733}
734
736 MachineBasicBlock &MBB) const {
737 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
738
739 // FIXME: If we only have SGPR spills, we won't actually be using scratch
740 // memory since these spill to VGPRs. We should be cleaning up these unused
741 // SGPR spill frame indices somewhere.
742
743 // FIXME: We still have implicit uses on SGPR spill instructions in case they
744 // need to spill to vector memory. It's likely that will not happen, but at
745 // this point it appears we need the setup. This part of the prolog should be
746 // emitted after frame indices are eliminated.
747
748 // FIXME: Remove all of the isPhysRegUsed checks
749
751 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
752 const SIInstrInfo *TII = ST.getInstrInfo();
753 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
755 const Function &F = MF.getFunction();
756 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
757
758 assert(MFI->isEntryFunction());
759
760 // Debug location must be unknown since the first debug location is used to
761 // determine the end of the prologue.
762 DebugLoc DL;
764
765 if (MF.needsFrameMoves()) {
766 // On entry the SP/FP are not set up, so we need to define the CFA in terms
767 // of a literal location expression.
768 static const char CFAEncodedInstUserOpsArr[] = {
769 dwarf::DW_CFA_def_cfa_expression,
770 4, // length
771 static_cast<char>(dwarf::DW_OP_lit0),
772 static_cast<char>(dwarf::DW_OP_lit0 +
773 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave),
774 static_cast<char>(dwarf::DW_OP_LLVM_user),
775 static_cast<char>(dwarf::DW_OP_LLVM_form_aspace_address)};
776 static StringRef CFAEncodedInstUserOps =
777 StringRef(CFAEncodedInstUserOpsArr, sizeof(CFAEncodedInstUserOpsArr));
778 buildCFI(MBB, I, DL,
779 MCCFIInstruction::createEscape(nullptr, CFAEncodedInstUserOps,
780 SMLoc(),
781 "CFA is 0 in private_wave aspace"));
782 // Unwinding halts when the return address (PC) is undefined.
783 buildCFI(MBB, I, DL,
785 nullptr, TRI->getDwarfRegNum(AMDGPU::PC_REG, false)));
786 }
787
788 Register PreloadedScratchWaveOffsetReg = MFI->getPreloadedReg(
790
791 // We need to do the replacement of the private segment buffer register even
792 // if there are no stack objects. There could be stores to undef or a
793 // constant without an associated object.
794 //
795 // This will return `Register()` in cases where there are no actual
796 // uses of the SRSRC.
797 Register ScratchRsrcReg;
798 if (!ST.hasFlatScratchEnabled())
799 ScratchRsrcReg = getEntryFunctionReservedScratchRsrcReg(MF);
800
801 // Make the selected register live throughout the function.
802 if (ScratchRsrcReg) {
803 for (MachineBasicBlock &OtherBB : MF) {
804 if (&OtherBB != &MBB) {
805 OtherBB.addLiveIn(ScratchRsrcReg);
806 }
807 }
808 }
809
810 // Now that we have fixed the reserved SRSRC we need to locate the
811 // (potentially) preloaded SRSRC.
812 Register PreloadedScratchRsrcReg;
813 if (ST.isAmdHsaOrMesa(F)) {
814 PreloadedScratchRsrcReg =
816 if (ScratchRsrcReg && PreloadedScratchRsrcReg) {
817 // We added live-ins during argument lowering, but since they were not
818 // used they were deleted. We're adding the uses now, so add them back.
819 MRI.addLiveIn(PreloadedScratchRsrcReg);
820 MBB.addLiveIn(PreloadedScratchRsrcReg);
821 }
822 }
823
824 // We found the SRSRC first because it needs four registers and has an
825 // alignment requirement. If the SRSRC that we found is clobbering with
826 // the scratch wave offset, which may be in a fixed SGPR or a free SGPR
827 // chosen by SITargetLowering::allocateSystemSGPRs, COPY the scratch
828 // wave offset to a free SGPR.
829 Register ScratchWaveOffsetReg;
830 if (PreloadedScratchWaveOffsetReg &&
831 TRI->isSubRegisterEq(ScratchRsrcReg, PreloadedScratchWaveOffsetReg)) {
832 ArrayRef<MCPhysReg> AllSGPRs = TRI->getAllSGPR32(MF);
833 unsigned NumPreloaded = MFI->getNumPreloadedSGPRs();
834 AllSGPRs = AllSGPRs.slice(
835 std::min(static_cast<unsigned>(AllSGPRs.size()), NumPreloaded));
836 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
837 for (MCPhysReg Reg : AllSGPRs) {
838 if (!MRI.isPhysRegUsed(Reg) && MRI.isAllocatable(Reg) &&
839 !TRI->isSubRegisterEq(ScratchRsrcReg, Reg) && GITPtrLoReg != Reg) {
840 ScratchWaveOffsetReg = Reg;
841 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchWaveOffsetReg)
842 .addReg(PreloadedScratchWaveOffsetReg, RegState::Kill);
843 break;
844 }
845 }
846
847 // FIXME: We can spill incoming arguments and restore at the end of the
848 // prolog.
849 if (!ScratchWaveOffsetReg)
851 "could not find temporary scratch offset register in prolog");
852 } else {
853 ScratchWaveOffsetReg = PreloadedScratchWaveOffsetReg;
854 }
855 assert(ScratchWaveOffsetReg || !PreloadedScratchWaveOffsetReg);
856
857 unsigned Offset = FrameInfo.getStackSize() * getScratchScaleFactor(ST);
858 if (!mayReserveScratchForCWSR(MF)) {
859 if (hasFP(MF)) {
861 assert(FPReg != AMDGPU::FP_REG);
862 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), FPReg).addImm(0);
863 }
864
867 assert(SPReg != AMDGPU::SP_REG);
868 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), SPReg).addImm(Offset);
869 }
870 } else {
871 // We need to check if we're on a compute queue - if we are, then the CWSR
872 // trap handler may need to store some VGPRs on the stack. The first VGPR
873 // block is saved separately, so we only need to allocate space for any
874 // additional VGPR blocks used. For now, we will make sure there's enough
875 // room for the theoretical maximum number of VGPRs that can be allocated.
876 // FIXME: Figure out if the shader uses fewer VGPRs in practice.
877 assert(hasFP(MF));
879 assert(FPReg != AMDGPU::FP_REG);
880 unsigned VGPRSize = llvm::alignTo(
881 (ST.getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize()) -
883 MFI->getDynamicVGPRBlockSize())) *
884 4,
885 FrameInfo.getMaxAlign());
887
888 BuildMI(MBB, I, DL, TII->get(AMDGPU::GET_STACK_BASE), FPReg);
891 assert(SPReg != AMDGPU::SP_REG);
892
893 // If at least one of the constants can be inlined, then we can use
894 // s_cselect. Otherwise, use a mov and cmovk.
895 if (AMDGPU::isInlinableLiteral32(Offset, ST.hasInv2PiInlineImm()) ||
897 ST.hasInv2PiInlineImm())) {
898 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CSELECT_B32), SPReg)
899 .addImm(Offset + VGPRSize)
900 .addImm(Offset);
901 } else {
902 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), SPReg).addImm(Offset);
903 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CMOVK_I32), SPReg)
904 .addImm(Offset + VGPRSize);
905 }
906 }
907 }
908
909 bool NeedsFlatScratchInit =
911 (MRI.isPhysRegUsed(AMDGPU::FLAT_SCR) || FrameInfo.hasCalls() ||
912 (!allStackObjectsAreDead(FrameInfo) && ST.hasFlatScratchEnabled()));
913
914 if ((NeedsFlatScratchInit || ScratchRsrcReg) &&
915 PreloadedScratchWaveOffsetReg && !ST.hasArchitectedFlatScratch()) {
916 MRI.addLiveIn(PreloadedScratchWaveOffsetReg);
917 MBB.addLiveIn(PreloadedScratchWaveOffsetReg);
918 }
919
920 if (NeedsFlatScratchInit) {
921 emitEntryFunctionFlatScratchInit(MF, MBB, I, DL, ScratchWaveOffsetReg);
922 }
923
924 if (ScratchRsrcReg) {
925 emitEntryFunctionScratchRsrcRegSetup(MF, MBB, I, DL,
926 PreloadedScratchRsrcReg,
927 ScratchRsrcReg, ScratchWaveOffsetReg);
928 }
929}
930
931// Emit scratch RSRC setup code, assuming `ScratchRsrcReg != AMDGPU::NoReg`
932void SIFrameLowering::emitEntryFunctionScratchRsrcRegSetup(
934 const DebugLoc &DL, Register PreloadedScratchRsrcReg,
935 Register ScratchRsrcReg, Register ScratchWaveOffsetReg) const {
936
937 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
938 const SIInstrInfo *TII = ST.getInstrInfo();
939 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
941 const Function &Fn = MF.getFunction();
942
943 if (ST.isAmdPalOS()) {
944 // The pointer to the GIT is formed from the offset passed in and either
945 // the amdgpu-git-ptr-high function attribute or the top part of the PC
946 Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
947 Register Rsrc03 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
948
949 buildGitPtr(MBB, I, DL, TII, Rsrc01);
950
951 // We now have the GIT ptr - now get the scratch descriptor from the entry
952 // at offset 0 (or offset 16 for a compute shader).
954 const MCInstrDesc &LoadDwordX4 = TII->get(AMDGPU::S_LOAD_DWORDX4_IMM);
955 auto *MMO = MF.getMachineMemOperand(
956 PtrInfo,
959 16, Align(4));
960 unsigned Offset = Fn.getCallingConv() == CallingConv::AMDGPU_CS ? 16 : 0;
962 unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
963 BuildMI(MBB, I, DL, LoadDwordX4, ScratchRsrcReg)
964 .addReg(Rsrc01)
965 .addImm(EncodedOffset) // offset
966 .addImm(0) // cpol
967 .addReg(ScratchRsrcReg, RegState::ImplicitDefine)
968 .addMemOperand(MMO);
969
970 // The driver will always set the SRD for wave 64 (bits 118:117 of
971 // descriptor / bits 22:21 of third sub-reg will be 0b11)
972 // If the shader is actually wave32 we have to modify the const_index_stride
973 // field of the descriptor 3rd sub-reg (bits 22:21) to 0b10 (stride=32). The
974 // reason the driver does this is that there can be cases where it presents
975 // 2 shaders with different wave size (e.g. VsFs).
976 // TODO: convert to using SCRATCH instructions or multiple SRD buffers
977 if (ST.isWave32()) {
978 const MCInstrDesc &SBitsetB32 = TII->get(AMDGPU::S_BITSET0_B32);
979 BuildMI(MBB, I, DL, SBitsetB32, Rsrc03)
980 .addImm(21)
981 .addReg(Rsrc03);
982 }
983 } else if (ST.isMesaGfxShader(Fn) || !PreloadedScratchRsrcReg) {
984 assert(!ST.isAmdHsaOrMesa(Fn));
985 const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
986
987 Register Rsrc2 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub2);
988 Register Rsrc3 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
989
990 // Use relocations to get the pointer, and setup the other bits manually.
991 uint64_t Rsrc23 = TII->getScratchRsrcWords23();
992
994 Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
995
997 const MCInstrDesc &Mov64 = TII->get(AMDGPU::S_MOV_B64);
998
999 BuildMI(MBB, I, DL, Mov64, Rsrc01)
1001 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1002 } else {
1003 const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
1004
1005 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1006 auto *MMO = MF.getMachineMemOperand(
1007 PtrInfo,
1010 8, Align(4));
1011 BuildMI(MBB, I, DL, LoadDwordX2, Rsrc01)
1013 .addImm(0) // offset
1014 .addImm(0) // cpol
1015 .addMemOperand(MMO)
1016 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1017 }
1018
1021 } else {
1022 Register Rsrc0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
1023 Register Rsrc1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
1024
1025 BuildMI(MBB, I, DL, SMovB32, Rsrc0)
1026 .addExternalSymbol("SCRATCH_RSRC_DWORD0")
1027 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1028
1029 BuildMI(MBB, I, DL, SMovB32, Rsrc1)
1030 .addExternalSymbol("SCRATCH_RSRC_DWORD1")
1031 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1032 }
1033
1034 BuildMI(MBB, I, DL, SMovB32, Rsrc2)
1035 .addImm(Lo_32(Rsrc23))
1036 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1037
1038 BuildMI(MBB, I, DL, SMovB32, Rsrc3)
1039 .addImm(Hi_32(Rsrc23))
1040 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1041 } else if (ST.isAmdHsaOrMesa(Fn)) {
1042 assert(PreloadedScratchRsrcReg);
1043
1044 if (ScratchRsrcReg != PreloadedScratchRsrcReg) {
1045 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchRsrcReg)
1046 .addReg(PreloadedScratchRsrcReg, RegState::Kill);
1047 }
1048 }
1049
1050 // Add the scratch wave offset into the scratch RSRC.
1051 //
1052 // We only want to update the first 48 bits, which is the base address
1053 // pointer, without touching the adjacent 16 bits of flags. We know this add
1054 // cannot carry-out from bit 47, otherwise the scratch allocation would be
1055 // impossible to fit in the 48-bit global address space.
1056 //
1057 // TODO: Evaluate if it is better to just construct an SRD using the flat
1058 // scratch init and some constants rather than update the one we are passed.
1059 Register ScratchRsrcSub0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
1060 Register ScratchRsrcSub1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
1061
1062 // We cannot Kill ScratchWaveOffsetReg here because we allow it to be used in
1063 // the kernel body via inreg arguments.
1064 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), ScratchRsrcSub0)
1065 .addReg(ScratchRsrcSub0)
1066 .addReg(ScratchWaveOffsetReg)
1067 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1068 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32), ScratchRsrcSub1)
1069 .addReg(ScratchRsrcSub1)
1070 .addImm(0)
1071 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1072 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
1073}
1074
1076 switch (ID) {
1080 return true;
1085 return false;
1086 }
1087 llvm_unreachable("Invalid TargetStackID::Value");
1088}
1089
1090void SIFrameLowering::emitPrologueEntryCFI(MachineBasicBlock &MBB,
1092 const DebugLoc &DL) const {
1093 const MachineFunction &MF = *MBB.getParent();
1094 const MachineRegisterInfo &MRI = MF.getRegInfo();
1095 const MCRegisterInfo *MCRI = MF.getContext().getRegisterInfo();
1096 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1097 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
1098 MCRegister StackPtrReg =
1099 MF.getInfo<SIMachineFunctionInfo>()->getStackPtrOffsetReg();
1100
1101 emitDefCFA(MBB, MBBI, DL, StackPtrReg, /*AspaceAlreadyDefined=*/true,
1103
1104 buildCFIForSRegToSRegSpill(MBB, MBBI, DL, AMDGPU::PC_REG,
1105 TRI.getReturnAddressReg(MF));
1106
1107 BitVector IsCalleeSaved(TRI.getNumRegs());
1108 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1109 for (unsigned I = 0; CSRegs[I]; ++I) {
1110 IsCalleeSaved.set(CSRegs[I]);
1111 }
1112 auto ProcessReg = [&](MCPhysReg Reg) {
1113 // VCC is not preserved across calls.
1114 if (Reg == AMDGPU::VCC || Reg == AMDGPU::VCC_LO || Reg == AMDGPU::VCC_HI)
1115 return;
1116 if (IsCalleeSaved.test(Reg) || !MRI.isPhysRegModified(Reg))
1117 return;
1118 unsigned DwarfReg = MCRI->getDwarfRegNum(Reg, false);
1119 buildCFI(MBB, MBBI, DL,
1120 MCCFIInstruction::createUndefined(nullptr, DwarfReg));
1121 };
1122
1123 // Emit CFI rules for caller saved Arch VGPRs which are clobbered
1124 unsigned NumArchVGPRs = ST.getAddressableNumArchVGPRs();
1125 for_each(AMDGPU::VGPR_32RegClass.getRegisters().take_front(NumArchVGPRs),
1126 ProcessReg);
1127
1128 // Emit CFI rules for caller saved Accum VGPRs which are clobbered
1129 if (ST.hasMAIInsts()) {
1130 for_each(AMDGPU::AGPR_32RegClass.getRegisters(), ProcessReg);
1131 }
1132
1133 // Emit CFI rules for caller saved SGPRs which are clobbered
1134 for_each(AMDGPU::SGPR_32RegClass.getRegisters(), ProcessReg);
1135}
1136
1137// Activate only the inactive lanes when \p EnableInactiveLanes is true.
1138// Otherwise, activate all lanes. It returns the saved exec.
1140 MachineFunction &MF,
1143 const DebugLoc &DL, bool IsProlog,
1144 bool EnableInactiveLanes) {
1145 Register ScratchExecCopy;
1147 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1148 const SIInstrInfo *TII = ST.getInstrInfo();
1149 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1151
1152 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, IsProlog);
1153
1154 if (FuncInfo->isWholeWaveFunction()) {
1155 // Whole wave functions already have a copy of the original EXEC mask that
1156 // we can use.
1157 assert(IsProlog && "Epilog should look at return, not setup");
1158 ScratchExecCopy =
1159 TII->getWholeWaveFunctionSetup(MF)->getOperand(0).getReg();
1160 assert(ScratchExecCopy && "Couldn't find copy of EXEC");
1161 } else {
1162 ScratchExecCopy = findScratchNonCalleeSaveRegister(
1163 MRI, LiveUnits, *TRI.getWaveMaskRegClass());
1164 }
1165
1166 if (!ScratchExecCopy)
1167 report_fatal_error("failed to find free scratch register");
1168
1169 LiveUnits.addReg(ScratchExecCopy);
1170
1171 const unsigned SaveExecOpc =
1172 ST.isWave32() ? (EnableInactiveLanes ? AMDGPU::S_XOR_SAVEEXEC_B32
1173 : AMDGPU::S_OR_SAVEEXEC_B32)
1174 : (EnableInactiveLanes ? AMDGPU::S_XOR_SAVEEXEC_B64
1175 : AMDGPU::S_OR_SAVEEXEC_B64);
1176 auto SaveExec =
1177 BuildMI(MBB, MBBI, DL, TII->get(SaveExecOpc), ScratchExecCopy).addImm(-1);
1178 SaveExec->getOperand(3).setIsDead(); // Mark SCC as dead.
1179
1180 return ScratchExecCopy;
1181}
1182
1186 LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy,
1187 const bool NeedsFrameMoves) const {
1189 MachineFrameInfo &MFI = MF.getFrameInfo();
1190 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1191 const SIInstrInfo *TII = ST.getInstrInfo();
1192 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1193 const MCRegisterInfo *MCRI = MF.getContext().getRegisterInfo();
1196
1197 // Spill Whole-Wave Mode VGPRs. Save only the inactive lanes of the scratch
1198 // registers. However, save all lanes of callee-saved VGPRs. Due to this, we
1199 // might end up flipping the EXEC bits twice.
1200 Register ScratchExecCopy;
1201 SmallVector<std::pair<Register, int>, 2> WWMCalleeSavedRegs, WWMScratchRegs;
1202 FuncInfo->splitWWMSpillRegisters(MF, WWMCalleeSavedRegs, WWMScratchRegs);
1203 if (!WWMScratchRegs.empty())
1204 ScratchExecCopy =
1205 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1206 /*IsProlog*/ true, /*EnableInactiveLanes*/ true);
1207
1208 auto StoreWWMRegisters =
1210 for (const auto &Reg : WWMRegs) {
1211 Register VGPR = Reg.first;
1212 int FI = Reg.second;
1213 buildPrologSpill(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MBBI, DL,
1214 VGPR, FI, FrameReg);
1215 if (NeedsFrameMoves) {
1216 // We spill the entire VGPR, so we can get away with just cfi_offset
1217 buildCFI(MBB, MBBI, DL,
1219 nullptr, MCRI->getDwarfRegNum(VGPR, false),
1220 MFI.getObjectOffset(FI) * ST.getWavefrontSize()));
1221 }
1222 }
1223 };
1224
1225 for (const Register Reg : make_first_range(WWMScratchRegs)) {
1226 if (!MRI.isReserved(Reg)) {
1227 MRI.addLiveIn(Reg);
1228 MBB.addLiveIn(Reg);
1229 }
1230 }
1231 StoreWWMRegisters(WWMScratchRegs);
1232
1233 auto EnableAllLanes = [&]() {
1234 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
1235 };
1236
1237 if (!WWMCalleeSavedRegs.empty()) {
1238 if (ScratchExecCopy) {
1239 EnableAllLanes();
1240 } else {
1241 ScratchExecCopy = buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1242 /*IsProlog*/ true,
1243 /*EnableInactiveLanes*/ false);
1244 }
1245 }
1246
1247 StoreWWMRegisters(WWMCalleeSavedRegs);
1248 if (FuncInfo->isWholeWaveFunction()) {
1249 // If we have already saved some WWM CSR registers, then the EXEC is already
1250 // -1 and we don't need to do anything else. Otherwise, save the original
1251 // EXEC into the setup register and set EXEC to -1 here.
1252 if (!ScratchExecCopy)
1253 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL, /*IsProlog*/ true,
1254 /*EnableInactiveLanes*/ false);
1255 else if (WWMCalleeSavedRegs.empty())
1256 EnableAllLanes();
1257 } else if (ScratchExecCopy) {
1258 // FIXME: Split block and make terminator.
1259 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
1260 .addReg(ScratchExecCopy, RegState::Kill);
1261 LiveUnits.addReg(ScratchExecCopy);
1262 }
1263
1264 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1265
1266 for (const auto &Spill : FuncInfo->getPrologEpilogSGPRSpills()) {
1267 // Special handle FP spill:
1268 // Skip if FP is saved to a scratch SGPR, the save has already been emitted.
1269 // Otherwise, FP has been moved to a temporary register and spill it
1270 // instead.
1271 bool IsFramePtrPrologSpill = Spill.first == FramePtrReg;
1272 Register Reg = IsFramePtrPrologSpill ? FramePtrRegScratchCopy : Spill.first;
1273 if (!Reg)
1274 continue;
1275
1276 PrologEpilogSGPRSpillBuilder SB(Reg, Spill.second, MBB, MBBI, DL, TII, TRI,
1277 LiveUnits, FrameReg, IsFramePtrPrologSpill);
1278 SB.save();
1279 }
1280
1281 // If a copy to scratch SGPR has been chosen for any of the SGPR spills, make
1282 // such scratch registers live throughout the function.
1283 SmallVector<Register, 1> ScratchSGPRs;
1284 FuncInfo->getAllScratchSGPRCopyDstRegs(ScratchSGPRs);
1285 if (!ScratchSGPRs.empty()) {
1286 for (MachineBasicBlock &MBB : MF) {
1287 for (MCPhysReg Reg : ScratchSGPRs)
1288 MBB.addLiveIn(Reg);
1289
1290 MBB.sortUniqueLiveIns();
1291 }
1292 if (!LiveUnits.empty()) {
1293 for (MCPhysReg Reg : ScratchSGPRs)
1294 LiveUnits.addReg(Reg);
1295 }
1296 }
1297
1298 // Remove the spill entry created for EXEC. It is needed only for CFISaves in
1299 // the prologue.
1300 if (TRI.isCFISavedRegsSpillEnabled())
1301 FuncInfo->removePrologEpilogSGPRSpillEntry(TRI.getExec());
1302}
1303
1307 LiveRegUnits &LiveUnits, Register FrameReg,
1308 Register FramePtrRegScratchCopy) const {
1309 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1310 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1311 const SIInstrInfo *TII = ST.getInstrInfo();
1312 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1314 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1315
1316 for (const auto &Spill : FuncInfo->getPrologEpilogSGPRSpills()) {
1317 // Special handle FP restore:
1318 // Skip if FP needs to be restored from the scratch SGPR. Otherwise, restore
1319 // the FP value to a temporary register. The frame pointer should be
1320 // overwritten only at the end when all other spills are restored from
1321 // current frame.
1322 Register Reg =
1323 Spill.first == FramePtrReg ? FramePtrRegScratchCopy : Spill.first;
1324 if (!Reg)
1325 continue;
1326
1327 PrologEpilogSGPRSpillBuilder SB(Reg, Spill.second, MBB, MBBI, DL, TII, TRI,
1328 LiveUnits, FrameReg);
1329 SB.restore();
1330 }
1331
1332 // Restore Whole-Wave Mode VGPRs. Restore only the inactive lanes of the
1333 // scratch registers. However, restore all lanes of callee-saved VGPRs. Due to
1334 // this, we might end up flipping the EXEC bits twice.
1335 Register ScratchExecCopy;
1336 SmallVector<std::pair<Register, int>, 2> WWMCalleeSavedRegs, WWMScratchRegs;
1337 FuncInfo->splitWWMSpillRegisters(MF, WWMCalleeSavedRegs, WWMScratchRegs);
1338 auto RestoreWWMRegisters =
1340 for (const auto &Reg : WWMRegs) {
1341 Register VGPR = Reg.first;
1342 int FI = Reg.second;
1343 buildEpilogRestore(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MBBI, DL,
1344 VGPR, FI, FrameReg);
1345 }
1346 };
1347
1348 if (FuncInfo->isWholeWaveFunction()) {
1349 // For whole wave functions, the EXEC is already -1 at this point.
1350 // Therefore, we can restore the CSR WWM registers right away.
1351 RestoreWWMRegisters(WWMCalleeSavedRegs);
1352
1353 // The original EXEC is the first operand of the return instruction.
1354 MachineInstr &Return = MBB.instr_back();
1355 unsigned Opcode = Return.getOpcode();
1356 switch (Opcode) {
1357 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN:
1358 Opcode = AMDGPU::SI_RETURN;
1359 break;
1360 case AMDGPU::SI_TCRETURN_GFX_WholeWave:
1361 Opcode = AMDGPU::SI_TCRETURN_GFX;
1362 break;
1363 default:
1364 llvm_unreachable("Unexpected return inst");
1365 }
1366 Register OrigExec = Return.getOperand(0).getReg();
1367
1368 if (!WWMScratchRegs.empty()) {
1369 BuildMI(MBB, MBBI, DL, TII->get(LMC.XorOpc), LMC.ExecReg)
1370 .addReg(OrigExec)
1371 .addImm(-1);
1372 RestoreWWMRegisters(WWMScratchRegs);
1373 }
1374
1375 // Restore original EXEC.
1376 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addReg(OrigExec);
1377
1378 // Drop the first operand and update the opcode.
1379 Return.removeOperand(0);
1380 Return.setDesc(TII->get(Opcode));
1381
1382 return;
1383 }
1384
1385 if (!WWMScratchRegs.empty()) {
1386 ScratchExecCopy =
1387 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1388 /*IsProlog=*/false, /*EnableInactiveLanes=*/true);
1389 }
1390 RestoreWWMRegisters(WWMScratchRegs);
1391 if (!WWMCalleeSavedRegs.empty()) {
1392 if (ScratchExecCopy) {
1393 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
1394 } else {
1395 ScratchExecCopy = buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1396 /*IsProlog*/ false,
1397 /*EnableInactiveLanes*/ false);
1398 }
1399 }
1400
1401 RestoreWWMRegisters(WWMCalleeSavedRegs);
1402 if (ScratchExecCopy) {
1403 // FIXME: Split block and make terminator.
1404 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
1405 .addReg(ScratchExecCopy, RegState::Kill);
1406 }
1407}
1408
1410 MachineBasicBlock &MBB) const {
1412 if (FuncInfo->isEntryFunction()) {
1414 return;
1415 }
1416
1417 MachineFrameInfo &MFI = MF.getFrameInfo();
1418 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1419 const SIInstrInfo *TII = ST.getInstrInfo();
1420 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1422
1423 Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
1424 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1425 Register BasePtrReg =
1426 TRI.hasBasePointer(MF) ? TRI.getBaseRegister() : Register();
1427 LiveRegUnits LiveUnits;
1428
1430 // DebugLoc must be unknown since the first instruction with DebugLoc is used
1431 // to determine the end of the prologue.
1432 DebugLoc DL;
1433
1434 bool HasFP = false;
1435 bool HasBP = false;
1436 int64_t NumBytes = MFI.getStackSize();
1437 int64_t RoundedSize = NumBytes;
1438
1439 // Functions that never return don't need to save and restore the FP or BP.
1440 const Function &F = MF.getFunction();
1441 bool SavesStackRegs =
1442 !F.hasFnAttribute(Attribute::NoReturn) && !FuncInfo->isChainFunction();
1443
1444 const bool NeedsFrameMoves = MF.needsFrameMoves();
1445
1446 if (NeedsFrameMoves)
1447 emitPrologueEntryCFI(MBB, MBBI, DL);
1448
1449 if (TRI.hasStackRealignment(MF))
1450 HasFP = true;
1451
1452 Register FramePtrRegScratchCopy;
1453 if (!HasFP && !hasFP(MF)) {
1454 // Emit the CSR spill stores with SP base register.
1455 emitCSRSpillStores(MF, MBB, MBBI, DL, LiveUnits, StackPtrReg,
1456 FramePtrRegScratchCopy, NeedsFrameMoves);
1457 } else if (SavesStackRegs) {
1458 // CSR spill stores will use FP as base register.
1459 Register SGPRForFPSaveRestoreCopy =
1460 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
1461
1462 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ true);
1463 if (SGPRForFPSaveRestoreCopy) {
1464 // Copy FP to the scratch register now and emit the CFI entry. It avoids
1465 // the extra FP copy needed in the other two cases when FP is spilled to
1466 // memory or to a VGPR lane.
1468 FramePtrReg,
1469 FuncInfo->getPrologEpilogSGPRSaveRestoreInfo(FramePtrReg), MBB, MBBI,
1470 DL, TII, TRI, LiveUnits, FramePtrReg,
1471 /*IsFramePtrPrologSpill*/ true);
1472 SB.save();
1473 LiveUnits.addReg(SGPRForFPSaveRestoreCopy);
1474 } else {
1475 // Copy FP into a new scratch register so that its previous value can be
1476 // spilled after setting up the new frame.
1477 FramePtrRegScratchCopy = findScratchNonCalleeSaveRegister(
1478 MRI, LiveUnits, AMDGPU::SReg_32_XM0_XEXECRegClass);
1479 if (!FramePtrRegScratchCopy)
1480 report_fatal_error("failed to find free scratch register");
1481
1482 LiveUnits.addReg(FramePtrRegScratchCopy);
1483 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrRegScratchCopy)
1484 .addReg(FramePtrReg);
1485 }
1486 }
1487
1488 if (HasFP) {
1489 const unsigned Alignment = MFI.getMaxAlign().value();
1490
1491 RoundedSize += Alignment;
1492 if (LiveUnits.empty()) {
1493 LiveUnits.init(TRI);
1494 LiveUnits.addLiveIns(MBB);
1495 }
1496
1497 // s_add_i32 s33, s32, NumBytes
1498 // s_and_b32 s33, s33, 0b111...0000
1499 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_I32), FramePtrReg)
1500 .addReg(StackPtrReg)
1501 .addImm((Alignment - 1) * getScratchScaleFactor(ST))
1503 auto And = BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_AND_B32), FramePtrReg)
1504 .addReg(FramePtrReg, RegState::Kill)
1505 .addImm(-Alignment * getScratchScaleFactor(ST))
1507 And->getOperand(3).setIsDead(); // Mark SCC as dead.
1508 FuncInfo->setIsStackRealigned(true);
1509 } else if ((HasFP = hasFP(MF))) {
1510 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
1511 .addReg(StackPtrReg)
1513 }
1514
1515 // If FP is used, emit the CSR spills with FP base register.
1516 if (HasFP) {
1517 emitCSRSpillStores(MF, MBB, MBBI, DL, LiveUnits, FramePtrReg,
1518 FramePtrRegScratchCopy, NeedsFrameMoves);
1519 if (FramePtrRegScratchCopy)
1520 LiveUnits.removeReg(FramePtrRegScratchCopy);
1521 }
1522
1523 // If we need a base pointer, set it up here. It's whatever the value of
1524 // the stack pointer is at this point. Any variable size objects will be
1525 // allocated after this, so we can still use the base pointer to reference
1526 // the incoming arguments.
1527 if ((HasBP = TRI.hasBasePointer(MF))) {
1528 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), BasePtrReg)
1529 .addReg(StackPtrReg)
1531 }
1532
1533 if (HasFP) {
1534 if (NeedsFrameMoves)
1535 emitDefCFA(MBB, MBBI, DL, FramePtrReg, /*AspaceAlreadyDefined=*/false,
1537 }
1538
1539 if (HasFP && RoundedSize != 0) {
1540 auto Add = BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_I32), StackPtrReg)
1541 .addReg(StackPtrReg)
1542 .addImm(RoundedSize * getScratchScaleFactor(ST))
1544 Add->getOperand(3).setIsDead(); // Mark SCC as dead.
1545 }
1546
1547 bool FPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(FramePtrReg);
1548 (void)FPSaved;
1549 assert((!HasFP || FPSaved || !SavesStackRegs) &&
1550 "Needed to save FP but didn't save it anywhere");
1551
1552 // If we allow spilling to AGPRs we may have saved FP but then spill
1553 // everything into AGPRs instead of the stack.
1554 assert((HasFP || !FPSaved || !SavesStackRegs || EnableSpillVGPRToAGPR) &&
1555 "Saved FP but didn't need it");
1556
1557 bool BPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(BasePtrReg);
1558 (void)BPSaved;
1559 assert((!HasBP || BPSaved || !SavesStackRegs) &&
1560 "Needed to save BP but didn't save it anywhere");
1561
1562 assert((HasBP || !BPSaved) && "Saved BP but didn't need it");
1563
1564 if (FuncInfo->isWholeWaveFunction()) {
1565 // SI_WHOLE_WAVE_FUNC_SETUP has outlived its purpose.
1566 TII->getWholeWaveFunctionSetup(MF)->eraseFromParent();
1567 }
1568}
1569
1571 MachineBasicBlock &MBB) const {
1572 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1573 if (FuncInfo->isEntryFunction())
1574 return;
1575
1576 const MachineFrameInfo &MFI = MF.getFrameInfo();
1577 if (FuncInfo->isChainFunction() && !MFI.hasTailCall())
1578 return;
1579
1580 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1581 const SIInstrInfo *TII = ST.getInstrInfo();
1582 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1584 LiveRegUnits LiveUnits;
1585 // Get the insert location for the epilogue. If there were no terminators in
1586 // the block, get the last instruction.
1588 DebugLoc DL;
1589 if (!MBB.empty()) {
1590 MBBI = MBB.getLastNonDebugInstr();
1591 if (MBBI != MBB.end())
1592 DL = MBBI->getDebugLoc();
1593
1594 MBBI = MBB.getFirstTerminator();
1595 }
1596
1597 uint32_t NumBytes = MFI.getStackSize();
1598 uint32_t RoundedSize = FuncInfo->isStackRealigned()
1599 ? NumBytes + MFI.getMaxAlign().value()
1600 : NumBytes;
1601 const Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
1602 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1603 bool FPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(FramePtrReg);
1604
1605 if (RoundedSize != 0) {
1606 if (TRI.hasBasePointer(MF)) {
1607 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), StackPtrReg)
1608 .addReg(TRI.getBaseRegister())
1610 } else if (hasFP(MF)) {
1611 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), StackPtrReg)
1612 .addReg(FramePtrReg)
1614 }
1615 }
1616
1617 Register FramePtrRegScratchCopy;
1618 Register SGPRForFPSaveRestoreCopy =
1619 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
1620 if (FPSaved) {
1621 // CSR spill restores should use FP as base register. If
1622 // SGPRForFPSaveRestoreCopy is not true, restore the previous value of FP
1623 // into a new scratch register and copy to FP later when other registers are
1624 // restored from the current stack frame.
1625 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ false);
1626 if (SGPRForFPSaveRestoreCopy) {
1627 LiveUnits.addReg(SGPRForFPSaveRestoreCopy);
1628 } else {
1629 FramePtrRegScratchCopy = findScratchNonCalleeSaveRegister(
1630 MRI, LiveUnits, AMDGPU::SReg_32_XM0_XEXECRegClass);
1631 if (!FramePtrRegScratchCopy)
1632 report_fatal_error("failed to find free scratch register");
1633
1634 LiveUnits.addReg(FramePtrRegScratchCopy);
1635 }
1636
1637 emitCSRSpillRestores(MF, MBB, MBBI, DL, LiveUnits, FramePtrReg,
1638 FramePtrRegScratchCopy);
1639 }
1640
1641 if (hasFP(MF) && MF.needsFrameMoves()) {
1642 emitDefCFA(MBB, MBBI, DL, StackPtrReg, /*AspaceAlreadyDefined=*/false,
1644 }
1645
1646 if (FPSaved) {
1647 // Insert the copy to restore FP.
1648 Register SrcReg = SGPRForFPSaveRestoreCopy ? SGPRForFPSaveRestoreCopy
1649 : FramePtrRegScratchCopy;
1651 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
1652 .addReg(SrcReg);
1653 if (SGPRForFPSaveRestoreCopy)
1655 } else {
1656 // Insert the CSR spill restores with SP as the base register.
1657 emitCSRSpillRestores(MF, MBB, MBBI, DL, LiveUnits, StackPtrReg,
1658 FramePtrRegScratchCopy);
1659 }
1660}
1661
1662#ifndef NDEBUG
1664 const MachineFrameInfo &MFI = MF.getFrameInfo();
1665 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1666 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
1667 I != E; ++I) {
1668 if (!MFI.isDeadObjectIndex(I) &&
1671 return false;
1672 }
1673 }
1674
1675 return true;
1676}
1677#endif
1678
1680 int FI,
1681 Register &FrameReg) const {
1682 const SIRegisterInfo *RI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1683
1684 FrameReg = RI->getFrameRegister(MF);
1686}
1687
1689 MachineFunction &MF,
1690 RegScavenger *RS) const {
1691 MachineFrameInfo &MFI = MF.getFrameInfo();
1692
1693 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1694 const SIInstrInfo *TII = ST.getInstrInfo();
1695 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1698
1699 const bool SpillVGPRToAGPR = ST.hasMAIInsts() && FuncInfo->hasSpilledVGPRs()
1701
1702 if (SpillVGPRToAGPR) {
1703 // To track the spill frame indices handled in this pass.
1704 BitVector SpillFIs(MFI.getObjectIndexEnd(), false);
1705 BitVector NonVGPRSpillFIs(MFI.getObjectIndexEnd(), false);
1706
1707 bool SeenDbgInstr = false;
1708
1709 for (MachineBasicBlock &MBB : MF) {
1711 int FrameIndex;
1712 if (MI.isDebugInstr())
1713 SeenDbgInstr = true;
1714
1715 if (TII->isVGPRSpill(MI)) {
1716 // Try to eliminate stack used by VGPR spills before frame
1717 // finalization.
1718 unsigned FIOp = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
1719 AMDGPU::OpName::vaddr);
1720 int FI = MI.getOperand(FIOp).getIndex();
1721 Register VReg =
1722 TII->getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
1723 if (FuncInfo->allocateVGPRSpillToAGPR(MF, FI,
1724 TRI->isAGPR(MRI, VReg))) {
1725 assert(RS != nullptr);
1726 RS->enterBasicBlockEnd(MBB);
1727 RS->backward(std::next(MI.getIterator()));
1728 TRI->eliminateFrameIndex(MI, 0, FIOp, RS);
1729 SpillFIs.set(FI);
1730 continue;
1731 }
1732 } else if (TII->isStoreToStackSlot(MI, FrameIndex) ||
1733 TII->isLoadFromStackSlot(MI, FrameIndex))
1734 if (!MFI.isFixedObjectIndex(FrameIndex))
1735 NonVGPRSpillFIs.set(FrameIndex);
1736 }
1737 }
1738
1739 // Stack slot coloring may assign different objects to the same stack slot.
1740 // If not, then the VGPR to AGPR spill slot is dead.
1741 for (unsigned FI : SpillFIs.set_bits())
1742 if (!NonVGPRSpillFIs.test(FI))
1743 FuncInfo->setVGPRToAGPRSpillDead(FI);
1744
1745 for (MachineBasicBlock &MBB : MF) {
1746 for (MCPhysReg Reg : FuncInfo->getVGPRSpillAGPRs())
1747 MBB.addLiveIn(Reg);
1748
1749 for (MCPhysReg Reg : FuncInfo->getAGPRSpillVGPRs())
1750 MBB.addLiveIn(Reg);
1751
1752 MBB.sortUniqueLiveIns();
1753
1754 if (!SpillFIs.empty() && SeenDbgInstr)
1755 clearDebugInfoForSpillFIs(MFI, MBB, SpillFIs);
1756 }
1757 }
1758
1759 // At this point we've already allocated all spilled SGPRs to VGPRs if we
1760 // can. Any remaining SGPR spills will go to memory, so move them back to the
1761 // default stack.
1762 bool HaveSGPRToVMemSpill =
1763 FuncInfo->removeDeadFrameIndices(MFI, /*ResetSGPRSpillStackIDs*/ true);
1765 "SGPR spill should have been removed in SILowerSGPRSpills");
1766
1767 // FIXME: The other checks should be redundant with allStackObjectsAreDead,
1768 // but currently hasNonSpillStackObjects is set only from source
1769 // allocas. Stack temps produced from legalization are not counted currently.
1770 if (!allStackObjectsAreDead(MFI)) {
1771 assert(RS && "RegScavenger required if spilling");
1772
1773 // Add an emergency spill slot
1774 RS->addScavengingFrameIndex(FuncInfo->getScavengeFI(MFI, *TRI));
1775
1776 if (HaveSGPRToVMemSpill && FuncInfo->hasNoWWMPoolSGPRSpillFallback()) {
1777 // The no-WWM-pool fallback can reach SGPR-to-memory lowering while an
1778 // ordinary frame-index scavenge is live. It may then need one slot for
1779 // its temporary VGPR and another for recursive address materialization.
1780 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1781 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1782 } else if (HaveSGPRToVMemSpill &&
1784 // Existing large-frame SGPR-to-memory spills need one additional VGPR
1785 // emergency frame index.
1786 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1787 }
1788 }
1789}
1790
1792 MachineFunction &MF, RegScavenger *RS) const {
1793 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1794 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1797
1798 if (ST.hasMAIInsts() && !ST.hasGFX90AInsts()) {
1799 // On gfx908, we had initially reserved highest available VGPR for AGPR
1800 // copy. Now since we are done with RA, check if there exist an unused VGPR
1801 // which is lower than the eariler reserved VGPR before RA. If one exist,
1802 // use it for AGPR copy instead of one reserved before RA.
1803 Register VGPRForAGPRCopy = FuncInfo->getVGPRForAGPRCopy();
1804 Register UnusedLowVGPR =
1805 TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass, MF);
1806 if (UnusedLowVGPR && (TRI->getHWRegIndex(UnusedLowVGPR) <
1807 TRI->getHWRegIndex(VGPRForAGPRCopy))) {
1808 // Reserve this newly identified VGPR (for AGPR copy)
1809 // reserved registers should already be frozen at this point
1810 // so we can avoid calling MRI.freezeReservedRegs and just use
1811 // MRI.reserveReg
1812 FuncInfo->setVGPRForAGPRCopy(UnusedLowVGPR);
1813 MRI.reserveReg(UnusedLowVGPR, TRI);
1814 }
1815 }
1816 // We initally reserved the highest available SGPR pair for long branches
1817 // now, after RA, we shift down to a lower unused one if one exists
1818 Register LongBranchReservedReg = FuncInfo->getLongBranchReservedReg();
1819 Register UnusedLowSGPR =
1820 TRI->findUnusedRegister(MRI, &AMDGPU::SGPR_64RegClass, MF);
1821 // If LongBranchReservedReg is null then we didn't find a long branch
1822 // and never reserved a register to begin with so there is nothing to
1823 // shift down. Then if UnusedLowSGPR is null, there isn't available lower
1824 // register to use so just keep the original one we set.
1825 if (LongBranchReservedReg && UnusedLowSGPR) {
1826 FuncInfo->setLongBranchReservedReg(UnusedLowSGPR);
1827 MRI.reserveReg(UnusedLowSGPR, TRI);
1828 }
1829}
1830
1831// The special SGPR spills like the one needed for FP, BP or any reserved
1832// registers delayed until frame lowering.
1834 MachineFunction &MF, BitVector &SavedVGPRs,
1835 bool NeedExecCopyReservedReg) const {
1836 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1839 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1840 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1841 LiveRegUnits LiveUnits;
1842 LiveUnits.init(*TRI);
1843 // Initially mark callee saved registers as used so we will not choose them
1844 // while looking for scratch SGPRs.
1845 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
1846 for (unsigned I = 0; CSRegs[I]; ++I)
1847 LiveUnits.addReg(CSRegs[I]);
1848
1849 const TargetRegisterClass &RC = *TRI->getWaveMaskRegClass();
1850
1851 Register ReservedRegForExecCopy = MFI->getSGPRForEXECCopy();
1852 if (NeedExecCopyReservedReg ||
1853 (ReservedRegForExecCopy &&
1854 MRI.isPhysRegUsed(ReservedRegForExecCopy, /*SkipRegMaskTest=*/true))) {
1855 MRI.reserveReg(ReservedRegForExecCopy, TRI);
1856 Register UnusedScratchReg = findUnusedRegister(MRI, LiveUnits, RC);
1857 if (UnusedScratchReg) {
1858 // If found any unused scratch SGPR, reserve the register itself for Exec
1859 // copy and there is no need for any spills in that case.
1860 MFI->setSGPRForEXECCopy(UnusedScratchReg);
1861 MRI.replaceRegWith(ReservedRegForExecCopy, UnusedScratchReg);
1862 LiveUnits.addReg(UnusedScratchReg);
1863 } else {
1864 // Needs spill.
1865 assert(!MFI->hasPrologEpilogSGPRSpillEntry(ReservedRegForExecCopy) &&
1866 "Re-reserving spill slot for EXEC copy register");
1867 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, ReservedRegForExecCopy, RC,
1868 /*IncludeScratchCopy=*/false);
1869 }
1870 } else if (ReservedRegForExecCopy) {
1871 // Reset it at this point. There are no whole-wave copies and spills
1872 // encountered.
1873 MFI->setSGPRForEXECCopy(AMDGPU::NoRegister);
1874 }
1875
1876 if (TRI->isCFISavedRegsSpillEnabled()) {
1877 Register Exec = TRI->getExec();
1879 "Re-reserving spill slot for EXEC");
1880 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, Exec, RC);
1881 }
1882
1883 // Functions that don't return to the caller don't need to preserve
1884 // the FP and BP.
1885 const Function &F = MF.getFunction();
1886 if (F.hasFnAttribute(Attribute::NoReturn) ||
1887 AMDGPU::isChainCC(F.getCallingConv()))
1888 return;
1889
1890 // hasFP only knows about stack objects that already exist. We're now
1891 // determining the stack slots that will be created, so we have to predict
1892 // them. Stack objects force FP usage with calls.
1893 //
1894 // Note a new VGPR CSR may be introduced if one is used for the spill, but we
1895 // don't want to report it here.
1896 //
1897 // FIXME: Is this really hasReservedCallFrame?
1898 const bool WillHaveFP =
1899 FrameInfo.hasCalls() &&
1900 (SavedVGPRs.any() || !allStackObjectsAreDead(FrameInfo));
1901
1902 if (WillHaveFP || hasFP(MF)) {
1903 Register FramePtrReg = MFI->getFrameOffsetReg();
1904 assert(!MFI->hasPrologEpilogSGPRSpillEntry(FramePtrReg) &&
1905 "Re-reserving spill slot for FP");
1906 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, FramePtrReg);
1907 }
1908
1909 if (TRI->hasBasePointer(MF)) {
1910 Register BasePtrReg = TRI->getBaseRegister();
1911 assert(!MFI->hasPrologEpilogSGPRSpillEntry(BasePtrReg) &&
1912 "Re-reserving spill slot for BP");
1913 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, BasePtrReg);
1914 }
1915}
1916
1917// Only report VGPRs to generic code.
1919 BitVector &SavedVGPRs,
1920 RegScavenger *RS) const {
1922
1923 // If this is a function with the amdgpu_cs_chain[_preserve] calling
1924 // convention and it doesn't contain any calls to llvm.amdgcn.cs.chain, then
1925 // we don't need to save and restore anything.
1926 if (MFI->isChainFunction() && !MF.getFrameInfo().hasTailCall())
1927 return;
1928
1930
1931 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1932 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1933 const SIInstrInfo *TII = ST.getInstrInfo();
1934 bool NeedExecCopyReservedReg = false;
1935
1936 MachineInstr *ReturnMI = nullptr;
1937 for (MachineBasicBlock &MBB : MF) {
1938 for (MachineInstr &MI : MBB) {
1939 // TODO: Walking through all MBBs here would be a bad heuristic. Better
1940 // handle them elsewhere.
1941 if (TII->isWWMRegSpillOpcode(MI.getOpcode()))
1942 NeedExecCopyReservedReg = true;
1943 else if (MI.getOpcode() == AMDGPU::SI_RETURN ||
1944 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
1945 MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1946 (MFI->isChainFunction() &&
1947 TII->isChainCallOpcode(MI.getOpcode()))) {
1948 // We expect all return to be the same size.
1949 assert(!ReturnMI ||
1950 (count_if(MI.operands(), [](auto Op) { return Op.isReg(); }) ==
1951 count_if(ReturnMI->operands(), [](auto Op) { return Op.isReg(); })));
1952 ReturnMI = &MI;
1953 }
1954 }
1955 }
1956
1957 SmallVector<Register> SortedWWMVGPRs;
1958 for (Register Reg : MFI->getWWMReservedRegs()) {
1959 // The shift-back is needed only for the VGPRs used for SGPR spills and they
1960 // are of 32-bit size. SIPreAllocateWWMRegs pass can add tuples into WWM
1961 // reserved registers.
1962 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Reg);
1963 if (TRI->getRegSizeInBits(*RC) != 32)
1964 continue;
1965 SortedWWMVGPRs.push_back(Reg);
1966 }
1967
1968 sort(SortedWWMVGPRs, std::greater<Register>());
1969 MFI->shiftWwmVGPRsToLowestRange(MF, SortedWWMVGPRs, SavedVGPRs);
1970
1971 if (MFI->isEntryFunction())
1972 return;
1973
1974 if (MFI->isWholeWaveFunction()) {
1975 // In practice, all the VGPRs are WWM registers, and we will need to save at
1976 // least their inactive lanes. Add them to WWMReservedRegs.
1977 assert(!NeedExecCopyReservedReg &&
1978 "Whole wave functions can use the reg mapped for their i1 argument");
1979
1980 unsigned NumArchVGPRs = ST.getAddressableNumArchVGPRs();
1981 for (MCRegister Reg :
1982 AMDGPU::VGPR_32RegClass.getRegisters().take_front(NumArchVGPRs))
1983 if (MF.getRegInfo().isPhysRegModified(Reg)) {
1984 MFI->reserveWWMRegister(Reg);
1985 MF.begin()->addLiveIn(Reg);
1986 }
1987 MF.begin()->sortUniqueLiveIns();
1988 }
1989
1990 // Remove any VGPRs used in the return value because these do not need to be saved.
1991 // This prevents CSR restore from clobbering return VGPRs.
1992 if (ReturnMI) {
1993 for (auto &Op : ReturnMI->operands()) {
1994 if (Op.isReg())
1995 SavedVGPRs.reset(Op.getReg());
1996 }
1997 }
1998
1999 // Create the stack objects for WWM registers now.
2000 for (Register Reg : MFI->getWWMReservedRegs()) {
2001 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Reg);
2002 MFI->allocateWWMSpill(MF, Reg, TRI->getSpillSize(*RC),
2003 TRI->getSpillAlign(*RC));
2004 }
2005
2006 // Ignore the SGPRs the default implementation found.
2007 SavedVGPRs.clearBitsNotInMask(TRI->getAllVectorRegMask());
2008
2009 // Do not save AGPRs prior to GFX90A because there was no easy way to do so.
2010 // In gfx908 there was do AGPR loads and stores and thus spilling also
2011 // require a temporary VGPR.
2012 if (!ST.hasGFX90AInsts())
2013 SavedVGPRs.clearBitsInMask(TRI->getAllAGPRRegMask());
2014
2015 determinePrologEpilogSGPRSaves(MF, SavedVGPRs, NeedExecCopyReservedReg);
2016
2017 // The Whole-Wave VGPRs need to be specially inserted in the prolog, so don't
2018 // allow the default insertion to handle them.
2019 for (auto &Reg : MFI->getWWMSpills())
2020 SavedVGPRs.reset(Reg.first);
2021}
2022
2024 BitVector &SavedRegs,
2025 RegScavenger *RS) const {
2028 if (MFI->isEntryFunction())
2029 return;
2030
2031 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2032 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2033
2034 // The SP is specifically managed and we don't want extra spills of it.
2035 SavedRegs.reset(MFI->getStackPtrOffsetReg());
2036
2037 const BitVector AllSavedRegs = SavedRegs;
2038 SavedRegs.clearBitsInMask(TRI->getAllVectorRegMask());
2039
2040 // We have to anticipate introducing CSR VGPR spills or spill of caller
2041 // save VGPR reserved for SGPR spills as we now always create stack entry
2042 // for it, if we don't have any stack objects already, since we require a FP
2043 // if there is a call and stack. We will allocate a VGPR for SGPR spills if
2044 // there are any SGPR spills. Whether they are CSR spills or otherwise.
2045 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
2046 const bool WillHaveFP =
2047 FrameInfo.hasCalls() && (AllSavedRegs.any() || MFI->hasSpilledSGPRs());
2048
2049 // FP will be specially managed like SP.
2050 if (WillHaveFP || hasFP(MF))
2051 SavedRegs.reset(MFI->getFrameOffsetReg());
2052
2053 // Return address use with return instruction is hidden through the SI_RETURN
2054 // pseudo. Given that and since the IPRA computes actual register usage and
2055 // does not use CSR list, the clobbering of return address by function calls
2056 // (D117243) or otherwise (D120922) is ignored/not seen by the IPRA's register
2057 // usage collection. This will ensure save/restore of return address happens
2058 // in those scenarios.
2059 const MachineRegisterInfo &MRI = MF.getRegInfo();
2060 Register RetAddrReg = TRI->getReturnAddressReg(MF);
2061 if (!MFI->isEntryFunction() &&
2062 (FrameInfo.hasCalls() || MRI.isPhysRegModified(RetAddrReg))) {
2063 SavedRegs.set(TRI->getSubReg(RetAddrReg, AMDGPU::sub0));
2064 SavedRegs.set(TRI->getSubReg(RetAddrReg, AMDGPU::sub1));
2065 }
2066}
2067
2069 const GCNSubtarget &ST,
2070 std::vector<CalleeSavedInfo> &CSI) {
2072 MachineFrameInfo &MFI = MF.getFrameInfo();
2073 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2074
2075 assert(
2076 llvm::is_sorted(CSI,
2077 [](const CalleeSavedInfo &A, const CalleeSavedInfo &B) {
2078 return A.getReg() < B.getReg();
2079 }) &&
2080 "Callee saved registers not sorted");
2081
2082 auto CanUseBlockOps = [&](const CalleeSavedInfo &CSI) {
2083 return !CSI.isSpilledToReg() &&
2084 TRI->getPhysRegBaseClass(CSI.getReg()) == &AMDGPU::VGPR_32RegClass &&
2085 !FuncInfo->isWWMReservedRegister(CSI.getReg());
2086 };
2087
2088 auto CSEnd = CSI.end();
2089 for (auto CSIt = CSI.begin(); CSIt != CSEnd; ++CSIt) {
2090 Register Reg = CSIt->getReg();
2091 if (!CanUseBlockOps(*CSIt))
2092 continue;
2093
2094 // Find all the regs that will fit in a 32-bit mask starting at the current
2095 // reg and build said mask. It should have 1 for every register that's
2096 // included, with the current register as the least significant bit.
2097 uint32_t Mask = 1;
2098 CSEnd = std::remove_if(
2099 CSIt + 1, CSEnd, [&](const CalleeSavedInfo &CSI) -> bool {
2100 if (CanUseBlockOps(CSI) && CSI.getReg() < Reg + 32) {
2101 Mask |= 1 << (CSI.getReg() - Reg);
2102 return true;
2103 } else {
2104 return false;
2105 }
2106 });
2107
2108 const TargetRegisterClass *BlockRegClass = TRI->getRegClassForBlockOp(MF);
2109 Register RegBlock =
2110 TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, BlockRegClass);
2111 if (!RegBlock) {
2112 // We couldn't find a super register for the block. This can happen if
2113 // the register we started with is too high (e.g. v232 if the maximum is
2114 // v255). We therefore try to get the last register block and figure out
2115 // the mask from there.
2116 Register LastBlockStart =
2117 AMDGPU::VGPR0 + alignDown(Reg - AMDGPU::VGPR0, 32);
2118 RegBlock =
2119 TRI->getMatchingSuperReg(LastBlockStart, AMDGPU::sub0, BlockRegClass);
2120 assert(RegBlock && TRI->isSubRegister(RegBlock, Reg) &&
2121 "Couldn't find super register");
2122 int RegDelta = Reg - LastBlockStart;
2123 assert(RegDelta > 0 && llvm::countl_zero(Mask) >= RegDelta &&
2124 "Bad shift amount");
2125 Mask <<= RegDelta;
2126 }
2127
2128 FuncInfo->setMaskForVGPRBlockOps(RegBlock, Mask);
2129
2130 // The stack objects can be a bit smaller than the register block if we know
2131 // some of the high bits of Mask are 0. This may happen often with calling
2132 // conventions where the caller and callee-saved VGPRs are interleaved at
2133 // a small boundary (e.g. 8 or 16).
2134 int UnusedBits = llvm::countl_zero(Mask);
2135 unsigned BlockSize = TRI->getSpillSize(*BlockRegClass) - UnusedBits * 4;
2136 int FrameIdx =
2137 MFI.CreateStackObject(BlockSize, TRI->getSpillAlign(*BlockRegClass),
2138 /*isSpillSlot=*/true);
2139 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2140
2141 CSIt->setFrameIdx(FrameIdx);
2142 CSIt->setReg(RegBlock);
2143 }
2144 CSI.erase(CSEnd, CSI.end());
2145}
2146
2149 std::vector<CalleeSavedInfo> &CSI) const {
2150 if (CSI.empty())
2151 return true; // Early exit if no callee saved registers are modified!
2152
2153 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2154 bool UseVGPRBlocks = ST.useVGPRBlockOpsForCSR();
2155
2156 if (UseVGPRBlocks)
2157 assignSlotsUsingVGPRBlocks(MF, ST, CSI);
2158
2159 return assignCalleeSavedSpillSlotsImpl(MF, TRI, CSI) || UseVGPRBlocks;
2160}
2161
2164 std::vector<CalleeSavedInfo> &CSI) const {
2165 if (CSI.empty())
2166 return true; // Early exit if no callee saved registers are modified!
2167
2168 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2169 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2170 const SIRegisterInfo *RI = ST.getRegisterInfo();
2171 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
2172 Register BasePtrReg = RI->getBaseRegister();
2173 Register SGPRForFPSaveRestoreCopy =
2174 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
2175 Register SGPRForBPSaveRestoreCopy =
2176 FuncInfo->getScratchSGPRCopyDstReg(BasePtrReg);
2177 if (!SGPRForFPSaveRestoreCopy && !SGPRForBPSaveRestoreCopy)
2178 return false;
2179
2180 unsigned NumModifiedRegs = 0;
2181
2182 if (SGPRForFPSaveRestoreCopy)
2183 NumModifiedRegs++;
2184 if (SGPRForBPSaveRestoreCopy)
2185 NumModifiedRegs++;
2186
2187 for (auto &CS : CSI) {
2188 if (CS.getReg() == FramePtrReg.asMCReg() && SGPRForFPSaveRestoreCopy) {
2189 CS.setDstReg(SGPRForFPSaveRestoreCopy);
2190 if (--NumModifiedRegs)
2191 break;
2192 } else if (CS.getReg() == BasePtrReg.asMCReg() &&
2193 SGPRForBPSaveRestoreCopy) {
2194 CS.setDstReg(SGPRForBPSaveRestoreCopy);
2195 if (--NumModifiedRegs)
2196 break;
2197 }
2198 }
2199
2200 return false;
2201}
2202
2204 const MachineFunction &MF) const {
2205
2206 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2207 const MachineFrameInfo &MFI = MF.getFrameInfo();
2208 const SIInstrInfo *TII = ST.getInstrInfo();
2209 uint64_t EstStackSize = MFI.estimateStackSize(MF);
2210 uint64_t MaxOffset = EstStackSize - 1;
2211
2212 // We need the emergency stack slots to be allocated in range of the
2213 // MUBUF/flat scratch immediate offset from the base register, so assign these
2214 // first at the incoming SP position.
2215 //
2216 // TODO: We could try sorting the objects to find a hole in the first bytes
2217 // rather than allocating as close to possible. This could save a lot of space
2218 // on frames with alignment requirements.
2219 if (ST.hasFlatScratchEnabled()) {
2220 if (TII->isLegalFLATOffset(MaxOffset, AMDGPUAS::PRIVATE_ADDRESS,
2222 return false;
2223 } else {
2224 if (TII->isLegalMUBUFImmOffset(MaxOffset))
2225 return false;
2226 }
2227
2228 return true;
2229}
2230
2231/// Return the set of all root registers of regunits live-in to @p MBB.
2232///
2233/// Intended to avoid using the expensive @c MCRegAliasIterator when deciding
2234/// if a register to be spilled is already live-in (see @c isAnyRootLiveIn).
2236 const SIRegisterInfo &TRI) {
2237 SparseBitVector<> LiveInRoots;
2238 for (const auto &LI : MBB.liveins()) {
2239 for (MCRegUnitMaskIterator MI(LI.PhysReg, &TRI); MI.isValid(); ++MI) {
2240 auto [Unit, UnitLaneMask] = *MI;
2241 if ((LI.LaneMask & UnitLaneMask).none())
2242 continue;
2243 for (MCRegUnitRootIterator RI(Unit, &TRI); RI.isValid(); ++RI)
2244 LiveInRoots.set(*RI);
2245 }
2246 }
2247 return LiveInRoots;
2248}
2249
2250/// Returns true iff any root of @p Reg is in @p LiveInRoots
2251/// (see @c buildLiveInRoots).
2252static bool isAnyRootLiveIn(const SparseBitVector<> &LiveInRoots,
2253 const SIRegisterInfo &TRI, MCRegister Reg) {
2254 for (MCRegUnitIterator UI(Reg, &TRI); UI.isValid(); ++UI) {
2255 for (MCRegUnitRootIterator RI(*UI, &TRI); RI.isValid(); ++RI) {
2256 if (LiveInRoots.test(*RI))
2257 return true;
2258 }
2259 }
2260 return false;
2261}
2262
2263void SIFrameLowering::spillCalleeSavedRegisterWithoutBlockOps(
2265 const CalleeSavedInfo &CS, const SIInstrInfo *TII,
2266 const SIRegisterInfo &TRI,
2267 const std::optional<SparseBitVector<>> &LiveInRoots) const {
2268 MCRegister Reg = CS.getReg();
2269
2270 // We assume a sortUniqueLiveIns later
2271 MBB.addLiveIn(Reg);
2272
2273 if (CS.isSpilledToReg()) {
2274 BuildMI(MBB, MI, DebugLoc(), TII->get(TargetOpcode::COPY), CS.getDstReg())
2275 .addReg(Reg, getKillRegState(true));
2276 } else {
2277 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
2278 bool IsKill = true;
2279 // If this value was already livein, we probably have a direct use of
2280 // the incoming register value, so don't kill at the spill point. This
2281 // happens since we pass some special inputs (workgroup IDs) in the
2282 // callee saved range.
2283 if (LiveInRoots)
2284 IsKill = !isAnyRootLiveIn(*LiveInRoots, TRI, Reg);
2285 TII->storeRegToStackSlotCFI(MBB, MI, Reg, IsKill, CS.getFrameIdx(), RC);
2286 }
2287}
2288
2291 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *OrigTRI) const {
2292 auto &TRI = *static_cast<const SIRegisterInfo *>(OrigTRI);
2293 MachineFunction *MF = MBB.getParent();
2294 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2295 const SIInstrInfo *TII = ST.getInstrInfo();
2296
2297 std::optional<SparseBitVector<>> LiveInRoots;
2298 if (MBB.getParent()->getRegInfo().tracksLiveness())
2299 LiveInRoots = buildLiveInRoots(MBB, TRI);
2300
2301 if (!ST.useVGPRBlockOpsForCSR()) {
2302 for (const CalleeSavedInfo &CS : CSI)
2303 spillCalleeSavedRegisterWithoutBlockOps(MBB, MI, CS, TII, TRI,
2304 LiveInRoots);
2305 if (LiveInRoots)
2306 MBB.sortUniqueLiveIns();
2307 return true;
2308 }
2309
2310 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
2312
2313 const TargetRegisterClass *BlockRegClass = TRI.getRegClassForBlockOp(*MF);
2314 for (const CalleeSavedInfo &CS : CSI) {
2315 Register Reg = CS.getReg();
2316 if (!BlockRegClass->contains(Reg) ||
2317 !FuncInfo->hasMaskForVGPRBlockOps(Reg)) {
2318 spillCalleeSavedRegisterWithoutBlockOps(MBB, MI, CS, TII, TRI,
2319 LiveInRoots);
2320 continue;
2321 }
2322
2323 // Build a scratch block store.
2324 uint32_t Mask = FuncInfo->getMaskForVGPRBlockOps(Reg);
2325 int FrameIndex = CS.getFrameIdx();
2326 MachinePointerInfo PtrInfo =
2327 MachinePointerInfo::getFixedStack(*MF, FrameIndex);
2328 MachineMemOperand *MMO =
2330 FrameInfo.getObjectSize(FrameIndex),
2331 FrameInfo.getObjectAlign(FrameIndex));
2332
2333 BuildMI(MBB, MI, MI->getDebugLoc(),
2334 TII->get(AMDGPU::SI_BLOCK_SPILL_V1024_CFI_SAVE))
2335 .addReg(Reg, getKillRegState(false))
2336 .addFrameIndex(FrameIndex)
2337 .addReg(FuncInfo->getStackPtrOffsetReg())
2338 .addImm(0)
2339 .addImm(Mask)
2340 .addMemOperand(MMO);
2341
2342 FuncInfo->setHasSpilledVGPRs();
2343
2344 // Add the register to the liveins. This is necessary because if any of the
2345 // VGPRs in the register block is reserved (e.g. if it's a WWM register),
2346 // then the whole block will be marked as reserved and `updateLiveness` will
2347 // skip it.
2348 if (LiveInRoots)
2349 MBB.addLiveIn(Reg);
2350 }
2351 if (LiveInRoots)
2352 MBB.sortUniqueLiveIns();
2353
2354 return true;
2355}
2356
2360 const TargetRegisterInfo *OrigTRI) const {
2361 auto &TRI = *static_cast<const SIRegisterInfo *>(OrigTRI);
2362 MachineFunction *MF = MBB.getParent();
2363 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2364 if (!ST.useVGPRBlockOpsForCSR())
2365 return false;
2366
2368 MachineFrameInfo &MFI = MF->getFrameInfo();
2369 const SIInstrInfo *TII = ST.getInstrInfo();
2370 const TargetRegisterClass *BlockRegClass = TRI.getRegClassForBlockOp(*MF);
2371 for (const CalleeSavedInfo &CS : reverse(CSI)) {
2372 Register Reg = CS.getReg();
2373 if (!BlockRegClass->contains(Reg) ||
2374 !FuncInfo->hasMaskForVGPRBlockOps(Reg)) {
2376 continue;
2377 }
2378
2379 // Build a scratch block load.
2380 uint32_t Mask = FuncInfo->getMaskForVGPRBlockOps(Reg);
2381 int FrameIndex = CS.getFrameIdx();
2382 MachinePointerInfo PtrInfo =
2383 MachinePointerInfo::getFixedStack(*MF, FrameIndex);
2385 PtrInfo, MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIndex),
2386 MFI.getObjectAlign(FrameIndex));
2387
2388 auto MIB = BuildMI(MBB, MI, MI->getDebugLoc(),
2389 TII->get(AMDGPU::SI_BLOCK_SPILL_V1024_RESTORE), Reg)
2390 .addFrameIndex(FrameIndex)
2391 .addReg(FuncInfo->getStackPtrOffsetReg())
2392 .addImm(0)
2393 .addImm(Mask)
2394 .addMemOperand(MMO);
2395 TRI.addImplicitUsesForBlockCSRLoad(MIB, Reg);
2396
2397 // Add the register to the liveins. This is necessary because if any of the
2398 // VGPRs in the register block is reserved (e.g. if it's a WWM register),
2399 // then the whole block will be marked as reserved and `updateLiveness` will
2400 // skip it.
2401 MBB.addLiveIn(Reg);
2402 }
2403
2404 MBB.sortUniqueLiveIns();
2405 return true;
2406}
2407
2409 MachineFunction &MF,
2412 int64_t Amount = I->getOperand(0).getImm();
2413 if (Amount == 0)
2414 return MBB.erase(I);
2415
2416 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2417 const SIInstrInfo *TII = ST.getInstrInfo();
2418 const DebugLoc &DL = I->getDebugLoc();
2419 unsigned Opc = I->getOpcode();
2420 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
2421 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
2422
2423 if (!hasReservedCallFrame(MF)) {
2424 Amount = alignTo(Amount, getStackAlign());
2425 assert(isUInt<32>(Amount) && "exceeded stack address space size");
2428
2429 Amount *= getScratchScaleFactor(ST);
2430 if (IsDestroy)
2431 Amount = -Amount;
2432 auto Add = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SPReg)
2433 .addReg(SPReg)
2434 .addImm(Amount);
2435 Add->getOperand(3).setIsDead(); // Mark SCC as dead.
2436 } else if (CalleePopAmount != 0) {
2437 llvm_unreachable("is this used?");
2438 }
2439
2440 return MBB.erase(I);
2441}
2442
2443/// Returns true if the frame will require a reference to the stack pointer.
2444///
2445/// This is the set of conditions common to setting up the stack pointer in a
2446/// kernel, and for using a frame pointer in a callable function.
2447///
2448/// FIXME: Should also check hasOpaqueSPAdjustment and if any inline asm
2449/// references SP.
2451 return MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint();
2452}
2453
2454// The FP for kernels is always known 0, so we never really need to setup an
2455// explicit register for it. However, DisableFramePointerElim will force us to
2456// use a register for it.
2458 const MachineFrameInfo &MFI = MF.getFrameInfo();
2459
2460 // For entry functions we can use an immediate offset in most cases,
2461 // so the presence of calls doesn't imply we need a distinct frame pointer.
2462 if (MFI.hasCalls() &&
2464 // All offsets are unsigned, so need to be addressed in the same direction
2465 // as stack growth.
2466
2467 // FIXME: This function is pretty broken, since it can be called before the
2468 // frame layout is determined or CSR spills are inserted.
2469 return MFI.getStackSize() != 0;
2470 }
2471
2472 return frameTriviallyRequiresSP(MFI) || MFI.isFrameAddressTaken() ||
2473 MF.getSubtarget<GCNSubtarget>().getRegisterInfo()->hasStackRealignment(
2474 MF) ||
2476}
2477
2479 const MachineFunction &MF) const {
2480 return MF.getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() &&
2483}
2484
2485// This is essentially a reduced version of hasFP for entry functions. Since the
2486// stack pointer is known 0 on entry to kernels, we never really need an FP
2487// register. We may need to initialize the stack pointer depending on the frame
2488// properties, which logically overlaps many of the cases where an ordinary
2489// function would require an FP.
2491 const MachineFunction &MF) const {
2492 // Callable functions always require a stack pointer reference.
2494 "only expected to call this for entry points functions");
2495
2496 const MachineFrameInfo &MFI = MF.getFrameInfo();
2497
2498 // Entry points ordinarily don't need to initialize SP. We have to set it up
2499 // for callees if there are any. Also note tail calls are only possible via
2500 // the `llvm.amdgcn.cs.chain` intrinsic.
2501 if (MFI.hasCalls() || MFI.hasTailCall())
2502 return true;
2503
2504 // We still need to initialize the SP if we're doing anything weird that
2505 // references the SP, like variable sized stack objects.
2506 return frameTriviallyRequiresSP(MFI);
2507}
2508
2511 const DebugLoc &DL,
2512 const MCCFIInstruction &CFIInst,
2513 MachineInstr::MIFlag Flag) const {
2514 MachineFunction &MF = *MBB.getParent();
2515 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2516 return BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2517 .addCFIIndex(MF.addFrameInst(CFIInst))
2518 .setMIFlag(Flag);
2519}
2520
2523 const DebugLoc &DL, const MCRegister Reg, const MCRegister RegCopy) const {
2524 MachineFunction &MF = *MBB.getParent();
2525 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2526 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2527
2528 unsigned MaskReg = MCRI.getDwarfRegNum(
2529 ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC, false);
2531 nullptr, MCRI.getDwarfRegNum(Reg, false),
2532 MCRI.getDwarfRegNum(RegCopy, false), VGPRLaneBitSize, MaskReg,
2533 ST.getWavefrontSize());
2534 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2535}
2536
2539 const DebugLoc &DL, const MCRegister SGPR, const MCRegister VGPR,
2540 const int Lane) const {
2541 const MachineFunction &MF = *MBB.getParent();
2542 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2543
2544 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2545 int DwarfVGPR = MCRI.getDwarfRegNum(VGPR, false);
2546 assert(DwarfSGPR != -1 && DwarfVGPR != -1);
2547 assert(Lane != -1 && "Expected a lane to be present");
2548
2549 // Build a CFI instruction that represents a SGPR spilled to a single lane of
2550 // a VGPR.
2552 unsigned(Lane), VGPRLaneBitSize};
2553 auto CFIInst =
2554 MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR, {VR});
2555 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2556}
2557
2560 const DebugLoc &DL, MCRegister SGPR,
2561 ArrayRef<SIRegisterInfo::SpilledReg> VGPRSpills) const {
2562 if (VGPRSpills.size() == 1u)
2563 return buildCFIForSGPRToVGPRSpill(MBB, MBBI, DL, SGPR, VGPRSpills[0].VGPR,
2564 VGPRSpills[0].Lane);
2565 const MachineFunction &MF = *MBB.getParent();
2566 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2567
2568 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2569 assert(DwarfSGPR != -1);
2570
2571 // Build a CFI instruction that represents a SGPR spilled to multiple lanes of
2572 // multiple VGPRs.
2573
2575 for (SIRegisterInfo::SpilledReg Spill : VGPRSpills) {
2576 int DwarfVGPR = MCRI.getDwarfRegNum(Spill.VGPR, false);
2577 assert(DwarfVGPR != -1);
2578 assert(Spill.hasLane() && "Expected a lane to be present");
2579 VGPRs.push_back(
2580 {unsigned(DwarfVGPR), unsigned(Spill.Lane), VGPRLaneBitSize});
2581 }
2582
2583 auto CFIInst = MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR,
2584 std::move(VGPRs));
2585 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2586}
2587
2590 const DebugLoc &DL, MCRegister SGPR, int64_t Offset) const {
2591 MachineFunction &MF = *MBB.getParent();
2592 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2593 return buildCFI(MBB, MBBI, DL,
2595 nullptr, MCRI.getDwarfRegNum(SGPR, false), Offset));
2596}
2597
2600 const DebugLoc &DL, MCRegister VGPR, int64_t Offset) const {
2601 const MachineFunction &MF = *MBB.getParent();
2602 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2603 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2604
2605 int DwarfVGPR = MCRI.getDwarfRegNum(VGPR, false);
2606 assert(DwarfVGPR != -1);
2607
2608 unsigned MaskReg = MCRI.getDwarfRegNum(
2609 ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC, false);
2611 nullptr, DwarfVGPR, VGPRLaneBitSize, MaskReg, ST.getWavefrontSize(),
2612 Offset);
2613 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2614}
2615
2617 SmallVectorImpl<unsigned> &DwarfRegs) {
2618 int64_t DwarfReg = TRI.getDwarfRegNum(Reg, /*IsEH=*/false);
2619 if (DwarfReg >= 0) {
2620 DwarfRegs.push_back(unsigned(DwarfReg));
2621 return;
2622 }
2623
2624 const TargetRegisterClass *RC = TRI.getPhysRegBaseClass(Reg);
2625 ArrayRef<int16_t> SplitParts = TRI.getRegSplitParts(RC, SGPRByteSize);
2626 for (unsigned I = 0; I < SplitParts.size(); ++I) {
2627 MCRegister SubReg = TRI.getSubReg(Reg, SplitParts[I]);
2628 DwarfReg = TRI.getDwarfRegNum(SubReg, /*IsEH=*/false);
2629 if (DwarfReg < 0) {
2630 DwarfRegs.clear();
2631 return;
2632 }
2633 DwarfRegs.push_back(unsigned(DwarfReg));
2634 }
2635}
2636
2639 const DebugLoc &DL, MCRegister Reg, MCRegister CopyReg) const {
2640 const MachineFunction &MF = *MBB.getParent();
2641 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2642 const SIRegisterInfo &TRI = *ST.getRegisterInfo();
2643
2644 SmallVector<unsigned> DwarfRegs, DwarfCopyRegs;
2645 decomposeDwarfRegs(TRI, Reg, DwarfRegs);
2646 decomposeDwarfRegs(TRI, CopyReg, DwarfCopyRegs);
2647
2648 if (DwarfRegs.size() == DwarfCopyRegs.size()) {
2649 for (unsigned I = 0, E = DwarfRegs.size(); I < E; ++I) {
2650 auto CFI = MCCFIInstruction::createRegister(nullptr, DwarfRegs[I],
2651 DwarfCopyRegs[I]);
2652 buildCFI(MBB, MBBI, DL, CFI);
2653 }
2654 return;
2655 }
2656
2657 if (DwarfRegs.size() == 1 && DwarfCopyRegs.size() == 2) {
2659 nullptr, DwarfRegs[0], DwarfCopyRegs[0], SGPRBitSize, DwarfCopyRegs[1],
2660 SGPRBitSize);
2661 buildCFI(MBB, MBBI, DL, CFI);
2662 return;
2663 }
2664
2665 for (unsigned I = 0, E = DwarfRegs.size(); I < E; ++I) {
2666 auto CFI = MCCFIInstruction::createUndefined(nullptr, DwarfRegs[I]);
2667 buildCFI(MBB, MBBI, DL, CFI);
2668 }
2669}
2670
2673 const DebugLoc &DL, MCRegister SGPR, MCRegister VCCHalf) const {
2674 const MachineFunction &MF = *MBB.getParent();
2675 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2677
2678 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2679 int DwarfVCC = MCRI.getDwarfRegNum(AMDGPU::VCC, false);
2680 assert(DwarfSGPR != -1 && DwarfVCC != -1);
2681
2682 // Describe the copy as one 32-bit lane of VCC_64: lane 0 is vcc_lo and lane 1
2683 // is vcc_hi.
2685 unsigned(DwarfVCC), VCCHalf == AMDGPU::VCC_HI ? 1u : 0u, SGPRBitSize};
2686 auto CFIInst =
2687 MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR, {Half});
2688 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2689}
2690
2693 const DebugLoc &DL, MCRegister Reg) const {
2694 const MachineFunction &MF = *MBB.getParent();
2695 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2696 int DwarfReg = MCRI.getDwarfRegNum(Reg, /*isEH=*/false);
2697 auto CFIInst = MCCFIInstruction::createSameValue(nullptr, DwarfReg);
2698 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2699}
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains constants used for implementing Dwarf debug support.
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
A set of register units.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
static void buildEpilogRestore(const GCNSubtarget &ST, const SIRegisterInfo &TRI, const SIMachineFunctionInfo &FuncInfo, LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SpillReg, int FI, Register FrameReg, int64_t DwordOff=0)
static cl::opt< bool > EnableSpillVGPRToAGPR("amdgpu-spill-vgpr-to-agpr", cl::desc("Enable spilling VGPRs to AGPRs"), cl::ReallyHidden, cl::init(true))
static void getVGPRSpillLaneOrTempRegister(MachineFunction &MF, LiveRegUnits &LiveUnits, Register SGPR, const TargetRegisterClass &RC=AMDGPU::SReg_32_XM0_XEXECRegClass, bool IncludeScratchCopy=true)
Query target location for spilling SGPRs IncludeScratchCopy : Also look for free scratch SGPRs.
static void buildGitPtr(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, const SIInstrInfo *TII, Register TargetReg)
static bool allStackObjectsAreDead(const MachineFrameInfo &MFI)
static MCCFIInstruction createScaledCFAInPrivateWave(const GCNSubtarget &ST, int64_t DwarfStackPtrReg)
static void buildPrologSpill(const GCNSubtarget &ST, const SIRegisterInfo &TRI, const SIMachineFunctionInfo &FuncInfo, LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SpillReg, int FI, Register FrameReg, int64_t DwordOff=0)
static Register buildScratchExecCopy(LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool IsProlog, bool EnableInactiveLanes)
static void encodeDwarfRegisterLocation(int DwarfReg, raw_ostream &OS)
static constexpr unsigned SGPRBitSize
static bool frameTriviallyRequiresSP(const MachineFrameInfo &MFI)
Returns true if the frame will require a reference to the stack pointer.
static void decomposeDwarfRegs(const SIRegisterInfo &TRI, MCRegister Reg, SmallVectorImpl< unsigned > &DwarfRegs)
static SparseBitVector buildLiveInRoots(const MachineBasicBlock &MBB, const SIRegisterInfo &TRI)
Return the set of all root registers of regunits live-in to MBB.
static void initLiveUnits(LiveRegUnits &LiveUnits, const SIRegisterInfo &TRI, const SIMachineFunctionInfo *FuncInfo, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, bool IsProlog)
static constexpr unsigned VGPRLaneBitSize
static bool allSGPRSpillsAreDead(const MachineFunction &MF)
static bool isWave64VCCHalf(const GCNSubtarget &ST, MCRegister Reg)
static MCRegister findScratchNonCalleeSaveRegister(MachineRegisterInfo &MRI, LiveRegUnits &LiveUnits, const TargetRegisterClass &RC, bool Unused=false)
static MCRegister findUnusedRegister(MachineRegisterInfo &MRI, const LiveRegUnits &LiveUnits, const TargetRegisterClass &RC)
static constexpr unsigned SGPRByteSize
static void assignSlotsUsingVGPRBlocks(MachineFunction &MF, const GCNSubtarget &ST, std::vector< CalleeSavedInfo > &CSI)
static bool isAnyRootLiveIn(const SparseBitVector<> &LiveInRoots, const SIRegisterInfo &TRI, MCRegister Reg)
Returns true iff any root of Reg is in LiveInRoots (see buildLiveInRoots).
static unsigned getScratchScaleFactor(const GCNSubtarget &ST)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const int BlockSize
Definition TarWriter.cpp:33
static const LaneMaskConstants & get(const GCNSubtarget &ST)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear a bit in this vector for every '0' bit in Mask.
Definition BitVector.h:760
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool any() const
Returns true if any bit is set.
Definition BitVector.h:189
void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear any bits in this vector that are set in Mask.
Definition BitVector.h:748
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:175
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
MCRegister getReg() const
MCRegister getDstReg() const
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
const HexagonRegisterInfo & getRegisterInfo() const
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
void addReg(MCRegister Reg)
Adds register units covered by physical register Reg.
LLVM_ABI void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
LLVM_ABI void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
void removeReg(MCRegister Reg)
Removes all register units covered by physical register Reg.
bool empty() const
Returns true if the set is empty.
LLVM_ABI void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
static MCCFIInstruction createLLVMVectorOffset(MCSymbol *L, unsigned Register, unsigned RegisterSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, int64_t Offset, SMLoc Loc={})
.cfi_llvm_vector_offset Previous value of Register is saved at Offset from CFA.
Definition MCDwarf.h:797
static MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_undefined From now on the previous value of Register can't be restored anymore.
Definition MCDwarf.h:732
static MCCFIInstruction createLLVMVectorRegisters(MCSymbol *L, unsigned Register, ArrayRef< VectorRegisterWithLane > VectorRegisters, SMLoc Loc={})
.cfi_llvm_vector_registers Previous value of Register is saved in lanes of vector registers.
Definition MCDwarf.h:787
static MCCFIInstruction createLLVMVectorRegisterMask(MCSymbol *L, unsigned Register, unsigned SpillRegister, unsigned SpillRegisterLaneSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, SMLoc Loc={})
.cfi_llvm_vector_register_mask Previous value of Register is saved in SpillRegister,...
Definition MCDwarf.h:808
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2, SMLoc Loc={})
.cfi_register Previous value of Register1 is saved in register Register2.
Definition MCDwarf.h:685
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:670
static MCCFIInstruction createLLVMRegisterPair(MCSymbol *L, unsigned Register, unsigned R1, unsigned R1SizeInBits, unsigned R2, unsigned R2SizeInBits, SMLoc Loc={})
.cfi_llvm_register_pair Previous value of Register is saved in R1:R2.
Definition MCDwarf.h:777
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:756
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition MCDwarf.h:739
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:413
Describe properties that are true of each instruction in the target description file.
bool isValid() const
Returns true if this iterator is not yet at the end.
MCRegUnitMaskIterator enumerates a list of register units and their associated lane masks for Reg.
MCRegUnitRootIterator enumerates the root registers of a register unit.
bool isValid() const
Check if the iterator is at the end of the list.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
virtual int64_t getDwarfRegNum(MCRegister Reg, bool isEH) const
Map a target register to an equivalent dwarf register number.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool hasTailCall() const
Returns true if the function contains a tail call.
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
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
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
mop_range operands()
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
void setIsDead(bool Val=true)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
void reserveReg(MCRegister PhysReg, const TargetRegisterInfo *TRI)
reserveReg – Mark a register as reserved so checks like isAllocatable will not suggest using it.
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI bool isPhysRegModified(MCRegister PhysReg, bool SkipNoReturnDef=false) const
Return true if the specified register is modified in this function.
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
PrologEpilogSGPRSpillBuilder(Register Reg, const PrologEpilogSGPRSaveRestoreInfo SI, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, const SIInstrInfo *TII, const SIRegisterInfo &TRI, LiveRegUnits &LiveUnits, Register FrameReg, bool IsFramePtrPrologSpill=false)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
void determinePrologEpilogSGPRSaves(MachineFunction &MF, BitVector &SavedRegs, bool NeedExecCopyReservedReg) const
MachineInstr * buildCFIForSGPRToVMEMSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister SGPR, int64_t Offset) const
Create a CFI index describing a spill of a SGPR to VMEM and build a MachineInstr around it.
void buildCFIForSRegToSRegSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister Reg, MCRegister CopyReg) const
void emitCSRSpillRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy) const
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool mayReserveScratchForCWSR(const MachineFunction &MF) const
bool allocateScavengingFrameIndexesNearIncomingSP(const MachineFunction &MF) const override
Control the placement of special register scavenging spill slots when allocating a stack frame.
bool requiresStackPointerReference(const MachineFunction &MF) const
void emitEntryFunctionPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const
MachineInstr * buildCFIForSGPRToVCCHalfCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister SGPR, MCRegister VCCHalf) const
Create a CFI index describing a copy of the 32-bit SGPR to VCCHalf (vcc_lo or vcc_hi) in wave64 and b...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool hasFPImpl(const MachineFunction &MF) const override
bool assignCalleeSavedSpillSlotsImpl(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
MachineInstr * buildCFIForVRegToVRegSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCRegister Reg, const MCRegister RegCopy) const
Create a CFI index describing a spill of the VGPR/AGPR Reg to another VGPR/AGPR RegCopy and build a M...
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
MachineInstr * buildCFIForVGPRToVMEMSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister VGPR, int64_t Offset) const
Create a CFI index describing a spill of a VGPR to VMEM and build a MachineInstr around it.
MachineInstr * buildCFIForSGPRToVGPRSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCRegister SGPR, const MCRegister VGPR, const int Lane) const
Create a CFI index describing a spill of an SGPR to a single lane of a VGPR and build a MachineInstr ...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void determineCalleeSavesSGPR(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
MachineInstr * buildCFIForSameValue(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister Reg) const
MachineInstr * buildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag flag=MachineInstr::FrameSetup) const
Create a CFI index for CFIInst and build a MachineInstr around it.
void emitCSRSpillStores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy, const bool NeedsFrameMoves) const
void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
bool isSupportedStackID(TargetStackID::Value ID) const override
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
ArrayRef< PrologEpilogSGPRSpill > getPrologEpilogSGPRSpills() const
const WWMSpillsMap & getWWMSpills() const
void getAllScratchSGPRCopyDstRegs(SmallVectorImpl< Register > &Regs) const
ArrayRef< MCPhysReg > getAGPRSpillVGPRs() const
void removePrologEpilogSGPRSpillEntry(Register Reg)
void shiftWwmVGPRsToLowestRange(MachineFunction &MF, SmallVectorImpl< Register > &WWMVGPRs, BitVector &SavedVGPRs)
void setMaskForVGPRBlockOps(Register RegisterBlock, uint32_t Mask)
GCNUserSGPRUsageInfo & getUserSGPRInfo()
void allocateWWMSpill(MachineFunction &MF, Register VGPR, uint64_t Size=4, Align Alignment=Align(4))
void setVGPRToAGPRSpillDead(int FrameIndex)
Register getScratchRSrcReg() const
Returns the physical register reserved for use as the resource descriptor for scratch accesses.
ArrayRef< MCPhysReg > getVGPRSpillAGPRs() const
int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI)
uint32_t getMaskForVGPRBlockOps(Register RegisterBlock) const
bool hasMaskForVGPRBlockOps(Register RegisterBlock) const
bool hasPrologEpilogSGPRSpillEntry(Register Reg) const
Register getGITPtrLoReg(const MachineFunction &MF) const
void setVGPRForAGPRCopy(Register NewVGPRForAGPRCopy)
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 isWWMReservedRegister(Register Reg) const
ArrayRef< SIRegisterInfo::SpilledReg > getSGPRSpillToPhysicalVGPRLanes(int FrameIndex) const
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
void setLongBranchReservedReg(Register Reg)
void setHasSpilledVGPRs(bool Spill=true)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
void setScratchReservedForDynamicVGPRs(unsigned SizeInBytes)
MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const
bool checkIndexInPrologEpilogSGPRSpills(int FI) const
const ReservedRegSet & getWWMReservedRegs() const
const PrologEpilogSGPRSaveRestoreInfo & getPrologEpilogSGPRSaveRestoreInfo(Register Reg) const
void setIsStackRealigned(bool Realigned=true)
void addToPrologEpilogSGPRSpills(Register Reg, PrologEpilogSGPRSaveRestoreInfo SI)
Register getScratchSGPRCopyDstReg(Register Reg) const
Register getFrameRegister(const MachineFunction &MF) const override
Represents a location in source code.
Definition SMLoc.h:22
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void set(unsigned Idx)
bool test(unsigned Idx) const
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned getVGPRAllocGranule(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
uint64_t convertSMRDOffsetUnits(const MCSubtargetInfo &ST, uint64_t ByteOffset)
Convert ByteOffset to dwords if the subtarget uses dword SMRD immediate offsets.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isCompute(CallingConv::ID CC)
LLVM_READNONE constexpr bool isChainCC(CallingConv::ID CC)
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
constexpr RegState getKillRegState(bool B)
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:649
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
void clearDebugInfoForSpillFIs(MachineFrameInfo &MFI, MachineBasicBlock &MBB, const BitVector &SpillFIs)
Replace frame index operands with null registers in debug value instructions for the specified spill ...
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
LLVM_ABI 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.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.