LLVM 24.0.0git
RISCVFrameLowering.cpp
Go to the documentation of this file.
1//===-- RISCVFrameLowering.cpp - RISC-V Frame Information -----------------===//
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// This file contains the RISC-V implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVFrameLowering.h"
17#include "RISCVSubtarget.h"
28#include "llvm/MC/MCDwarf.h"
29#include "llvm/Support/LEB128.h"
30
31#include <algorithm>
32#include <cstdint>
33
34#define DEBUG_TYPE "riscv-frame"
35
36using namespace llvm;
37
39 if (ABI == RISCVABI::ABI_ILP32E)
40 return Align(4);
41 if (ABI == RISCVABI::ABI_LP64E)
42 return Align(8);
43 return Align(16);
44}
45
49 /*LocalAreaOffset=*/0,
50 /*TransientStackAlignment=*/getABIStackAlignment(STI.getTargetABI())),
51 STI(STI) {}
52
53// The register used to hold the frame pointer.
54static constexpr MCPhysReg FPReg = RISCV::X8;
55
56// The register used to hold the stack pointer.
57static constexpr MCPhysReg SPReg = RISCV::X2;
58
59// The register used to hold the return address.
60static constexpr MCPhysReg RAReg = RISCV::X1;
61
62// LIst of CSRs that are given a fixed location by save/restore libcalls or
63// Zcmp/Xqccmp Push/Pop. The order in this table indicates the order the
64// registers are saved on the stack. Zcmp uses the reverse order of save/restore
65// and Xqccmp on the stack, but this is handled when offsets are calculated.
66static const MCPhysReg FixedCSRFIMap[] = {
67 /*ra*/ RAReg, /*s0*/ FPReg, /*s1*/ RISCV::X9,
68 /*s2*/ RISCV::X18, /*s3*/ RISCV::X19, /*s4*/ RISCV::X20,
69 /*s5*/ RISCV::X21, /*s6*/ RISCV::X22, /*s7*/ RISCV::X23,
70 /*s8*/ RISCV::X24, /*s9*/ RISCV::X25, /*s10*/ RISCV::X26,
71 /*s11*/ RISCV::X27};
72
73// The number of stack bytes allocated by `QC.C.MIENTER(.NEST)` and popped by
74// `QC.C.MILEAVERET`.
75static constexpr uint64_t QCIInterruptPushAmount = 96;
76
77static const std::pair<MCPhysReg, int8_t> FixedCSRFIQCIInterruptMap[] = {
78 /* -1 is a gap for mepc/mnepc */
79 {/*fp*/ FPReg, -2},
80 /* -3 is a gap for qc.mcause */
81 {/*ra*/ RAReg, -4},
82 /* -5 is reserved */
83 {/*t0*/ RISCV::X5, -6},
84 {/*t1*/ RISCV::X6, -7},
85 {/*t2*/ RISCV::X7, -8},
86 {/*a0*/ RISCV::X10, -9},
87 {/*a1*/ RISCV::X11, -10},
88 {/*a2*/ RISCV::X12, -11},
89 {/*a3*/ RISCV::X13, -12},
90 {/*a4*/ RISCV::X14, -13},
91 {/*a5*/ RISCV::X15, -14},
92 {/*a6*/ RISCV::X16, -15},
93 {/*a7*/ RISCV::X17, -16},
94 {/*t3*/ RISCV::X28, -17},
95 {/*t4*/ RISCV::X29, -18},
96 {/*t5*/ RISCV::X30, -19},
97 {/*t6*/ RISCV::X31, -20},
98 /* -21, -22, -23, -24 are reserved */
99};
100
101/// Returns true if DWARF CFI instructions ("frame moves") should be emitted.
102static bool needsDwarfCFI(const MachineFunction &MF) {
103 return MF.needsFrameMoves();
104}
105
106// For now we use x3, a.k.a gp, as pointer to shadow call stack.
107// User should not use x3 in their asm.
110 const DebugLoc &DL) {
111 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
112 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
114 return;
115
116 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
117 const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
118
119 // Do not save RA to the SCS if it's not saved to the regular stack,
120 // i.e. RA is not at risk of being overwritten.
121 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
122 if (llvm::none_of(
123 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
124 return;
125
126 const RISCVInstrInfo *TII = STI.getInstrInfo();
128 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH))
129 .addReg(RAReg)
131 return;
132 }
133
135 "Unexpected Shadow Stack Kind");
136
137 Register SCSPReg = RISCVABI::getSCSPReg();
138
139 bool IsRV64 = STI.is64Bit();
140 int64_t SlotSize = STI.getXLen() / 8;
141 // Store return address to shadow call stack
142 // addi gp, gp, [4|8]
143 // s[w|d] ra, -[4|8](gp)
144 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
145 .addReg(SCSPReg)
146 .addImm(SlotSize)
148 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
149 .addReg(RAReg)
150 .addReg(SCSPReg)
151 .addImm(-SlotSize)
153
154 if (!needsDwarfCFI(MF))
155 return;
156
157 // Emit a CFI instruction that causes SlotSize to be subtracted from the value
158 // of the shadow stack pointer when unwinding past this frame.
159 char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
160 assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
161
162 char Offset = static_cast<char>(-SlotSize) & 0x7f;
163 const char CFIInst[] = {
164 dwarf::DW_CFA_val_expression,
165 DwarfSCSReg, // register
166 2, // length
167 static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
168 Offset, // addend (sleb128)
169 };
170
172 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
173}
174
177 const DebugLoc &DL) {
178 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
179 RISCVMachineFunctionInfo::ShadowStackKind SSK = RVFI->getShadowStackKind(MF);
181 return;
182
183 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
184
185 // See emitSCSPrologue() above.
186 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
187 if (llvm::none_of(
188 CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
189 return;
190
191 // The shadow call stack popchk needs to happen after cm.pop that loads ra.
192 if (MI != MBB.end() &&
193 (MI->getOpcode() == RISCV::CM_POP || MI->getOpcode() == RISCV::QC_CM_POP))
194 ++MI;
195 const RISCVInstrInfo *TII = STI.getInstrInfo();
197 // `sspopchk x5` is the only compressible form, but this would require using
198 // `x5` as the return address everywhere, which would also mean reserving
199 // it. We prefer to just use `x1` to avoid that complexity.
200 BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK))
201 .addReg(RAReg)
203 return;
204 }
205
207 "Unexpected Shadow Stack Kind");
208
209 Register SCSPReg = RISCVABI::getSCSPReg();
210
211 bool IsRV64 = STI.is64Bit();
212 int64_t SlotSize = STI.getXLen() / 8;
213 // Load return address from shadow call stack
214 // l[w|d] ra, -[4|8](gp)
215 // addi gp, gp, -[4|8]
216 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW), RAReg)
217 .addReg(SCSPReg)
218 .addImm(-SlotSize)
220 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI), SCSPReg)
221 .addReg(SCSPReg)
222 .addImm(-SlotSize)
224 if (needsDwarfCFI(MF)) {
225 // Restore the SCS pointer
227 }
228}
229
230// Insert instruction to swap mscratchsw with sp
233 const DebugLoc &DL,
234 MachineInstr::MIFlag FrameFlag) {
235 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
236
237 if (!RVFI->isSiFiveStackSwapInterrupt(MF))
238 return;
239
240 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
241 const RISCVInstrInfo *TII = STI.getInstrInfo();
242
243 assert(STI.hasVendorXSfmclic() && "Stack Swapping Requires XSfmclic");
244
245 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), SPReg)
246 .addImm(RISCVSysReg::sf_mscratchcsw)
248 .setMIFlag(FrameFlag);
249
250 // FIXME: CFI Information for this swap.
251}
252
253static void
256 if (!RVFI.isSiFivePreemptibleInterrupt(MF))
257 return;
258
259 const TargetRegisterClass &RC = RISCV::GPRRegClass;
260 const TargetRegisterInfo &TRI =
261 *MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
262 MachineFrameInfo &MFI = MF.getFrameInfo();
263
264 // Create two frame objects for saving `mcause` and `mepc`.
265 for (int I = 0; I < 2; ++I) {
266 int FI = MFI.CreateStackObject(TRI.getSpillSize(RC), TRI.getSpillAlign(RC),
267 true);
269 }
270}
271
272// The scratch register retains an ordinary CSI slot, but its save and restore
273// are emitted explicitly as part of the SiFive CLIC interrupt sequence.
275 const auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
276 auto ScratchCS = llvm::find_if(
277 CSI, [](const CalleeSavedInfo &CS) { return CS.getReg() == RISCV::X5; });
278 assert(ScratchCS != CSI.end() && "Missing SiFive CLIC scratch spill slot");
279 return ScratchCS->getFrameIdx();
280}
281
285 const DebugLoc &DL) {
286 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
287
288 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
289 return;
290
291 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
292 const RISCVInstrInfo *TII = STI.getInstrInfo();
293
294 // FIXME: CFI information for `mcause` and `mepc` is missing.
295
296 // Preserve X5 before using it to save the interrupt CSRs. Other GPRs
297 // are saved by the ordinary spill sequence after preemption is enabled.
298 int ScratchFI = getSiFiveCLICScratchFrameIndex(MF);
299 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /*IsKill=*/true, ScratchFI,
300 &RISCV::GPRRegClass, Register(),
302 if (needsDwarfCFI(MF))
304 .buildOffset(RISCV::X5, MF.getFrameInfo().getObjectOffset(ScratchFI));
305
306 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
307 .addImm(RISCVSysReg::mcause)
308 .addReg(RISCV::X0)
310 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
311 RVFI->getInterruptCSRFrameIndex(0),
312 &RISCV::GPRRegClass, Register(),
314
315 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRS), RISCV::X5)
316 .addImm(RISCVSysReg::mepc)
317 .addReg(RISCV::X0)
319
320 // Enable interrupts.
321 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRSI), RISCV::X0)
322 .addImm(RISCVSysReg::mstatus)
323 .addImm(8)
325 TII->storeRegToStackSlot(MBB, MBBI, RISCV::X5, /* IsKill=*/true,
326 RVFI->getInterruptCSRFrameIndex(1),
327 &RISCV::GPRRegClass, Register(),
329}
330
334 CFIInstBuilder &CFIBuilder,
335 const DebugLoc &DL) {
336 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
337
338 if (!RVFI->isSiFivePreemptibleInterrupt(MF))
339 return;
340
341 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
342 const RISCVInstrInfo *TII = STI.getInstrInfo();
343
344 // FIXME: CFI information for `mcause` and `mepc` is missing.
345
346 // Load mepc while preemption is still enabled. A nested handler preserves
347 // X5. Interrupts only need to be disabled before writing the CSRs back.
348 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
349 RVFI->getInterruptCSRFrameIndex(1),
350 &RISCV::GPRRegClass, Register(),
351 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
352
353 // Disable interrupts.
354 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRCI), RISCV::X0)
355 .addImm(RISCVSysReg::mstatus)
356 .addImm(8)
358
359 // Restore `mepc` and `mcause` through X5, then restore the value X5 held
360 // on entry to the handler.
361 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
362 .addImm(RISCVSysReg::mepc)
363 .addReg(RISCV::X5, RegState::Kill)
365
366 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
367 RVFI->getInterruptCSRFrameIndex(0),
368 &RISCV::GPRRegClass, Register(),
369 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
370 BuildMI(MBB, MBBI, DL, TII->get(RISCV::CSRRW), RISCV::X0)
371 .addImm(RISCVSysReg::mcause)
372 .addReg(RISCV::X5, RegState::Kill)
374
375 // The ordinary reloads have finished. Recover the interrupted value of X5
376 // only after it has restored both CSRs.
377 TII->loadRegFromStackSlot(MBB, MBBI, RISCV::X5,
379 &RISCV::GPRRegClass, Register(),
380 RISCV::NoSubRegister, MachineInstr::FrameDestroy);
381 if (needsDwarfCFI(MF))
382 CFIBuilder.buildRestore(RISCV::X5);
383}
384
385// Get the ID of the libcall used for spilling and restoring callee saved
386// registers. The ID is representative of the number of registers saved or
387// restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
388// single register.
389static int getLibCallID(const MachineFunction &MF,
390 const std::vector<CalleeSavedInfo> &CSI) {
391 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
392
393 if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
394 return -1;
395
396 MCRegister MaxReg;
397 for (auto &CS : CSI)
398 // assignCalleeSavedSpillSlots assigns negative frame indexes to
399 // registers which can be saved by libcall.
400 if (CS.getFrameIdx() < 0)
401 MaxReg = std::max(MaxReg.id(), CS.getReg().id());
402
403 if (!MaxReg)
404 return -1;
405
406 switch (MaxReg.id()) {
407 default:
408 llvm_unreachable("Something has gone wrong!");
409 // clang-format off
410 case /*s11*/ RISCV::X27: return 12;
411 case /*s10*/ RISCV::X26: return 11;
412 case /*s9*/ RISCV::X25: return 10;
413 case /*s8*/ RISCV::X24: return 9;
414 case /*s7*/ RISCV::X23: return 8;
415 case /*s6*/ RISCV::X22: return 7;
416 case /*s5*/ RISCV::X21: return 6;
417 case /*s4*/ RISCV::X20: return 5;
418 case /*s3*/ RISCV::X19: return 4;
419 case /*s2*/ RISCV::X18: return 3;
420 case /*s1*/ RISCV::X9: return 2;
421 case /*s0*/ FPReg: return 1;
422 case /*ra*/ RAReg: return 0;
423 // clang-format on
424 }
425}
426
427// Get the name of the libcall used for spilling callee saved registers.
428// If this function will not use save/restore libcalls, then return a nullptr.
429static const char *
431 const std::vector<CalleeSavedInfo> &CSI) {
432 static const char *const SpillLibCalls[] = {
433 "__riscv_save_0",
434 "__riscv_save_1",
435 "__riscv_save_2",
436 "__riscv_save_3",
437 "__riscv_save_4",
438 "__riscv_save_5",
439 "__riscv_save_6",
440 "__riscv_save_7",
441 "__riscv_save_8",
442 "__riscv_save_9",
443 "__riscv_save_10",
444 "__riscv_save_11",
445 "__riscv_save_12"
446 };
447
448 int LibCallID = getLibCallID(MF, CSI);
449 if (LibCallID == -1)
450 return nullptr;
451 return SpillLibCalls[LibCallID];
452}
453
454// Get the name of the libcall used for restoring callee saved registers.
455// If this function will not use save/restore libcalls, then return a nullptr.
456static const char *
458 const std::vector<CalleeSavedInfo> &CSI) {
459 static const char *const RestoreLibCalls[] = {
460 "__riscv_restore_0",
461 "__riscv_restore_1",
462 "__riscv_restore_2",
463 "__riscv_restore_3",
464 "__riscv_restore_4",
465 "__riscv_restore_5",
466 "__riscv_restore_6",
467 "__riscv_restore_7",
468 "__riscv_restore_8",
469 "__riscv_restore_9",
470 "__riscv_restore_10",
471 "__riscv_restore_11",
472 "__riscv_restore_12"
473 };
474
475 int LibCallID = getLibCallID(MF, CSI);
476 if (LibCallID == -1)
477 return nullptr;
478 return RestoreLibCalls[LibCallID];
479}
480
481// Get the max reg of Push/Pop for restoring callee saved registers.
482static unsigned getNumPushPopRegs(const std::vector<CalleeSavedInfo> &CSI) {
483 unsigned NumPushPopRegs = 0;
484 for (auto &CS : CSI) {
485 auto *FII = llvm::find_if(FixedCSRFIMap,
486 [&](MCPhysReg P) { return P == CS.getReg(); });
487 if (FII != std::end(FixedCSRFIMap)) {
488 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
489 NumPushPopRegs = std::max(NumPushPopRegs, RegNum + 1);
490 }
491 }
492 assert(NumPushPopRegs != 12 && "x26 requires x27 to also be pushed");
493 return NumPushPopRegs;
494}
495
496// Return true if the specified function should have a dedicated frame
497// pointer register. This is true if frame pointer elimination is
498// disabled, if it needs dynamic stack realignment, if the function has
499// variable sized allocas, or if the frame address is taken.
501 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
502
503 const MachineFrameInfo &MFI = MF.getFrameInfo();
504 if (MF.disableFramePointerElim() || RegInfo->hasStackRealignment(MF) ||
506 return true;
507
508 // With large callframes around we may need to use FP to access the scavenging
509 // emergency spillslot.
510 //
511 // We calculate the MaxCallFrameSize at the end of isel so this value should
512 // be stable for the whole post-isel MIR pipeline.
513 //
514 // NOTE: The idea of forcing a frame pointer is copied from AArch64, but they
515 // conservatively return true when the call frame size hasd not been
516 // computed yet. On RISC-V that caused MachineOutliner tests to fail the
517 // MachineVerifier due to outlined functions not computing max call frame
518 // size thus the frame pointer would always be reserved.
519 if (MFI.isMaxCallFrameSizeComputed() && MFI.getMaxCallFrameSize() > 2047)
520 return true;
521
522 return false;
523}
524
526 const MachineFrameInfo &MFI = MF.getFrameInfo();
527 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
528
529 // If we do not reserve stack space for outgoing arguments in prologue,
530 // we will adjust the stack pointer before call instruction. After the
531 // adjustment, we can not use SP to access the stack objects for the
532 // arguments. Instead, use BP to access these stack objects.
533 return (MFI.hasVarSizedObjects() ||
535 MFI.getMaxCallFrameSize() != 0))) &&
536 TRI->hasStackRealignment(MF);
537}
538
539// Determines the size of the frame and maximum call frame size.
540void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
541 MachineFrameInfo &MFI = MF.getFrameInfo();
542 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
543
544 // Get the number of bytes to allocate from the FrameInfo.
545 uint64_t FrameSize = MFI.getStackSize();
546
547 // QCI Interrupts use at least 96 bytes of stack space
548 if (RVFI->useQCIInterrupt(MF))
549 FrameSize = std::max(FrameSize, QCIInterruptPushAmount);
550
551 // Get the alignment.
552 Align StackAlign = getStackAlign();
553
554 // Make sure the frame is aligned.
555 FrameSize = alignTo(FrameSize, StackAlign);
556
557 // Update frame info.
558 MFI.setStackSize(FrameSize);
559
560 // When using SP or BP to access stack objects, we may require extra padding
561 // to ensure the bottom of the RVV stack is correctly aligned within the main
562 // stack. We calculate this as the amount required to align the scalar local
563 // variable section up to the RVV alignment.
565 if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
566 int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
567 RVFI->getVarArgsSaveSize();
568 if (auto RVVPadding =
569 offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
570 RVFI->setRVVPadding(RVVPadding);
571 }
572}
573
574// Returns the stack size including RVV padding (when required), rounded back
575// up to the required stack alignment.
577 const MachineFunction &MF) const {
578 const MachineFrameInfo &MFI = MF.getFrameInfo();
579 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
580 return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
581}
582
585 const std::vector<CalleeSavedInfo> &CSI,
586 bool ReverseOrder = false) {
587 const MachineFrameInfo &MFI = MF.getFrameInfo();
589
590 for (auto &CS : CSI) {
591 int FI = CS.getFrameIdx();
592 // Callee saves with negative frame indices have fixed positions on the
593 // stack, usually relating to libcalls or push/pop.
594 bool IsManagedFI = (FI < 0);
595 if (!IsManagedFI && MFI.getStackID(FI) == TargetStackID::Default)
596 NonLibcallCSI.push_back(CS);
597 }
598
599 // Reverse the order so that load/store operations use ascending addresses,
600 // enabling better load/store clustering and fusion.
601 if (ReverseOrder)
602 std::reverse(NonLibcallCSI.begin(), NonLibcallCSI.end());
603
604 return NonLibcallCSI;
605}
606
607// Exclude X5 from ordinary spills and restores for SiFive CLIC preemptible
608// handlers, which save and restore it explicitly.
611 const std::vector<CalleeSavedInfo> &CSI,
612 bool ReverseOrder = false) {
613 auto InterruptCSI = getUnmanagedCSI(MF, CSI, ReverseOrder);
615 llvm::erase_if(InterruptCSI, [](const CalleeSavedInfo &CS) {
616 return CS.getReg() == RISCV::X5;
617 });
618 return InterruptCSI;
619}
620
623 const std::vector<CalleeSavedInfo> &CSI) {
624 const MachineFrameInfo &MFI = MF.getFrameInfo();
626
627 for (auto &CS : CSI) {
628 int FI = CS.getFrameIdx();
629 if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::ScalableVector)
630 RVVCSI.push_back(CS);
631 }
632
633 return RVVCSI;
634}
635
638 const std::vector<CalleeSavedInfo> &CSI) {
639 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
640
641 SmallVector<CalleeSavedInfo, 8> PushOrLibCallsCSI;
642 if (!RVFI->useSaveRestoreLibCalls(MF) && !RVFI->isPushable(MF))
643 return PushOrLibCallsCSI;
644
645 for (const auto &CS : CSI) {
646 if (RVFI->useQCIInterrupt(MF)) {
647 // Some registers are saved by both `QC.C.MIENTER(.NEST)` and
648 // `QC.CM.PUSH(FP)`. In these cases, prioritise the CFI info that points
649 // to the versions saved by `QC.C.MIENTER(.NEST)` which is what FP
650 // unwinding would use.
652 CS.getReg()))
653 continue;
654 }
655
656 if (llvm::is_contained(FixedCSRFIMap, CS.getReg()))
657 PushOrLibCallsCSI.push_back(CS);
658 }
659
660 return PushOrLibCallsCSI;
661}
662
665 const std::vector<CalleeSavedInfo> &CSI) {
666 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
667
668 SmallVector<CalleeSavedInfo, 8> QCIInterruptCSI;
669 if (!RVFI->useQCIInterrupt(MF))
670 return QCIInterruptCSI;
671
672 for (const auto &CS : CSI) {
674 CS.getReg()))
675 QCIInterruptCSI.push_back(CS);
676 }
677
678 return QCIInterruptCSI;
679}
680
682 const MachineBasicBlock &MBB) {
683 const MachineFunction *MF = MBB.getParent();
684 LiveRegs.addLiveIns(MBB);
685 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
686 for (unsigned i = 0; CSRegs[i]; ++i)
687 LiveRegs.addReg(CSRegs[i]);
688}
689
691 MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg) const {
692 MachineFunction *MF = MBB->getParent();
693
694 // Stack protection code is being inserted at beginning of function, use
695 // register which has been historically used
696 if (&MF->front() == MBB)
697 return PreferredReg;
698
699 const RISCVSubtarget &Subtarget = MF->getSubtarget<RISCVSubtarget>();
700 const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
703
704 const MachineRegisterInfo &MRI = MF->getRegInfo();
705 // Prefer the register which has been historically used for stack protector
706 if (LiveRegs.available(MRI, PreferredReg))
707 return PreferredReg;
708
709 static const MCPhysReg CandidateRegs[] = {
710 RISCV::X5, RISCV::X6, RISCV::X7, RISCV::X28,
711 RISCV::X29, RISCV::X30, RISCV::X31,
712 };
713
714 for (unsigned Reg : CandidateRegs) {
715 if (Reg != DontUseReg && LiveRegs.available(MRI, Reg))
716 return Reg;
717 }
718
719 return Register();
720}
721
722void RISCVFrameLowering::allocateAndProbeStackForRVV(
724 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, int64_t Amount,
725 MachineInstr::MIFlag Flag, bool EmitCFI, bool DynAllocation) const {
726 assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
727
728 // Emit a variable-length allocation probing loop.
729
730 // Get VLEN in TargetReg
731 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
732 assert(TargetReg.isValid() &&
733 "No available scratch register for stack probing");
735 uint32_t NumOfVReg = Amount / RISCV::RVVBytesPerBlock;
736 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PseudoReadVLENB), TargetReg)
737 .setMIFlag(Flag);
738 TII->mulImm(MF, MBB, MBBI, DL, TargetReg, NumOfVReg, Flag);
739
741 if (EmitCFI) {
742 // Set the CFA register to TargetReg.
743 CFIBuilder.buildDefCFA(TargetReg, -Amount);
744 }
745
746 // It will be expanded to a probe loop in `inlineStackProbe`.
747 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC_RVV))
748 .addReg(TargetReg);
749
750 if (EmitCFI) {
751 // Set the CFA register back to SP.
752 CFIBuilder.buildDefCFARegister(SPReg);
753 }
754
755 // SUB SP, SP, T1
756 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SUB), SPReg)
757 .addReg(SPReg)
758 .addReg(TargetReg)
759 .setMIFlag(Flag);
760
761 // If we have a dynamic allocation later we need to probe any residuals.
762 if (DynAllocation) {
763 BuildMI(MBB, MBBI, DL, TII->get(STI.is64Bit() ? RISCV::SD : RISCV::SW))
764 .addReg(RISCV::X0)
765 .addReg(SPReg)
766 .addImm(0)
768 }
769}
770
774 llvm::raw_string_ostream &Comment) {
775 int64_t FixedOffset = Offset.getFixed();
776 int64_t ScalableOffset = Offset.getScalable();
777 unsigned DwarfVLenB = TRI.getDwarfRegNum(RISCV::VLENB, true);
778 if (FixedOffset) {
779 Expr.push_back(dwarf::DW_OP_consts);
780 appendLEB128<LEB128Sign::Signed>(Expr, FixedOffset);
781 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
782 Comment << (FixedOffset < 0 ? " - " : " + ") << std::abs(FixedOffset);
783 }
784
785 Expr.push_back((uint8_t)dwarf::DW_OP_consts);
786 appendLEB128<LEB128Sign::Signed>(Expr, ScalableOffset);
787
788 Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
789 appendLEB128<LEB128Sign::Unsigned>(Expr, DwarfVLenB);
790 Expr.push_back(0);
791
792 Expr.push_back((uint8_t)dwarf::DW_OP_mul);
793 Expr.push_back((uint8_t)dwarf::DW_OP_plus);
794
795 Comment << (ScalableOffset < 0 ? " - " : " + ") << std::abs(ScalableOffset)
796 << " * vlenb";
797}
798
802 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
803 SmallString<64> Expr;
804 std::string CommentBuffer;
805 llvm::raw_string_ostream Comment(CommentBuffer);
806 // Build up the expression (Reg + FixedOffset + ScalableOffset * VLENB).
807 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
808 Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
809 Expr.push_back(0);
810 if (Reg == SPReg)
811 Comment << "sp";
812 else
813 Comment << printReg(Reg, &TRI);
814
816
817 SmallString<64> DefCfaExpr;
818 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
819 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
820 DefCfaExpr.append(Expr.str());
821
822 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
823 Comment.str());
824}
825
828 assert(Offset.getScalable() != 0 && "Did not need to adjust CFA for RVV");
829 SmallString<64> Expr;
830 std::string CommentBuffer;
831 llvm::raw_string_ostream Comment(CommentBuffer);
832 Comment << printReg(Reg, &TRI) << " @ cfa";
833
834 // Build up the expression (FixedOffset + ScalableOffset * VLENB).
836
837 SmallString<64> DefCfaExpr;
838 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
839 DefCfaExpr.push_back(dwarf::DW_CFA_expression);
840 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, DwarfReg);
841 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
842 DefCfaExpr.append(Expr.str());
843
844 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
845 Comment.str());
846}
847
848// Allocate stack space and probe it if necessary.
851 MachineFunction &MF, uint64_t Offset,
852 uint64_t RealStackSize, bool EmitCFI,
853 bool NeedProbe, uint64_t ProbeSize,
854 bool DynAllocation,
855 MachineInstr::MIFlag Flag) const {
856 DebugLoc DL;
857 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
858 const RISCVInstrInfo *TII = STI.getInstrInfo();
859 bool IsRV64 = STI.is64Bit();
861
862 // Simply allocate the stack if it's not big enough to require a probe.
863 if (!NeedProbe || Offset <= ProbeSize) {
865 Flag, getStackAlign());
866
867 if (EmitCFI)
868 CFIBuilder.buildDefCFAOffset(RealStackSize);
869
870 if (NeedProbe && DynAllocation) {
871 // s[d|w] zero, 0(sp)
872 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
873 .addReg(RISCV::X0)
874 .addReg(SPReg)
875 .addImm(0)
876 .setMIFlags(Flag);
877 }
878
879 return;
880 }
881
882 // The amount of stack that was already allocated before this allocation.
883 uint64_t CFAAdjust = RealStackSize - Offset;
884
885 // Unroll the probe loop depending on the number of iterations.
886 if (Offset < ProbeSize * 5) {
887 uint64_t CurrentOffset = 0;
888 while (CurrentOffset + ProbeSize <= Offset) {
889 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
890 StackOffset::getFixed(-ProbeSize), Flag, getStackAlign());
891 // s[d|w] zero, 0(sp)
892 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
893 .addReg(RISCV::X0)
894 .addReg(SPReg)
895 .addImm(0)
896 .setMIFlags(Flag);
897
898 CurrentOffset += ProbeSize;
899 if (EmitCFI)
900 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
901 }
902
903 uint64_t Residual = Offset - CurrentOffset;
904 if (Residual) {
905 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
906 StackOffset::getFixed(-Residual), Flag, getStackAlign());
907 if (EmitCFI)
908 CFIBuilder.buildDefCFAOffset(RealStackSize);
909
910 if (DynAllocation) {
911 // s[d|w] zero, 0(sp)
912 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
913 .addReg(RISCV::X0)
914 .addReg(SPReg)
915 .addImm(0)
916 .setMIFlags(Flag);
917 }
918 }
919
920 return;
921 }
922
923 // Emit a variable-length allocation probing loop.
924 uint64_t RoundedSize = alignDown(Offset, ProbeSize);
925 uint64_t Residual = Offset - RoundedSize;
926
927 Register TargetReg = findScratchNonCalleeSaveRegister(&MBB, RISCV::X6);
928 assert(TargetReg.isValid() &&
929 "No available scratch register for stack probing");
930 // SUB TargetReg, SP, RoundedSize
931 RI->adjustReg(MBB, MBBI, DL, TargetReg, SPReg,
932 StackOffset::getFixed(-RoundedSize), Flag, getStackAlign());
933
934 if (EmitCFI) {
935 // Set the CFA register to TargetReg.
936 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
937 }
938
939 // It will be expanded to a probe loop in `inlineStackProbe`.
940 BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC)).addReg(TargetReg);
941
942 if (EmitCFI) {
943 // Set the CFA register back to SP.
944 CFIBuilder.buildDefCFARegister(SPReg);
945 }
946
947 if (Residual) {
949 Flag, getStackAlign());
950 if (DynAllocation) {
951 // s[d|w] zero, 0(sp)
952 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
953 .addReg(RISCV::X0)
954 .addReg(SPReg)
955 .addImm(0)
956 .setMIFlags(Flag);
957 }
958 }
959
960 if (EmitCFI)
961 CFIBuilder.buildDefCFAOffset(RealStackSize);
962}
963
964static bool isPush(unsigned Opcode) {
965 switch (Opcode) {
966 case RISCV::CM_PUSH:
967 case RISCV::QC_CM_PUSH:
968 case RISCV::QC_CM_PUSHFP:
969 return true;
970 default:
971 return false;
972 }
973}
974
975static bool isPop(unsigned Opcode) {
976 // There are other pops but these are the only ones introduced during this
977 // pass.
978 switch (Opcode) {
979 case RISCV::CM_POP:
980 case RISCV::QC_CM_POP:
981 return true;
982 default:
983 return false;
984 }
985}
986
988 bool UpdateFP) {
989 switch (Kind) {
991 return RISCV::CM_PUSH;
993 return UpdateFP ? RISCV::QC_CM_PUSHFP : RISCV::QC_CM_PUSH;
994 default:
995 llvm_unreachable("Unhandled PushPopKind");
996 }
997}
998
1000 // There are other pops but they are introduced later by the Push/Pop
1001 // Optimizer.
1002 switch (Kind) {
1004 return RISCV::CM_POP;
1006 return RISCV::QC_CM_POP;
1007 default:
1008 llvm_unreachable("Unhandled PushPopKind");
1009 }
1010}
1011
1013 MachineBasicBlock &MBB) const {
1014 MachineFrameInfo &MFI = MF.getFrameInfo();
1015 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1016 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1018 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1019
1020 Register BPReg = RISCVABI::getBPReg();
1021
1022 // Debug location must be unknown since the first debug location is used
1023 // to determine the end of the prologue.
1024 DebugLoc DL;
1025
1026 // All calls are tail calls in GHC calling conv, and functions have no
1027 // prologue/epilogue.
1029 return;
1030
1031 // SiFive CLIC needs to swap `sp` into `sf.mscratchcsw`
1033
1034 // Emit prologue for shadow call stack.
1035 emitSCSPrologue(MF, MBB, MBBI, DL);
1036
1037 // We keep track of the first instruction because it might be a
1038 // `(QC.)CM.PUSH(FP)`, and we may need to adjust the immediate rather than
1039 // inserting an `addi sp, sp, -N*16`
1040 auto PossiblePush = MBBI;
1041
1042 // Skip past all callee-saved register spill instructions.
1043 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
1044 ++MBBI;
1045
1046 // Determine the correct frame layout
1047 determineFrameLayout(MF);
1048
1049 const auto &CSI = MFI.getCalleeSavedInfo();
1050
1051 // Skip to before the spills of scalar callee-saved registers
1052 // FIXME: assumes exactly one instruction is used to restore each
1053 // callee-saved register.
1054 MBBI = std::prev(
1055 MBBI, getRVVCalleeSavedInfo(MF, CSI).size() +
1056 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1058 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1059
1060 if (unsigned LibCallFrameSize = RVFI->getLibCallStackSize()) {
1061 if (NeedsDwarfCFI) {
1062 CFIBuilder.buildDefCFAOffset(LibCallFrameSize);
1063 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1064 CFIBuilder.buildOffset(CS.getReg(),
1065 MFI.getObjectOffset(CS.getFrameIdx()));
1066 }
1067 }
1068
1069 // FIXME (note copied from Lanai): This appears to be overallocating. Needs
1070 // investigation. Get the number of bytes to allocate from the FrameInfo.
1071 uint64_t RealStackSize = getStackSizeWithRVVPadding(MF);
1072 uint64_t StackSize = RealStackSize - RVFI->getReservedSpillsSize();
1073 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1074
1075 // Early exit if there is no need to allocate on the stack
1076 if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
1077 return;
1078
1079 // If the stack pointer has been marked as reserved, then produce an error if
1080 // the frame requires stack allocation
1081 if (STI.isRegisterReservedByUser(SPReg))
1083 MF.getFunction(), "Stack pointer required, but has been reserved."});
1084
1085 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1086 // Split the SP adjustment to reduce the offsets of callee saved spill.
1087 if (FirstSPAdjustAmount) {
1088 StackSize = FirstSPAdjustAmount;
1089 RealStackSize = FirstSPAdjustAmount;
1090 }
1091
1092 if (RVFI->useQCIInterrupt(MF)) {
1093 // The function starts with `QC.C.MIENTER(.NEST)`, so the `(QC.)CM.PUSH(FP)`
1094 // could only be the next instruction.
1095 ++PossiblePush;
1096
1097 if (NeedsDwarfCFI) {
1098 // Insert the CFI metadata before where we think the `(QC.)CM.PUSH(FP)`
1099 // could be. The PUSH will also get its own CFI metadata for its own
1100 // modifications, which should come after the PUSH.
1101 CFIInstBuilder PushCFIBuilder(MBB, PossiblePush,
1104 for (const CalleeSavedInfo &CS : getQCISavedInfo(MF, CSI))
1105 PushCFIBuilder.buildOffset(CS.getReg(),
1106 MFI.getObjectOffset(CS.getFrameIdx()));
1107 }
1108 }
1109
1110 if (RVFI->isPushable(MF) && PossiblePush != MBB.end() &&
1111 isPush(PossiblePush->getOpcode())) {
1112 // Use available stack adjustment in push instruction to allocate additional
1113 // stack space. Align the stack size down to a multiple of 16. This is
1114 // needed for RVE.
1115 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1116 uint64_t StackAdj =
1117 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1118 PossiblePush->getOperand(1).setImm(StackAdj);
1119 StackSize -= StackAdj;
1120
1121 if (NeedsDwarfCFI) {
1122 CFIBuilder.buildDefCFAOffset(RealStackSize - StackSize);
1123 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1124 CFIBuilder.buildOffset(CS.getReg(),
1125 MFI.getObjectOffset(CS.getFrameIdx()));
1126 }
1127 }
1128
1129 // Allocate space on the stack if necessary.
1130 auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
1131 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
1132 bool NeedProbe = TLI->hasInlineStackProbe(MF);
1133 uint64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
1134 bool DynAllocation =
1135 MF.getInfo<RISCVMachineFunctionInfo>()->hasDynamicAllocation();
1136 if (StackSize != 0)
1137 allocateStack(MBB, MBBI, MF, StackSize, RealStackSize, NeedsDwarfCFI,
1138 NeedProbe, ProbeSize, DynAllocation,
1140
1141 // Save SiFive CLIC CSRs into Stack
1143
1144 // The frame pointer is callee-saved, and code has been generated for us to
1145 // save it to the stack. We need to skip over the storing of callee-saved
1146 // registers as the frame pointer must be modified after it has been saved
1147 // to the stack, not before.
1148 // FIXME: assumes exactly one instruction is used to save each callee-saved
1149 // register.
1150 std::advance(MBBI,
1151 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1152 CFIBuilder.setInsertPoint(MBBI);
1153
1154 // Iterate over list of callee-saved registers and emit .cfi_offset
1155 // directives.
1156 if (NeedsDwarfCFI) {
1157 for (const CalleeSavedInfo &CS :
1158 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS)) {
1159 MCRegister Reg = CS.getReg();
1160 int64_t Offset = MFI.getObjectOffset(CS.getFrameIdx());
1161 // Emit CFI for both sub-registers. The even register is at the base
1162 // offset and odd at base+4.
1163 if (RISCV::GPRPairRegClass.contains(Reg)) {
1164 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1165 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1166 CFIBuilder.buildOffset(EvenReg, Offset);
1167 CFIBuilder.buildOffset(OddReg, Offset + 4);
1168 } else {
1169 CFIBuilder.buildOffset(Reg, Offset);
1170 }
1171 }
1172 }
1173
1174 // Generate new FP.
1175 if (hasFP(MF)) {
1176 if (STI.isRegisterReservedByUser(FPReg))
1178 MF.getFunction(), "Frame pointer required, but has been reserved."});
1179 // The frame pointer does need to be reserved from register allocation.
1180 assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
1181
1182 // Some stack management variants automatically keep FP updated, so we don't
1183 // need an instruction to do so.
1184 if (!RVFI->hasImplicitFPUpdates(MF)) {
1185 RI->adjustReg(
1186 MBB, MBBI, DL, FPReg, SPReg,
1187 StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
1189 }
1190
1191 if (NeedsDwarfCFI)
1192 CFIBuilder.buildDefCFA(FPReg, RVFI->getVarArgsSaveSize());
1193 }
1194
1195 uint64_t SecondSPAdjustAmount = 0;
1196 // Emit the second SP adjustment after saving callee saved registers.
1197 if (FirstSPAdjustAmount) {
1198 SecondSPAdjustAmount = getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1199 assert(SecondSPAdjustAmount > 0 &&
1200 "SecondSPAdjustAmount should be greater than zero");
1201
1202 allocateStack(MBB, MBBI, MF, SecondSPAdjustAmount,
1203 getStackSizeWithRVVPadding(MF), NeedsDwarfCFI && !hasFP(MF),
1204 NeedProbe, ProbeSize, DynAllocation,
1206 }
1207
1208 if (RVVStackSize) {
1209 if (NeedProbe) {
1210 allocateAndProbeStackForRVV(MF, MBB, MBBI, DL, RVVStackSize,
1212 NeedsDwarfCFI && !hasFP(MF), DynAllocation);
1213 } else {
1214 // We must keep the stack pointer aligned through any intermediate
1215 // updates.
1216 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
1217 StackOffset::getScalable(-RVVStackSize),
1219 }
1220
1221 if (NeedsDwarfCFI && !hasFP(MF)) {
1222 // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
1224 *RI, SPReg,
1225 StackOffset::get(getStackSizeWithRVVPadding(MF), RVVStackSize / 8)));
1226 }
1227
1228 std::advance(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1229 if (NeedsDwarfCFI)
1230 emitCalleeSavedRVVPrologCFI(MBB, MBBI, hasFP(MF));
1231 }
1232
1233 if (hasFP(MF)) {
1234 // Realign Stack
1235 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1236 if (RI->hasStackRealignment(MF)) {
1237 Align MaxAlignment = MFI.getMaxAlign();
1238
1239 const RISCVInstrInfo *TII = STI.getInstrInfo();
1240 if (isInt<12>(-(int64_t)MaxAlignment.value())) {
1241 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
1242 .addReg(SPReg)
1243 .addImm(-(int64_t)MaxAlignment.value())
1245 } else {
1246 unsigned ShiftAmount = Log2(MaxAlignment);
1247 Register VR =
1248 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
1249 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
1250 .addReg(SPReg)
1251 .addImm(ShiftAmount)
1253 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
1254 .addReg(VR)
1255 .addImm(ShiftAmount)
1257 }
1258 if (NeedProbe && RVVStackSize == 0) {
1259 // Do a probe if the align + size allocated just passed the probe size
1260 // and was not yet probed.
1261 if (SecondSPAdjustAmount < ProbeSize &&
1262 SecondSPAdjustAmount + MaxAlignment.value() >= ProbeSize) {
1263 bool IsRV64 = STI.is64Bit();
1264 BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
1265 .addReg(RISCV::X0)
1266 .addReg(SPReg)
1267 .addImm(0)
1269 }
1270 }
1271 // FP will be used to restore the frame in the epilogue, so we need
1272 // another base register BP to record SP after re-alignment. SP will
1273 // track the current stack after allocating variable sized objects.
1274 if (hasBP(MF)) {
1275 // move BP, SP
1276 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
1277 .addReg(SPReg)
1278 .addImm(0)
1280 }
1281 }
1282 }
1283}
1284
1285void RISCVFrameLowering::deallocateStack(MachineFunction &MF,
1288 const DebugLoc &DL,
1289 uint64_t &StackSize,
1290 int64_t CFAOffset) const {
1292
1293 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
1295 StackSize = 0;
1296
1297 if (needsDwarfCFI(MF))
1299 .buildDefCFAOffset(CFAOffset);
1300}
1301
1303 MachineBasicBlock &MBB) const {
1304 const RISCVRegisterInfo *RI = STI.getRegisterInfo();
1305 MachineFrameInfo &MFI = MF.getFrameInfo();
1306 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1307 bool PreferAscendingLS = STI.preferAscendingLoadStore();
1308
1309 // All calls are tail calls in GHC calling conv, and functions have no
1310 // prologue/epilogue.
1312 return;
1313
1314 // Get the insert location for the epilogue. If there were no terminators in
1315 // the block, get the last instruction.
1317 DebugLoc DL;
1318 if (!MBB.empty()) {
1319 MBBI = MBB.getLastNonDebugInstr();
1320 if (MBBI != MBB.end())
1321 DL = MBBI->getDebugLoc();
1322
1323 MBBI = MBB.getFirstTerminator();
1324
1325 // Skip to before the restores of all callee-saved registers.
1326 while (MBBI != MBB.begin() &&
1327 std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
1328 --MBBI;
1329 }
1330
1331 const auto &CSI = MFI.getCalleeSavedInfo();
1332
1333 // Skip to before the restores of scalar callee-saved registers
1334 // FIXME: assumes exactly one instruction is used to restore each
1335 // callee-saved register.
1336 auto FirstScalarCSRRestoreInsn =
1337 std::next(MBBI, getRVVCalleeSavedInfo(MF, CSI).size());
1338 CFIInstBuilder CFIBuilder(MBB, FirstScalarCSRRestoreInsn,
1340 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1341
1342 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1343 uint64_t RealStackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1345 uint64_t StackSize = FirstSPAdjustAmount ? FirstSPAdjustAmount
1347 RVFI->getReservedSpillsSize();
1348 uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
1349 uint64_t RVVStackSize = RVFI->getRVVStackSize();
1350
1351 bool RestoreSPFromFP = RI->hasStackRealignment(MF) ||
1353 if (RVVStackSize) {
1354 // If RestoreSPFromFP the stack pointer will be restored using the frame
1355 // pointer value.
1356 if (!RestoreSPFromFP)
1357 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1358 StackOffset::getScalable(RVVStackSize),
1360
1361 if (NeedsDwarfCFI) {
1362 if (!hasFP(MF))
1363 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1364 emitCalleeSavedRVVEpilogCFI(MBB, FirstScalarCSRRestoreInsn);
1365 }
1366 }
1367
1368 if (FirstSPAdjustAmount) {
1369 uint64_t SecondSPAdjustAmount =
1370 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
1371 assert(SecondSPAdjustAmount > 0 &&
1372 "SecondSPAdjustAmount should be greater than zero");
1373
1374 // If RestoreSPFromFP the stack pointer will be restored using the frame
1375 // pointer value.
1376 if (!RestoreSPFromFP)
1377 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, SPReg,
1378 StackOffset::getFixed(SecondSPAdjustAmount),
1380
1381 if (NeedsDwarfCFI && !hasFP(MF))
1382 CFIBuilder.buildDefCFAOffset(FirstSPAdjustAmount);
1383 }
1384
1385 // Restore the stack pointer using the value of the frame pointer. Only
1386 // necessary if the stack pointer was modified, meaning the stack size is
1387 // unknown.
1388 //
1389 // In order to make sure the stack point is right through the EH region,
1390 // we also need to restore stack pointer from the frame pointer if we
1391 // don't preserve stack space within prologue/epilogue for outgoing variables,
1392 // normally it's just checking the variable sized object is present or not
1393 // is enough, but we also don't preserve that at prologue/epilogue when
1394 // have vector objects in stack.
1395 if (RestoreSPFromFP) {
1396 assert(hasFP(MF) && "frame pointer should not have been eliminated");
1397 RI->adjustReg(MBB, FirstScalarCSRRestoreInsn, DL, SPReg, FPReg,
1399 getStackAlign());
1400 }
1401
1402 if (NeedsDwarfCFI && hasFP(MF))
1403 CFIBuilder.buildDefCFA(SPReg, RealStackSize);
1404
1405 // Skip to after the restores of scalar callee-saved registers
1406 // FIXME: assumes exactly one instruction is used to restore each
1407 // callee-saved register.
1408 MBBI = std::next(FirstScalarCSRRestoreInsn,
1409 getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS).size());
1410 CFIBuilder.setInsertPoint(MBBI);
1411 emitSiFiveCLICPreemptibleRestores(MF, MBB, MBBI, CFIBuilder, DL);
1412
1413 auto emitRestoreCFI = [&](auto CSInfo) {
1414 for (auto &CS : CSInfo) {
1415 MCRegister Reg = CS.getReg();
1416 // Emit CFI for both sub-registers.
1417 if (RISCV::GPRPairRegClass.contains(Reg)) {
1418 MCRegister EvenReg = RI->getSubReg(Reg, RISCV::sub_gpr_even);
1419 MCRegister OddReg = RI->getSubReg(Reg, RISCV::sub_gpr_odd);
1420 CFIBuilder.buildRestore(EvenReg);
1421 CFIBuilder.buildRestore(OddReg);
1422 } else {
1423 CFIBuilder.buildRestore(Reg);
1424 }
1425 }
1426 };
1427
1428 if (RVFI->useSaveRestoreLibCalls(MF)) {
1429 if (RVFI->hasShadowStack(MF)) {
1430 // We don't use `__riscv_restore_<N>` to restore in this case, so we need
1431 // to make sure we're correctly accounting for the stack deallocation we
1432 // need to do, which now must include the allocation made by
1433 // `__riscv_save_<N>`.
1434 StackSize += RVFI->getLibCallStackSize();
1435
1438 MBBI = std::next(MBBI, LibcallCSI.size());
1439 CFIBuilder.setInsertPoint(MBBI);
1440
1441 if (NeedsDwarfCFI)
1442 emitRestoreCFI(LibcallCSI);
1443 } else {
1444 // tail __riscv_restore_[0-12] instruction is considered as a terminator,
1445 // therefore it is unnecessary to place any CFI instructions after it.
1446 // Just deallocate stack if needed and return.
1447 if (StackSize != 0)
1448 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1449 RVFI->getLibCallStackSize());
1450
1451 // Emit epilogue for shadow call stack.
1452 emitSCSEpilogue(MF, MBB, MBBI, DL);
1453 return;
1454 }
1455 }
1456
1457 // Recover callee-saved registers.
1458 if (NeedsDwarfCFI)
1459 emitRestoreCFI(getUnmanagedInterruptCSI(MF, CSI, PreferAscendingLS));
1460
1461 if (RVFI->isPushable(MF) && MBBI != MBB.end() && isPop(MBBI->getOpcode())) {
1462 // Use available stack adjustment in pop instruction to deallocate stack
1463 // space. Align the stack size down to a multiple of 16. This is needed for
1464 // RVE.
1465 // FIXME: Can we increase the stack size to a multiple of 16 instead?
1466 uint64_t StackAdj =
1467 std::min(alignDown(StackSize, 16), static_cast<uint64_t>(48));
1468 MBBI->getOperand(1).setImm(StackAdj);
1469 StackSize -= StackAdj;
1470
1471 if (StackSize != 0)
1472 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1473 /*stack_adj of cm.pop instr*/ RealStackSize - StackSize);
1474
1475 auto NextI = next_nodbg(MBBI, MBB.end());
1476 if (NextI == MBB.end() || NextI->getOpcode() != RISCV::PseudoRET) {
1477 ++MBBI;
1478 if (NeedsDwarfCFI) {
1479 CFIBuilder.setInsertPoint(MBBI);
1480
1481 for (const CalleeSavedInfo &CS : getPushOrLibCallsSavedInfo(MF, CSI))
1482 CFIBuilder.buildRestore(CS.getReg());
1483
1484 // Update CFA Offset. If this is a QCI interrupt function, there will
1485 // be a leftover offset which is deallocated by `QC.C.MILEAVERET`,
1486 // otherwise getQCIInterruptStackSize() will be 0.
1487 CFIBuilder.buildDefCFAOffset(RVFI->getQCIInterruptStackSize());
1488 }
1489 }
1490 }
1491
1492 // Deallocate stack if StackSize isn't a zero yet. If this is a QCI interrupt
1493 // function, there will be a leftover offset which is deallocated by
1494 // `QC.C.MILEAVERET`, otherwise getQCIInterruptStackSize() will be 0.
1495 if (StackSize != 0)
1496 deallocateStack(MF, MBB, MBBI, DL, StackSize,
1497 RVFI->getQCIInterruptStackSize());
1498
1499 // Emit epilogue for shadow call stack.
1500 emitSCSEpilogue(MF, MBB, MBBI, DL);
1501
1502 // SiFive CLIC needs to swap `sf.mscratchcsw` into `sp`
1504}
1505
1507 MCRegister Reg) {
1508 if (RISCV::GPRRegClass.contains(Reg))
1509 return Reg;
1510
1511 std::array<TargetRegisterClass const *, 2> RegisterClasses = {
1512 &RISCV::GPRF16RegClass, &RISCV::GPRF32RegClass};
1513 std::array<unsigned, 2> SubIdx = {RISCV::sub_16, RISCV::sub_32};
1514
1515 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1516 if (RegClass->contains(Reg)) {
1517 if (MCRegister Super =
1518 TRI.getMatchingSuperReg(Reg, SubReg, &RISCV::GPRRegClass))
1519 return Super;
1520 }
1521 }
1522
1524 "getPhysicalGPR called with unsupported register");
1525}
1526
1528 const TargetRegisterInfo &TRI,
1529 MCRegister Reg) {
1530 if (!STI.hasStdExtF())
1531 return MCRegister();
1532
1533 TargetRegisterClass const *LargestFPRegClass = STI.getLargestFPRegClass();
1534 assert(LargestFPRegClass);
1535
1536 if (LargestFPRegClass->contains(Reg))
1537 return Reg;
1538
1539 std::array<TargetRegisterClass const *, 3> RegisterClasses = {
1540 &RISCV::FPR16RegClass, &RISCV::FPR32RegClass, &RISCV::FPR64RegClass};
1541 std::array<unsigned, 3> SubIdx = {RISCV::sub_16, RISCV::sub_32,
1542 RISCV::sub_64};
1543
1544 for (auto [RegClass, SubReg] : zip(RegisterClasses, SubIdx)) {
1545 if (RegClass->contains(Reg)) {
1546 if (MCRegister Super =
1547 TRI.getMatchingSuperReg(Reg, SubReg, LargestFPRegClass))
1548 return Super;
1549 }
1550 }
1551
1552 // Reg is bigger than what's currently available for the target, we can ignore
1553 // it.
1554 return MCRegister();
1555}
1556
1557void RISCVFrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
1559 RegScavenger *RS) const {
1560 // Insertion point.
1562
1563 // Fake a debug loc.
1564 DebugLoc DL;
1565 if (MBBI != MBB.end())
1566 DL = MBBI->getDebugLoc();
1567
1568 const MachineFunction &MF = *MBB.getParent();
1569 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1570 const RISCVInstrInfo &TII = *STI.getInstrInfo();
1571
1572 BitVector FinalRegsToZero(TRI.getNumRegs());
1573
1574 bool HasVRegister = false;
1575
1576 for (MCRegister Reg : RegsToZero.set_bits()) {
1577 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1578 FinalRegsToZero.set(getPhysicalGPR(TRI, Reg).id());
1579 } else if (RISCV::GPRPairRegClass.contains(Reg)) {
1580 FinalRegsToZero.set(
1581 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_even)).id());
1582 FinalRegsToZero.set(
1583 getPhysicalGPR(TRI, TRI.getSubReg(Reg, RISCV::sub_gpr_odd)).id());
1584 } else if (TRI.isFPRegister(Reg)) {
1585 if (MCRegister MaybeReg = getLargestFPRegisterOrZero(STI, TRI, Reg))
1586 FinalRegsToZero.set(MaybeReg.id());
1588 TRI.getMinimalPhysRegClass(Reg))) {
1589 if (!STI.hasVInstructions())
1590 continue;
1591 HasVRegister = true;
1592
1593 for (MCRegister SubReg : TRI.subregs_inclusive(Reg)) {
1594 if (TRI.subregs(SubReg).empty())
1595 FinalRegsToZero.set(SubReg.id());
1596 }
1597 }
1598 }
1599
1600 if (HasVRegister) {
1601 RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(1, /*Fractional=*/false);
1602 unsigned VTypeImm = RISCVVType::encodeVTYPE(
1603 VLMUL, /*SEW=*/32, /*TailAgnostic=*/true, /*MaskAgnostic=*/true);
1604
1605 MCRegister TemporaryReg = RISCV::NoRegister;
1606 for (MCRegister Reg : FinalRegsToZero.set_bits()) {
1607 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
1608 TemporaryReg = Reg;
1609 break;
1610 }
1611 }
1612
1613 if (TemporaryReg == RISCV::NoRegister) {
1614 RS->enterBasicBlockEnd(MBB);
1615 TemporaryReg = RS->scavengeRegisterBackwards(RISCV::GPRRegClass, MBBI,
1616 /*RestoreAfter=*/false,
1617 /*SPAdj=*/0);
1618 }
1619
1620 if (MBB.getParent()
1621 ->getFunction()
1622 .getFnAttribute("zero-call-used-regs")
1623 .getValueAsString() == "used")
1624 FinalRegsToZero.set(TemporaryReg.id());
1625
1626 BuildMI(MBB, MBBI, DL, TII.get(RISCV::VSETVLI), TemporaryReg)
1627 .addReg(RISCV::X0)
1628 .addImm(VTypeImm)
1629 .addReg(RISCV::VL, RegState::ImplicitDefine)
1630 .addReg(RISCV::VTYPE, RegState::ImplicitDefine);
1631 }
1632
1633 for (MCRegister Reg : FinalRegsToZero.set_bits())
1634 TII.buildClearRegister(Reg, MBB, MBBI, DL);
1635}
1636
1639 Register &FrameReg) const {
1640 const MachineFrameInfo &MFI = MF.getFrameInfo();
1642 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1643
1644 // Callee-saved registers should be referenced relative to the stack
1645 // pointer (positive offset), otherwise use the frame pointer (negative
1646 // offset).
1647 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo(),
1648 STI.preferAscendingLoadStore());
1649 int MinCSFI = 0;
1650 int MaxCSFI = -1;
1652 auto StackID = MFI.getStackID(FI);
1653
1654 assert((StackID == TargetStackID::Default ||
1655 StackID == TargetStackID::ScalableVector) &&
1656 "Unexpected stack ID for the frame object.");
1657 if (StackID == TargetStackID::Default) {
1658 assert(getOffsetOfLocalArea() == 0 && "LocalAreaOffset is not 0!");
1660 MFI.getOffsetAdjustment());
1661 } else if (StackID == TargetStackID::ScalableVector) {
1663 }
1664
1665 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
1666
1667 if (CSI.size()) {
1668 MinCSFI = std::min(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1669 MaxCSFI = std::max(CSI.front().getFrameIdx(), CSI.back().getFrameIdx());
1670 }
1671
1672 auto FIIsCalleeSave = [&](const CalleeSavedInfo &CS) -> bool {
1673 return FI == CS.getFrameIdx();
1674 };
1675
1676 bool IsInterruptCSR = RVFI->isSiFivePreemptibleInterrupt(MF) &&
1677 (FI == RVFI->getInterruptCSRFrameIndex(0) ||
1678 FI == RVFI->getInterruptCSRFrameIndex(1));
1679 bool IsInlineRestoredLibcallCSR = llvm::any_of(
1680 getPushOrLibCallsSavedInfo(MF, MFI.getCalleeSavedInfo()), FIIsCalleeSave);
1681 if ((FI >= MinCSFI && FI <= MaxCSFI) || IsInterruptCSR ||
1682 IsInlineRestoredLibcallCSR) {
1683 FrameReg = SPReg;
1684
1685 if (FirstSPAdjustAmount)
1686 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
1687 else
1689 return Offset;
1690 }
1691
1692 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
1693 // If the stack was realigned, the frame pointer is set in order to allow
1694 // SP to be restored, so we need another base register to record the stack
1695 // after realignment.
1696 // |--------------------------| --
1697 // | callee-allocated save | | <----|
1698 // | area for register varargs| | |
1699 // |--------------------------| <-- FP |
1700 // | callee-saved registers | | |
1701 // |--------------------------| -- |
1702 // | realignment (the size of | | |
1703 // | this area is not counted | | |
1704 // | in MFI.getStackSize()) | | |
1705 // |--------------------------| -- |-- MFI.getStackSize()
1706 // | RVV alignment padding | | |
1707 // | (not counted in | | |
1708 // | MFI.getStackSize() but | | |
1709 // | counted in | | |
1710 // | RVFI.getRVVStackSize()) | | |
1711 // |--------------------------| -- |
1712 // | RVV objects | | |
1713 // | (not counted in | | |
1714 // | MFI.getStackSize()) | | |
1715 // |--------------------------| -- |
1716 // | padding before RVV | | |
1717 // | (not counted in | | |
1718 // | MFI.getStackSize() or in | | |
1719 // | RVFI.getRVVStackSize()) | | |
1720 // |--------------------------| -- |
1721 // | scalar local variables | | <----'
1722 // |--------------------------| -- <-- BP (if var sized objects present)
1723 // | VarSize objects | |
1724 // |--------------------------| -- <-- SP
1725 if (hasBP(MF)) {
1726 FrameReg = RISCVABI::getBPReg();
1727 } else {
1728 // VarSize objects must be empty in this case!
1729 assert(!MFI.hasVarSizedObjects());
1730 FrameReg = SPReg;
1731 }
1732 } else if (!RI->hasStackRealignment(MF)) {
1733 // Note: Keeping the following as multiple 'if' statements rather than
1734 // merging to a single expression for readability.
1735 if (!hasFP(MF)) {
1736 // No FP available, must use SP.
1737 FrameReg = SPReg;
1738 } else {
1739 FrameReg = FPReg;
1740 // SP-relative addressing is only valid when SP is stable throughout
1741 // the function body: no dynamic SP adjustments for outgoing call args,
1742 // no variable-sized objects, and no RVV scalable stack regions.
1743 // hasReservedCallFrame() conservatively encompasses all these checks.
1744 if (hasReservedCallFrame(MF)) {
1745 // Both FP and SP are candidates.
1746 // Prefer SP when the SP-relative offset fits in the compressed
1747 // instruction immediate range.
1748 int64_t SPOff = Offset.getFixed() + MFI.getStackSize();
1749 int64_t CLWSPMaxOffset = 252;
1750 int64_t CLDSPMaxOffset = 504;
1751 int64_t SPThreshold = STI.is64Bit() ? CLDSPMaxOffset : CLWSPMaxOffset;
1752 if (SPOff >= 0 && SPOff <= SPThreshold)
1753 FrameReg = SPReg;
1754 }
1755 }
1756 } else {
1757 assert(RI->hasStackRealignment(MF) && MFI.isFixedObjectIndex(FI) &&
1758 "Expected fixed object with stack realignment");
1759 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1760 FrameReg = FPReg;
1761 }
1762
1763 if (FrameReg == FPReg) {
1764 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
1765 // When using FP to access scalable vector objects, we need to minus
1766 // the frame size.
1767 //
1768 // |--------------------------| --
1769 // | callee-allocated save | |
1770 // | area for register varargs| |
1771 // |--------------------------| | -- <-- FP
1772 // | callee-saved registers | |
1773 // |--------------------------| | MFI.getStackSize()
1774 // | scalar local variables | |
1775 // |--------------------------| -- (Offset of RVV objects is from here.)
1776 // | RVV objects |
1777 // |--------------------------|
1778 // | VarSize objects |
1779 // |--------------------------| <-- SP
1780 if (StackID == TargetStackID::ScalableVector) {
1781 assert(!RI->hasStackRealignment(MF) &&
1782 "Can't index across variable sized realign");
1783 // We don't expect any extra RVV alignment padding, as the stack size
1784 // and RVV object sections should be correct aligned in their own
1785 // right.
1787 "Inconsistent stack layout");
1789 }
1790 return Offset;
1791 }
1792
1793 // This case handles indexing off both SP and BP.
1794 // If indexing off SP, there must not be any var sized objects
1795 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
1796
1797 // When using SP to access frame objects, we need to add RVV stack size.
1798 //
1799 // |--------------------------| --
1800 // | callee-allocated save | | <----|
1801 // | area for register varargs| | |
1802 // |--------------------------| | | <-- FP
1803 // | callee-saved registers | | |
1804 // |--------------------------| -- |
1805 // | RVV alignment padding | | |
1806 // | (not counted in | | |
1807 // | MFI.getStackSize() but | | |
1808 // | counted in | | |
1809 // | RVFI.getRVVStackSize()) | | |
1810 // |--------------------------| -- |
1811 // | RVV objects | | |-- MFI.getStackSize()
1812 // | (not counted in | | |
1813 // | MFI.getStackSize()) | | |
1814 // |--------------------------| -- |
1815 // | padding before RVV | | |
1816 // | (not counted in | | |
1817 // | MFI.getStackSize()) | | |
1818 // |--------------------------| -- |
1819 // | scalar local variables | | <----'
1820 // |--------------------------| -- <-- BP (if var sized objects present)
1821 // | VarSize objects | |
1822 // |--------------------------| -- <-- SP
1823 //
1824 // The total amount of padding surrounding RVV objects is described by
1825 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
1826 // objects to the required alignment.
1827 if (MFI.getStackID(FI) == TargetStackID::Default) {
1828 if (MFI.isFixedObjectIndex(FI)) {
1829 assert(!RI->hasStackRealignment(MF) &&
1830 "Can't index across variable sized realign");
1832 RVFI->getRVVStackSize());
1833 } else {
1835 }
1836 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
1837 // Ensure the base of the RVV stack is correctly aligned: add on the
1838 // alignment padding.
1839 int64_t ScalarLocalVarSize =
1840 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
1841 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
1842 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
1843 }
1844 return Offset;
1845}
1846
1848 const Register &Reg) {
1849 MCRegister BaseReg = TRI.getSubReg(Reg, RISCV::sub_vrm1_0);
1850 // If it's not a grouped vector register, it doesn't have subregister, so
1851 // the base register is just itself.
1852 if (!BaseReg.isValid())
1853 BaseReg = Reg;
1854 return BaseReg;
1855}
1856
1858 BitVector &SavedRegs,
1859 RegScavenger *RS) const {
1861
1862 // In TargetFrameLowering::determineCalleeSaves, any vector register is marked
1863 // as saved if any of its subregister is clobbered, this is not correct in
1864 // vector registers. We only want the vector register to be marked as saved
1865 // if all of its subregisters are clobbered.
1866 // For example:
1867 // Original behavior: If v24 is marked, v24m2, v24m4, v24m8 are also marked.
1868 // Correct behavior: v24m2 is marked only if v24 and v25 are marked.
1869 MachineRegisterInfo &MRI = MF.getRegInfo();
1870 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1871 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
1872 for (unsigned i = 0; CSRegs[i]; ++i) {
1873 unsigned CSReg = CSRegs[i];
1874 // Only vector registers need special care.
1875 if (!RISCV::VRRegClass.contains(getRVVBaseRegister(TRI, CSReg)))
1876 continue;
1877
1878 SavedRegs.reset(CSReg);
1879
1880 auto SubRegs = TRI.subregs(CSReg);
1881 // Set the register and all its subregisters.
1882 if (!MRI.def_empty(CSReg) || MRI.getUsedPhysRegsMask().test(CSReg)) {
1883 SavedRegs.set(CSReg);
1884 for (unsigned Reg : SubRegs)
1885 SavedRegs.set(Reg);
1886 }
1887
1888 }
1889
1890 // Unconditionally spill RA and FP only if the function uses a frame
1891 // pointer.
1892 if (hasFP(MF)) {
1893 SavedRegs.set(RAReg);
1894 SavedRegs.set(FPReg);
1895 }
1896 // Mark BP as used if function has dedicated base pointer.
1897 if (hasBP(MF))
1898 SavedRegs.set(RISCVABI::getBPReg());
1899
1900 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1901 // X5 is used as a temporary for saving and restoring `mcause` and `mepc`.
1902 if (RVFI->isSiFivePreemptibleInterrupt(MF))
1903 SavedRegs.set(RISCV::X5);
1904
1905 // When using cm.push/pop we must save X27 if we save X26.
1906 if (RVFI->isPushable(MF) && SavedRegs.test(RISCV::X26))
1907 SavedRegs.set(RISCV::X27);
1908
1909 // For Zilsd on RV32, append GPRPair registers to the CSR list. This prevents
1910 // the need to create register sets for each abi which is a lot more complex.
1911 // Don't use Zilsd for callee-saved coalescing if the required alignment
1912 // exceeds the stack alignment or when Zcmp/Xqccmp or save/restore libcalls
1913 // are enabled.
1914 bool UseZilsd = !STI.is64Bit() && STI.hasStdExtZilsd() &&
1915 STI.getZilsdAlign() <= getStackAlign() &&
1916 !RVFI->isPushable(MF) && !RVFI->useSaveRestoreLibCalls(MF);
1917 if (UseZilsd) {
1920 for (unsigned i = 0; CSRegs[i]; ++i) {
1921 NewCSRs.push_back(CSRegs[i]);
1922 CSRSet.insert(CSRegs[i]);
1923 }
1924
1925 // Append GPRPair registers for pairs where both sub-registers are in CSR
1926 // list. Iterate through all GPRPairs and check if both sub-regs are CSRs.
1927 for (MCPhysReg Pair : RISCV::GPRPairRegClass) {
1928 // Do not append a pair that's already in the CSR list.
1929 if (CSRSet.contains(Pair))
1930 continue;
1931 MCRegister EvenReg = TRI.getSubReg(Pair, RISCV::sub_gpr_even);
1932 MCRegister OddReg = TRI.getSubReg(Pair, RISCV::sub_gpr_odd);
1933 if (CSRSet.contains(EvenReg.id()) && CSRSet.contains(OddReg.id())) {
1934 NewCSRs.push_back(Pair);
1935 CSRSet.insert(Pair);
1936 }
1937 }
1938
1939 MRI.setCalleeSavedRegs(NewCSRs);
1940 CSRegs = MRI.getCalleeSavedRegs();
1941 }
1942
1943 // Check if all subregisters are marked for saving. If so, set the super
1944 // register bit. For GPRPair, only check sub_gpr_even and sub_gpr_odd, not
1945 // aliases like X8_W or X8_H which are not set in SavedRegs.
1946 for (unsigned i = 0; CSRegs[i]; ++i) {
1947 MCRegister CSReg = CSRegs[i];
1948 bool CombineToSuperReg;
1949 if (RISCV::GPRPairRegClass.contains(CSReg)) {
1950 MCRegister EvenReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_even);
1951 MCRegister OddReg = TRI.getSubReg(CSReg, RISCV::sub_gpr_odd);
1952 CombineToSuperReg =
1953 SavedRegs.test(EvenReg.id()) && SavedRegs.test(OddReg.id());
1954 // If s0(x8) is used as FP we can't generate load/store pair because it
1955 // breaks the frame chain.
1956 if (hasFP(MF) && CSReg == RISCV::X8_X9)
1957 CombineToSuperReg = false;
1958 } else {
1959 auto SubRegs = TRI.subregs(CSReg);
1960 CombineToSuperReg =
1961 !SubRegs.empty() && llvm::all_of(SubRegs, [&](unsigned Reg) {
1962 return SavedRegs.test(Reg);
1963 });
1964 }
1965
1966 if (CombineToSuperReg)
1967 SavedRegs.set(CSReg);
1968 }
1969
1970 // SiFive Preemptible Interrupt Handlers need additional frame entries
1972}
1973
1974std::pair<int64_t, Align>
1975RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
1976 MachineFrameInfo &MFI = MF.getFrameInfo();
1977 // Create a buffer of RVV objects to allocate.
1978 SmallVector<int, 8> ObjectsToAllocate;
1979 auto pushRVVObjects = [&](int FIBegin, int FIEnd) {
1980 for (int I = FIBegin, E = FIEnd; I != E; ++I) {
1981 unsigned StackID = MFI.getStackID(I);
1982 if (StackID != TargetStackID::ScalableVector)
1983 continue;
1984 if (MFI.isDeadObjectIndex(I))
1985 continue;
1986
1987 ObjectsToAllocate.push_back(I);
1988 }
1989 };
1990 // First push RVV Callee Saved object, then push RVV stack object
1991 std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
1992 const auto &RVVCSI = getRVVCalleeSavedInfo(MF, CSI);
1993 if (!RVVCSI.empty())
1994 pushRVVObjects(RVVCSI[0].getFrameIdx(),
1995 RVVCSI[RVVCSI.size() - 1].getFrameIdx() + 1);
1996 pushRVVObjects(0, MFI.getObjectIndexEnd() - RVVCSI.size());
1997
1998 // The minimum alignment is 16 bytes.
1999 Align RVVStackAlign(16);
2000 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
2001
2002 if (!ST.hasVInstructions()) {
2003 assert(ObjectsToAllocate.empty() &&
2004 "Can't allocate scalable-vector objects without V instructions");
2005 return std::make_pair(0, RVVStackAlign);
2006 }
2007
2008 // Allocate all RVV locals and spills
2009 int64_t Offset = 0;
2010 for (int FI : ObjectsToAllocate) {
2011 // ObjectSize in bytes.
2012 int64_t ObjectSize = MFI.getObjectSize(FI);
2013 auto ObjectAlign =
2014 std::max(Align(RISCV::RVVBytesPerBlock), MFI.getObjectAlign(FI));
2015 // If the data type is the fractional vector type, reserve one vector
2016 // register for it.
2017 if (ObjectSize < RISCV::RVVBytesPerBlock)
2018 ObjectSize = RISCV::RVVBytesPerBlock;
2019 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
2020 MFI.setObjectOffset(FI, -Offset);
2021 // Update the maximum alignment of the RVV stack section
2022 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
2023 }
2024
2025 uint64_t StackSize = Offset;
2026
2027 // Ensure the alignment of the RVV stack. Since we want the most-aligned
2028 // object right at the bottom (i.e., any padding at the top of the frame),
2029 // readjust all RVV objects down by the alignment padding.
2030 // Stack size and offsets are multiples of vscale, stack alignment is in
2031 // bytes, we can divide stack alignment by minimum vscale to get a maximum
2032 // stack alignment multiple of vscale.
2033 auto VScale =
2034 std::max<uint64_t>(ST.getRealMinVLen() / RISCV::RVVBitsPerBlock, 1);
2035 if (auto RVVStackAlignVScale = RVVStackAlign.value() / VScale) {
2036 if (auto AlignmentPadding =
2037 offsetToAlignment(StackSize, Align(RVVStackAlignVScale))) {
2038 StackSize += AlignmentPadding;
2039 for (int FI : ObjectsToAllocate)
2040 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
2041 }
2042 }
2043
2044 return std::make_pair(StackSize, RVVStackAlign);
2045}
2046
2048 // For RVV spill, scalable stack offsets computing requires up to two scratch
2049 // registers
2050 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
2051
2052 // For RVV spill, non-scalable stack offsets computing requires up to one
2053 // scratch register.
2054 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
2055
2056 // ADDI instruction's destination register can be used for computing
2057 // offsets. So Scalable stack offsets require up to one scratch register.
2058 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
2059
2060 static constexpr unsigned MaxScavSlotsNumKnown =
2061 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
2062 ScavSlotsNumRVVSpillNonScalableObject});
2063
2064 unsigned MaxScavSlotsNum = 0;
2066 return false;
2067 for (const MachineBasicBlock &MBB : MF)
2068 for (const MachineInstr &MI : MBB) {
2069 bool IsRVVSpill = RISCV::isRVVSpill(MI);
2070 for (auto &MO : MI.operands()) {
2071 if (!MO.isFI())
2072 continue;
2073 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
2075 if (IsRVVSpill) {
2076 MaxScavSlotsNum = std::max(
2077 MaxScavSlotsNum, IsScalableVectorID
2078 ? ScavSlotsNumRVVSpillScalableObject
2079 : ScavSlotsNumRVVSpillNonScalableObject);
2080 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
2081 MaxScavSlotsNum =
2082 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
2083 }
2084 }
2085 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
2086 return MaxScavSlotsNumKnown;
2087 }
2088 return MaxScavSlotsNum;
2089}
2090
2091static bool hasRVVFrameObject(const MachineFunction &MF) {
2092 // Originally, the function will scan all the stack objects to check whether
2093 // if there is any scalable vector object on the stack or not. However, it
2094 // causes errors in the register allocator. In issue 53016, it returns false
2095 // before RA because there is no RVV stack objects. After RA, it returns true
2096 // because there are spilling slots for RVV values during RA. It will not
2097 // reserve BP during register allocation and generate BP access in the PEI
2098 // pass due to the inconsistent behavior of the function.
2099 //
2100 // The function is changed to use hasVInstructions() as the return value. It
2101 // is not precise, but it can make the register allocation correct.
2102 //
2103 // FIXME: Find a better way to make the decision or revisit the solution in
2104 // D103622.
2105 //
2106 // Refer to https://github.com/llvm/llvm-project/issues/53016.
2107 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
2108}
2109
2111 const RISCVInstrInfo &TII) {
2112 unsigned FnSize = 0;
2113 for (auto &MBB : MF) {
2114 for (auto &MI : MBB) {
2115 // Far branches over 20-bit offset will be relaxed in branch relaxation
2116 // pass. In the worst case, conditional branches will be relaxed into
2117 // the following instruction sequence. Unconditional branches are
2118 // relaxed in the same way, with the exception that there is no first
2119 // branch instruction.
2120 //
2121 // foo
2122 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
2123 // sd s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2124 // jump .restore, s11 # 8 bytes
2125 // .rev_cond
2126 // bar
2127 // j .dest_bb # 4 bytes, or 2 bytes with Zca
2128 // .restore:
2129 // ld s11, 0(sp) # 4 bytes, or 2 bytes with Zca
2130 // .dest:
2131 // baz
2132 if (MI.isConditionalBranch())
2133 FnSize += TII.getInstSizeInBytes(MI);
2134 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
2135 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtZca())
2136 FnSize += 2 + 8 + 2 + 2;
2137 else
2138 FnSize += 4 + 8 + 4 + 4;
2139 continue;
2140 }
2141
2142 FnSize += TII.getInstSizeInBytes(MI);
2143 }
2144 }
2145 return FnSize;
2146}
2147
2149 MachineFunction &MF, RegScavenger *RS) const {
2150 const RISCVRegisterInfo *RegInfo =
2151 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
2152 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
2153 MachineFrameInfo &MFI = MF.getFrameInfo();
2154 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
2155 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2156
2157 int64_t RVVStackSize;
2158 Align RVVStackAlign;
2159 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
2160
2161 RVFI->setRVVStackSize(RVVStackSize);
2162 RVFI->setRVVStackAlign(RVVStackAlign);
2163
2164 if (hasRVVFrameObject(MF)) {
2165 // Ensure the entire stack is aligned to at least the RVV requirement: some
2166 // scalable-vector object alignments are not considered by the
2167 // target-independent code.
2168 MFI.ensureMaxAlignment(RVVStackAlign);
2169 }
2170
2171 unsigned ScavSlotsNum = 0;
2172
2173 // estimateStackSize has been observed to under-estimate the final stack
2174 // size, so give ourselves wiggle-room by checking for stack size
2175 // representable an 11-bit signed field rather than 12-bits.
2176 if (!isInt<11>(MFI.estimateStackSize(MF)))
2177 ScavSlotsNum = 1;
2178
2179 // Far branches over 20-bit offset require a spill slot for scratch register.
2180 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
2181 if (IsLargeFunction)
2182 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
2183
2184 // RVV loads & stores have no capacity to hold the immediate address offsets
2185 // so we must always reserve an emergency spill slot if the MachineFunction
2186 // contains any RVV spills.
2187 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
2188
2189 for (unsigned I = 0; I < ScavSlotsNum; I++) {
2190 int FI = MFI.CreateSpillStackObject(RegInfo->getSpillSize(*RC),
2191 RegInfo->getSpillAlign(*RC));
2192 RS->addScavengingFrameIndex(FI);
2193
2194 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
2195 RVFI->setBranchRelaxationScratchFrameIndex(FI);
2196 }
2197
2198 unsigned Size = RVFI->getReservedSpillsSize();
2199 for (const auto &Info : MFI.getCalleeSavedInfo()) {
2200 int FrameIdx = Info.getFrameIdx();
2201 if (FrameIdx < 0 || MFI.getStackID(FrameIdx) != TargetStackID::Default)
2202 continue;
2203
2204 Size += MFI.getObjectSize(FrameIdx);
2205 }
2206 RVFI->setCalleeSavedStackSize(Size);
2207}
2208
2209// Not preserve stack space within prologue for outgoing variables when the
2210// function contains variable size objects or there are vector objects accessed
2211// by the frame pointer.
2212// Let eliminateCallFramePseudoInstr preserve stack space for it.
2214 return !MF.getFrameInfo().hasVarSizedObjects() &&
2215 !(hasFP(MF) && hasRVVFrameObject(MF));
2216}
2217
2218// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
2222 DebugLoc DL = MI->getDebugLoc();
2223
2224 if (!hasReservedCallFrame(MF)) {
2225 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
2226 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
2227 // pointer. This is necessary when there is a variable length stack
2228 // allocation (e.g. alloca), which means it's not possible to allocate
2229 // space for outgoing arguments from within the function prologue.
2230 int64_t Amount = MI->getOperand(0).getImm();
2231
2232 if (Amount != 0) {
2233 // Ensure the stack remains aligned after adjustment.
2234 Amount = alignSPAdjust(Amount);
2235
2236 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
2237 Amount = -Amount;
2238
2239 const RISCVTargetLowering *TLI =
2240 MF.getSubtarget<RISCVSubtarget>().getTargetLowering();
2241 int64_t ProbeSize = TLI->getStackProbeSize(MF, getStackAlign());
2242 if (TLI->hasInlineStackProbe(MF) && -Amount >= ProbeSize) {
2243 // When stack probing is enabled, the decrement of SP may need to be
2244 // probed. We can handle both the decrement and the probing in
2245 // allocateStack.
2246 bool DynAllocation =
2247 MF.getInfo<RISCVMachineFunctionInfo>()->hasDynamicAllocation();
2248 allocateStack(MBB, MI, MF, -Amount, -Amount,
2249 needsDwarfCFI(MF) && !hasFP(MF),
2250 /*NeedProbe=*/true, ProbeSize, DynAllocation,
2252 inlineStackProbe(MF, MBB);
2253 } else {
2254 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
2257 }
2258 }
2259 }
2260
2261 return MBB.erase(MI);
2262}
2263
2264// We would like to split the SP adjustment to reduce prologue/epilogue
2265// as following instructions. In this way, the offset of the callee saved
2266// register could fit in a single store. Supposed that the first sp adjust
2267// amount is 2032.
2268// add sp,sp,-2032
2269// sw ra,2028(sp)
2270// sw s0,2024(sp)
2271// sw s1,2020(sp)
2272// sw s3,2012(sp)
2273// sw s4,2008(sp)
2274// add sp,sp,-64
2275uint64_t
2277 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2278 const MachineFrameInfo &MFI = MF.getFrameInfo();
2279 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2280 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
2281
2282 // Disable SplitSPAdjust if save-restore libcall, push/pop or QCI interrupts
2283 // are used. The callee-saved registers will be pushed by the save-restore
2284 // libcalls, so we don't have to split the SP adjustment in this case.
2285 if (RVFI->getReservedSpillsSize())
2286 return 0;
2287
2288 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
2289 // 12-bit and there exists a callee-saved register needing to be pushed.
2290 if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
2291 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
2292 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
2293 // instructions. Offsets smaller than 2048 can fit in a single load/store
2294 // instruction, and we have to stick with the stack alignment. 2048 has
2295 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
2296 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
2297 const uint64_t StackAlign = getStackAlign().value();
2298
2299 // Amount of (2048 - StackAlign) will prevent callee saved and restored
2300 // instructions be compressed, so try to adjust the amount to the largest
2301 // offset that stack compression instructions accept when target supports
2302 // compression instructions.
2303 if (STI.hasStdExtZca()) {
2304 // The compression extensions may support the following instructions:
2305 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
2306 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
2307 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
2308 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
2309 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
2310 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
2311 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
2312 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
2313 const uint64_t RVCompressLen = STI.getXLen() * 8;
2314 // Compared with amount (2048 - StackAlign), StackSize needs to
2315 // satisfy the following conditions to avoid using more instructions
2316 // to adjust the sp after adjusting the amount, such as
2317 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
2318 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
2319 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
2320 auto CanCompress = [&](uint64_t CompressLen) -> bool {
2321 if (StackSize <= 2047 + CompressLen ||
2322 (StackSize > 2048 * 2 - StackAlign &&
2323 StackSize <= 2047 * 2 + CompressLen) ||
2324 StackSize > 2048 * 3 - StackAlign)
2325 return true;
2326
2327 return false;
2328 };
2329 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
2330 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
2331 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
2332 const uint64_t ADDI16SPCompressLen = 496;
2333 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
2334 return ADDI16SPCompressLen;
2335 if (CanCompress(RVCompressLen))
2336 return RVCompressLen;
2337 }
2338 return 2048 - StackAlign;
2339 }
2340 return 0;
2341}
2342
2345 std::vector<CalleeSavedInfo> &CSI) const {
2346 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2347 MachineFrameInfo &MFI = MF.getFrameInfo();
2348 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
2349
2350 // Preemptible Interrupts have two additional Callee-save Frame Indexes,
2351 // not tracked by `CSI`.
2352 if (RVFI->isSiFivePreemptibleInterrupt(MF)) {
2353 for (int I = 0; I < 2; ++I) {
2354 int FI = RVFI->getInterruptCSRFrameIndex(I);
2355 MFI.setIsCalleeSavedObjectIndex(FI, true);
2356 }
2357 }
2358
2359 // Early exit if no callee saved registers are modified!
2360 if (CSI.empty())
2361 return true;
2362
2363 if (RVFI->useQCIInterrupt(MF)) {
2364 RVFI->setQCIInterruptStackSize(QCIInterruptPushAmount);
2365 }
2366
2367 if (RVFI->isPushable(MF)) {
2368 // Determine how many GPRs we need to push and save it to RVFI.
2369 unsigned PushedRegNum = getNumPushPopRegs(CSI);
2370
2371 // `QC.C.MIENTER(.NEST)` will save `ra` and `s0`, so we should only push if
2372 // we want to push more than 2 registers. Otherwise, we should push if we
2373 // want to push more than 0 registers.
2374 unsigned OnlyPushIfMoreThan = RVFI->useQCIInterrupt(MF) ? 2 : 0;
2375 if (PushedRegNum > OnlyPushIfMoreThan) {
2376 RVFI->setRVPushRegs(PushedRegNum);
2377 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
2378 }
2379 }
2380
2381 for (auto &CS : CSI) {
2382 MCRegister Reg = CS.getReg();
2383 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2384 unsigned Size = RegInfo->getSpillSize(*RC);
2385
2386 if (RVFI->useQCIInterrupt(MF)) {
2387 const auto *FFI = llvm::find_if(FixedCSRFIQCIInterruptMap, [&](auto P) {
2388 return P.first == CS.getReg();
2389 });
2390 if (FFI != std::end(FixedCSRFIQCIInterruptMap)) {
2391 int64_t Offset = FFI->second * (int64_t)Size;
2392
2393 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2394 assert(FrameIdx < 0);
2395 CS.setFrameIdx(FrameIdx);
2396 continue;
2397 }
2398 }
2399
2400 if (RVFI->useSaveRestoreLibCalls(MF) || RVFI->isPushable(MF)) {
2401 const auto *FII = llvm::find_if(
2402 FixedCSRFIMap, [&](MCPhysReg P) { return P == CS.getReg(); });
2403 unsigned RegNum = std::distance(std::begin(FixedCSRFIMap), FII);
2404
2405 if (FII != std::end(FixedCSRFIMap)) {
2406 int64_t Offset;
2407 if (RVFI->getPushPopKind(MF) ==
2409 Offset = -int64_t(RVFI->getRVPushRegs() - RegNum) * Size;
2410 else
2411 Offset = -int64_t(RegNum + 1) * Size;
2412
2413 if (RVFI->useQCIInterrupt(MF))
2415
2416 int FrameIdx = MFI.CreateFixedSpillStackObject(Size, Offset);
2417 assert(FrameIdx < 0);
2418 CS.setFrameIdx(FrameIdx);
2419 continue;
2420 }
2421 }
2422
2423 // For GPRPair registers, use 8-byte slots with required alignment by zilsd.
2424 if (!STI.is64Bit() && STI.hasStdExtZilsd() &&
2425 RISCV::GPRPairRegClass.contains(Reg)) {
2426 Align PairAlign = STI.getZilsdAlign();
2427 int FrameIdx = MFI.CreateStackObject(8, PairAlign, true);
2428 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2429 CS.setFrameIdx(FrameIdx);
2430 continue;
2431 }
2432
2433 // Not a fixed slot.
2434 Align Alignment = RegInfo->getSpillAlign(*RC);
2435 // We may not be able to satisfy the desired alignment specification of
2436 // the TargetRegisterClass if the stack alignment is smaller. Use the
2437 // min.
2438 Alignment = std::min(Alignment, getStackAlign());
2439 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2440 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2441 CS.setFrameIdx(FrameIdx);
2443 MFI.setStackID(FrameIdx, TargetStackID::ScalableVector);
2444 }
2445
2446 if (RVFI->useQCIInterrupt(MF)) {
2447 // Allocate a fixed object that covers the entire QCI stack allocation,
2448 // because there are gaps which are reserved for future use.
2449 MFI.CreateFixedSpillStackObject(
2450 QCIInterruptPushAmount, -static_cast<int64_t>(QCIInterruptPushAmount));
2451 }
2452
2453 if (RVFI->isPushable(MF)) {
2454 int64_t QCIOffset = RVFI->useQCIInterrupt(MF) ? QCIInterruptPushAmount : 0;
2455 // Allocate a fixed object that covers the full push.
2456 if (int64_t PushSize = RVFI->getRVPushStackSize())
2457 MFI.CreateFixedSpillStackObject(PushSize, -PushSize - QCIOffset);
2458 } else if (int LibCallRegs = getLibCallID(MF, CSI) + 1) {
2459 // If libcalls are used to spill and restore callee-saved registers, the
2460 // frame has two sections; the opaque section managed by the libcalls, and
2461 // the section managed by MachineFrameInfo which can also hold callee saved
2462 // registers in fixed stack slots, both of which have negative frame
2463 // indices. This gets even more complicated when incoming arguments are
2464 // passed via the stack, as these too have negative frame indices. An
2465 // example is detailed below:
2466 //
2467 // | incoming arg | <- FI[-3]
2468 // | libcallspill |
2469 // | calleespill | <- FI[-2]
2470 // | calleespill | <- FI[-1]
2471 // | this_frame | <- FI[0]
2472 //
2473 // For negative frame indices, the offset from the frame pointer will differ
2474 // depending on which of these groups the frame index applies to.
2475 // The following calculates the correct offset knowing the number of callee
2476 // saved registers spilt by the two methods.
2477 unsigned LibCallFrameSize =
2478 alignTo((STI.getXLen() / 8) * LibCallRegs, getStackAlign());
2479 RVFI->setLibCallStackSize(LibCallFrameSize);
2480 // Allocate a fixed object that covers the entire libcall area.
2481 MFI.CreateFixedSpillStackObject(LibCallFrameSize,
2482 -static_cast<int64_t>(LibCallFrameSize));
2483 }
2484
2485 return true;
2486}
2487
2491 if (CSI.empty())
2492 return true;
2493
2494 MachineFunction *MF = MBB.getParent();
2495 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2496 DebugLoc DL;
2497 if (MI != MBB.end() && !MI->isDebugInstr())
2498 DL = MI->getDebugLoc();
2499
2501 if (RVFI->useQCIInterrupt(*MF)) {
2502 // Emit QC.C.MIENTER(.NEST)
2503 BuildMI(
2504 MBB, MI, DL,
2505 TII.get(RVFI->getInterruptStackKind(*MF) ==
2507 ? RISCV::QC_C_MIENTER_NEST
2508 : RISCV::QC_C_MIENTER))
2510
2511 for (auto [Reg, _Offset] : FixedCSRFIQCIInterruptMap)
2512 MBB.addLiveIn(Reg);
2513 }
2514
2515 if (RVFI->isPushable(*MF)) {
2516 // Emit CM.PUSH with base StackAdj & evaluate Push stack
2517 unsigned PushedRegNum = RVFI->getRVPushRegs();
2518 if (PushedRegNum > 0) {
2519 // Use encoded number to represent registers to spill.
2520 unsigned Opcode = getPushOpcode(
2521 RVFI->getPushPopKind(*MF), hasFP(*MF) && !RVFI->useQCIInterrupt(*MF));
2522 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2523 MachineInstrBuilder PushBuilder =
2524 BuildMI(MBB, MI, DL, TII.get(Opcode))
2526 PushBuilder.addImm(RegEnc);
2527 PushBuilder.addImm(0);
2528
2529 for (unsigned i = 0; i < PushedRegNum; i++)
2530 PushBuilder.addUse(FixedCSRFIMap[i], RegState::Implicit);
2531 }
2532 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
2533 // Add spill libcall via non-callee-saved register t0.
2534 MachineInstrBuilder NewMI =
2535 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
2536 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
2538 .addUse(RISCV::X2, RegState::Implicit)
2539 .addDef(RISCV::X2, RegState::ImplicitDefine);
2540
2541 // Add registers spilled as implicit used.
2542 for (auto &CS : CSI)
2543 NewMI.addUse(CS.getReg(), RegState::Implicit);
2544 }
2545
2546 // Manually spill values not spilled by libcall & Push/Pop.
2547 const auto &UnmanagedCSI =
2548 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2549 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2550
2551 auto storeRegsToStackSlots = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2552 for (auto &CS : CSInfo) {
2553 // Insert the spill to the stack frame.
2554 MCRegister Reg = CS.getReg();
2555 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2556 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg),
2557 CS.getFrameIdx(), RC, Register(),
2559 }
2560 };
2561 storeRegsToStackSlots(UnmanagedCSI);
2562 storeRegsToStackSlots(RVVCSI);
2563
2564 return true;
2565}
2566
2567static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg) {
2568 return RISCV::VRRegClass.contains(BaseReg) ? 1
2569 : RISCV::VRM2RegClass.contains(BaseReg) ? 2
2570 : RISCV::VRM4RegClass.contains(BaseReg) ? 4
2571 : 8;
2572}
2573
2574void RISCVFrameLowering::emitCalleeSavedRVVPrologCFI(
2577 const MachineFrameInfo &MFI = MF->getFrameInfo();
2578 RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2579 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2580
2581 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2582 if (RVVCSI.empty())
2583 return;
2584
2585 uint64_t FixedSize = getStackSizeWithRVVPadding(*MF);
2586 if (!HasFP) {
2587 uint64_t ScalarLocalVarSize =
2588 MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
2589 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
2590 FixedSize -= ScalarLocalVarSize;
2591 }
2592
2593 CFIInstBuilder CFIBuilder(MBB, MI, MachineInstr::FrameSetup);
2594 for (auto &CS : RVVCSI) {
2595 // Insert the spill to the stack frame.
2596 int FI = CS.getFrameIdx();
2597 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2598 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2599 for (unsigned i = 0; i < NumRegs; ++i) {
2600 CFIBuilder.insertCFIInst(createDefCFAOffset(
2601 TRI, BaseReg + i,
2602 StackOffset::get(-FixedSize, MFI.getObjectOffset(FI) / 8 + i)));
2603 }
2604 }
2605}
2606
2607void RISCVFrameLowering::emitCalleeSavedRVVEpilogCFI(
2610 const MachineFrameInfo &MFI = MF->getFrameInfo();
2611 const RISCVRegisterInfo &TRI = *STI.getRegisterInfo();
2612
2613 CFIInstBuilder CFIHelper(MBB, MI, MachineInstr::FrameDestroy);
2614 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, MFI.getCalleeSavedInfo());
2615 for (auto &CS : RVVCSI) {
2616 MCRegister BaseReg = getRVVBaseRegister(TRI, CS.getReg());
2617 unsigned NumRegs = getCalleeSavedRVVNumRegs(CS.getReg());
2618 for (unsigned i = 0; i < NumRegs; ++i)
2619 CFIHelper.buildRestore(BaseReg + i);
2620 }
2621}
2622
2626 if (CSI.empty())
2627 return true;
2628
2629 MachineFunction *MF = MBB.getParent();
2630 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2631 DebugLoc DL;
2632 if (MI != MBB.end() && !MI->isDebugInstr())
2633 DL = MI->getDebugLoc();
2634
2635 // Manually restore values not restored by libcall & Push/Pop.
2636 // Reverse the restore order in epilog. In addition, the return
2637 // address will be restored first in the epilogue. It increases
2638 // the opportunity to avoid the load-to-use data hazard between
2639 // loading RA and return by RA. loadRegFromStackSlot can insert
2640 // multiple instructions.
2641 const auto &UnmanagedCSI =
2642 getUnmanagedInterruptCSI(*MF, CSI, STI.preferAscendingLoadStore());
2643 const auto &RVVCSI = getRVVCalleeSavedInfo(*MF, CSI);
2644
2645 auto loadRegFromStackSlot = [&](ArrayRef<CalleeSavedInfo> CSInfo) {
2646 for (auto &CS : CSInfo) {
2647 MCRegister Reg = CS.getReg();
2648 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
2649 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, Register(),
2650 RISCV::NoSubRegister,
2652 assert(MI != MBB.begin() &&
2653 "loadRegFromStackSlot didn't insert any code!");
2654 }
2655 };
2656 loadRegFromStackSlot(RVVCSI);
2657 loadRegFromStackSlot(UnmanagedCSI);
2658
2660 if (RVFI->useQCIInterrupt(*MF)) {
2661 // Don't emit anything here because restoration is handled by
2662 // QC.C.MILEAVERET which we already inserted to return.
2663 assert(MI->getOpcode() == RISCV::QC_C_MILEAVERET &&
2664 "Unexpected QCI Interrupt Return Instruction");
2665 }
2666
2667 if (RVFI->isPushable(*MF)) {
2668 unsigned PushedRegNum = RVFI->getRVPushRegs();
2669 if (PushedRegNum > 0) {
2670 unsigned Opcode = getPopOpcode(RVFI->getPushPopKind(*MF));
2671 unsigned RegEnc = RISCVZC::encodeRegListNumRegs(PushedRegNum);
2672 MachineInstrBuilder PopBuilder =
2673 BuildMI(MBB, MI, DL, TII.get(Opcode))
2675 // Use encoded number to represent registers to restore.
2676 PopBuilder.addImm(RegEnc);
2677 PopBuilder.addImm(0);
2678
2679 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
2681 }
2682 } else if (const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI)) {
2683 assert(RVFI->useSaveRestoreLibCalls(*MF) &&
2684 "Expected restore with libcall to use save restore libcalls");
2685
2686 // Restore is not compatible with shadow stacks, so do the restore manually.
2687 // This ensures we still get the code size saving of `__riscv_save_<N>`.
2688 if (RVFI->hasShadowStack(*MF)) {
2689 loadRegFromStackSlot(getPushOrLibCallsSavedInfo(*MF, CSI));
2690 return true;
2691 }
2692
2693 // Add restore libcall via tail call.
2694 MachineInstrBuilder NewMI =
2695 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
2696 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
2698 .addDef(RISCV::X2, RegState::ImplicitDefine);
2699
2700 // Add registers restored as implicit defined.
2701 for (auto &CS : CSI)
2702 NewMI.addDef(CS.getReg(), RegState::ImplicitDefine);
2703
2704 // Remove trailing returns, since the terminator is now a tail call to the
2705 // restore function.
2706 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
2707 NewMI.getInstr()->copyImplicitOps(*MF, *MI);
2708 MI->eraseFromParent();
2709 }
2710 }
2711 return true;
2712}
2713
2715 // Keep the conventional code flow when not optimizing.
2716 if (MF.getFunction().hasOptNone())
2717 return false;
2718
2719 // QCI and SiFive CLIC interrupt entry sequences must precede all handler
2720 // code.
2721 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
2722 if (RVFI->useQCIInterrupt(MF) || RVFI->useSiFiveInterrupt(MF))
2723 return false;
2724
2725 return true;
2726}
2727
2729 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2730 const MachineFunction *MF = MBB.getParent();
2731 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2732
2733 // Make sure VTYPE and VL are not live-in since we will use vsetvli in the
2734 // prologue to get the VLEN, and that will clobber these registers.
2735 //
2736 // We may do also check the stack contains objects with scalable vector type,
2737 // but this will require iterating over all the stack objects, but this may
2738 // not worth since the situation is rare, we could do further check in future
2739 // if we find it is necessary.
2740 if (STI.preferVsetvliOverReadVLENB() &&
2741 (MBB.isLiveIn(RISCV::VTYPE) || MBB.isLiveIn(RISCV::VL)))
2742 return false;
2743
2744 if (!RVFI->useSaveRestoreLibCalls(*MF))
2745 return true;
2746
2747 // Inserting a call to a __riscv_save libcall requires the use of the register
2748 // t0 (X5) to hold the return address. Therefore if this register is already
2749 // used we can't insert the call.
2750
2751 RegScavenger RS;
2752 RS.enterBasicBlock(*TmpMBB);
2753 return !RS.isRegUsed(RISCV::X5);
2754}
2755
2757 const MachineFunction *MF = MBB.getParent();
2758 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
2759 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
2760
2761 // If we have a shadow stack, we don't use `__riscv_restore` libcalls.
2762 if (RVFI->hasShadowStack(*MF))
2763 return true;
2764
2765 if (!RVFI->useSaveRestoreLibCalls(*MF))
2766 return true;
2767
2768 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
2769 // This means if we still need to continue executing code within this function
2770 // the restore cannot take place in this basic block.
2771
2772 if (MBB.succ_size() > 1)
2773 return false;
2774
2775 MachineBasicBlock *SuccMBB =
2776 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
2777
2778 // Doing a tail call should be safe if there are no successors, because either
2779 // we have a returning block or the end of the block is unreachable, so the
2780 // restore will be eliminated regardless.
2781 if (!SuccMBB)
2782 return true;
2783
2784 // The successor can only contain a return and debug instructions, since we
2785 // would effectively replace it with our own tail return at the end of this
2786 // block. The debug instructions would not execute on the tail-return path.
2787 return SuccMBB->isReturnBlock() &&
2788 llvm::count_if(SuccMBB->instrs(), [](const MachineInstr &MI) {
2789 return !MI.isDebugInstr();
2790 }) == 1;
2791}
2792
2796
2800
2801// Synthesize the probe loop.
2803 Register TargetReg, Register ScratchReg,
2804 bool IsRVV) {
2805 assert(TargetReg != RISCV::X2 && "New top of stack cannot already be in SP");
2806 assert(ScratchReg != RISCV::X2 && "Scratch register cannot be SP");
2807 assert(TargetReg != ScratchReg && "Target and scratch must be different");
2808
2809 MachineBasicBlock &MBB = *MBBI->getParent();
2810 MachineFunction &MF = *MBB.getParent();
2811
2812 auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
2813 const RISCVInstrInfo *TII = Subtarget.getInstrInfo();
2814 bool IsRV64 = Subtarget.is64Bit();
2815 Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
2816 const RISCVTargetLowering *TLI = Subtarget.getTargetLowering();
2817 uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
2818
2819 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
2820 MachineBasicBlock *LoopTestMBB =
2821 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2822 MF.insert(MBBInsertPoint, LoopTestMBB);
2823 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
2824 MF.insert(MBBInsertPoint, ExitMBB);
2826
2827 // ScratchReg = ProbeSize
2828 TII->movImm(MBB, MBBI, DL, ScratchReg, ProbeSize, Flags);
2829
2830 // LoopTest:
2831 // SUB SP, SP, ProbeSize
2832 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB), SPReg)
2833 .addReg(SPReg)
2834 .addReg(ScratchReg)
2835 .setMIFlags(Flags);
2836
2837 // s[d|w] zero, 0(sp)
2838 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
2839 TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
2840 .addReg(RISCV::X0)
2841 .addReg(SPReg)
2842 .addImm(0)
2843 .setMIFlags(Flags);
2844
2845 if (IsRVV) {
2846 // SUB TargetReg, TargetReg, ProbeSize
2847 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::SUB),
2848 TargetReg)
2849 .addReg(TargetReg)
2850 .addReg(ScratchReg)
2851 .setMIFlags(Flags);
2852
2853 // BGE TargetReg, ProbeSize, LoopTest
2854 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BGE))
2855 .addReg(TargetReg)
2856 .addReg(ScratchReg)
2857 .addMBB(LoopTestMBB)
2858 .setMIFlags(Flags);
2859
2860 } else {
2861 // BNE SP, TargetReg, LoopTest
2862 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(RISCV::BNE))
2863 .addReg(SPReg)
2864 .addReg(TargetReg)
2865 .addMBB(LoopTestMBB)
2866 .setMIFlags(Flags);
2867 }
2868
2869 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
2871
2872 LoopTestMBB->addSuccessor(ExitMBB);
2873 LoopTestMBB->addSuccessor(LoopTestMBB);
2874 MBB.addSuccessor(LoopTestMBB);
2875 // Update liveins.
2876 fullyRecomputeLiveIns({ExitMBB, LoopTestMBB});
2877}
2878
2879void RISCVFrameLowering::inlineStackProbe(MachineFunction &MF,
2880 MachineBasicBlock &MBB) const {
2881 // Get the instructions that need to be replaced. We emit at most two of
2882 // these. Remember them in order to avoid complications coming from the need
2883 // to traverse the block while potentially creating more blocks.
2884 SmallVector<MachineInstr *, 4> ToReplace;
2885 for (MachineInstr &MI : MBB) {
2886 unsigned Opc = MI.getOpcode();
2887 if (Opc == RISCV::PROBED_STACKALLOC ||
2888 Opc == RISCV::PROBED_STACKALLOC_RVV) {
2889 ToReplace.push_back(&MI);
2890 }
2891 }
2892
2893 for (MachineInstr *MI : ToReplace) {
2894 if (MI->getOpcode() == RISCV::PROBED_STACKALLOC ||
2895 MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV) {
2898 Register TargetReg = MI->getOperand(0).getReg();
2899
2900 Register ScratchReg =
2901 findScratchNonCalleeSaveRegister(&MBB, RISCV::X7, TargetReg);
2902
2903 assert(ScratchReg.isValid() &&
2904 "No available scratch register for stack probe loop");
2905
2906 emitStackProbeInline(MBBI, DL, TargetReg, ScratchReg,
2907 (MI->getOpcode() == RISCV::PROBED_STACKALLOC_RVV));
2909 }
2910 }
2911}
2912
2914 return 0;
2915}
2916
2919 return RISCV::X2;
2920}
2921
2922// On 64-bit systems the fixed stack can hold INT64_MAX bytes, since
2923// stack-offset calculation is done in 2s-complement.
2924// NOTE: In theory a register can hold any 64-bit number, so this constraint
2925// might be relaxed to UINT64_MAX in the future, if anyone actually needs
2926// that.
2928 return STI.is64Bit() ? INT64_MAX : UINT32_MAX;
2929}
static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains constants used for implementing Dwarf debug support.
const HexagonInstrInfo * TII
static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static void emitStackProbeInline(MachineBasicBlock::iterator MBBI, DebugLoc DL, Register TargetReg)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
static constexpr uint64_t QCIInterruptPushAmount
static void emitSiFiveCLICStackSwap(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MachineInstr::MIFlag FrameFlag)
static unsigned getPushOpcode(RISCVMachineFunctionInfo::PushPopKind Kind, bool UpdateFP)
static void emitSiFiveCLICPreemptibleSaves(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL)
static MCRegister getRVVBaseRegister(const RISCVRegisterInfo &TRI, const Register &Reg)
static void createSiFivePreemptibleInterruptFrameEntries(MachineFunction &MF, RISCVMachineFunctionInfo &RVFI)
static constexpr MCPhysReg FPReg
static const char * getRestoreLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool needsDwarfCFI(const MachineFunction &MF)
Returns true if DWARF CFI instructions ("frame moves") should be emitted.
static constexpr MCPhysReg SPReg
static const char * getSpillLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool hasRVVFrameObject(const MachineFunction &MF)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedInterruptCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void appendScalableVectorExpression(const TargetRegisterInfo &TRI, SmallVectorImpl< char > &Expr, StackOffset Offset, llvm::raw_string_ostream &Comment)
static SmallVector< CalleeSavedInfo, 8 > getQCISavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getRVVCalleeSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI, bool ReverseOrder=false)
static void emitSiFiveCLICPreemptibleRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, CFIInstBuilder &CFIBuilder, const DebugLoc &DL)
static bool isPop(unsigned Opcode)
static unsigned getCalleeSavedRVVNumRegs(const Register &BaseReg)
static MCCFIInstruction createDefCFAOffset(const TargetRegisterInfo &TRI, Register Reg, StackOffset Offset)
static Align getABIStackAlignment(RISCVABI::ABI ABI)
static unsigned getPopOpcode(RISCVMachineFunctionInfo::PushPopKind Kind)
static SmallVector< CalleeSavedInfo, 8 > getPushOrLibCallsSavedInfo(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static int getLibCallID(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static const std::pair< MCPhysReg, int8_t > FixedCSRFIQCIInterruptMap[]
static bool isPush(unsigned Opcode)
static constexpr MCPhysReg RAReg
static MCRegister getLargestFPRegisterOrZero(const RISCVSubtarget &STI, const TargetRegisterInfo &TRI, MCRegister Reg)
static const MCPhysReg FixedCSRFIMap[]
static int getSiFiveCLICScratchFrameIndex(const MachineFunction &MF)
static unsigned getNumPushPopRegs(const std::vector< CalleeSavedInfo > &CSI)
static MCRegister getPhysicalGPR(const TargetRegisterInfo &TRI, MCRegister Reg)
static unsigned getScavSlotsNumForRVV(MachineFunction &MF)
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
Helper class for creating CFI instructions and inserting them into MIR.
void buildEscape(StringRef Bytes, StringRef Comment="") const
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildRestore(MCRegister Reg) const
void buildDefCFARegister(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void insertCFIInst(const MCCFIInstruction &CFIInst) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
void setInsertPoint(MachineBasicBlock::iterator IP)
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
MCRegister getReg() const
A debug info location.
Definition DebugLoc.h:126
Diagnostic information for unsupported feature in backend.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
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
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
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 adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
LLVM_ABI void ensureMaxAlignment(Align Alignment)
Make sure the function's frame is at least Align bytes aligned.
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.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isMaxCallFrameSizeComputed() const
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...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
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.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
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
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
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 & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
LLVM_ABI void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const BitVector & getUsedPhysRegsMask() const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
LLVM_ABI void setCalleeSavedRegs(ArrayRef< MCPhysReg > CSRs)
Sets the updated Callee Saved Registers list.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
uint64_t getStackThreshold() const override
getStackThreshold - Return the maximum stack size
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...
bool hasBP(const MachineFunction &MF) const
void allocateStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, MachineFunction &MF, uint64_t Offset, uint64_t RealStackSize, bool EmitCFI, bool NeedProbe, uint64_t ProbeSize, bool DynAllocation, MachineInstr::MIFlag Flag) const
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
bool hasFPImpl(const MachineFunction &MF) const override
Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB, Register PreferredReg, Register DontUseReg=Register()) const
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...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
Register getInitialCFARegister(const MachineFunction &MF) const override
Return initial CFA register value i.e.
const RISCVSubtarget & STI
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...
bool isSupportedStackID(TargetStackID::Value ID) const override
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
TargetStackID::Value getStackIDForScalableVectors() const override
Returns the StackID that scalable vectors should be associated with.
int getInitialCFAOffset(const MachineFunction &MF) const override
Return initial CFA offset value i.e.
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified 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 canUseAsPrologue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a prologue for the target.
RISCVFrameLowering(const RISCVSubtarget &STI)
uint64_t getStackSizeWithRVVPadding(const MachineFunction &MF) const
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isPushable(const MachineFunction &MF) const
InterruptStackKind getInterruptStackKind(const MachineFunction &MF) const
bool useSiFiveInterrupt(const MachineFunction &MF) const
bool isSiFivePreemptibleInterrupt(const MachineFunction &MF) const
PushPopKind getPushPopKind(const MachineFunction &MF) const
bool hasShadowStack(const MachineFunction &MF) const
bool useSaveRestoreLibCalls(const MachineFunction &MF) const
bool useQCIInterrupt(const MachineFunction &MF) const
TargetRegisterClass const * getLargestFPRegClass() const
bool hasVInstructions() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this functions.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
Represents a location in source code.
Definition SMLoc.h:22
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
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.
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
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
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 void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
MCRegister getBPReg()
MCRegister getSCSPReg()
static VLMUL encodeLMUL(unsigned LMUL, bool Fractional)
LLVM_ABI unsigned encodeVTYPE(VLMUL VLMUL, unsigned SEW, bool TailAgnostic, bool MaskAgnostic, bool AltFmt=false)
static unsigned encodeRegListNumRegs(unsigned NumRegs)
static constexpr unsigned RVVBitsPerBlock
bool isRVVSpill(const MachineInstr &MI)
static constexpr unsigned RVVBytesPerBlock
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
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:541
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:191
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
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
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:280
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
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
static bool isRVVRegClass(const TargetRegisterClass *RC)
void adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator II, const DebugLoc &DL, Register DestReg, Register SrcReg, StackOffset Offset, MachineInstr::MIFlag Flag, MaybeAlign RequiredAlign) const