LLVM 24.0.0git
XtensaFrameLowering.cpp
Go to the documentation of this file.
1//===- XtensaFrameLowering.cpp - Xtensa 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 Xtensa implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "XtensaFrameLowering.h"
14#include "XtensaInstrInfo.h"
16#include "XtensaSubtarget.h"
22#include "llvm/IR/Function.h"
23
24using namespace llvm;
25
26// Minimum frame = reg save area (4 words) plus static chain (1 word)
27// and the total number of words must be a multiple of 128 bits.
28// Width of a word, in units (bytes).
29#define UNITS_PER_WORD 4
30#define MIN_FRAME_SIZE (8 * UNITS_PER_WORD)
31
32// Both the windowed and the call0 ABI keep SP 16-byte aligned at calls, so
33// outgoing argument areas have to be a multiple of 16 bytes.
36 Align(4)),
37 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {}
38
40 const MachineFrameInfo &MFI = MF.getFrameInfo();
42}
43
45 MachineBasicBlock &MBB) const {
46 assert(&MBB == &MF.front() && "Shrink-wrapping not yet implemented");
49 DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
50 MCRegister SP = Xtensa::SP;
51 MCRegister FP = TRI->getFrameRegister(MF);
54
55 // First, compute final stack size.
56 uint64_t StackSize = MFI.getStackSize();
57 uint64_t PrevStackSize = StackSize;
58
59 // Round up StackSize to 16*N
60 StackSize += (16 - StackSize) & 0xf;
61
62 if (STI.isWindowedABI()) {
63 StackSize += 32;
64 uint64_t MaxAlignment = MFI.getMaxAlign().value();
65 if (MaxAlignment > 32)
66 StackSize += MaxAlignment;
67
68 if (StackSize <= 32760) {
69 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::ENTRY))
70 .addReg(SP)
71 .addImm(StackSize);
72 } else {
73 // Use a8 as a temporary since a0-a7 may be live.
74 MCRegister TmpReg = Xtensa::A8;
75
76 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::ENTRY))
77 .addReg(SP)
79 TII.loadImmediate(MBB, MBBI, &TmpReg, StackSize - MIN_FRAME_SIZE);
80 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::SUB), TmpReg)
81 .addReg(SP)
82 .addReg(TmpReg);
83 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::MOVSP), SP).addReg(TmpReg);
84 }
85
86 // Calculate how much is needed to have the correct alignment.
87 // Change offset to: alignment + difference.
88 // For example, in case of alignment of 128:
89 // diff_to_128_aligned_address = (128 - (SP & 127))
90 // new_offset = SP + diff_to_128_aligned_address
91 // This is safe to do because we increased the stack size by MaxAlignment.
92 MCRegister Reg, RegMisAlign;
93 if (MaxAlignment > 32) {
94 TII.loadImmediate(MBB, MBBI, &RegMisAlign, MaxAlignment - 1);
95 TII.loadImmediate(MBB, MBBI, &Reg, MaxAlignment);
96 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::AND))
97 .addReg(RegMisAlign, RegState::Define)
98 .addReg(FP)
99 .addReg(RegMisAlign);
100 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::SUB), RegMisAlign)
101 .addReg(Reg)
102 .addReg(RegMisAlign);
103 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::ADD), SP)
104 .addReg(SP)
105 .addReg(RegMisAlign, RegState::Kill);
106 }
107
108 // Store FP register in A8, because FP may be used to pass function
109 // arguments
110 if (XtensaFI->isSaveFrameRegister()) {
111 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::OR), Xtensa::A8)
112 .addReg(FP)
113 .addReg(FP);
114 }
115
116 // if framepointer enabled, set it to point to the stack pointer.
117 if (hasFP(MF)) {
118 // Insert instruction "move $fp, $sp" at this location.
119 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::OR), FP)
120 .addReg(SP)
121 .addReg(SP)
123
125 nullptr, MRI->getDwarfRegNum(FP, true), StackSize);
126 unsigned CFIIndex = MF.addFrameInst(Inst);
127 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
128 .addCFIIndex(CFIIndex);
129 } else {
130 // emit ".cfi_def_cfa_offset StackSize"
131 unsigned CFIIndex = MF.addFrameInst(
132 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize));
133 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
134 .addCFIIndex(CFIIndex);
135 }
136 } else {
137 // No need to allocate space on the stack.
138 if (StackSize == 0 && !MFI.adjustsStack())
139 return;
140
141 // Adjust stack.
142 TII.adjustStackPtr(SP, -StackSize, MBB, MBBI);
143
144 // emit ".cfi_def_cfa_offset StackSize"
145 unsigned CFIIndex =
146 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize));
147 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
148 .addCFIIndex(CFIIndex);
149
150 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
151
152 if (!CSI.empty()) {
153 // Find the instruction past the last instruction that saves a
154 // callee-saved register to the stack. The callee-saved store
155 // instructions are placed at the begin of basic block, so
156 // iterate over instruction sequence and check that
157 // save instructions are placed correctly.
158 for (unsigned i = 0, e = CSI.size(); i < e; ++i) {
159#ifndef NDEBUG
160 const CalleeSavedInfo &Info = CSI[i];
161 int FI = Info.getFrameIdx();
162 int StoreFI = 0;
163
164 // Checking that the instruction is exactly as expected
165 bool IsStoreInst = false;
166 if (MBBI->getOpcode() == TargetOpcode::COPY && Info.isSpilledToReg()) {
167 Register DstReg = MBBI->getOperand(0).getReg();
168 Register Reg = MBBI->getOperand(1).getReg();
169 IsStoreInst = Info.getDstReg() == DstReg.asMCReg() &&
170 Info.getReg() == Reg.asMCReg();
171 } else {
172 Register Reg = TII.isStoreToStackSlot(*MBBI, StoreFI);
173 IsStoreInst = Reg.asMCReg() == Info.getReg() && StoreFI == FI;
174 }
175 assert(IsStoreInst &&
176 "Unexpected callee-saved register store instruction");
177#endif
178 ++MBBI;
179 }
180
181 // Iterate over list of callee-saved registers and emit .cfi_offset
182 // directives.
183 for (const auto &I : CSI) {
184 int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
185 MCRegister Reg = I.getReg();
186
187 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
188 nullptr, MRI->getDwarfRegNum(Reg, 1), Offset));
189 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
190 .addCFIIndex(CFIIndex);
191 }
192 }
193
194 // if framepointer enabled, set it to point to the stack pointer.
195 if (hasFP(MF)) {
196 // Insert instruction "move $fp, $sp" at this location.
197 BuildMI(MBB, MBBI, DL, TII.get(Xtensa::OR), FP)
198 .addReg(SP)
199 .addReg(SP)
201
202 // emit ".cfi_def_cfa_register $fp"
203 unsigned CFIIndex =
205 nullptr, MRI->getDwarfRegNum(FP, true)));
206 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
207 .addCFIIndex(CFIIndex);
208 }
209 }
210
211 if (StackSize != PrevStackSize) {
212 MFI.setStackSize(StackSize);
213
214 for (int i = MFI.getObjectIndexBegin(); i < MFI.getObjectIndexEnd(); i++) {
215 if (!MFI.isDeadObjectIndex(i)) {
216 int64_t SPOffset = MFI.getObjectOffset(i);
217
218 if (SPOffset < 0)
219 MFI.setObjectOffset(i, SPOffset - StackSize + PrevStackSize);
220 }
221 }
222 }
223}
224
226 MachineBasicBlock &MBB) const {
227 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
228 MachineFrameInfo &MFI = MF.getFrameInfo();
229 DebugLoc DL = MBBI->getDebugLoc();
230 MCRegister SP = Xtensa::SP;
231 MCRegister FP = TRI->getFrameRegister(MF);
232
233 // if framepointer enabled, restore the stack pointer.
234 if (hasFP(MF)) {
235 // We should place restore stack pointer instruction just before
236 // sequence of instructions which restores callee-saved registers.
237 // This sequence is placed at the end of the basic block,
238 // so we should find first instruction of the sequence.
240
241 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
242
243 // Find the first instruction at the end that restores a callee-saved
244 // register.
245 for (unsigned i = 0, e = CSI.size(); i < e; ++i) {
246 --I;
247#ifndef NDEBUG
248 const CalleeSavedInfo &Info = CSI[i];
249 int FI = Info.getFrameIdx();
250 int LoadFI = 0;
251
252 // Checking that the instruction is exactly as expected
253 bool IsRestoreInst = false;
254 if (I->getOpcode() == TargetOpcode::COPY && Info.isSpilledToReg()) {
255 Register Reg = I->getOperand(0).getReg();
256 Register DstReg = I->getOperand(1).getReg();
257 IsRestoreInst = Info.getDstReg() == DstReg.asMCReg() &&
258 Info.getReg() == Reg.asMCReg();
259 } else {
260 Register Reg = TII.isLoadFromStackSlot(*I, LoadFI);
261 IsRestoreInst = Info.getReg() == Reg.asMCReg() && LoadFI == FI;
262 }
263 assert(IsRestoreInst &&
264 "Unexpected callee-saved register restore instruction");
265#endif
266 }
267 if (STI.isWindowedABI()) {
268 // In most architectures, we need to explicitly restore the stack pointer
269 // before returning.
270 //
271 // For Xtensa Windowed Register option, it is not needed to explicitly
272 // restore the stack pointer. Reason being is that on function return,
273 // the window of the caller (including the old stack pointer) gets
274 // restored anyways.
275 } else {
276 BuildMI(MBB, I, DL, TII.get(Xtensa::OR), SP).addReg(FP).addReg(FP);
277 }
278 }
279
280 if (STI.isWindowedABI())
281 return;
282
283 // Get the number of bytes from FrameInfo
284 uint64_t StackSize = MFI.getStackSize();
285
286 if (!StackSize)
287 return;
288
289 // Adjust stack.
290 TII.adjustStackPtr(SP, StackSize, MBB, MBBI);
291}
292
295 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
296 MachineFunction *MF = MBB.getParent();
297 MachineBasicBlock &EntryBlock = *(MF->begin());
298
299 if (STI.isWindowedABI())
300 return true;
301
302 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
303 // Add the callee-saved register as live-in. Do not add if the register is
304 // A0 and return address is taken, because it will be implemented in
305 // method XtensaTargetLowering::LowerRETURNADDR.
306 // It's killed at the spill, unless the register is RA and return address
307 // is taken.
308 MCRegister Reg = CSI[i].getReg();
309 bool IsA0AndRetAddrIsTaken =
310 (Reg == Xtensa::A0) && MF->getFrameInfo().isReturnAddressTaken();
311 if (!IsA0AndRetAddrIsTaken)
312 EntryBlock.addLiveIn(Reg);
313
314 // Insert the spill to the stack frame.
315 bool IsKill = !IsA0AndRetAddrIsTaken;
316 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
317 TII.storeRegToStackSlot(EntryBlock, MI, Reg, IsKill, CSI[i].getFrameIdx(),
318 RC, Register());
319 }
320
321 return true;
322}
323
331
332// Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions
336 if (!hasReservedCallFrame(MF)) {
337 int64_t Amount = I->getOperand(0).getImm();
338
339 if (I->getOpcode() == Xtensa::ADJCALLSTACKDOWN)
340 Amount = -Amount;
341
342 TII.adjustStackPtr(Xtensa::SP, Amount, MBB, I);
343 }
344
345 return MBB.erase(I);
346}
347
349 BitVector &SavedRegs,
350 RegScavenger *RS) const {
351 MCRegister FP = TRI->getFrameRegister(MF);
352
353 if (STI.isWindowedABI()) {
354 return;
355 }
356
358
359 // Mark $fp as used if function has dedicated frame pointer.
360 if (hasFP(MF))
361 SavedRegs.set(FP);
362}
363
365 MachineFunction &MF, RegScavenger *RS) const {
366 // Set scavenging frame index if necessary.
367 MachineFrameInfo &MFI = MF.getFrameInfo();
368 uint64_t MaxSPOffset = MFI.estimateStackSize(MF);
369 auto *XtensaFI = MF.getInfo<XtensaMachineFunctionInfo>();
370 unsigned ScavSlotsNum = 0;
371
372 // Without a reserved call frame, adjusting SP around a call with stack
373 // arguments needs a scratch register.
374 if (!isInt<12>(MaxSPOffset) ||
375 (!hasReservedCallFrame(MF) && MFI.getMaxCallFrameSize() > 0))
376 ScavSlotsNum = 1;
377
378 // Far branches over 18-bit offset require a spill slot for scratch register.
379 bool IsLargeFunction = !isInt<18>(MF.estimateFunctionSizeInBytes());
380 if (IsLargeFunction)
381 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
382
383 const TargetRegisterClass &RC = Xtensa::ARRegClass;
384 unsigned Size = TRI->getSpillSize(RC);
385 Align Alignment = TRI->getSpillAlign(RC);
386 for (unsigned I = 0; I < ScavSlotsNum; I++) {
387 int FI = MFI.CreateSpillStackObject(Size, Alignment);
388 RS->addScavengingFrameIndex(FI);
389
390 if (IsLargeFunction &&
391 XtensaFI->getBranchRelaxationScratchFrameIndex() == -1)
392 XtensaFI->setBranchRelaxationScratchFrameIndex(FI);
393 }
394}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
#define MIN_FRAME_SIZE
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:638
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:631
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:673
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:646
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:409
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool isReturnAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
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.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
int64_t estimateFunctionSizeInBytes()
Return an estimate of the function's code size, taking into account block and function alignment.
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool hasFPImpl(const MachineFunction &MF) const override
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 emitPrologue(MachineFunction &, MachineBasicBlock &) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
XtensaFrameLowering(const XtensaSubtarget &STI)
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...
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...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Kill
The last use of a register.
@ Define
Register definition.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82