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