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