1 //===-- llvm/CodeGen/TargetFrameLowering.h ----------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Interface to describe the layout of a stack frame on the target machine.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CODEGEN_TARGETFRAMELOWERING_H
14 #define LLVM_CODEGEN_TARGETFRAMELOWERING_H
16 #include "llvm/CodeGen/MachineBasicBlock.h"
21 class CalleeSavedInfo;
22 class MachineFunction;
25 namespace TargetStackID {
34 /// Information about stack frame layout on the target. It holds the direction
35 /// of stack growth, the known stack alignment on entry to each function, and
36 /// the offset to the locals area.
38 /// The offset to the local area is the offset from the stack pointer on
39 /// function entry to the first location where function data (local variables,
40 /// spill locations) can be stored.
41 class TargetFrameLowering {
44 StackGrowsUp, // Adding to the stack increases the stack address
45 StackGrowsDown // Adding to the stack decreases the stack address
48 // Maps a callee saved register to a stack slot with a fixed offset.
51 int Offset; // Offset relative to stack pointer on function entry.
54 struct DwarfFrameBase {
55 // The frame base may be either a register (the default), the CFA,
56 // or a WebAssembly-specific location description.
57 enum FrameBaseKind { Register, CFA, WasmFrameBase } Kind;
58 struct WasmFrameBase {
59 unsigned Kind; // Wasm local, global, or value stack
64 struct WasmFrameBase WasmLoc;
69 StackDirection StackDir;
71 Align TransientStackAlignment;
73 bool StackRealignable;
75 TargetFrameLowering(StackDirection D, Align StackAl, int LAO,
76 Align TransAl = Align(1), bool StackReal = true)
77 : StackDir(D), StackAlignment(StackAl), TransientStackAlignment(TransAl),
78 LocalAreaOffset(LAO), StackRealignable(StackReal) {}
80 virtual ~TargetFrameLowering();
82 // These methods return information that describes the abstract stack layout
83 // of the target machine.
85 /// getStackGrowthDirection - Return the direction the stack grows
87 StackDirection getStackGrowthDirection() const { return StackDir; }
89 /// getStackAlignment - This method returns the number of bytes to which the
90 /// stack pointer must be aligned on entry to a function. Typically, this
91 /// is the largest alignment for any data object in the target.
93 unsigned getStackAlignment() const { return StackAlignment.value(); }
94 /// getStackAlignment - This method returns the number of bytes to which the
95 /// stack pointer must be aligned on entry to a function. Typically, this
96 /// is the largest alignment for any data object in the target.
98 Align getStackAlign() const { return StackAlignment; }
100 /// alignSPAdjust - This method aligns the stack adjustment to the correct
103 int alignSPAdjust(int SPAdj) const {
105 SPAdj = -alignTo(-SPAdj, StackAlignment);
107 SPAdj = alignTo(SPAdj, StackAlignment);
112 /// getTransientStackAlignment - This method returns the number of bytes to
113 /// which the stack pointer must be aligned at all times, even between
116 LLVM_ATTRIBUTE_DEPRECATED(unsigned getTransientStackAlignment() const,
117 "Use getTransientStackAlign instead") {
118 return TransientStackAlignment.value();
120 /// getTransientStackAlignment - This method returns the number of bytes to
121 /// which the stack pointer must be aligned at all times, even between
124 Align getTransientStackAlign() const { return TransientStackAlignment; }
126 /// isStackRealignable - This method returns whether the stack can be
128 bool isStackRealignable() const {
129 return StackRealignable;
132 /// Return the skew that has to be applied to stack alignment under
133 /// certain conditions (e.g. stack was adjusted before function \p MF
135 virtual unsigned getStackAlignmentSkew(const MachineFunction &MF) const;
137 /// getOffsetOfLocalArea - This method returns the offset of the local area
138 /// from the stack pointer on entrance to a function.
140 int getOffsetOfLocalArea() const { return LocalAreaOffset; }
142 /// isFPCloseToIncomingSP - Return true if the frame pointer is close to
143 /// the incoming stack pointer, false if it is close to the post-prologue
145 virtual bool isFPCloseToIncomingSP() const { return true; }
147 /// assignCalleeSavedSpillSlots - Allows target to override spill slot
148 /// assignment logic. If implemented, assignCalleeSavedSpillSlots() should
149 /// assign frame slots to all CSI entries and return true. If this method
150 /// returns false, spill slots will be assigned using generic implementation.
151 /// assignCalleeSavedSpillSlots() may add, delete or rearrange elements of
154 assignCalleeSavedSpillSlots(MachineFunction &MF,
155 const TargetRegisterInfo *TRI,
156 std::vector<CalleeSavedInfo> &CSI) const {
160 /// getCalleeSavedSpillSlots - This method returns a pointer to an array of
161 /// pairs, that contains an entry for each callee saved register that must be
162 /// spilled to a particular stack location if it is spilled.
164 /// Each entry in this array contains a <register,offset> pair, indicating the
165 /// fixed offset from the incoming stack pointer that each register should be
166 /// spilled at. If a register is not listed here, the code generator is
167 /// allowed to spill it anywhere it chooses.
169 virtual const SpillSlot *
170 getCalleeSavedSpillSlots(unsigned &NumEntries) const {
175 /// targetHandlesStackFrameRounding - Returns true if the target is
176 /// responsible for rounding up the stack frame (probably at emitPrologue
178 virtual bool targetHandlesStackFrameRounding() const {
182 /// Returns true if the target will correctly handle shrink wrapping.
183 virtual bool enableShrinkWrapping(const MachineFunction &MF) const {
187 /// Returns true if the stack slot holes in the fixed and callee-save stack
188 /// area should be used when allocating other stack locations to reduce stack
190 virtual bool enableStackSlotScavenging(const MachineFunction &MF) const {
194 /// Returns true if the target can safely skip saving callee-saved registers
195 /// for noreturn nounwind functions.
196 virtual bool enableCalleeSaveSkip(const MachineFunction &MF) const;
198 /// emitProlog/emitEpilog - These methods insert prolog and epilog code into
200 virtual void emitPrologue(MachineFunction &MF,
201 MachineBasicBlock &MBB) const = 0;
202 virtual void emitEpilogue(MachineFunction &MF,
203 MachineBasicBlock &MBB) const = 0;
205 /// With basic block sections, emit callee saved frame moves for basic blocks
206 /// that are in a different section.
208 emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
209 MachineBasicBlock::iterator MBBI) const {}
211 virtual void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
212 MachineBasicBlock::iterator MBBI,
214 bool IsPrologue) const {}
216 /// Replace a StackProbe stub (if any) with the actual probe code inline
217 virtual void inlineStackProbe(MachineFunction &MF,
218 MachineBasicBlock &PrologueMBB) const {}
220 /// Adjust the prologue to have the function use segmented stacks. This works
221 /// by adding a check even before the "normal" function prologue.
222 virtual void adjustForSegmentedStacks(MachineFunction &MF,
223 MachineBasicBlock &PrologueMBB) const {}
225 /// Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in
226 /// the assembly prologue to explicitly handle the stack.
227 virtual void adjustForHiPEPrologue(MachineFunction &MF,
228 MachineBasicBlock &PrologueMBB) const {}
230 /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
231 /// saved registers and returns true if it isn't possible / profitable to do
232 /// so by issuing a series of store instructions via
233 /// storeRegToStackSlot(). Returns false otherwise.
234 virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
235 MachineBasicBlock::iterator MI,
236 ArrayRef<CalleeSavedInfo> CSI,
237 const TargetRegisterInfo *TRI) const {
241 /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
242 /// saved registers and returns true if it isn't possible / profitable to do
243 /// so by issuing a series of load instructions via loadRegToStackSlot().
244 /// If it returns true, and any of the registers in CSI is not restored,
245 /// it sets the corresponding Restored flag in CSI to false.
246 /// Returns false otherwise.
248 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
249 MachineBasicBlock::iterator MI,
250 MutableArrayRef<CalleeSavedInfo> CSI,
251 const TargetRegisterInfo *TRI) const {
255 /// Return true if the target wants to keep the frame pointer regardless of
256 /// the function attribute "frame-pointer".
257 virtual bool keepFramePointer(const MachineFunction &MF) const {
261 /// hasFP - Return true if the specified function should have a dedicated
262 /// frame pointer register. For most targets this is true only if the function
263 /// has variable sized allocas or if frame pointer elimination is disabled.
264 virtual bool hasFP(const MachineFunction &MF) const = 0;
266 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
267 /// not required, we reserve argument space for call sites in the function
268 /// immediately on entry to the current function. This eliminates the need for
269 /// add/sub sp brackets around call sites. Returns true if the call frame is
270 /// included as part of the stack frame.
271 virtual bool hasReservedCallFrame(const MachineFunction &MF) const {
275 /// canSimplifyCallFramePseudos - When possible, it's best to simplify the
276 /// call frame pseudo ops before doing frame index elimination. This is
277 /// possible only when frame index references between the pseudos won't
278 /// need adjusting for the call frame adjustments. Normally, that's true
279 /// if the function has a reserved call frame or a frame pointer. Some
280 /// targets (Thumb2, for example) may have more complicated criteria,
281 /// however, and can override this behavior.
282 virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const {
283 return hasReservedCallFrame(MF) || hasFP(MF);
286 // needsFrameIndexResolution - Do we need to perform FI resolution for
287 // this function. Normally, this is required only when the function
288 // has any stack objects. However, targets may want to override this.
289 virtual bool needsFrameIndexResolution(const MachineFunction &MF) const;
291 /// getFrameIndexReference - This method should return the base register
292 /// and offset used to reference a frame index location. The offset is
293 /// returned directly, and the base register is returned via FrameReg.
294 virtual int getFrameIndexReference(const MachineFunction &MF, int FI,
295 Register &FrameReg) const;
297 /// Same as \c getFrameIndexReference, except that the stack pointer (as
298 /// opposed to the frame pointer) will be the preferred value for \p
299 /// FrameReg. This is generally used for emitting statepoint or EH tables that
300 /// use offsets from RSP. If \p IgnoreSPUpdates is true, the returned
301 /// offset is only guaranteed to be valid with respect to the value of SP at
302 /// the end of the prologue.
303 virtual int getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI,
305 bool IgnoreSPUpdates) const {
306 // Always safe to dispatch to getFrameIndexReference.
307 return getFrameIndexReference(MF, FI, FrameReg);
310 /// getNonLocalFrameIndexReference - This method returns the offset used to
311 /// reference a frame index location. The offset can be from either FP/BP/SP
312 /// based on which base register is returned by llvm.localaddress.
313 virtual int getNonLocalFrameIndexReference(const MachineFunction &MF,
315 // By default, dispatch to getFrameIndexReference. Interested targets can
318 return getFrameIndexReference(MF, FI, FrameReg);
321 /// Returns the callee-saved registers as computed by determineCalleeSaves
322 /// in the BitVector \p SavedRegs.
323 virtual void getCalleeSaves(const MachineFunction &MF,
324 BitVector &SavedRegs) const;
326 /// This method determines which of the registers reported by
327 /// TargetRegisterInfo::getCalleeSavedRegs() should actually get saved.
328 /// The default implementation checks populates the \p SavedRegs bitset with
329 /// all registers which are modified in the function, targets may override
330 /// this function to save additional registers.
331 /// This method also sets up the register scavenger ensuring there is a free
332 /// register or a frameindex available.
333 /// This method should not be called by any passes outside of PEI, because
334 /// it may change state passed in by \p MF and \p RS. The preferred
335 /// interface outside PEI is getCalleeSaves.
336 virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
337 RegScavenger *RS = nullptr) const;
339 /// processFunctionBeforeFrameFinalized - This method is called immediately
340 /// before the specified function's frame layout (MF.getFrameInfo()) is
341 /// finalized. Once the frame is finalized, MO_FrameIndex operands are
342 /// replaced with direct constants. This method is optional.
344 virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF,
345 RegScavenger *RS = nullptr) const {
348 /// processFunctionBeforeFrameIndicesReplaced - This method is called
349 /// immediately before MO_FrameIndex operands are eliminated, but after the
350 /// frame is finalized. This method is optional.
352 processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF,
353 RegScavenger *RS = nullptr) const {}
355 virtual unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const {
356 report_fatal_error("WinEH not implemented for this target");
359 /// This method is called during prolog/epilog code insertion to eliminate
360 /// call frame setup and destroy pseudo instructions (but only if the Target
361 /// is using them). It is responsible for eliminating these instructions,
362 /// replacing them with concrete instructions. This method need only be
363 /// implemented if using call frame setup/destroy pseudo instructions.
364 /// Returns an iterator pointing to the instruction after the replaced one.
365 virtual MachineBasicBlock::iterator
366 eliminateCallFramePseudoInstr(MachineFunction &MF,
367 MachineBasicBlock &MBB,
368 MachineBasicBlock::iterator MI) const {
369 llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
374 /// Order the symbols in the local stack frame.
375 /// The list of objects that we want to order is in \p objectsToAllocate as
376 /// indices into the MachineFrameInfo. The array can be reordered in any way
377 /// upon return. The contents of the array, however, may not be modified (i.e.
378 /// only their order may be changed).
379 /// By default, just maintain the original order.
381 orderFrameObjects(const MachineFunction &MF,
382 SmallVectorImpl<int> &objectsToAllocate) const {
385 /// Check whether or not the given \p MBB can be used as a prologue
387 /// The prologue will be inserted first in this basic block.
388 /// This method is used by the shrink-wrapping pass to decide if
389 /// \p MBB will be correctly handled by the target.
390 /// As soon as the target enable shrink-wrapping without overriding
391 /// this method, we assume that each basic block is a valid
393 virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const {
397 /// Check whether or not the given \p MBB can be used as a epilogue
399 /// The epilogue will be inserted before the first terminator of that block.
400 /// This method is used by the shrink-wrapping pass to decide if
401 /// \p MBB will be correctly handled by the target.
402 /// As soon as the target enable shrink-wrapping without overriding
403 /// this method, we assume that each basic block is a valid
405 virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const {
409 /// Returns the StackID that scalable vectors should be associated with.
410 virtual TargetStackID::Value getStackIDForScalableVectors() const {
411 return TargetStackID::Default;
414 virtual bool isSupportedStackID(TargetStackID::Value ID) const {
418 case TargetStackID::Default:
419 case TargetStackID::NoAlloc:
424 /// Check if given function is safe for not having callee saved registers.
425 /// This is used when interprocedural register allocation is enabled.
426 static bool isSafeForNoCSROpt(const Function &F);
428 /// Check if the no-CSR optimisation is profitable for the given function.
429 virtual bool isProfitableForNoCSROpt(const Function &F) const {
433 /// Return initial CFA offset value i.e. the one valid at the beginning of the
434 /// function (before any stack operations).
435 virtual int getInitialCFAOffset(const MachineFunction &MF) const;
437 /// Return initial CFA register value i.e. the one valid at the beginning of
438 /// the function (before any stack operations).
439 virtual Register getInitialCFARegister(const MachineFunction &MF) const;
441 /// Return the frame base information to be encoded in the DWARF subprogram
443 virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const;
446 } // End llvm namespace