LLVM 20.0.0git
MSP430FrameLowering.cpp
Go to the documentation of this file.
1//===-- MSP430FrameLowering.cpp - MSP430 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 MSP430 implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MSP430FrameLowering.h"
14#include "MSP430InstrInfo.h"
16#include "MSP430Subtarget.h"
22
23using namespace llvm;
24
26 : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(2), -2,
27 Align(2)),
28 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {}
29
31 const MachineFrameInfo &MFI = MF.getFrameInfo();
32
33 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
36}
37
39 return !MF.getFrameInfo().hasVarSizedObjects();
40}
41
44 const DebugLoc &DL,
45 const MCCFIInstruction &CFIInst,
46 MachineInstr::MIFlag Flag) const {
48 unsigned CFIIndex = MF.addFrameInst(CFIInst);
49 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
50 .addCFIIndex(CFIIndex)
51 .setMIFlag(Flag);
52}
53
56 const DebugLoc &DL, bool IsPrologue) const {
60
61 // Add callee saved registers to move list.
62 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
63
64 // Calculate offsets.
65 for (const CalleeSavedInfo &I : CSI) {
66 int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
67 Register Reg = I.getReg();
68 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
69
70 if (IsPrologue) {
72 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
73 } else {
75 MCCFIInstruction::createRestore(nullptr, DwarfReg));
76 }
77 }
78}
79
81 MachineBasicBlock &MBB) const {
82 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
85 const MSP430InstrInfo &TII =
86 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
87
89 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
90
91 // Get the number of bytes to allocate from the FrameInfo.
92 uint64_t StackSize = MFI.getStackSize();
93 int stackGrowth = -2;
94
95 uint64_t NumBytes = 0;
96 if (hasFP(MF)) {
97 // Calculate required stack adjustment
98 uint64_t FrameSize = StackSize - 2;
99 NumBytes = FrameSize - MSP430FI->getCalleeSavedFrameSize();
100
101 // Get the offset of the stack slot for the EBP register... which is
102 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
103 // Update the frame offset adjustment.
104 MFI.setOffsetAdjustment(-NumBytes);
105
106 // Save FP into the appropriate stack slot...
107 BuildMI(MBB, MBBI, DL, TII.get(MSP430::PUSH16r))
108 .addReg(MSP430::R4, RegState::Kill)
110
111 // Mark the place where FP was saved.
112 // Define the current CFA rule to use the provided offset.
114 MCCFIInstruction::cfiDefCfaOffset(nullptr, -2 * stackGrowth),
116
117 // Change the rule for the FramePtr to be an "offset" rule.
118 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MSP430::R4, true);
119 BuildCFI(
120 MBB, MBBI, DL,
121 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr, 2 * stackGrowth),
123
124 // Update FP with the new base value...
125 BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::R4)
126 .addReg(MSP430::SP)
128
129 // Mark effective beginning of when frame pointer becomes valid.
130 // Define the current CFA to use the FP register.
132 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
134
135 // Mark the FramePtr as live-in in every block except the entry.
136 for (MachineBasicBlock &MBBJ : llvm::drop_begin(MF))
137 MBBJ.addLiveIn(MSP430::R4);
138 } else
139 NumBytes = StackSize - MSP430FI->getCalleeSavedFrameSize();
140
141 // Skip the callee-saved push instructions.
142 int StackOffset = 2 * stackGrowth;
143 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup) &&
144 (MBBI->getOpcode() == MSP430::PUSH16r)) {
145 ++MBBI;
146
147 if (!hasFP(MF)) {
148 // Mark callee-saved push instruction.
149 // Define the current CFA rule to use the provided offset.
150 assert(StackSize && "Expected stack frame");
154 StackOffset += stackGrowth;
155 }
156 }
157
158 if (MBBI != MBB.end())
159 DL = MBBI->getDebugLoc();
160
161 if (NumBytes) { // adjust stack pointer: SP -= numbytes
162 // If there is an SUB16ri of SP immediately before this instruction, merge
163 // the two.
164 //NumBytes -= mergeSPUpdates(MBB, MBBI, true);
165 // If there is an ADD16ri or SUB16ri of SP immediately after this
166 // instruction, merge the two instructions.
167 // mergeSPUpdatesDown(MBB, MBBI, &NumBytes);
168
169 if (NumBytes) {
171 BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SP)
172 .addReg(MSP430::SP)
173 .addImm(NumBytes)
175 // The SRW implicit def is dead.
176 MI->getOperand(3).setIsDead();
177 }
178 if (!hasFP(MF)) {
179 // Adjust the previous CFA value if CFA was not redefined by FP
180 BuildCFI(
181 MBB, MBBI, DL,
182 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
184 }
185 }
186
188}
189
191 MachineBasicBlock &MBB) const {
192 const MachineFrameInfo &MFI = MF.getFrameInfo();
194 const MSP430InstrInfo &TII =
195 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
196
198 unsigned RetOpcode = MBBI->getOpcode();
199 DebugLoc DL = MBBI->getDebugLoc();
200
201 switch (RetOpcode) {
202 case MSP430::RET:
203 case MSP430::RETI: break; // These are ok
204 default:
205 llvm_unreachable("Can only insert epilog into returning blocks");
206 }
207
208 // Get the number of bytes to allocate from the FrameInfo
209 uint64_t StackSize = MFI.getStackSize();
210 unsigned CSSize = MSP430FI->getCalleeSavedFrameSize();
211 uint64_t NumBytes = 0;
212
214 if (hasFP(MF)) {
215 // Calculate required stack adjustment
216 uint64_t FrameSize = StackSize - 2;
217 NumBytes = FrameSize - CSSize;
218
219 // pop FP.
220 BuildMI(MBB, MBBI, DL, TII.get(MSP430::POP16r), MSP430::R4)
222 unsigned DwarfStackPtr = TRI->getDwarfRegNum(MSP430::SP, true);
224 MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 2),
226 --MBBI;
227 if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
228 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MSP430::R4, true);
229 BuildCFI(MBB, AfterPop, DL,
230 MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
232 --MBBI;
233 --AfterPop;
234 }
235 } else
236 NumBytes = StackSize - CSSize;
237
238 // Skip the callee-saved pop instructions.
240 while (MBBI != MBB.begin()) {
241 MachineBasicBlock::iterator PI = std::prev(MBBI);
242 unsigned Opc = PI->getOpcode();
243 if ((Opc != MSP430::POP16r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
244 !PI->isTerminator())
245 break;
246 FirstCSPop = PI;
247 --MBBI;
248 }
249 MBBI = FirstCSPop;
250
251 DL = MBBI->getDebugLoc();
252
253 // If there is an ADD16ri or SUB16ri of SP immediately before this
254 // instruction, merge the two instructions.
255 //if (NumBytes || MFI.hasVarSizedObjects())
256 // mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
257
258 if (MFI.hasVarSizedObjects()) {
259 BuildMI(MBB, MBBI, DL, TII.get(MSP430::MOV16rr), MSP430::SP)
260 .addReg(MSP430::R4)
262 if (CSSize) {
264 BuildMI(MBB, MBBI, DL, TII.get(MSP430::SUB16ri), MSP430::SP)
265 .addReg(MSP430::SP)
266 .addImm(CSSize)
268 // The SRW implicit def is dead.
269 MI->getOperand(3).setIsDead();
270 }
271 } else {
272 // adjust stack pointer back: SP += numbytes
273 if (NumBytes) {
275 BuildMI(MBB, MBBI, DL, TII.get(MSP430::ADD16ri), MSP430::SP)
276 .addReg(MSP430::SP)
277 .addImm(NumBytes)
279 // The SRW implicit def is dead.
280 MI->getOperand(3).setIsDead();
281
282 if (!hasFP(MF)) {
283 // Adjust CFA value if it was defined by SP
285 MCCFIInstruction::cfiDefCfaOffset(nullptr, CSSize + 2),
287 }
288 }
289 }
290
291 if (!hasFP(MF)) {
292 MBBI = FirstCSPop;
293 int64_t Offset = -(int64_t)CSSize - 2;
294 // Mark callee-saved pop instruction.
295 // Define the current CFA rule to use the provided offset.
296 while (MBBI != MBB.end()) {
298 unsigned Opc = PI->getOpcode();
299 ++MBBI;
300 if (Opc == MSP430::POP16r) {
301 Offset += 2;
305 }
306 }
307 }
308 emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
309}
310
311// FIXME: Can we eleminate these in favour of generic code?
315 if (CSI.empty())
316 return false;
317
318 DebugLoc DL;
319 if (MI != MBB.end()) DL = MI->getDebugLoc();
320
324 MFI->setCalleeSavedFrameSize(CSI.size() * 2);
325
326 for (const CalleeSavedInfo &I : CSI) {
327 Register Reg = I.getReg();
328 // Add the callee-saved register as live-in. It's killed at the spill.
329 MBB.addLiveIn(Reg);
330 BuildMI(MBB, MI, DL, TII.get(MSP430::PUSH16r))
333 }
334 return true;
335}
336
340 if (CSI.empty())
341 return false;
342
343 DebugLoc DL;
344 if (MI != MBB.end()) DL = MI->getDebugLoc();
345
348
349 for (const CalleeSavedInfo &I : llvm::reverse(CSI))
350 BuildMI(MBB, MI, DL, TII.get(MSP430::POP16r), I.getReg())
352
353 return true;
354}
355
359 const MSP430InstrInfo &TII =
360 *static_cast<const MSP430InstrInfo *>(MF.getSubtarget().getInstrInfo());
361 if (!hasReservedCallFrame(MF)) {
362 // If the stack pointer can be changed after prologue, turn the
363 // adjcallstackup instruction into a 'sub SP, <amt>' and the
364 // adjcallstackdown instruction into 'add SP, <amt>'
365 // TODO: consider using push / pop instead of sub + store / add
366 MachineInstr &Old = *I;
367 uint64_t Amount = TII.getFrameSize(Old);
368 if (Amount != 0) {
369 // We need to keep the stack aligned properly. To do this, we round the
370 // amount of space needed for the outgoing arguments up to the next
371 // alignment boundary.
372 Amount = alignTo(Amount, getStackAlign());
373
374 MachineInstr *New = nullptr;
375 if (Old.getOpcode() == TII.getCallFrameSetupOpcode()) {
376 New =
377 BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SP)
378 .addReg(MSP430::SP)
379 .addImm(Amount);
380 } else {
381 assert(Old.getOpcode() == TII.getCallFrameDestroyOpcode());
382 // factor out the amount the callee already popped.
383 Amount -= TII.getFramePoppedByCallee(Old);
384 if (Amount)
385 New = BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::ADD16ri),
386 MSP430::SP)
387 .addReg(MSP430::SP)
388 .addImm(Amount);
389 }
390
391 if (New) {
392 // The SRW implicit def is dead.
393 New->getOperand(3).setIsDead();
394
395 // Replace the pseudo instruction with a new instruction...
396 MBB.insert(I, New);
397 }
398 }
399 } else if (I->getOpcode() == TII.getCallFrameDestroyOpcode()) {
400 // If we are performing frame pointer elimination and if the callee pops
401 // something off the stack pointer, add it back.
402 if (uint64_t CalleeAmt = TII.getFramePoppedByCallee(*I)) {
403 MachineInstr &Old = *I;
404 MachineInstr *New =
405 BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SP)
406 .addReg(MSP430::SP)
407 .addImm(CalleeAmt);
408 if (!hasFP(MF)) {
409 DebugLoc DL = I->getDebugLoc();
410 BuildCFI(MBB, I, DL,
411 MCCFIInstruction::createAdjustCfaOffset(nullptr, CalleeAmt));
412 }
413 // The SRW implicit def is dead.
414 New->getOperand(3).setIsDead();
415
416 MBB.insert(I, New);
417 }
418 }
419
420 return MBB.erase(I);
421}
422
423void
425 RegScavenger *) const {
426 // Create a frame entry for the FP register that must be saved.
427 if (hasFP(MF)) {
428 int FrameIdx = MF.getFrameInfo().CreateFixedObject(2, -4, true);
429 (void)FrameIdx;
430 assert(FrameIdx == MF.getFrameInfo().getObjectIndexBegin() &&
431 "Slot for FP register must be last in order to be found!");
432 }
433}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition: DebugLoc.h:33
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition: MCDwarf.h:582
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:656
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t 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:575
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition: MCDwarf.h:617
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition: MCDwarf.h:590
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition: MCDwarf.h:598
const MCRegisterInfo * getRegisterInfo() const
Definition: MCContext.h:414
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
MSP430FrameLowering(const MSP430Subtarget &STI)
bool hasFPImpl(const MachineFunction &MF) const override
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
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...
void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool IsPrologue) const
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
const MSP430RegisterInfo * TRI
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
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...
void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag Flag=MachineInstr::NoFlags) const
Wraps up getting a CFI index and building a MachineInstr for it.
const MSP430InstrInfo & TII
int64_t getFramePoppedByCallee(const MachineInstr &I) const
MSP430MachineFunctionInfo - This class is derived from MachineFunction and contains private MSP430 ta...
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
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.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
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 isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
int getObjectIndexBegin() const
Return the minimum frame object index.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
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.
MCContext & getContext() const
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
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.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:575
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:499
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StackOffset holds a fixed and a scalable offset in bytes.
Definition: TypeSize.h:33
Information about stack frame layout on the target.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
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...
virtual const TargetInstrInfo * getInstrInfo() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Kill
The last use of a register.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39