xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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"
14 #include "RISCVMachineFunctionInfo.h"
15 #include "RISCVSubtarget.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/RegisterScavenging.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/MC/MCDwarf.h"
24 #include "llvm/Support/LEB128.h"
25 
26 #include <algorithm>
27 
28 using namespace llvm;
29 
30 static const Register AllPopRegs[] = {
31     RISCV::X1,  RISCV::X8,  RISCV::X9,  RISCV::X18, RISCV::X19,
32     RISCV::X20, RISCV::X21, RISCV::X22, RISCV::X23, RISCV::X24,
33     RISCV::X25, RISCV::X26, RISCV::X27};
34 
35 // For now we use x3, a.k.a gp, as pointer to shadow call stack.
36 // User should not use x3 in their asm.
37 static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB,
38                             MachineBasicBlock::iterator MI,
39                             const DebugLoc &DL) {
40   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
41     return;
42 
43   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
44   const llvm::RISCVRegisterInfo *TRI = STI.getRegisterInfo();
45   Register RAReg = TRI->getRARegister();
46 
47   // Do not save RA to the SCS if it's not saved to the regular stack,
48   // i.e. RA is not at risk of being overwritten.
49   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
50   if (llvm::none_of(
51           CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
52     return;
53 
54   Register SCSPReg = RISCVABI::getSCSPReg();
55 
56   const RISCVInstrInfo *TII = STI.getInstrInfo();
57   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
58   int64_t SlotSize = STI.getXLen() / 8;
59   // Store return address to shadow call stack
60   // addi    gp, gp, [4|8]
61   // s[w|d]  ra, -[4|8](gp)
62   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
63       .addReg(SCSPReg, RegState::Define)
64       .addReg(SCSPReg)
65       .addImm(SlotSize)
66       .setMIFlag(MachineInstr::FrameSetup);
67   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
68       .addReg(RAReg)
69       .addReg(SCSPReg)
70       .addImm(-SlotSize)
71       .setMIFlag(MachineInstr::FrameSetup);
72 
73   // Emit a CFI instruction that causes SlotSize to be subtracted from the value
74   // of the shadow stack pointer when unwinding past this frame.
75   char DwarfSCSReg = TRI->getDwarfRegNum(SCSPReg, /*IsEH*/ true);
76   assert(DwarfSCSReg < 32 && "SCS Register should be < 32 (X3).");
77 
78   char Offset = static_cast<char>(-SlotSize) & 0x7f;
79   const char CFIInst[] = {
80       dwarf::DW_CFA_val_expression,
81       DwarfSCSReg, // register
82       2,           // length
83       static_cast<char>(unsigned(dwarf::DW_OP_breg0 + DwarfSCSReg)),
84       Offset, // addend (sleb128)
85   };
86 
87   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
88       nullptr, StringRef(CFIInst, sizeof(CFIInst))));
89   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
90       .addCFIIndex(CFIIndex)
91       .setMIFlag(MachineInstr::FrameSetup);
92 }
93 
94 static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
95                             MachineBasicBlock::iterator MI,
96                             const DebugLoc &DL) {
97   if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
98     return;
99 
100   const auto &STI = MF.getSubtarget<RISCVSubtarget>();
101   Register RAReg = STI.getRegisterInfo()->getRARegister();
102 
103   // See emitSCSPrologue() above.
104   std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
105   if (llvm::none_of(
106           CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
107     return;
108 
109   Register SCSPReg = RISCVABI::getSCSPReg();
110 
111   const RISCVInstrInfo *TII = STI.getInstrInfo();
112   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
113   int64_t SlotSize = STI.getXLen() / 8;
114   // Load return address from shadow call stack
115   // l[w|d]  ra, -[4|8](gp)
116   // addi    gp, gp, -[4|8]
117   BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
118       .addReg(RAReg, RegState::Define)
119       .addReg(SCSPReg)
120       .addImm(-SlotSize)
121       .setMIFlag(MachineInstr::FrameDestroy);
122   BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
123       .addReg(SCSPReg, RegState::Define)
124       .addReg(SCSPReg)
125       .addImm(-SlotSize)
126       .setMIFlag(MachineInstr::FrameDestroy);
127   // Restore the SCS pointer
128   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(
129       nullptr, STI.getRegisterInfo()->getDwarfRegNum(SCSPReg, /*IsEH*/ true)));
130   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
131       .addCFIIndex(CFIIndex)
132       .setMIFlags(MachineInstr::FrameDestroy);
133 }
134 
135 // Get the ID of the libcall used for spilling and restoring callee saved
136 // registers. The ID is representative of the number of registers saved or
137 // restored by the libcall, except it is zero-indexed - ID 0 corresponds to a
138 // single register.
139 static int getLibCallID(const MachineFunction &MF,
140                         const std::vector<CalleeSavedInfo> &CSI) {
141   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
142 
143   if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
144     return -1;
145 
146   Register MaxReg = RISCV::NoRegister;
147   for (auto &CS : CSI)
148     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indexes to
149     // registers which can be saved by libcall.
150     if (CS.getFrameIdx() < 0)
151       MaxReg = std::max(MaxReg.id(), CS.getReg().id());
152 
153   if (MaxReg == RISCV::NoRegister)
154     return -1;
155 
156   switch (MaxReg) {
157   default:
158     llvm_unreachable("Something has gone wrong!");
159   case /*s11*/ RISCV::X27: return 12;
160   case /*s10*/ RISCV::X26: return 11;
161   case /*s9*/  RISCV::X25: return 10;
162   case /*s8*/  RISCV::X24: return 9;
163   case /*s7*/  RISCV::X23: return 8;
164   case /*s6*/  RISCV::X22: return 7;
165   case /*s5*/  RISCV::X21: return 6;
166   case /*s4*/  RISCV::X20: return 5;
167   case /*s3*/  RISCV::X19: return 4;
168   case /*s2*/  RISCV::X18: return 3;
169   case /*s1*/  RISCV::X9:  return 2;
170   case /*s0*/  RISCV::X8:  return 1;
171   case /*ra*/  RISCV::X1:  return 0;
172   }
173 }
174 
175 // Get the name of the libcall used for spilling callee saved registers.
176 // If this function will not use save/restore libcalls, then return a nullptr.
177 static const char *
178 getSpillLibCallName(const MachineFunction &MF,
179                     const std::vector<CalleeSavedInfo> &CSI) {
180   static const char *const SpillLibCalls[] = {
181     "__riscv_save_0",
182     "__riscv_save_1",
183     "__riscv_save_2",
184     "__riscv_save_3",
185     "__riscv_save_4",
186     "__riscv_save_5",
187     "__riscv_save_6",
188     "__riscv_save_7",
189     "__riscv_save_8",
190     "__riscv_save_9",
191     "__riscv_save_10",
192     "__riscv_save_11",
193     "__riscv_save_12"
194   };
195 
196   int LibCallID = getLibCallID(MF, CSI);
197   if (LibCallID == -1)
198     return nullptr;
199   return SpillLibCalls[LibCallID];
200 }
201 
202 // Get the name of the libcall used for restoring callee saved registers.
203 // If this function will not use save/restore libcalls, then return a nullptr.
204 static const char *
205 getRestoreLibCallName(const MachineFunction &MF,
206                       const std::vector<CalleeSavedInfo> &CSI) {
207   static const char *const RestoreLibCalls[] = {
208     "__riscv_restore_0",
209     "__riscv_restore_1",
210     "__riscv_restore_2",
211     "__riscv_restore_3",
212     "__riscv_restore_4",
213     "__riscv_restore_5",
214     "__riscv_restore_6",
215     "__riscv_restore_7",
216     "__riscv_restore_8",
217     "__riscv_restore_9",
218     "__riscv_restore_10",
219     "__riscv_restore_11",
220     "__riscv_restore_12"
221   };
222 
223   int LibCallID = getLibCallID(MF, CSI);
224   if (LibCallID == -1)
225     return nullptr;
226   return RestoreLibCalls[LibCallID];
227 }
228 
229 // Return encoded value and register count for PUSH/POP instruction,
230 // representing registers to store/load.
231 static std::pair<unsigned, unsigned>
232 getPushPopEncodingAndNum(const Register MaxReg) {
233   switch (MaxReg) {
234   default:
235     llvm_unreachable("Unexpected Reg for Push/Pop Inst");
236   case RISCV::X27: /*s11*/
237   case RISCV::X26: /*s10*/
238     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S11, 13);
239   case RISCV::X25: /*s9*/
240     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S9, 11);
241   case RISCV::X24: /*s8*/
242     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S8, 10);
243   case RISCV::X23: /*s7*/
244     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S7, 9);
245   case RISCV::X22: /*s6*/
246     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S6, 8);
247   case RISCV::X21: /*s5*/
248     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S5, 7);
249   case RISCV::X20: /*s4*/
250     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S4, 6);
251   case RISCV::X19: /*s3*/
252     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S3, 5);
253   case RISCV::X18: /*s2*/
254     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S2, 4);
255   case RISCV::X9: /*s1*/
256     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0_S1, 3);
257   case RISCV::X8: /*s0*/
258     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA_S0, 2);
259   case RISCV::X1: /*ra*/
260     return std::make_pair(llvm::RISCVZC::RLISTENCODE::RA, 1);
261   }
262 }
263 
264 // Get the max reg of Push/Pop for restoring callee saved registers.
265 static Register getMaxPushPopReg(const MachineFunction &MF,
266                                  const std::vector<CalleeSavedInfo> &CSI) {
267   Register MaxPushPopReg = RISCV::NoRegister;
268   for (auto &CS : CSI) {
269     // RISCVRegisterInfo::hasReservedSpillSlot assigns negative frame indices to
270     // registers which can be saved by Zcmp Push.
271     if (CS.getFrameIdx() < 0)
272       MaxPushPopReg = std::max(MaxPushPopReg.id(), CS.getReg().id());
273   }
274   // if rlist is {rs, s0-s10}, then s11 will also be included
275   if (MaxPushPopReg == RISCV::X26)
276     MaxPushPopReg = RISCV::X27;
277   return MaxPushPopReg;
278 }
279 
280 // Return true if the specified function should have a dedicated frame
281 // pointer register.  This is true if frame pointer elimination is
282 // disabled, if it needs dynamic stack realignment, if the function has
283 // variable sized allocas, or if the frame address is taken.
284 bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
285   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
286 
287   const MachineFrameInfo &MFI = MF.getFrameInfo();
288   return MF.getTarget().Options.DisableFramePointerElim(MF) ||
289          RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
290          MFI.isFrameAddressTaken();
291 }
292 
293 bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
294   const MachineFrameInfo &MFI = MF.getFrameInfo();
295   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
296 
297   // If we do not reserve stack space for outgoing arguments in prologue,
298   // we will adjust the stack pointer before call instruction. After the
299   // adjustment, we can not use SP to access the stack objects for the
300   // arguments. Instead, use BP to access these stack objects.
301   return (MFI.hasVarSizedObjects() ||
302           (!hasReservedCallFrame(MF) && (!MFI.isMaxCallFrameSizeComputed() ||
303                                          MFI.getMaxCallFrameSize() != 0))) &&
304          TRI->hasStackRealignment(MF);
305 }
306 
307 // Determines the size of the frame and maximum call frame size.
308 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
309   MachineFrameInfo &MFI = MF.getFrameInfo();
310   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
311 
312   // Get the number of bytes to allocate from the FrameInfo.
313   uint64_t FrameSize = MFI.getStackSize();
314 
315   // Get the alignment.
316   Align StackAlign = getStackAlign();
317 
318   // Make sure the frame is aligned.
319   FrameSize = alignTo(FrameSize, StackAlign);
320 
321   // Update frame info.
322   MFI.setStackSize(FrameSize);
323 
324   // When using SP or BP to access stack objects, we may require extra padding
325   // to ensure the bottom of the RVV stack is correctly aligned within the main
326   // stack. We calculate this as the amount required to align the scalar local
327   // variable section up to the RVV alignment.
328   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
329   if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
330     int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
331                              RVFI->getVarArgsSaveSize();
332     if (auto RVVPadding =
333             offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
334       RVFI->setRVVPadding(RVVPadding);
335   }
336 }
337 
338 // Returns the stack size including RVV padding (when required), rounded back
339 // up to the required stack alignment.
340 uint64_t RISCVFrameLowering::getStackSizeWithRVVPadding(
341     const MachineFunction &MF) const {
342   const MachineFrameInfo &MFI = MF.getFrameInfo();
343   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
344   return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
345 }
346 
347 // Returns the register used to hold the frame pointer.
348 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
349 
350 // Returns the register used to hold the stack pointer.
351 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
352 
353 static SmallVector<CalleeSavedInfo, 8>
354 getUnmanagedCSI(const MachineFunction &MF,
355                 const std::vector<CalleeSavedInfo> &CSI) {
356   const MachineFrameInfo &MFI = MF.getFrameInfo();
357   SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
358 
359   for (auto &CS : CSI) {
360     int FI = CS.getFrameIdx();
361     if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
362       NonLibcallCSI.push_back(CS);
363   }
364 
365   return NonLibcallCSI;
366 }
367 
368 void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
369                                            MachineBasicBlock &MBB,
370                                            MachineBasicBlock::iterator MBBI,
371                                            const DebugLoc &DL, int64_t Amount,
372                                            MachineInstr::MIFlag Flag) const {
373   assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
374 
375   const Register SPReg = getSPReg(STI);
376 
377   // Optimize compile time offset case
378   StackOffset Offset = StackOffset::getScalable(Amount);
379   if (STI.getRealMinVLen() == STI.getRealMaxVLen()) {
380     // 1. Multiply the number of v-slots by the (constant) length of register
381     const int64_t VLENB = STI.getRealMinVLen() / 8;
382     assert(Amount % 8 == 0 &&
383            "Reserve the stack by the multiple of one vector size.");
384     const int64_t NumOfVReg = Amount / 8;
385     const int64_t FixedOffset = NumOfVReg * VLENB;
386     if (!isInt<32>(FixedOffset)) {
387       report_fatal_error(
388         "Frame size outside of the signed 32-bit range not supported");
389     }
390     Offset = StackOffset::getFixed(FixedOffset);
391   }
392 
393   const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
394   // We must keep the stack pointer aligned through any intermediate
395   // updates.
396   RI.adjustReg(MBB, MBBI, DL, SPReg, SPReg, Offset,
397                Flag, getStackAlign());
398 }
399 
400 static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI,
401                                                Register Reg,
402                                                uint64_t FixedOffset,
403                                                uint64_t ScalableOffset) {
404   assert(ScalableOffset != 0 && "Did not need to adjust CFA for RVV");
405   SmallString<64> Expr;
406   std::string CommentBuffer;
407   llvm::raw_string_ostream Comment(CommentBuffer);
408   // Build up the expression (Reg + FixedOffset + ScalableOffset * VLENB).
409   unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
410   Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
411   Expr.push_back(0);
412   if (Reg == RISCV::X2)
413     Comment << "sp";
414   else
415     Comment << printReg(Reg, &TRI);
416 
417   uint8_t buffer[16];
418   if (FixedOffset) {
419     Expr.push_back(dwarf::DW_OP_consts);
420     Expr.append(buffer, buffer + encodeSLEB128(FixedOffset, buffer));
421     Expr.push_back((uint8_t)dwarf::DW_OP_plus);
422     Comment << " + " << FixedOffset;
423   }
424 
425   Expr.push_back((uint8_t)dwarf::DW_OP_consts);
426   Expr.append(buffer, buffer + encodeSLEB128(ScalableOffset, buffer));
427 
428   unsigned DwarfVlenb = TRI.getDwarfRegNum(RISCV::VLENB, true);
429   Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
430   Expr.append(buffer, buffer + encodeULEB128(DwarfVlenb, buffer));
431   Expr.push_back(0);
432 
433   Expr.push_back((uint8_t)dwarf::DW_OP_mul);
434   Expr.push_back((uint8_t)dwarf::DW_OP_plus);
435 
436   Comment << " + " << ScalableOffset << " * vlenb";
437 
438   SmallString<64> DefCfaExpr;
439   DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
440   DefCfaExpr.append(buffer, buffer + encodeULEB128(Expr.size(), buffer));
441   DefCfaExpr.append(Expr.str());
442 
443   return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
444                                         Comment.str());
445 }
446 
447 void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
448                                       MachineBasicBlock &MBB) const {
449   MachineFrameInfo &MFI = MF.getFrameInfo();
450   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
451   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
452   const RISCVInstrInfo *TII = STI.getInstrInfo();
453   MachineBasicBlock::iterator MBBI = MBB.begin();
454 
455   Register FPReg = getFPReg(STI);
456   Register SPReg = getSPReg(STI);
457   Register BPReg = RISCVABI::getBPReg();
458 
459   // Debug location must be unknown since the first debug location is used
460   // to determine the end of the prologue.
461   DebugLoc DL;
462 
463   // All calls are tail calls in GHC calling conv, and functions have no
464   // prologue/epilogue.
465   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
466     return;
467 
468   // Emit prologue for shadow call stack.
469   emitSCSPrologue(MF, MBB, MBBI, DL);
470 
471   auto FirstFrameSetup = MBBI;
472 
473   // Since spillCalleeSavedRegisters may have inserted a libcall, skip past
474   // any instructions marked as FrameSetup
475   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
476     ++MBBI;
477 
478   // Determine the correct frame layout
479   determineFrameLayout(MF);
480 
481   // If libcalls are used to spill and restore callee-saved registers, the frame
482   // has two sections; the opaque section managed by the libcalls, and the
483   // section managed by MachineFrameInfo which can also hold callee saved
484   // registers in fixed stack slots, both of which have negative frame indices.
485   // This gets even more complicated when incoming arguments are passed via the
486   // stack, as these too have negative frame indices. An example is detailed
487   // below:
488   //
489   //  | incoming arg | <- FI[-3]
490   //  | libcallspill |
491   //  | calleespill  | <- FI[-2]
492   //  | calleespill  | <- FI[-1]
493   //  | this_frame   | <- FI[0]
494   //
495   // For negative frame indices, the offset from the frame pointer will differ
496   // depending on which of these groups the frame index applies to.
497   // The following calculates the correct offset knowing the number of callee
498   // saved registers spilt by the two methods.
499   if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
500     // Calculate the size of the frame managed by the libcall. The libcalls are
501     // implemented such that the stack will always be 16 byte aligned.
502     unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
503     RVFI->setLibCallStackSize(LibCallFrameSize);
504   }
505 
506   // FIXME (note copied from Lanai): This appears to be overallocating.  Needs
507   // investigation. Get the number of bytes to allocate from the FrameInfo.
508   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
509   uint64_t RealStackSize = StackSize + RVFI->getReservedSpillsSize();
510   uint64_t RVVStackSize = RVFI->getRVVStackSize();
511 
512   // Early exit if there is no need to allocate on the stack
513   if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
514     return;
515 
516   // If the stack pointer has been marked as reserved, then produce an error if
517   // the frame requires stack allocation
518   if (STI.isRegisterReservedByUser(SPReg))
519     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
520         MF.getFunction(), "Stack pointer required, but has been reserved."});
521 
522   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
523   // Split the SP adjustment to reduce the offsets of callee saved spill.
524   if (FirstSPAdjustAmount) {
525     StackSize = FirstSPAdjustAmount;
526     RealStackSize = FirstSPAdjustAmount;
527   }
528 
529   if (RVFI->isPushable(MF) && FirstFrameSetup != MBB.end() &&
530       FirstFrameSetup->getOpcode() == RISCV::CM_PUSH) {
531     // Use available stack adjustment in push instruction to allocate additional
532     // stack space.
533     uint64_t Spimm = std::min(StackSize, (uint64_t)48);
534     FirstFrameSetup->getOperand(1).setImm(Spimm);
535     StackSize -= Spimm;
536   }
537 
538   if (StackSize != 0) {
539     // Allocate space on the stack if necessary.
540     RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
541                   StackOffset::getFixed(-StackSize), MachineInstr::FrameSetup,
542                   getStackAlign());
543   }
544 
545   // Emit ".cfi_def_cfa_offset RealStackSize"
546   unsigned CFIIndex = MF.addFrameInst(
547       MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
548   BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
549       .addCFIIndex(CFIIndex)
550       .setMIFlag(MachineInstr::FrameSetup);
551 
552   const auto &CSI = MFI.getCalleeSavedInfo();
553 
554   // The frame pointer is callee-saved, and code has been generated for us to
555   // save it to the stack. We need to skip over the storing of callee-saved
556   // registers as the frame pointer must be modified after it has been saved
557   // to the stack, not before.
558   // FIXME: assumes exactly one instruction is used to save each callee-saved
559   // register.
560   std::advance(MBBI, getUnmanagedCSI(MF, CSI).size());
561 
562   // Iterate over list of callee-saved registers and emit .cfi_offset
563   // directives.
564   for (const auto &Entry : CSI) {
565     int FrameIdx = Entry.getFrameIdx();
566     int64_t Offset;
567     // Offsets for objects with fixed locations (IE: those saved by libcall) are
568     // simply calculated from the frame index.
569     if (FrameIdx < 0) {
570       if (RVFI->isPushable(MF)) {
571         // Callee-saved register stored by Zcmp push is in reverse order.
572         Offset = -(FrameIdx + RVFI->getRVPushRegs() + 1) *
573                  (int64_t)STI.getXLen() / 8;
574       } else {
575         Offset = FrameIdx * (int64_t)STI.getXLen() / 8;
576       }
577     } else {
578       Offset = MFI.getObjectOffset(FrameIdx) - RVFI->getReservedSpillsSize();
579     }
580     Register Reg = Entry.getReg();
581     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
582         nullptr, RI->getDwarfRegNum(Reg, true), Offset));
583     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
584         .addCFIIndex(CFIIndex)
585         .setMIFlag(MachineInstr::FrameSetup);
586   }
587 
588   // Generate new FP.
589   if (hasFP(MF)) {
590     if (STI.isRegisterReservedByUser(FPReg))
591       MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
592           MF.getFunction(), "Frame pointer required, but has been reserved."});
593     // The frame pointer does need to be reserved from register allocation.
594     assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
595 
596     RI->adjustReg(MBB, MBBI, DL, FPReg, SPReg,
597                   StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
598                   MachineInstr::FrameSetup, getStackAlign());
599 
600     // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
601     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
602         nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
603     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
604         .addCFIIndex(CFIIndex)
605         .setMIFlag(MachineInstr::FrameSetup);
606   }
607 
608   // Emit the second SP adjustment after saving callee saved registers.
609   if (FirstSPAdjustAmount) {
610     uint64_t SecondSPAdjustAmount =
611         getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
612     assert(SecondSPAdjustAmount > 0 &&
613            "SecondSPAdjustAmount should be greater than zero");
614     RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
615                   StackOffset::getFixed(-SecondSPAdjustAmount),
616                   MachineInstr::FrameSetup, getStackAlign());
617 
618     // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
619     // don't emit an sp-based .cfi_def_cfa_offset
620     if (!hasFP(MF)) {
621       // Emit ".cfi_def_cfa_offset StackSize"
622       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
623           nullptr, getStackSizeWithRVVPadding(MF)));
624       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
625           .addCFIIndex(CFIIndex)
626           .setMIFlag(MachineInstr::FrameSetup);
627     }
628   }
629 
630   if (RVVStackSize) {
631     adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
632                       MachineInstr::FrameSetup);
633     if (!hasFP(MF)) {
634       // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
635       unsigned CFIIndex = MF.addFrameInst(createDefCFAExpression(
636           *RI, SPReg, getStackSizeWithRVVPadding(MF), RVVStackSize / 8));
637       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
638           .addCFIIndex(CFIIndex)
639           .setMIFlag(MachineInstr::FrameSetup);
640     }
641   }
642 
643   if (hasFP(MF)) {
644     // Realign Stack
645     const RISCVRegisterInfo *RI = STI.getRegisterInfo();
646     if (RI->hasStackRealignment(MF)) {
647       Align MaxAlignment = MFI.getMaxAlign();
648 
649       const RISCVInstrInfo *TII = STI.getInstrInfo();
650       if (isInt<12>(-(int)MaxAlignment.value())) {
651         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
652             .addReg(SPReg)
653             .addImm(-(int)MaxAlignment.value())
654             .setMIFlag(MachineInstr::FrameSetup);
655       } else {
656         unsigned ShiftAmount = Log2(MaxAlignment);
657         Register VR =
658             MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
659         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
660             .addReg(SPReg)
661             .addImm(ShiftAmount)
662             .setMIFlag(MachineInstr::FrameSetup);
663         BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
664             .addReg(VR)
665             .addImm(ShiftAmount)
666             .setMIFlag(MachineInstr::FrameSetup);
667       }
668       // FP will be used to restore the frame in the epilogue, so we need
669       // another base register BP to record SP after re-alignment. SP will
670       // track the current stack after allocating variable sized objects.
671       if (hasBP(MF)) {
672         // move BP, SP
673         BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
674             .addReg(SPReg)
675             .addImm(0)
676             .setMIFlag(MachineInstr::FrameSetup);
677       }
678     }
679   }
680 }
681 
682 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
683                                       MachineBasicBlock &MBB) const {
684   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
685   MachineFrameInfo &MFI = MF.getFrameInfo();
686   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
687   Register FPReg = getFPReg(STI);
688   Register SPReg = getSPReg(STI);
689 
690   // All calls are tail calls in GHC calling conv, and functions have no
691   // prologue/epilogue.
692   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
693     return;
694 
695   // Get the insert location for the epilogue. If there were no terminators in
696   // the block, get the last instruction.
697   MachineBasicBlock::iterator MBBI = MBB.end();
698   DebugLoc DL;
699   if (!MBB.empty()) {
700     MBBI = MBB.getLastNonDebugInstr();
701     if (MBBI != MBB.end())
702       DL = MBBI->getDebugLoc();
703 
704     MBBI = MBB.getFirstTerminator();
705 
706     // If callee-saved registers are saved via libcall, place stack adjustment
707     // before this call.
708     while (MBBI != MBB.begin() &&
709            std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
710       --MBBI;
711   }
712 
713   const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo());
714 
715   // Skip to before the restores of callee-saved registers
716   // FIXME: assumes exactly one instruction is used to restore each
717   // callee-saved register.
718   auto LastFrameDestroy = MBBI;
719   if (!CSI.empty())
720     LastFrameDestroy = std::prev(MBBI, CSI.size());
721 
722   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
723   uint64_t RealStackSize = StackSize + RVFI->getReservedSpillsSize();
724   uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
725   uint64_t RVVStackSize = RVFI->getRVVStackSize();
726 
727   // Restore the stack pointer using the value of the frame pointer. Only
728   // necessary if the stack pointer was modified, meaning the stack size is
729   // unknown.
730   //
731   // In order to make sure the stack point is right through the EH region,
732   // we also need to restore stack pointer from the frame pointer if we
733   // don't preserve stack space within prologue/epilogue for outgoing variables,
734   // normally it's just checking the variable sized object is present or not
735   // is enough, but we also don't preserve that at prologue/epilogue when
736   // have vector objects in stack.
737   if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
738       !hasReservedCallFrame(MF)) {
739     assert(hasFP(MF) && "frame pointer should not have been eliminated");
740     RI->adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg,
741                   StackOffset::getFixed(-FPOffset),
742                   MachineInstr::FrameDestroy, getStackAlign());
743   } else {
744     if (RVVStackSize)
745       adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
746                         MachineInstr::FrameDestroy);
747   }
748 
749   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
750   if (FirstSPAdjustAmount) {
751     uint64_t SecondSPAdjustAmount =
752         getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
753     assert(SecondSPAdjustAmount > 0 &&
754            "SecondSPAdjustAmount should be greater than zero");
755 
756     RI->adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg,
757                   StackOffset::getFixed(SecondSPAdjustAmount),
758                   MachineInstr::FrameDestroy, getStackAlign());
759   }
760 
761   if (FirstSPAdjustAmount)
762     StackSize = FirstSPAdjustAmount;
763 
764   if (RVFI->isPushable(MF) && MBBI != MBB.end() &&
765       MBBI->getOpcode() == RISCV::CM_POP) {
766     // Use available stack adjustment in pop instruction to deallocate stack
767     // space.
768     uint64_t Spimm = std::min(StackSize, (uint64_t)48);
769     MBBI->getOperand(1).setImm(Spimm);
770     StackSize -= Spimm;
771   }
772 
773   // Deallocate stack
774   if (StackSize != 0) {
775     RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
776                   MachineInstr::FrameDestroy, getStackAlign());
777   }
778 
779   // Emit epilogue for shadow call stack.
780   emitSCSEpilogue(MF, MBB, MBBI, DL);
781 }
782 
783 StackOffset
784 RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
785                                            Register &FrameReg) const {
786   const MachineFrameInfo &MFI = MF.getFrameInfo();
787   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
788   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
789 
790   // Callee-saved registers should be referenced relative to the stack
791   // pointer (positive offset), otherwise use the frame pointer (negative
792   // offset).
793   const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo());
794   int MinCSFI = 0;
795   int MaxCSFI = -1;
796   StackOffset Offset;
797   auto StackID = MFI.getStackID(FI);
798 
799   assert((StackID == TargetStackID::Default ||
800           StackID == TargetStackID::ScalableVector) &&
801          "Unexpected stack ID for the frame object.");
802   if (StackID == TargetStackID::Default) {
803     Offset =
804         StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
805                               MFI.getOffsetAdjustment());
806   } else if (StackID == TargetStackID::ScalableVector) {
807     Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
808   }
809 
810   uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
811 
812   if (CSI.size()) {
813     MinCSFI = CSI[0].getFrameIdx();
814     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
815   }
816 
817   if (FI >= MinCSFI && FI <= MaxCSFI) {
818     FrameReg = RISCV::X2;
819 
820     if (FirstSPAdjustAmount)
821       Offset += StackOffset::getFixed(FirstSPAdjustAmount);
822     else
823       Offset += StackOffset::getFixed(getStackSizeWithRVVPadding(MF));
824     return Offset;
825   }
826 
827   if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
828     // If the stack was realigned, the frame pointer is set in order to allow
829     // SP to be restored, so we need another base register to record the stack
830     // after realignment.
831     // |--------------------------| -- <-- FP
832     // | callee-allocated save    | | <----|
833     // | area for register varargs| |      |
834     // |--------------------------| |      |
835     // | callee-saved registers   | |      |
836     // |--------------------------| --     |
837     // | realignment (the size of | |      |
838     // | this area is not counted | |      |
839     // | in MFI.getStackSize())   | |      |
840     // |--------------------------| --     |-- MFI.getStackSize()
841     // | RVV alignment padding    | |      |
842     // | (not counted in          | |      |
843     // | MFI.getStackSize() but   | |      |
844     // | counted in               | |      |
845     // | RVFI.getRVVStackSize())  | |      |
846     // |--------------------------| --     |
847     // | RVV objects              | |      |
848     // | (not counted in          | |      |
849     // | MFI.getStackSize())      | |      |
850     // |--------------------------| --     |
851     // | padding before RVV       | |      |
852     // | (not counted in          | |      |
853     // | MFI.getStackSize() or in | |      |
854     // | RVFI.getRVVStackSize())  | |      |
855     // |--------------------------| --     |
856     // | scalar local variables   | | <----'
857     // |--------------------------| -- <-- BP (if var sized objects present)
858     // | VarSize objects          | |
859     // |--------------------------| -- <-- SP
860     if (hasBP(MF)) {
861       FrameReg = RISCVABI::getBPReg();
862     } else {
863       // VarSize objects must be empty in this case!
864       assert(!MFI.hasVarSizedObjects());
865       FrameReg = RISCV::X2;
866     }
867   } else {
868     FrameReg = RI->getFrameRegister(MF);
869   }
870 
871   if (FrameReg == getFPReg(STI)) {
872     Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
873     if (FI >= 0)
874       Offset -= StackOffset::getFixed(RVFI->getReservedSpillsSize());
875     // When using FP to access scalable vector objects, we need to minus
876     // the frame size.
877     //
878     // |--------------------------| -- <-- FP
879     // | callee-allocated save    | |
880     // | area for register varargs| |
881     // |--------------------------| |
882     // | callee-saved registers   | |
883     // |--------------------------| | MFI.getStackSize()
884     // | scalar local variables   | |
885     // |--------------------------| -- (Offset of RVV objects is from here.)
886     // | RVV objects              |
887     // |--------------------------|
888     // | VarSize objects          |
889     // |--------------------------| <-- SP
890     if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
891       assert(!RI->hasStackRealignment(MF) &&
892              "Can't index across variable sized realign");
893       // We don't expect any extra RVV alignment padding, as the stack size
894       // and RVV object sections should be correct aligned in their own
895       // right.
896       assert(MFI.getStackSize() == getStackSizeWithRVVPadding(MF) &&
897              "Inconsistent stack layout");
898       Offset -= StackOffset::getFixed(MFI.getStackSize());
899     }
900     return Offset;
901   }
902 
903   // This case handles indexing off both SP and BP.
904   // If indexing off SP, there must not be any var sized objects
905   assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
906 
907   // When using SP to access frame objects, we need to add RVV stack size.
908   //
909   // |--------------------------| -- <-- FP
910   // | callee-allocated save    | | <----|
911   // | area for register varargs| |      |
912   // |--------------------------| |      |
913   // | callee-saved registers   | |      |
914   // |--------------------------| --     |
915   // | RVV alignment padding    | |      |
916   // | (not counted in          | |      |
917   // | MFI.getStackSize() but   | |      |
918   // | counted in               | |      |
919   // | RVFI.getRVVStackSize())  | |      |
920   // |--------------------------| --     |
921   // | RVV objects              | |      |-- MFI.getStackSize()
922   // | (not counted in          | |      |
923   // | MFI.getStackSize())      | |      |
924   // |--------------------------| --     |
925   // | padding before RVV       | |      |
926   // | (not counted in          | |      |
927   // | MFI.getStackSize())      | |      |
928   // |--------------------------| --     |
929   // | scalar local variables   | | <----'
930   // |--------------------------| -- <-- BP (if var sized objects present)
931   // | VarSize objects          | |
932   // |--------------------------| -- <-- SP
933   //
934   // The total amount of padding surrounding RVV objects is described by
935   // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
936   // objects to the required alignment.
937   if (MFI.getStackID(FI) == TargetStackID::Default) {
938     if (MFI.isFixedObjectIndex(FI)) {
939       assert(!RI->hasStackRealignment(MF) &&
940              "Can't index across variable sized realign");
941       Offset += StackOffset::get(getStackSizeWithRVVPadding(MF) +
942                                      RVFI->getReservedSpillsSize(),
943                                  RVFI->getRVVStackSize());
944     } else {
945       Offset += StackOffset::getFixed(MFI.getStackSize());
946     }
947   } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
948     // Ensure the base of the RVV stack is correctly aligned: add on the
949     // alignment padding.
950     int ScalarLocalVarSize = MFI.getStackSize() -
951                              RVFI->getCalleeSavedStackSize() -
952                              RVFI->getRVPushStackSize() -
953                              RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
954     Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
955   }
956   return Offset;
957 }
958 
959 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
960                                               BitVector &SavedRegs,
961                                               RegScavenger *RS) const {
962   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
963   // Unconditionally spill RA and FP only if the function uses a frame
964   // pointer.
965   if (hasFP(MF)) {
966     SavedRegs.set(RISCV::X1);
967     SavedRegs.set(RISCV::X8);
968   }
969   // Mark BP as used if function has dedicated base pointer.
970   if (hasBP(MF))
971     SavedRegs.set(RISCVABI::getBPReg());
972 
973   // If interrupt is enabled and there are calls in the handler,
974   // unconditionally save all Caller-saved registers and
975   // all FP registers, regardless whether they are used.
976   MachineFrameInfo &MFI = MF.getFrameInfo();
977 
978   if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
979 
980     static const MCPhysReg CSRegs[] = { RISCV::X1,      /* ra */
981       RISCV::X5, RISCV::X6, RISCV::X7,                  /* t0-t2 */
982       RISCV::X10, RISCV::X11,                           /* a0-a1, a2-a7 */
983       RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
984       RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31 /* t3-t6 */
985     };
986 
987     for (auto Reg : CSRegs)
988       SavedRegs.set(Reg);
989 
990     if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
991 
992       // If interrupt is enabled, this list contains all FP registers.
993       const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
994 
995       for (unsigned i = 0; Regs[i]; ++i)
996         if (RISCV::FPR16RegClass.contains(Regs[i]) ||
997             RISCV::FPR32RegClass.contains(Regs[i]) ||
998             RISCV::FPR64RegClass.contains(Regs[i]))
999           SavedRegs.set(Regs[i]);
1000     }
1001   }
1002 }
1003 
1004 std::pair<int64_t, Align>
1005 RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
1006   MachineFrameInfo &MFI = MF.getFrameInfo();
1007   // Create a buffer of RVV objects to allocate.
1008   SmallVector<int, 8> ObjectsToAllocate;
1009   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
1010     unsigned StackID = MFI.getStackID(I);
1011     if (StackID != TargetStackID::ScalableVector)
1012       continue;
1013     if (MFI.isDeadObjectIndex(I))
1014       continue;
1015 
1016     ObjectsToAllocate.push_back(I);
1017   }
1018 
1019   // The minimum alignment is 16 bytes.
1020   Align RVVStackAlign(16);
1021   const auto &ST = MF.getSubtarget<RISCVSubtarget>();
1022 
1023   if (!ST.hasVInstructions()) {
1024     assert(ObjectsToAllocate.empty() &&
1025            "Can't allocate scalable-vector objects without V instructions");
1026     return std::make_pair(0, RVVStackAlign);
1027   }
1028 
1029   // Allocate all RVV locals and spills
1030   int64_t Offset = 0;
1031   for (int FI : ObjectsToAllocate) {
1032     // ObjectSize in bytes.
1033     int64_t ObjectSize = MFI.getObjectSize(FI);
1034     auto ObjectAlign = std::max(Align(8), MFI.getObjectAlign(FI));
1035     // If the data type is the fractional vector type, reserve one vector
1036     // register for it.
1037     if (ObjectSize < 8)
1038       ObjectSize = 8;
1039     Offset = alignTo(Offset + ObjectSize, ObjectAlign);
1040     MFI.setObjectOffset(FI, -Offset);
1041     // Update the maximum alignment of the RVV stack section
1042     RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
1043   }
1044 
1045   // Ensure the alignment of the RVV stack. Since we want the most-aligned
1046   // object right at the bottom (i.e., any padding at the top of the frame),
1047   // readjust all RVV objects down by the alignment padding.
1048   uint64_t StackSize = Offset;
1049   if (auto AlignmentPadding = offsetToAlignment(StackSize, RVVStackAlign)) {
1050     StackSize += AlignmentPadding;
1051     for (int FI : ObjectsToAllocate)
1052       MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
1053   }
1054 
1055   return std::make_pair(StackSize, RVVStackAlign);
1056 }
1057 
1058 static unsigned getScavSlotsNumForRVV(MachineFunction &MF) {
1059   // For RVV spill, scalable stack offsets computing requires up to two scratch
1060   // registers
1061   static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
1062 
1063   // For RVV spill, non-scalable stack offsets computing requires up to one
1064   // scratch register.
1065   static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
1066 
1067   // ADDI instruction's destination register can be used for computing
1068   // offsets. So Scalable stack offsets require up to one scratch register.
1069   static constexpr unsigned ScavSlotsADDIScalableObject = 1;
1070 
1071   static constexpr unsigned MaxScavSlotsNumKnown =
1072       std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
1073                 ScavSlotsNumRVVSpillNonScalableObject});
1074 
1075   unsigned MaxScavSlotsNum = 0;
1076   if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
1077     return false;
1078   for (const MachineBasicBlock &MBB : MF)
1079     for (const MachineInstr &MI : MBB) {
1080       bool IsRVVSpill = RISCV::isRVVSpill(MI);
1081       for (auto &MO : MI.operands()) {
1082         if (!MO.isFI())
1083           continue;
1084         bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
1085                                   TargetStackID::ScalableVector;
1086         if (IsRVVSpill) {
1087           MaxScavSlotsNum = std::max(
1088               MaxScavSlotsNum, IsScalableVectorID
1089                                    ? ScavSlotsNumRVVSpillScalableObject
1090                                    : ScavSlotsNumRVVSpillNonScalableObject);
1091         } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
1092           MaxScavSlotsNum =
1093               std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
1094         }
1095       }
1096       if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
1097         return MaxScavSlotsNumKnown;
1098     }
1099   return MaxScavSlotsNum;
1100 }
1101 
1102 static bool hasRVVFrameObject(const MachineFunction &MF) {
1103   // Originally, the function will scan all the stack objects to check whether
1104   // if there is any scalable vector object on the stack or not. However, it
1105   // causes errors in the register allocator. In issue 53016, it returns false
1106   // before RA because there is no RVV stack objects. After RA, it returns true
1107   // because there are spilling slots for RVV values during RA. It will not
1108   // reserve BP during register allocation and generate BP access in the PEI
1109   // pass due to the inconsistent behavior of the function.
1110   //
1111   // The function is changed to use hasVInstructions() as the return value. It
1112   // is not precise, but it can make the register allocation correct.
1113   //
1114   // FIXME: Find a better way to make the decision or revisit the solution in
1115   // D103622.
1116   //
1117   // Refer to https://github.com/llvm/llvm-project/issues/53016.
1118   return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
1119 }
1120 
1121 static unsigned estimateFunctionSizeInBytes(const MachineFunction &MF,
1122                                             const RISCVInstrInfo &TII) {
1123   unsigned FnSize = 0;
1124   for (auto &MBB : MF) {
1125     for (auto &MI : MBB) {
1126       // Far branches over 20-bit offset will be relaxed in branch relaxation
1127       // pass. In the worst case, conditional branches will be relaxed into
1128       // the following instruction sequence. Unconditional branches are
1129       // relaxed in the same way, with the exception that there is no first
1130       // branch instruction.
1131       //
1132       //        foo
1133       //        bne     t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
1134       //        sd      s11, 0(sp)        # 4 bytes, or 2 bytes in RVC
1135       //        jump    .restore, s11     # 8 bytes
1136       // .rev_cond
1137       //        bar
1138       //        j       .dest_bb          # 4 bytes, or 2 bytes in RVC
1139       // .restore:
1140       //        ld      s11, 0(sp)        # 4 bytes, or 2 bytes in RVC
1141       // .dest:
1142       //        baz
1143       if (MI.isConditionalBranch())
1144         FnSize += TII.getInstSizeInBytes(MI);
1145       if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
1146         if (MF.getSubtarget<RISCVSubtarget>().hasStdExtC())
1147           FnSize += 2 + 8 + 2 + 2;
1148         else
1149           FnSize += 4 + 8 + 4 + 4;
1150         continue;
1151       }
1152 
1153       FnSize += TII.getInstSizeInBytes(MI);
1154     }
1155   }
1156   return FnSize;
1157 }
1158 
1159 void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
1160     MachineFunction &MF, RegScavenger *RS) const {
1161   const RISCVRegisterInfo *RegInfo =
1162       MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
1163   const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
1164   MachineFrameInfo &MFI = MF.getFrameInfo();
1165   const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1166   auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1167 
1168   int64_t RVVStackSize;
1169   Align RVVStackAlign;
1170   std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
1171 
1172   RVFI->setRVVStackSize(RVVStackSize);
1173   RVFI->setRVVStackAlign(RVVStackAlign);
1174 
1175   if (hasRVVFrameObject(MF)) {
1176     // Ensure the entire stack is aligned to at least the RVV requirement: some
1177     // scalable-vector object alignments are not considered by the
1178     // target-independent code.
1179     MFI.ensureMaxAlignment(RVVStackAlign);
1180   }
1181 
1182   unsigned ScavSlotsNum = 0;
1183 
1184   // estimateStackSize has been observed to under-estimate the final stack
1185   // size, so give ourselves wiggle-room by checking for stack size
1186   // representable an 11-bit signed field rather than 12-bits.
1187   if (!isInt<11>(MFI.estimateStackSize(MF)))
1188     ScavSlotsNum = 1;
1189 
1190   // Far branches over 20-bit offset require a spill slot for scratch register.
1191   bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
1192   if (IsLargeFunction)
1193     ScavSlotsNum = std::max(ScavSlotsNum, 1u);
1194 
1195   // RVV loads & stores have no capacity to hold the immediate address offsets
1196   // so we must always reserve an emergency spill slot if the MachineFunction
1197   // contains any RVV spills.
1198   ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
1199 
1200   for (unsigned I = 0; I < ScavSlotsNum; I++) {
1201     int FI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
1202                                    RegInfo->getSpillAlign(*RC), false);
1203     RS->addScavengingFrameIndex(FI);
1204 
1205     if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
1206       RVFI->setBranchRelaxationScratchFrameIndex(FI);
1207   }
1208 
1209   if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF) ||
1210       RVFI->isPushable(MF)) {
1211     RVFI->setCalleeSavedStackSize(0);
1212     return;
1213   }
1214 
1215   unsigned Size = 0;
1216   for (const auto &Info : MFI.getCalleeSavedInfo()) {
1217     int FrameIdx = Info.getFrameIdx();
1218     if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
1219       continue;
1220 
1221     Size += MFI.getObjectSize(FrameIdx);
1222   }
1223   RVFI->setCalleeSavedStackSize(Size);
1224 }
1225 
1226 // Not preserve stack space within prologue for outgoing variables when the
1227 // function contains variable size objects or there are vector objects accessed
1228 // by the frame pointer.
1229 // Let eliminateCallFramePseudoInstr preserve stack space for it.
1230 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
1231   return !MF.getFrameInfo().hasVarSizedObjects() &&
1232          !(hasFP(MF) && hasRVVFrameObject(MF));
1233 }
1234 
1235 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
1236 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
1237     MachineFunction &MF, MachineBasicBlock &MBB,
1238     MachineBasicBlock::iterator MI) const {
1239   Register SPReg = RISCV::X2;
1240   DebugLoc DL = MI->getDebugLoc();
1241 
1242   if (!hasReservedCallFrame(MF)) {
1243     // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
1244     // ADJCALLSTACKUP must be converted to instructions manipulating the stack
1245     // pointer. This is necessary when there is a variable length stack
1246     // allocation (e.g. alloca), which means it's not possible to allocate
1247     // space for outgoing arguments from within the function prologue.
1248     int64_t Amount = MI->getOperand(0).getImm();
1249 
1250     if (Amount != 0) {
1251       // Ensure the stack remains aligned after adjustment.
1252       Amount = alignSPAdjust(Amount);
1253 
1254       if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
1255         Amount = -Amount;
1256 
1257       const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
1258       RI.adjustReg(MBB, MI, DL, SPReg, SPReg, StackOffset::getFixed(Amount),
1259                    MachineInstr::NoFlags, getStackAlign());
1260     }
1261   }
1262 
1263   return MBB.erase(MI);
1264 }
1265 
1266 // We would like to split the SP adjustment to reduce prologue/epilogue
1267 // as following instructions. In this way, the offset of the callee saved
1268 // register could fit in a single store. Supposed that the first sp adjust
1269 // amount is 2032.
1270 //   add     sp,sp,-2032
1271 //   sw      ra,2028(sp)
1272 //   sw      s0,2024(sp)
1273 //   sw      s1,2020(sp)
1274 //   sw      s3,2012(sp)
1275 //   sw      s4,2008(sp)
1276 //   add     sp,sp,-64
1277 uint64_t
1278 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
1279   const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1280   const MachineFrameInfo &MFI = MF.getFrameInfo();
1281   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1282   uint64_t StackSize = getStackSizeWithRVVPadding(MF);
1283 
1284   // Disable SplitSPAdjust if save-restore libcall is used. The callee-saved
1285   // registers will be pushed by the save-restore libcalls, so we don't have to
1286   // split the SP adjustment in this case.
1287   if (RVFI->getReservedSpillsSize())
1288     return 0;
1289 
1290   // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
1291   // 12-bit and there exists a callee-saved register needing to be pushed.
1292   if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1293     // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
1294     // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
1295     // instructions. Offsets smaller than 2048 can fit in a single load/store
1296     // instruction, and we have to stick with the stack alignment. 2048 has
1297     // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
1298     // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1299     const uint64_t StackAlign = getStackAlign().value();
1300 
1301     // Amount of (2048 - StackAlign) will prevent callee saved and restored
1302     // instructions be compressed, so try to adjust the amount to the largest
1303     // offset that stack compression instructions accept when target supports
1304     // compression instructions.
1305     if (STI.hasStdExtCOrZca()) {
1306       // The compression extensions may support the following instructions:
1307       // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
1308       //          c.swsp rs2, offset[7:2] => 2^(6 + 2)
1309       //          c.flwsp rd, offset[7:2] => 2^(6 + 2)
1310       //          c.fswsp rs2, offset[7:2] => 2^(6 + 2)
1311       // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
1312       //          c.sdsp rs2, offset[8:3] => 2^(6 + 3)
1313       //          c.fldsp rd, offset[8:3] => 2^(6 + 3)
1314       //          c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
1315       const uint64_t RVCompressLen = STI.getXLen() * 8;
1316       // Compared with amount (2048 - StackAlign), StackSize needs to
1317       // satisfy the following conditions to avoid using more instructions
1318       // to adjust the sp after adjusting the amount, such as
1319       // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
1320       // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
1321       // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
1322       auto CanCompress = [&](uint64_t CompressLen) -> bool {
1323         if (StackSize <= 2047 + CompressLen ||
1324             (StackSize > 2048 * 2 - StackAlign &&
1325              StackSize <= 2047 * 2 + CompressLen) ||
1326             StackSize > 2048 * 3 - StackAlign)
1327           return true;
1328 
1329         return false;
1330       };
1331       // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
1332       // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
1333       // addi sp, sp, 512 can not be compressed. So try to use 496 first.
1334       const uint64_t ADDI16SPCompressLen = 496;
1335       if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
1336         return ADDI16SPCompressLen;
1337       if (CanCompress(RVCompressLen))
1338         return RVCompressLen;
1339     }
1340     return 2048 - StackAlign;
1341   }
1342   return 0;
1343 }
1344 
1345 bool RISCVFrameLowering::spillCalleeSavedRegisters(
1346     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1347     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1348   if (CSI.empty())
1349     return true;
1350 
1351   MachineFunction *MF = MBB.getParent();
1352   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1353   DebugLoc DL;
1354   if (MI != MBB.end() && !MI->isDebugInstr())
1355     DL = MI->getDebugLoc();
1356 
1357   // Emit CM.PUSH with base SPimm & evaluate Push stack
1358   RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1359   if (RVFI->isPushable(*MF)) {
1360     Register MaxReg = getMaxPushPopReg(*MF, CSI);
1361     if (MaxReg != RISCV::NoRegister) {
1362       auto [RegEnc, PushedRegNum] = getPushPopEncodingAndNum(MaxReg);
1363       RVFI->setRVPushRegs(PushedRegNum);
1364       RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
1365 
1366       // Use encoded number to represent registers to spill.
1367       RVFI->setRVPushRlist(RegEnc);
1368       MachineInstrBuilder PushBuilder =
1369           BuildMI(MBB, MI, DL, TII.get(RISCV::CM_PUSH))
1370               .setMIFlag(MachineInstr::FrameSetup);
1371       PushBuilder.addImm((int64_t)RegEnc);
1372       PushBuilder.addImm(0);
1373 
1374       for (unsigned i = 0; i < PushedRegNum; i++)
1375         PushBuilder.addUse(AllPopRegs[i], RegState::Implicit);
1376     }
1377   } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
1378     // Add spill libcall via non-callee-saved register t0.
1379     BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1380         .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1381         .setMIFlag(MachineInstr::FrameSetup);
1382 
1383     // Add registers spilled in libcall as liveins.
1384     for (auto &CS : CSI)
1385       MBB.addLiveIn(CS.getReg());
1386   }
1387 
1388   // Manually spill values not spilled by libcall & Push/Pop.
1389   const auto &UnmanagedCSI = getUnmanagedCSI(*MF, CSI);
1390   for (auto &CS : UnmanagedCSI) {
1391     // Insert the spill to the stack frame.
1392     Register Reg = CS.getReg();
1393     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1394     TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1395                             RC, TRI, Register());
1396   }
1397 
1398   return true;
1399 }
1400 
1401 bool RISCVFrameLowering::restoreCalleeSavedRegisters(
1402     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1403     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1404   if (CSI.empty())
1405     return true;
1406 
1407   MachineFunction *MF = MBB.getParent();
1408   const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1409   DebugLoc DL;
1410   if (MI != MBB.end() && !MI->isDebugInstr())
1411     DL = MI->getDebugLoc();
1412 
1413   // Manually restore values not restored by libcall & Push/Pop.
1414   // Keep the same order as in the prologue. There is no need to reverse the
1415   // order in the epilogue. In addition, the return address will be restored
1416   // first in the epilogue. It increases the opportunity to avoid the
1417   // load-to-use data hazard between loading RA and return by RA.
1418   // loadRegFromStackSlot can insert multiple instructions.
1419   const auto &UnmanagedCSI = getUnmanagedCSI(*MF, CSI);
1420   for (auto &CS : UnmanagedCSI) {
1421     Register Reg = CS.getReg();
1422     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1423     TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI,
1424                              Register());
1425     assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1426   }
1427 
1428   RISCVMachineFunctionInfo *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1429   if (RVFI->isPushable(*MF)) {
1430     int RegEnc = RVFI->getRVPushRlist();
1431     if (RegEnc != llvm::RISCVZC::RLISTENCODE::INVALID_RLIST) {
1432       MachineInstrBuilder PopBuilder =
1433           BuildMI(MBB, MI, DL, TII.get(RISCV::CM_POP))
1434               .setMIFlag(MachineInstr::FrameDestroy);
1435       // Use encoded number to represent registers to restore.
1436       PopBuilder.addImm(RegEnc);
1437       PopBuilder.addImm(0);
1438 
1439       for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
1440         PopBuilder.addDef(AllPopRegs[i], RegState::ImplicitDefine);
1441     }
1442   } else {
1443     const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1444     if (RestoreLibCall) {
1445       // Add restore libcall via tail call.
1446       MachineBasicBlock::iterator NewMI =
1447           BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1448               .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1449               .setMIFlag(MachineInstr::FrameDestroy);
1450 
1451       // Remove trailing returns, since the terminator is now a tail call to the
1452       // restore function.
1453       if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1454         NewMI->copyImplicitOps(*MF, *MI);
1455         MI->eraseFromParent();
1456       }
1457     }
1458   }
1459   return true;
1460 }
1461 
1462 bool RISCVFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1463   // Keep the conventional code flow when not optimizing.
1464   if (MF.getFunction().hasOptNone())
1465     return false;
1466 
1467   return true;
1468 }
1469 
1470 bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
1471   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1472   const MachineFunction *MF = MBB.getParent();
1473   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1474 
1475   if (!RVFI->useSaveRestoreLibCalls(*MF))
1476     return true;
1477 
1478   // Inserting a call to a __riscv_save libcall requires the use of the register
1479   // t0 (X5) to hold the return address. Therefore if this register is already
1480   // used we can't insert the call.
1481 
1482   RegScavenger RS;
1483   RS.enterBasicBlock(*TmpMBB);
1484   return !RS.isRegUsed(RISCV::X5);
1485 }
1486 
1487 bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1488   const MachineFunction *MF = MBB.getParent();
1489   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1490   const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1491 
1492   if (!RVFI->useSaveRestoreLibCalls(*MF))
1493     return true;
1494 
1495   // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1496   // This means if we still need to continue executing code within this function
1497   // the restore cannot take place in this basic block.
1498 
1499   if (MBB.succ_size() > 1)
1500     return false;
1501 
1502   MachineBasicBlock *SuccMBB =
1503       MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1504 
1505   // Doing a tail call should be safe if there are no successors, because either
1506   // we have a returning block or the end of the block is unreachable, so the
1507   // restore will be eliminated regardless.
1508   if (!SuccMBB)
1509     return true;
1510 
1511   // The successor can only contain a return, since we would effectively be
1512   // replacing the successor with our own tail return at the end of our block.
1513   return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1514 }
1515 
1516 bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
1517   switch (ID) {
1518   case TargetStackID::Default:
1519   case TargetStackID::ScalableVector:
1520     return true;
1521   case TargetStackID::NoAlloc:
1522   case TargetStackID::SGPRSpill:
1523   case TargetStackID::WasmLocal:
1524     return false;
1525   }
1526   llvm_unreachable("Invalid TargetStackID::Value");
1527 }
1528 
1529 TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
1530   return TargetStackID::ScalableVector;
1531 }
1532