LLVM 18.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"
15#include "RISCVSubtarget.h"
23#include "llvm/MC/MCDwarf.h"
24#include "llvm/Support/LEB128.h"
25
26#include <algorithm>
27
28using namespace llvm;
29
30static 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.
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
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)
67 BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
68 .addReg(RAReg)
69 .addReg(SCSPReg)
70 .addImm(-SlotSize)
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)
92}
93
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)
122 BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
123 .addReg(SCSPReg, RegState::Define)
124 .addReg(SCSPReg)
125 .addImm(-SlotSize)
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)
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.
139static 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.
177static const char *
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.
204static const char *
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.
231static std::pair<unsigned, unsigned>
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.
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.
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() ||
291}
292
294 const MachineFrameInfo &MFI = MF.getFrameInfo();
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() ||
303 MFI.getMaxCallFrameSize() != 0))) &&
304 TRI->hasStackRealignment(MF);
305}
306
307// Determines the size of the frame and maximum call frame size.
308void 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.
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.
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.
348static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
349
350// Returns the register used to hold the stack pointer.
351static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
352
355 const std::vector<CalleeSavedInfo> &CSI) {
356 const MachineFrameInfo &MFI = MF.getFrameInfo();
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
368void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
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
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)) {
388 "Frame size outside of the signed 32-bit range not supported");
389 }
390 Offset = StackOffset::getFixed(FixedOffset);
391 }
392
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
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
448 MachineBasicBlock &MBB) const {
449 MachineFrameInfo &MFI = MF.getFrameInfo();
450 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
454
455 Register FPReg = getFPReg(STI);
456 Register SPReg = getSPReg(STI);
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.
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))
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->getOpcode() == RISCV::CM_PUSH) {
530 // Use available stack adjustment in push instruction to allocate additional
531 // stack space.
532 uint64_t Spimm = std::min(StackSize, (uint64_t)48);
533 FirstFrameSetup->getOperand(1).setImm(Spimm);
534 StackSize -= Spimm;
535 }
536
537 if (StackSize != 0) {
538 // Allocate space on the stack if necessary.
539 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
541 getStackAlign());
542 }
543
544 // Emit ".cfi_def_cfa_offset RealStackSize"
545 unsigned CFIIndex = MF.addFrameInst(
546 MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
547 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
548 .addCFIIndex(CFIIndex)
550
551 const auto &CSI = MFI.getCalleeSavedInfo();
552
553 // The frame pointer is callee-saved, and code has been generated for us to
554 // save it to the stack. We need to skip over the storing of callee-saved
555 // registers as the frame pointer must be modified after it has been saved
556 // to the stack, not before.
557 // FIXME: assumes exactly one instruction is used to save each callee-saved
558 // register.
559 std::advance(MBBI, getUnmanagedCSI(MF, CSI).size());
560
561 // Iterate over list of callee-saved registers and emit .cfi_offset
562 // directives.
563 for (const auto &Entry : CSI) {
564 int FrameIdx = Entry.getFrameIdx();
565 int64_t Offset;
566 // Offsets for objects with fixed locations (IE: those saved by libcall) are
567 // simply calculated from the frame index.
568 if (FrameIdx < 0) {
569 if (RVFI->isPushable(MF)) {
570 // Callee-saved register stored by Zcmp push is in reverse order.
571 Offset = -(FrameIdx + RVFI->getRVPushRegs() + 1) *
572 (int64_t)STI.getXLen() / 8;
573 } else {
574 Offset = FrameIdx * (int64_t)STI.getXLen() / 8;
575 }
576 } else {
577 Offset = MFI.getObjectOffset(FrameIdx) - RVFI->getReservedSpillsSize();
578 }
579 Register Reg = Entry.getReg();
580 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
581 nullptr, RI->getDwarfRegNum(Reg, true), Offset));
582 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
583 .addCFIIndex(CFIIndex)
585 }
586
587 // Generate new FP.
588 if (hasFP(MF)) {
589 if (STI.isRegisterReservedByUser(FPReg))
591 MF.getFunction(), "Frame pointer required, but has been reserved."});
592 // The frame pointer does need to be reserved from register allocation.
593 assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved");
594
595 RI->adjustReg(MBB, MBBI, DL, FPReg, SPReg,
596 StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()),
598
599 // Emit ".cfi_def_cfa $fp, RVFI->getVarArgsSaveSize()"
600 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
601 nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
602 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
603 .addCFIIndex(CFIIndex)
605 }
606
607 // Emit the second SP adjustment after saving callee saved registers.
608 if (FirstSPAdjustAmount) {
609 uint64_t SecondSPAdjustAmount =
610 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
611 assert(SecondSPAdjustAmount > 0 &&
612 "SecondSPAdjustAmount should be greater than zero");
613 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
614 StackOffset::getFixed(-SecondSPAdjustAmount),
616
617 // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
618 // don't emit an sp-based .cfi_def_cfa_offset
619 if (!hasFP(MF)) {
620 // Emit ".cfi_def_cfa_offset StackSize"
621 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
622 nullptr, getStackSizeWithRVVPadding(MF)));
623 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
624 .addCFIIndex(CFIIndex)
626 }
627 }
628
629 if (RVVStackSize) {
630 adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
632 if (!hasFP(MF)) {
633 // Emit .cfi_def_cfa_expression "sp + StackSize + RVVStackSize * vlenb".
634 unsigned CFIIndex = MF.addFrameInst(createDefCFAExpression(
635 *RI, SPReg, getStackSizeWithRVVPadding(MF), RVVStackSize / 8));
636 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
637 .addCFIIndex(CFIIndex)
639 }
640 }
641
642 if (hasFP(MF)) {
643 // Realign Stack
645 if (RI->hasStackRealignment(MF)) {
646 Align MaxAlignment = MFI.getMaxAlign();
647
649 if (isInt<12>(-(int)MaxAlignment.value())) {
650 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
651 .addReg(SPReg)
652 .addImm(-(int)MaxAlignment.value())
654 } else {
655 unsigned ShiftAmount = Log2(MaxAlignment);
656 Register VR =
657 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
658 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
659 .addReg(SPReg)
660 .addImm(ShiftAmount)
662 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
663 .addReg(VR)
664 .addImm(ShiftAmount)
666 }
667 // FP will be used to restore the frame in the epilogue, so we need
668 // another base register BP to record SP after re-alignment. SP will
669 // track the current stack after allocating variable sized objects.
670 if (hasBP(MF)) {
671 // move BP, SP
672 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
673 .addReg(SPReg)
674 .addImm(0)
676 }
677 }
678 }
679}
680
682 MachineBasicBlock &MBB) const {
684 MachineFrameInfo &MFI = MF.getFrameInfo();
685 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
686 Register FPReg = getFPReg(STI);
687 Register SPReg = getSPReg(STI);
688
689 // All calls are tail calls in GHC calling conv, and functions have no
690 // prologue/epilogue.
692 return;
693
694 // Get the insert location for the epilogue. If there were no terminators in
695 // the block, get the last instruction.
697 DebugLoc DL;
698 if (!MBB.empty()) {
700 if (MBBI != MBB.end())
701 DL = MBBI->getDebugLoc();
702
704
705 // If callee-saved registers are saved via libcall, place stack adjustment
706 // before this call.
707 while (MBBI != MBB.begin() &&
708 std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
709 --MBBI;
710 }
711
712 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo());
713
714 // Skip to before the restores of callee-saved registers
715 // FIXME: assumes exactly one instruction is used to restore each
716 // callee-saved register.
717 auto LastFrameDestroy = MBBI;
718 if (!CSI.empty())
719 LastFrameDestroy = std::prev(MBBI, CSI.size());
720
721 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
722 uint64_t RealStackSize = StackSize + RVFI->getReservedSpillsSize();
723 uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
724 uint64_t RVVStackSize = RVFI->getRVVStackSize();
725
726 // Restore the stack pointer using the value of the frame pointer. Only
727 // necessary if the stack pointer was modified, meaning the stack size is
728 // unknown.
729 //
730 // In order to make sure the stack point is right through the EH region,
731 // we also need to restore stack pointer from the frame pointer if we
732 // don't preserve stack space within prologue/epilogue for outgoing variables,
733 // normally it's just checking the variable sized object is present or not
734 // is enough, but we also don't preserve that at prologue/epilogue when
735 // have vector objects in stack.
736 if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
738 assert(hasFP(MF) && "frame pointer should not have been eliminated");
739 RI->adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg,
740 StackOffset::getFixed(-FPOffset),
742 } else {
743 if (RVVStackSize)
744 adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
746 }
747
748 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
749 if (FirstSPAdjustAmount) {
750 uint64_t SecondSPAdjustAmount =
751 getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
752 assert(SecondSPAdjustAmount > 0 &&
753 "SecondSPAdjustAmount should be greater than zero");
754
755 RI->adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg,
756 StackOffset::getFixed(SecondSPAdjustAmount),
758 }
759
760 if (FirstSPAdjustAmount)
761 StackSize = FirstSPAdjustAmount;
762
763 if (RVFI->isPushable(MF) && MBBI != MBB.end() &&
764 MBBI->getOpcode() == RISCV::CM_POP) {
765 // Use available stack adjustment in pop instruction to deallocate stack
766 // space.
767 uint64_t Spimm = std::min(StackSize, (uint64_t)48);
768 MBBI->getOperand(1).setImm(Spimm);
769 StackSize -= Spimm;
770 }
771
772 // Deallocate stack
773 if (StackSize != 0) {
774 RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(StackSize),
776 }
777
778 // Emit epilogue for shadow call stack.
779 emitSCSEpilogue(MF, MBB, MBBI, DL);
780}
781
784 Register &FrameReg) const {
785 const MachineFrameInfo &MFI = MF.getFrameInfo();
787 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
788
789 // Callee-saved registers should be referenced relative to the stack
790 // pointer (positive offset), otherwise use the frame pointer (negative
791 // offset).
792 const auto &CSI = getUnmanagedCSI(MF, MFI.getCalleeSavedInfo());
793 int MinCSFI = 0;
794 int MaxCSFI = -1;
796 auto StackID = MFI.getStackID(FI);
797
798 assert((StackID == TargetStackID::Default ||
799 StackID == TargetStackID::ScalableVector) &&
800 "Unexpected stack ID for the frame object.");
801 if (StackID == TargetStackID::Default) {
802 Offset =
804 MFI.getOffsetAdjustment());
805 } else if (StackID == TargetStackID::ScalableVector) {
807 }
808
809 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
810
811 if (CSI.size()) {
812 MinCSFI = CSI[0].getFrameIdx();
813 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
814 }
815
816 if (FI >= MinCSFI && FI <= MaxCSFI) {
817 FrameReg = RISCV::X2;
818
819 if (FirstSPAdjustAmount)
820 Offset += StackOffset::getFixed(FirstSPAdjustAmount);
821 else
823 return Offset;
824 }
825
826 if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
827 // If the stack was realigned, the frame pointer is set in order to allow
828 // SP to be restored, so we need another base register to record the stack
829 // after realignment.
830 // |--------------------------| -- <-- FP
831 // | callee-allocated save | | <----|
832 // | area for register varargs| | |
833 // |--------------------------| | |
834 // | callee-saved registers | | |
835 // |--------------------------| -- |
836 // | realignment (the size of | | |
837 // | this area is not counted | | |
838 // | in MFI.getStackSize()) | | |
839 // |--------------------------| -- |-- MFI.getStackSize()
840 // | RVV alignment padding | | |
841 // | (not counted in | | |
842 // | MFI.getStackSize() but | | |
843 // | counted in | | |
844 // | RVFI.getRVVStackSize()) | | |
845 // |--------------------------| -- |
846 // | RVV objects | | |
847 // | (not counted in | | |
848 // | MFI.getStackSize()) | | |
849 // |--------------------------| -- |
850 // | padding before RVV | | |
851 // | (not counted in | | |
852 // | MFI.getStackSize() or in | | |
853 // | RVFI.getRVVStackSize()) | | |
854 // |--------------------------| -- |
855 // | scalar local variables | | <----'
856 // |--------------------------| -- <-- BP (if var sized objects present)
857 // | VarSize objects | |
858 // |--------------------------| -- <-- SP
859 if (hasBP(MF)) {
860 FrameReg = RISCVABI::getBPReg();
861 } else {
862 // VarSize objects must be empty in this case!
864 FrameReg = RISCV::X2;
865 }
866 } else {
867 FrameReg = RI->getFrameRegister(MF);
868 }
869
870 if (FrameReg == getFPReg(STI)) {
871 Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
872 if (FI >= 0)
873 Offset -= StackOffset::getFixed(RVFI->getReservedSpillsSize());
874 // When using FP to access scalable vector objects, we need to minus
875 // the frame size.
876 //
877 // |--------------------------| -- <-- FP
878 // | callee-allocated save | |
879 // | area for register varargs| |
880 // |--------------------------| |
881 // | callee-saved registers | |
882 // |--------------------------| | MFI.getStackSize()
883 // | scalar local variables | |
884 // |--------------------------| -- (Offset of RVV objects is from here.)
885 // | RVV objects |
886 // |--------------------------|
887 // | VarSize objects |
888 // |--------------------------| <-- SP
890 assert(!RI->hasStackRealignment(MF) &&
891 "Can't index across variable sized realign");
892 // We don't expect any extra RVV alignment padding, as the stack size
893 // and RVV object sections should be correct aligned in their own
894 // right.
896 "Inconsistent stack layout");
898 }
899 return Offset;
900 }
901
902 // This case handles indexing off both SP and BP.
903 // If indexing off SP, there must not be any var sized objects
904 assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
905
906 // When using SP to access frame objects, we need to add RVV stack size.
907 //
908 // |--------------------------| -- <-- FP
909 // | callee-allocated save | | <----|
910 // | area for register varargs| | |
911 // |--------------------------| | |
912 // | callee-saved registers | | |
913 // |--------------------------| -- |
914 // | RVV alignment padding | | |
915 // | (not counted in | | |
916 // | MFI.getStackSize() but | | |
917 // | counted in | | |
918 // | RVFI.getRVVStackSize()) | | |
919 // |--------------------------| -- |
920 // | RVV objects | | |-- MFI.getStackSize()
921 // | (not counted in | | |
922 // | MFI.getStackSize()) | | |
923 // |--------------------------| -- |
924 // | padding before RVV | | |
925 // | (not counted in | | |
926 // | MFI.getStackSize()) | | |
927 // |--------------------------| -- |
928 // | scalar local variables | | <----'
929 // |--------------------------| -- <-- BP (if var sized objects present)
930 // | VarSize objects | |
931 // |--------------------------| -- <-- SP
932 //
933 // The total amount of padding surrounding RVV objects is described by
934 // RVV->getRVVPadding() and it can be zero. It allows us to align the RVV
935 // objects to the required alignment.
936 if (MFI.getStackID(FI) == TargetStackID::Default) {
937 if (MFI.isFixedObjectIndex(FI)) {
938 assert(!RI->hasStackRealignment(MF) &&
939 "Can't index across variable sized realign");
941 RVFI->getReservedSpillsSize(),
942 RVFI->getRVVStackSize());
943 } else {
945 }
946 } else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
947 // Ensure the base of the RVV stack is correctly aligned: add on the
948 // alignment padding.
949 int ScalarLocalVarSize = MFI.getStackSize() -
950 RVFI->getCalleeSavedStackSize() -
951 RVFI->getRVPushStackSize() -
952 RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
953 Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
954 }
955 return Offset;
956}
957
959 BitVector &SavedRegs,
960 RegScavenger *RS) const {
962 // Unconditionally spill RA and FP only if the function uses a frame
963 // pointer.
964 if (hasFP(MF)) {
965 SavedRegs.set(RISCV::X1);
966 SavedRegs.set(RISCV::X8);
967 }
968 // Mark BP as used if function has dedicated base pointer.
969 if (hasBP(MF))
970 SavedRegs.set(RISCVABI::getBPReg());
971
972 // If interrupt is enabled and there are calls in the handler,
973 // unconditionally save all Caller-saved registers and
974 // all FP registers, regardless whether they are used.
975 MachineFrameInfo &MFI = MF.getFrameInfo();
976
977 if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
978
979 static const MCPhysReg CSRegs[] = { RISCV::X1, /* ra */
980 RISCV::X5, RISCV::X6, RISCV::X7, /* t0-t2 */
981 RISCV::X10, RISCV::X11, /* a0-a1, a2-a7 */
982 RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
983 RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */
984 };
985
986 for (unsigned i = 0; CSRegs[i]; ++i)
987 SavedRegs.set(CSRegs[i]);
988
989 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
990
991 // If interrupt is enabled, this list contains all FP registers.
992 const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
993
994 for (unsigned i = 0; Regs[i]; ++i)
995 if (RISCV::FPR16RegClass.contains(Regs[i]) ||
996 RISCV::FPR32RegClass.contains(Regs[i]) ||
997 RISCV::FPR64RegClass.contains(Regs[i]))
998 SavedRegs.set(Regs[i]);
999 }
1000 }
1001}
1002
1003std::pair<int64_t, Align>
1004RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
1005 MachineFrameInfo &MFI = MF.getFrameInfo();
1006 // Create a buffer of RVV objects to allocate.
1007 SmallVector<int, 8> ObjectsToAllocate;
1008 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
1009 unsigned StackID = MFI.getStackID(I);
1010 if (StackID != TargetStackID::ScalableVector)
1011 continue;
1012 if (MFI.isDeadObjectIndex(I))
1013 continue;
1014
1015 ObjectsToAllocate.push_back(I);
1016 }
1017
1018 // The minimum alignment is 16 bytes.
1019 Align RVVStackAlign(16);
1020 const auto &ST = MF.getSubtarget<RISCVSubtarget>();
1021
1022 if (!ST.hasVInstructions()) {
1023 assert(ObjectsToAllocate.empty() &&
1024 "Can't allocate scalable-vector objects without V instructions");
1025 return std::make_pair(0, RVVStackAlign);
1026 }
1027
1028 // Allocate all RVV locals and spills
1029 int64_t Offset = 0;
1030 for (int FI : ObjectsToAllocate) {
1031 // ObjectSize in bytes.
1032 int64_t ObjectSize = MFI.getObjectSize(FI);
1033 auto ObjectAlign = std::max(Align(8), MFI.getObjectAlign(FI));
1034 // If the data type is the fractional vector type, reserve one vector
1035 // register for it.
1036 if (ObjectSize < 8)
1037 ObjectSize = 8;
1038 Offset = alignTo(Offset + ObjectSize, ObjectAlign);
1039 MFI.setObjectOffset(FI, -Offset);
1040 // Update the maximum alignment of the RVV stack section
1041 RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
1042 }
1043
1044 // Ensure the alignment of the RVV stack. Since we want the most-aligned
1045 // object right at the bottom (i.e., any padding at the top of the frame),
1046 // readjust all RVV objects down by the alignment padding.
1047 uint64_t StackSize = Offset;
1048 if (auto AlignmentPadding = offsetToAlignment(StackSize, RVVStackAlign)) {
1049 StackSize += AlignmentPadding;
1050 for (int FI : ObjectsToAllocate)
1051 MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
1052 }
1053
1054 return std::make_pair(StackSize, RVVStackAlign);
1055}
1056
1058 // For RVV spill, scalable stack offsets computing requires up to two scratch
1059 // registers
1060 static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
1061
1062 // For RVV spill, non-scalable stack offsets computing requires up to one
1063 // scratch register.
1064 static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
1065
1066 // ADDI instruction's destination register can be used for computing
1067 // offsets. So Scalable stack offsets require up to one scratch register.
1068 static constexpr unsigned ScavSlotsADDIScalableObject = 1;
1069
1070 static constexpr unsigned MaxScavSlotsNumKnown =
1071 std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
1072 ScavSlotsNumRVVSpillNonScalableObject});
1073
1074 unsigned MaxScavSlotsNum = 0;
1076 return false;
1077 for (const MachineBasicBlock &MBB : MF)
1078 for (const MachineInstr &MI : MBB) {
1079 bool IsRVVSpill = RISCV::isRVVSpill(MI);
1080 for (auto &MO : MI.operands()) {
1081 if (!MO.isFI())
1082 continue;
1083 bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
1085 if (IsRVVSpill) {
1086 MaxScavSlotsNum = std::max(
1087 MaxScavSlotsNum, IsScalableVectorID
1088 ? ScavSlotsNumRVVSpillScalableObject
1089 : ScavSlotsNumRVVSpillNonScalableObject);
1090 } else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
1091 MaxScavSlotsNum =
1092 std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
1093 }
1094 }
1095 if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
1096 return MaxScavSlotsNumKnown;
1097 }
1098 return MaxScavSlotsNum;
1099}
1100
1101static bool hasRVVFrameObject(const MachineFunction &MF) {
1102 // Originally, the function will scan all the stack objects to check whether
1103 // if there is any scalable vector object on the stack or not. However, it
1104 // causes errors in the register allocator. In issue 53016, it returns false
1105 // before RA because there is no RVV stack objects. After RA, it returns true
1106 // because there are spilling slots for RVV values during RA. It will not
1107 // reserve BP during register allocation and generate BP access in the PEI
1108 // pass due to the inconsistent behavior of the function.
1109 //
1110 // The function is changed to use hasVInstructions() as the return value. It
1111 // is not precise, but it can make the register allocation correct.
1112 //
1113 // FIXME: Find a better way to make the decision or revisit the solution in
1114 // D103622.
1115 //
1116 // Refer to https://github.com/llvm/llvm-project/issues/53016.
1117 return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
1118}
1119
1121 const RISCVInstrInfo &TII) {
1122 unsigned FnSize = 0;
1123 for (auto &MBB : MF) {
1124 for (auto &MI : MBB) {
1125 // Far branches over 20-bit offset will be relaxed in branch relaxation
1126 // pass. In the worst case, conditional branches will be relaxed into
1127 // the following instruction sequence. Unconditional branches are
1128 // relaxed in the same way, with the exception that there is no first
1129 // branch instruction.
1130 //
1131 // foo
1132 // bne t5, t6, .rev_cond # `TII->getInstSizeInBytes(MI)` bytes
1133 // sd s11, 0(sp) # 4 bytes, or 2 bytes in RVC
1134 // jump .restore, s11 # 8 bytes
1135 // .rev_cond
1136 // bar
1137 // j .dest_bb # 4 bytes, or 2 bytes in RVC
1138 // .restore:
1139 // ld s11, 0(sp) # 4 bytes, or 2 bytes in RVC
1140 // .dest:
1141 // baz
1142 if (MI.isConditionalBranch())
1143 FnSize += TII.getInstSizeInBytes(MI);
1144 if (MI.isConditionalBranch() || MI.isUnconditionalBranch()) {
1145 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtC())
1146 FnSize += 2 + 8 + 2 + 2;
1147 else
1148 FnSize += 4 + 8 + 4 + 4;
1149 continue;
1150 }
1151
1152 FnSize += TII.getInstSizeInBytes(MI);
1153 }
1154 }
1155 return FnSize;
1156}
1157
1159 MachineFunction &MF, RegScavenger *RS) const {
1160 const RISCVRegisterInfo *RegInfo =
1161 MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
1162 const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
1163 MachineFrameInfo &MFI = MF.getFrameInfo();
1164 const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1165 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1166
1167 int64_t RVVStackSize;
1168 Align RVVStackAlign;
1169 std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
1170
1171 RVFI->setRVVStackSize(RVVStackSize);
1172 RVFI->setRVVStackAlign(RVVStackAlign);
1173
1174 if (hasRVVFrameObject(MF)) {
1175 // Ensure the entire stack is aligned to at least the RVV requirement: some
1176 // scalable-vector object alignments are not considered by the
1177 // target-independent code.
1178 MFI.ensureMaxAlignment(RVVStackAlign);
1179 }
1180
1181 unsigned ScavSlotsNum = 0;
1182
1183 // estimateStackSize has been observed to under-estimate the final stack
1184 // size, so give ourselves wiggle-room by checking for stack size
1185 // representable an 11-bit signed field rather than 12-bits.
1186 if (!isInt<11>(MFI.estimateStackSize(MF)))
1187 ScavSlotsNum = 1;
1188
1189 // Far branches over 20-bit offset require a spill slot for scratch register.
1190 bool IsLargeFunction = !isInt<20>(estimateFunctionSizeInBytes(MF, *TII));
1191 if (IsLargeFunction)
1192 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
1193
1194 // RVV loads & stores have no capacity to hold the immediate address offsets
1195 // so we must always reserve an emergency spill slot if the MachineFunction
1196 // contains any RVV spills.
1197 ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
1198
1199 for (unsigned I = 0; I < ScavSlotsNum; I++) {
1200 int FI = MFI.CreateStackObject(RegInfo->getSpillSize(*RC),
1201 RegInfo->getSpillAlign(*RC), false);
1203
1204 if (IsLargeFunction && RVFI->getBranchRelaxationScratchFrameIndex() == -1)
1205 RVFI->setBranchRelaxationScratchFrameIndex(FI);
1206 }
1207
1208 if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF) ||
1209 RVFI->isPushable(MF)) {
1210 RVFI->setCalleeSavedStackSize(0);
1211 return;
1212 }
1213
1214 unsigned Size = 0;
1215 for (const auto &Info : MFI.getCalleeSavedInfo()) {
1216 int FrameIdx = Info.getFrameIdx();
1217 if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
1218 continue;
1219
1220 Size += MFI.getObjectSize(FrameIdx);
1221 }
1222 RVFI->setCalleeSavedStackSize(Size);
1223}
1224
1225// Not preserve stack space within prologue for outgoing variables when the
1226// function contains variable size objects or there are vector objects accessed
1227// by the frame pointer.
1228// Let eliminateCallFramePseudoInstr preserve stack space for it.
1230 return !MF.getFrameInfo().hasVarSizedObjects() &&
1231 !(hasFP(MF) && hasRVVFrameObject(MF));
1232}
1233
1234// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions.
1238 Register SPReg = RISCV::X2;
1239 DebugLoc DL = MI->getDebugLoc();
1240
1241 if (!hasReservedCallFrame(MF)) {
1242 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and
1243 // ADJCALLSTACKUP must be converted to instructions manipulating the stack
1244 // pointer. This is necessary when there is a variable length stack
1245 // allocation (e.g. alloca), which means it's not possible to allocate
1246 // space for outgoing arguments from within the function prologue.
1247 int64_t Amount = MI->getOperand(0).getImm();
1248
1249 if (Amount != 0) {
1250 // Ensure the stack remains aligned after adjustment.
1251 Amount = alignSPAdjust(Amount);
1252
1253 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
1254 Amount = -Amount;
1255
1256 const RISCVRegisterInfo &RI = *STI.getRegisterInfo();
1257 RI.adjustReg(MBB, MI, DL, SPReg, SPReg, StackOffset::getFixed(Amount),
1259 }
1260 }
1261
1262 return MBB.erase(MI);
1263}
1264
1265// We would like to split the SP adjustment to reduce prologue/epilogue
1266// as following instructions. In this way, the offset of the callee saved
1267// register could fit in a single store. Supposed that the first sp adjust
1268// amount is 2032.
1269// add sp,sp,-2032
1270// sw ra,2028(sp)
1271// sw s0,2024(sp)
1272// sw s1,2020(sp)
1273// sw s3,2012(sp)
1274// sw s4,2008(sp)
1275// add sp,sp,-64
1278 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
1279 const MachineFrameInfo &MFI = MF.getFrameInfo();
1280 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1281 uint64_t StackSize = getStackSizeWithRVVPadding(MF);
1282
1283 // Disable SplitSPAdjust if save-restore libcall is used. The callee-saved
1284 // registers will be pushed by the save-restore libcalls, so we don't have to
1285 // split the SP adjustment in this case.
1286 if (RVFI->getReservedSpillsSize())
1287 return 0;
1288
1289 // Return the FirstSPAdjustAmount if the StackSize can not fit in a signed
1290 // 12-bit and there exists a callee-saved register needing to be pushed.
1291 if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
1292 // FirstSPAdjustAmount is chosen at most as (2048 - StackAlign) because
1293 // 2048 will cause sp = sp + 2048 in the epilogue to be split into multiple
1294 // instructions. Offsets smaller than 2048 can fit in a single load/store
1295 // instruction, and we have to stick with the stack alignment. 2048 has
1296 // 16-byte alignment. The stack alignment for RV32 and RV64 is 16 and for
1297 // RV32E it is 4. So (2048 - StackAlign) will satisfy the stack alignment.
1298 const uint64_t StackAlign = getStackAlign().value();
1299
1300 // Amount of (2048 - StackAlign) will prevent callee saved and restored
1301 // instructions be compressed, so try to adjust the amount to the largest
1302 // offset that stack compression instructions accept when target supports
1303 // compression instructions.
1304 if (STI.hasStdExtCOrZca()) {
1305 // The compression extensions may support the following instructions:
1306 // riscv32: c.lwsp rd, offset[7:2] => 2^(6 + 2)
1307 // c.swsp rs2, offset[7:2] => 2^(6 + 2)
1308 // c.flwsp rd, offset[7:2] => 2^(6 + 2)
1309 // c.fswsp rs2, offset[7:2] => 2^(6 + 2)
1310 // riscv64: c.ldsp rd, offset[8:3] => 2^(6 + 3)
1311 // c.sdsp rs2, offset[8:3] => 2^(6 + 3)
1312 // c.fldsp rd, offset[8:3] => 2^(6 + 3)
1313 // c.fsdsp rs2, offset[8:3] => 2^(6 + 3)
1314 const uint64_t RVCompressLen = STI.getXLen() * 8;
1315 // Compared with amount (2048 - StackAlign), StackSize needs to
1316 // satisfy the following conditions to avoid using more instructions
1317 // to adjust the sp after adjusting the amount, such as
1318 // StackSize meets the condition (StackSize <= 2048 + RVCompressLen),
1319 // case1: Amount is 2048 - StackAlign: use addi + addi to adjust sp.
1320 // case2: Amount is RVCompressLen: use addi + addi to adjust sp.
1321 auto CanCompress = [&](uint64_t CompressLen) -> bool {
1322 if (StackSize <= 2047 + CompressLen ||
1323 (StackSize > 2048 * 2 - StackAlign &&
1324 StackSize <= 2047 * 2 + CompressLen) ||
1325 StackSize > 2048 * 3 - StackAlign)
1326 return true;
1327
1328 return false;
1329 };
1330 // In the epilogue, addi sp, sp, 496 is used to recover the sp and it
1331 // can be compressed(C.ADDI16SP, offset can be [-512, 496]), but
1332 // addi sp, sp, 512 can not be compressed. So try to use 496 first.
1333 const uint64_t ADDI16SPCompressLen = 496;
1334 if (STI.is64Bit() && CanCompress(ADDI16SPCompressLen))
1335 return ADDI16SPCompressLen;
1336 if (CanCompress(RVCompressLen))
1337 return RVCompressLen;
1338 }
1339 return 2048 - StackAlign;
1340 }
1341 return 0;
1342}
1343
1347 if (CSI.empty())
1348 return true;
1349
1351 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1352 DebugLoc DL;
1353 if (MI != MBB.end() && !MI->isDebugInstr())
1354 DL = MI->getDebugLoc();
1355
1356 // Emit CM.PUSH with base SPimm & evaluate Push stack
1358 if (RVFI->isPushable(*MF)) {
1359 Register MaxReg = getMaxPushPopReg(*MF, CSI);
1360 if (MaxReg != RISCV::NoRegister) {
1361 auto [RegEnc, PushedRegNum] = getPushPopEncodingAndNum(MaxReg);
1362 RVFI->setRVPushRegs(PushedRegNum);
1363 RVFI->setRVPushStackSize(alignTo((STI.getXLen() / 8) * PushedRegNum, 16));
1364
1365 // Use encoded number to represent registers to spill.
1366 RVFI->setRVPushRlist(RegEnc);
1367 MachineInstrBuilder PushBuilder =
1368 BuildMI(MBB, MI, DL, TII.get(RISCV::CM_PUSH))
1370 PushBuilder.addImm((int64_t)RegEnc);
1371 PushBuilder.addImm(0);
1372
1373 for (unsigned i = 0; i < PushedRegNum; i++)
1374 PushBuilder.addUse(AllPopRegs[i], RegState::Implicit);
1375 }
1376 } else if (const char *SpillLibCall = getSpillLibCallName(*MF, CSI)) {
1377 // Add spill libcall via non-callee-saved register t0.
1378 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
1379 .addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
1381
1382 // Add registers spilled in libcall as liveins.
1383 for (auto &CS : CSI)
1384 MBB.addLiveIn(CS.getReg());
1385 }
1386
1387 // Manually spill values not spilled by libcall & Push/Pop.
1388 const auto &UnmanagedCSI = getUnmanagedCSI(*MF, CSI);
1389 for (auto &CS : UnmanagedCSI) {
1390 // Insert the spill to the stack frame.
1391 Register Reg = CS.getReg();
1392 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1393 TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
1394 RC, TRI, Register());
1395 }
1396
1397 return true;
1398}
1399
1403 if (CSI.empty())
1404 return true;
1405
1407 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
1408 DebugLoc DL;
1409 if (MI != MBB.end() && !MI->isDebugInstr())
1410 DL = MI->getDebugLoc();
1411
1412 // Manually restore values not restored by libcall & Push/Pop.
1413 // Keep the same order as in the prologue. There is no need to reverse the
1414 // order in the epilogue. In addition, the return address will be restored
1415 // first in the epilogue. It increases the opportunity to avoid the
1416 // load-to-use data hazard between loading RA and return by RA.
1417 // loadRegFromStackSlot can insert multiple instructions.
1418 const auto &UnmanagedCSI = getUnmanagedCSI(*MF, CSI);
1419 for (auto &CS : UnmanagedCSI) {
1420 Register Reg = CS.getReg();
1421 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1422 TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI,
1423 Register());
1424 assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
1425 }
1426
1428 if (RVFI->isPushable(*MF)) {
1429 int RegEnc = RVFI->getRVPushRlist();
1431 MachineInstrBuilder PopBuilder =
1432 BuildMI(MBB, MI, DL, TII.get(RISCV::CM_POP))
1434 // Use encoded number to represent registers to restore.
1435 PopBuilder.addImm(RegEnc);
1436 PopBuilder.addImm(0);
1437
1438 for (unsigned i = 0; i < RVFI->getRVPushRegs(); i++)
1440 }
1441 } else {
1442 const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
1443 if (RestoreLibCall) {
1444 // Add restore libcall via tail call.
1446 BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
1447 .addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
1449
1450 // Remove trailing returns, since the terminator is now a tail call to the
1451 // restore function.
1452 if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
1453 NewMI->copyImplicitOps(*MF, *MI);
1454 MI->eraseFromParent();
1455 }
1456 }
1457 }
1458 return true;
1459}
1460
1462 // Keep the conventional code flow when not optimizing.
1463 if (MF.getFunction().hasOptNone())
1464 return false;
1465
1466 return true;
1467}
1468
1470 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1471 const MachineFunction *MF = MBB.getParent();
1472 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1473
1474 if (!RVFI->useSaveRestoreLibCalls(*MF))
1475 return true;
1476
1477 // Inserting a call to a __riscv_save libcall requires the use of the register
1478 // t0 (X5) to hold the return address. Therefore if this register is already
1479 // used we can't insert the call.
1480
1481 RegScavenger RS;
1482 RS.enterBasicBlock(*TmpMBB);
1483 return !RS.isRegUsed(RISCV::X5);
1484}
1485
1487 const MachineFunction *MF = MBB.getParent();
1488 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
1489 const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
1490
1491 if (!RVFI->useSaveRestoreLibCalls(*MF))
1492 return true;
1493
1494 // Using the __riscv_restore libcalls to restore CSRs requires a tail call.
1495 // This means if we still need to continue executing code within this function
1496 // the restore cannot take place in this basic block.
1497
1498 if (MBB.succ_size() > 1)
1499 return false;
1500
1501 MachineBasicBlock *SuccMBB =
1502 MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
1503
1504 // Doing a tail call should be safe if there are no successors, because either
1505 // we have a returning block or the end of the block is unreachable, so the
1506 // restore will be eliminated regardless.
1507 if (!SuccMBB)
1508 return true;
1509
1510 // The successor can only contain a return, since we would effectively be
1511 // replacing the successor with our own tail return at the end of our block.
1512 return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
1513}
1514
1516 switch (ID) {
1519 return true;
1523 return false;
1524 }
1525 llvm_unreachable("Invalid TargetStackID::Value");
1526}
1527
1530}
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static Register getFPReg(const CSKYSubtarget &STI)
This file contains constants used for implementing Dwarf debug support.
uint64_t Size
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static const char * getRestoreLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static const char * getSpillLibCallName(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static bool hasRVVFrameObject(const MachineFunction &MF)
static const Register AllPopRegs[]
static std::pair< unsigned, unsigned > getPushPopEncodingAndNum(const Register MaxReg)
static int getLibCallID(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static Register getSPReg(const RISCVSubtarget &STI)
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)
static SmallVector< CalleeSavedInfo, 8 > getUnmanagedCSI(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static Register getMaxPushPopReg(const MachineFunction &MF, const std::vector< CalleeSavedInfo > &CSI)
static unsigned getScavSlotsNumForRVV(MachineFunction &MF)
This file declares the machine register scavenger class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:470
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
BitVector & set()
Definition: BitVector.h:351
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
Register getReg() const
A debug info location.
Definition: DebugLoc.h:33
Diagnostic information for unsupported feature in backend.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:239
bool hasOptNone() const
Do not optimize this function (-O0).
Definition: Function.h:641
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:320
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:645
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI, Register VReg) const override
Store the specified register of the given register class to the specified stack frame index.
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI, Register VReg) const override
Load the specified register of the given register class from the specified stack frame index.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition: MCDwarf.h:582
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition: MCDwarf.h:555
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition: MCDwarf.h:615
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition: MCDwarf.h:540
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:646
MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned succ_size() const
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
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.
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.
void ensureMaxAlignment(Align Alignment)
Make sure the function is at least Align bytes aligned.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
int getOffsetAdjustment() const
Return the correction for frame offsets.
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
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
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.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:68
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
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.
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
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a epilogue for the target.
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,...
bool hasFP(const MachineFunction &MF) const override
hasFP - Return true if the specified function should have a dedicated frame pointer register.
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.
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.
uint64_t getStackSizeWithRVVPadding(const MachineFunction &MF) const
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
bool isPushable(const MachineFunction &MF) const
bool hasStdExtCOrZca() const
unsigned getRealMinVLen() const
unsigned getXLen() const
bool isRegisterReservedByUser(Register i) const
bool hasVInstructions() const
unsigned getRealMaxVLen() const
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
bool isRegUsed(Register Reg, bool includeReserved=true) const
Return if a specific register is currently used.
void enterBasicBlock(MachineBasicBlock &MBB)
Start tracking liveness from the begin of basic block MBB.
void addScavengingFrameIndex(int FI)
Add a scavenging frame index.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr unsigned id() const
Definition: Register.h:103
Represents a location in source code.
Definition: SMLoc.h:23
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.
Definition: SmallString.h:261
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StackOffset holds a fixed and a scalable offset in bytes.
Definition: TypeSize.h:36
int64_t getFixed() const
Returns the fixed component of the stack.
Definition: TypeSize.h:52
int64_t getScalable() const
Returns the scalable component of the stack.
Definition: TypeSize.h:55
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition: TypeSize.h:47
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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...
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
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 Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition: CallingConv.h:50
MCRegister getBPReg()
MCRegister getSCSPReg()
bool isRVVSpill(const MachineInstr &MI)
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Define
Register definition.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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:1741
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
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:197
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
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.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
void adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator II, const DebugLoc &DL, Register DestReg, Register SrcReg, StackOffset Offset, MachineInstr::MIFlag Flag, MaybeAlign RequiredAlign) const