1 //===-- RISCVFrameLowering.cpp - RISCV 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 RISCV implementation of TargetFrameLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "RISCVFrameLowering.h" 14 #include "RISCVMachineFunctionInfo.h" 15 #include "RISCVSubtarget.h" 16 #include "llvm/CodeGen/MachineFrameInfo.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineInstrBuilder.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/RegisterScavenging.h" 21 #include "llvm/IR/DiagnosticInfo.h" 22 #include "llvm/MC/MCDwarf.h" 23 24 using namespace llvm; 25 26 bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const { 27 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 28 29 const MachineFrameInfo &MFI = MF.getFrameInfo(); 30 return MF.getTarget().Options.DisableFramePointerElim(MF) || 31 RegInfo->needsStackRealignment(MF) || MFI.hasVarSizedObjects() || 32 MFI.isFrameAddressTaken(); 33 } 34 35 // Determines the size of the frame and maximum call frame size. 36 void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const { 37 MachineFrameInfo &MFI = MF.getFrameInfo(); 38 const RISCVRegisterInfo *RI = STI.getRegisterInfo(); 39 40 // Get the number of bytes to allocate from the FrameInfo. 41 uint64_t FrameSize = MFI.getStackSize(); 42 43 // Get the alignment. 44 unsigned StackAlign = getStackAlignment(); 45 if (RI->needsStackRealignment(MF)) { 46 unsigned MaxStackAlign = std::max(StackAlign, MFI.getMaxAlignment()); 47 FrameSize += (MaxStackAlign - StackAlign); 48 StackAlign = MaxStackAlign; 49 } 50 51 // Set Max Call Frame Size 52 uint64_t MaxCallSize = alignTo(MFI.getMaxCallFrameSize(), StackAlign); 53 MFI.setMaxCallFrameSize(MaxCallSize); 54 55 // Make sure the frame is aligned. 56 FrameSize = alignTo(FrameSize, StackAlign); 57 58 // Update frame info. 59 MFI.setStackSize(FrameSize); 60 } 61 62 void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB, 63 MachineBasicBlock::iterator MBBI, 64 const DebugLoc &DL, Register DestReg, 65 Register SrcReg, int64_t Val, 66 MachineInstr::MIFlag Flag) const { 67 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 68 const RISCVInstrInfo *TII = STI.getInstrInfo(); 69 70 if (DestReg == SrcReg && Val == 0) 71 return; 72 73 if (isInt<12>(Val)) { 74 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg) 75 .addReg(SrcReg) 76 .addImm(Val) 77 .setMIFlag(Flag); 78 } else { 79 unsigned Opc = RISCV::ADD; 80 bool isSub = Val < 0; 81 if (isSub) { 82 Val = -Val; 83 Opc = RISCV::SUB; 84 } 85 86 Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 87 TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag); 88 BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg) 89 .addReg(SrcReg) 90 .addReg(ScratchReg, RegState::Kill) 91 .setMIFlag(Flag); 92 } 93 } 94 95 // Returns the register used to hold the frame pointer. 96 static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; } 97 98 // Returns the register used to hold the stack pointer. 99 static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; } 100 101 void RISCVFrameLowering::emitPrologue(MachineFunction &MF, 102 MachineBasicBlock &MBB) const { 103 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported"); 104 105 MachineFrameInfo &MFI = MF.getFrameInfo(); 106 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 107 const RISCVRegisterInfo *RI = STI.getRegisterInfo(); 108 const RISCVInstrInfo *TII = STI.getInstrInfo(); 109 MachineBasicBlock::iterator MBBI = MBB.begin(); 110 111 if (RI->needsStackRealignment(MF) && MFI.hasVarSizedObjects()) { 112 report_fatal_error( 113 "RISC-V backend can't currently handle functions that need stack " 114 "realignment and have variable sized objects"); 115 } 116 117 Register FPReg = getFPReg(STI); 118 Register SPReg = getSPReg(STI); 119 120 // Debug location must be unknown since the first debug location is used 121 // to determine the end of the prologue. 122 DebugLoc DL; 123 124 // Determine the correct frame layout 125 determineFrameLayout(MF); 126 127 // FIXME (note copied from Lanai): This appears to be overallocating. Needs 128 // investigation. Get the number of bytes to allocate from the FrameInfo. 129 uint64_t StackSize = MFI.getStackSize(); 130 131 // Early exit if there is no need to allocate on the stack 132 if (StackSize == 0 && !MFI.adjustsStack()) 133 return; 134 135 // If the stack pointer has been marked as reserved, then produce an error if 136 // the frame requires stack allocation 137 if (STI.isRegisterReservedByUser(SPReg)) 138 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 139 MF.getFunction(), "Stack pointer required, but has been reserved."}); 140 141 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF); 142 // Split the SP adjustment to reduce the offsets of callee saved spill. 143 if (FirstSPAdjustAmount) 144 StackSize = FirstSPAdjustAmount; 145 146 // Allocate space on the stack if necessary. 147 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup); 148 149 // Emit ".cfi_def_cfa_offset StackSize" 150 unsigned CFIIndex = MF.addFrameInst( 151 MCCFIInstruction::createDefCfaOffset(nullptr, -StackSize)); 152 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 153 .addCFIIndex(CFIIndex); 154 155 // The frame pointer is callee-saved, and code has been generated for us to 156 // save it to the stack. We need to skip over the storing of callee-saved 157 // registers as the frame pointer must be modified after it has been saved 158 // to the stack, not before. 159 // FIXME: assumes exactly one instruction is used to save each callee-saved 160 // register. 161 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 162 std::advance(MBBI, CSI.size()); 163 164 // Iterate over list of callee-saved registers and emit .cfi_offset 165 // directives. 166 for (const auto &Entry : CSI) { 167 int64_t Offset = MFI.getObjectOffset(Entry.getFrameIdx()); 168 Register Reg = Entry.getReg(); 169 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 170 nullptr, RI->getDwarfRegNum(Reg, true), Offset)); 171 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 172 .addCFIIndex(CFIIndex); 173 } 174 175 // Generate new FP. 176 if (hasFP(MF)) { 177 if (STI.isRegisterReservedByUser(FPReg)) 178 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 179 MF.getFunction(), "Frame pointer required, but has been reserved."}); 180 181 adjustReg(MBB, MBBI, DL, FPReg, SPReg, 182 StackSize - RVFI->getVarArgsSaveSize(), MachineInstr::FrameSetup); 183 184 // Emit ".cfi_def_cfa $fp, 0" 185 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa( 186 nullptr, RI->getDwarfRegNum(FPReg, true), 0)); 187 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 188 .addCFIIndex(CFIIndex); 189 } 190 191 // Emit the second SP adjustment after saving callee saved registers. 192 if (FirstSPAdjustAmount) { 193 uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount; 194 assert(SecondSPAdjustAmount > 0 && 195 "SecondSPAdjustAmount should be greater than zero"); 196 adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount, 197 MachineInstr::FrameSetup); 198 199 // If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0", 200 // don't emit an sp-based .cfi_def_cfa_offset 201 if (!hasFP(MF)) { 202 // Emit ".cfi_def_cfa_offset StackSize" 203 unsigned CFIIndex = MF.addFrameInst( 204 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize())); 205 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 206 .addCFIIndex(CFIIndex); 207 } 208 } 209 210 if (hasFP(MF)) { 211 // Realign Stack 212 const RISCVRegisterInfo *RI = STI.getRegisterInfo(); 213 if (RI->needsStackRealignment(MF)) { 214 unsigned MaxAlignment = MFI.getMaxAlignment(); 215 216 const RISCVInstrInfo *TII = STI.getInstrInfo(); 217 if (isInt<12>(-(int)MaxAlignment)) { 218 BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg) 219 .addReg(SPReg) 220 .addImm(-(int)MaxAlignment); 221 } else { 222 unsigned ShiftAmount = countTrailingZeros(MaxAlignment); 223 Register VR = 224 MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass); 225 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR) 226 .addReg(SPReg) 227 .addImm(ShiftAmount); 228 BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg) 229 .addReg(VR) 230 .addImm(ShiftAmount); 231 } 232 } 233 } 234 } 235 236 void RISCVFrameLowering::emitEpilogue(MachineFunction &MF, 237 MachineBasicBlock &MBB) const { 238 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 239 const RISCVRegisterInfo *RI = STI.getRegisterInfo(); 240 MachineFrameInfo &MFI = MF.getFrameInfo(); 241 auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 242 DebugLoc DL = MBBI->getDebugLoc(); 243 Register FPReg = getFPReg(STI); 244 Register SPReg = getSPReg(STI); 245 246 // Skip to before the restores of callee-saved registers 247 // FIXME: assumes exactly one instruction is used to restore each 248 // callee-saved register. 249 auto LastFrameDestroy = std::prev(MBBI, MFI.getCalleeSavedInfo().size()); 250 251 uint64_t StackSize = MFI.getStackSize(); 252 uint64_t FPOffset = StackSize - RVFI->getVarArgsSaveSize(); 253 254 // Restore the stack pointer using the value of the frame pointer. Only 255 // necessary if the stack pointer was modified, meaning the stack size is 256 // unknown. 257 if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) { 258 assert(hasFP(MF) && "frame pointer should not have been eliminated"); 259 adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset, 260 MachineInstr::FrameDestroy); 261 } 262 263 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF); 264 if (FirstSPAdjustAmount) { 265 uint64_t SecondSPAdjustAmount = MFI.getStackSize() - FirstSPAdjustAmount; 266 assert(SecondSPAdjustAmount > 0 && 267 "SecondSPAdjustAmount should be greater than zero"); 268 269 adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount, 270 MachineInstr::FrameDestroy); 271 } 272 273 if (FirstSPAdjustAmount) 274 StackSize = FirstSPAdjustAmount; 275 276 // Deallocate stack 277 adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy); 278 } 279 280 int RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, 281 int FI, 282 unsigned &FrameReg) const { 283 const MachineFrameInfo &MFI = MF.getFrameInfo(); 284 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 285 const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 286 287 // Callee-saved registers should be referenced relative to the stack 288 // pointer (positive offset), otherwise use the frame pointer (negative 289 // offset). 290 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 291 int MinCSFI = 0; 292 int MaxCSFI = -1; 293 294 int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + 295 MFI.getOffsetAdjustment(); 296 297 uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF); 298 299 if (CSI.size()) { 300 MinCSFI = CSI[0].getFrameIdx(); 301 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx(); 302 } 303 304 if (FI >= MinCSFI && FI <= MaxCSFI) { 305 FrameReg = RISCV::X2; 306 307 if (FirstSPAdjustAmount) 308 Offset += FirstSPAdjustAmount; 309 else 310 Offset += MF.getFrameInfo().getStackSize(); 311 } else if (RI->needsStackRealignment(MF)) { 312 assert(!MFI.hasVarSizedObjects() && 313 "Unexpected combination of stack realignment and varsized objects"); 314 // If the stack was realigned, the frame pointer is set in order to allow 315 // SP to be restored, but we still access stack objects using SP. 316 FrameReg = RISCV::X2; 317 Offset += MF.getFrameInfo().getStackSize(); 318 } else { 319 FrameReg = RI->getFrameRegister(MF); 320 if (hasFP(MF)) 321 Offset += RVFI->getVarArgsSaveSize(); 322 else 323 Offset += MF.getFrameInfo().getStackSize(); 324 } 325 return Offset; 326 } 327 328 void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF, 329 BitVector &SavedRegs, 330 RegScavenger *RS) const { 331 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 332 // Unconditionally spill RA and FP only if the function uses a frame 333 // pointer. 334 if (hasFP(MF)) { 335 SavedRegs.set(RISCV::X1); 336 SavedRegs.set(RISCV::X8); 337 } 338 339 // If interrupt is enabled and there are calls in the handler, 340 // unconditionally save all Caller-saved registers and 341 // all FP registers, regardless whether they are used. 342 MachineFrameInfo &MFI = MF.getFrameInfo(); 343 344 if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) { 345 346 static const MCPhysReg CSRegs[] = { RISCV::X1, /* ra */ 347 RISCV::X5, RISCV::X6, RISCV::X7, /* t0-t2 */ 348 RISCV::X10, RISCV::X11, /* a0-a1, a2-a7 */ 349 RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17, 350 RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */ 351 }; 352 353 for (unsigned i = 0; CSRegs[i]; ++i) 354 SavedRegs.set(CSRegs[i]); 355 356 if (MF.getSubtarget<RISCVSubtarget>().hasStdExtD() || 357 MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) { 358 359 // If interrupt is enabled, this list contains all FP registers. 360 const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs(); 361 362 for (unsigned i = 0; Regs[i]; ++i) 363 if (RISCV::FPR32RegClass.contains(Regs[i]) || 364 RISCV::FPR64RegClass.contains(Regs[i])) 365 SavedRegs.set(Regs[i]); 366 } 367 } 368 } 369 370 void RISCVFrameLowering::processFunctionBeforeFrameFinalized( 371 MachineFunction &MF, RegScavenger *RS) const { 372 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 373 MachineFrameInfo &MFI = MF.getFrameInfo(); 374 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 375 // estimateStackSize has been observed to under-estimate the final stack 376 // size, so give ourselves wiggle-room by checking for stack size 377 // representable an 11-bit signed field rather than 12-bits. 378 // FIXME: It may be possible to craft a function with a small stack that 379 // still needs an emergency spill slot for branch relaxation. This case 380 // would currently be missed. 381 if (!isInt<11>(MFI.estimateStackSize(MF))) { 382 int RegScavFI = MFI.CreateStackObject( 383 RegInfo->getSpillSize(*RC), RegInfo->getSpillAlignment(*RC), false); 384 RS->addScavengingFrameIndex(RegScavFI); 385 } 386 } 387 388 // Not preserve stack space within prologue for outgoing variables when the 389 // function contains variable size objects and let eliminateCallFramePseudoInstr 390 // preserve stack space for it. 391 bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 392 return !MF.getFrameInfo().hasVarSizedObjects(); 393 } 394 395 // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions. 396 MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr( 397 MachineFunction &MF, MachineBasicBlock &MBB, 398 MachineBasicBlock::iterator MI) const { 399 Register SPReg = RISCV::X2; 400 DebugLoc DL = MI->getDebugLoc(); 401 402 if (!hasReservedCallFrame(MF)) { 403 // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and 404 // ADJCALLSTACKUP must be converted to instructions manipulating the stack 405 // pointer. This is necessary when there is a variable length stack 406 // allocation (e.g. alloca), which means it's not possible to allocate 407 // space for outgoing arguments from within the function prologue. 408 int64_t Amount = MI->getOperand(0).getImm(); 409 410 if (Amount != 0) { 411 // Ensure the stack remains aligned after adjustment. 412 Amount = alignSPAdjust(Amount); 413 414 if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN) 415 Amount = -Amount; 416 417 adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags); 418 } 419 } 420 421 return MBB.erase(MI); 422 } 423 424 // We would like to split the SP adjustment to reduce prologue/epilogue 425 // as following instructions. In this way, the offset of the callee saved 426 // register could fit in a single store. 427 // add sp,sp,-2032 428 // sw ra,2028(sp) 429 // sw s0,2024(sp) 430 // sw s1,2020(sp) 431 // sw s3,2012(sp) 432 // sw s4,2008(sp) 433 // add sp,sp,-64 434 uint64_t 435 RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const { 436 const MachineFrameInfo &MFI = MF.getFrameInfo(); 437 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 438 uint64_t StackSize = MFI.getStackSize(); 439 uint64_t StackAlign = getStackAlignment(); 440 441 // FIXME: Disable SplitSPAdjust if save-restore libcall enabled when the patch 442 // landing. The callee saved registers will be pushed by the 443 // save-restore libcalls, so we don't have to split the SP adjustment 444 // in this case. 445 // 446 // Return the FirstSPAdjustAmount if the StackSize can not fit in signed 447 // 12-bit and there exists a callee saved register need to be pushed. 448 if (!isInt<12>(StackSize) && (CSI.size() > 0)) { 449 // FirstSPAdjustAmount is choosed as (2048 - StackAlign) 450 // because 2048 will cause sp = sp + 2048 in epilogue split into 451 // multi-instructions. The offset smaller than 2048 can fit in signle 452 // load/store instruction and we have to stick with the stack alignment. 453 // 2048 is 16-byte alignment. The stack alignment for RV32 and RV64 is 16, 454 // for RV32E is 4. So (2048 - StackAlign) will satisfy the stack alignment. 455 return 2048 - StackAlign; 456 } 457 return 0; 458 } 459