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