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