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