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 /// This method returns whether or not it is safe for an object with the
138 /// given stack id to be bundled into the local area.
139 virtual bool isStackIdSafeForLocalArea(unsigned StackId) const {
143 /// getOffsetOfLocalArea - This method returns the offset of the local area
144 /// from the stack pointer on entrance to a function.
146 int getOffsetOfLocalArea() const { return LocalAreaOffset; }
148 /// isFPCloseToIncomingSP - Return true if the frame pointer is close to
149 /// the incoming stack pointer, false if it is close to the post-prologue
151 virtual bool isFPCloseToIncomingSP() const { return true; }
153 /// assignCalleeSavedSpillSlots - Allows target to override spill slot
154 /// assignment logic. If implemented, assignCalleeSavedSpillSlots() should
155 /// assign frame slots to all CSI entries and return true. If this method
156 /// returns false, spill slots will be assigned using generic implementation.
157 /// assignCalleeSavedSpillSlots() may add, delete or rearrange elements of
160 assignCalleeSavedSpillSlots(MachineFunction &MF,
161 const TargetRegisterInfo *TRI,
162 std::vector<CalleeSavedInfo> &CSI) const {
166 /// getCalleeSavedSpillSlots - This method returns a pointer to an array of
167 /// pairs, that contains an entry for each callee saved register that must be
168 /// spilled to a particular stack location if it is spilled.
170 /// Each entry in this array contains a <register,offset> pair, indicating the
171 /// fixed offset from the incoming stack pointer that each register should be
172 /// spilled at. If a register is not listed here, the code generator is
173 /// allowed to spill it anywhere it chooses.
175 virtual const SpillSlot *
176 getCalleeSavedSpillSlots(unsigned &NumEntries) const {
181 /// targetHandlesStackFrameRounding - Returns true if the target is
182 /// responsible for rounding up the stack frame (probably at emitPrologue
184 virtual bool targetHandlesStackFrameRounding() const {
188 /// Returns true if the target will correctly handle shrink wrapping.
189 virtual bool enableShrinkWrapping(const MachineFunction &MF) const {
193 /// Returns true if the stack slot holes in the fixed and callee-save stack
194 /// area should be used when allocating other stack locations to reduce stack
196 virtual bool enableStackSlotScavenging(const MachineFunction &MF) const {
200 /// Returns true if the target can safely skip saving callee-saved registers
201 /// for noreturn nounwind functions.
202 virtual bool enableCalleeSaveSkip(const MachineFunction &MF) const;
204 /// emitProlog/emitEpilog - These methods insert prolog and epilog code into
206 virtual void emitPrologue(MachineFunction &MF,
207 MachineBasicBlock &MBB) const = 0;
208 virtual void emitEpilogue(MachineFunction &MF,
209 MachineBasicBlock &MBB) const = 0;
211 /// With basic block sections, emit callee saved frame moves for basic blocks
212 /// that are in a different section.
214 emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
215 MachineBasicBlock::iterator MBBI) const {}
217 virtual void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
218 MachineBasicBlock::iterator MBBI,
220 bool IsPrologue) const {}
222 /// Replace a StackProbe stub (if any) with the actual probe code inline
223 virtual void inlineStackProbe(MachineFunction &MF,
224 MachineBasicBlock &PrologueMBB) const {}
226 /// Adjust the prologue to have the function use segmented stacks. This works
227 /// by adding a check even before the "normal" function prologue.
228 virtual void adjustForSegmentedStacks(MachineFunction &MF,
229 MachineBasicBlock &PrologueMBB) const {}
231 /// Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in
232 /// the assembly prologue to explicitly handle the stack.
233 virtual void adjustForHiPEPrologue(MachineFunction &MF,
234 MachineBasicBlock &PrologueMBB) const {}
236 /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
237 /// saved registers and returns true if it isn't possible / profitable to do
238 /// so by issuing a series of store instructions via
239 /// storeRegToStackSlot(). Returns false otherwise.
240 virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
241 MachineBasicBlock::iterator MI,
242 ArrayRef<CalleeSavedInfo> CSI,
243 const TargetRegisterInfo *TRI) const {
247 /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
248 /// saved registers and returns true if it isn't possible / profitable to do
249 /// so by issuing a series of load instructions via loadRegToStackSlot().
250 /// If it returns true, and any of the registers in CSI is not restored,
251 /// it sets the corresponding Restored flag in CSI to false.
252 /// Returns false otherwise.
254 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
255 MachineBasicBlock::iterator MI,
256 MutableArrayRef<CalleeSavedInfo> CSI,
257 const TargetRegisterInfo *TRI) const {
261 /// Return true if the target wants to keep the frame pointer regardless of
262 /// the function attribute "frame-pointer".
263 virtual bool keepFramePointer(const MachineFunction &MF) const {
267 /// hasFP - Return true if the specified function should have a dedicated
268 /// frame pointer register. For most targets this is true only if the function
269 /// has variable sized allocas or if frame pointer elimination is disabled.
270 virtual bool hasFP(const MachineFunction &MF) const = 0;
272 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
273 /// not required, we reserve argument space for call sites in the function
274 /// immediately on entry to the current function. This eliminates the need for
275 /// add/sub sp brackets around call sites. Returns true if the call frame is
276 /// included as part of the stack frame.
277 virtual bool hasReservedCallFrame(const MachineFunction &MF) const {
281 /// canSimplifyCallFramePseudos - When possible, it's best to simplify the
282 /// call frame pseudo ops before doing frame index elimination. This is
283 /// possible only when frame index references between the pseudos won't
284 /// need adjusting for the call frame adjustments. Normally, that's true
285 /// if the function has a reserved call frame or a frame pointer. Some
286 /// targets (Thumb2, for example) may have more complicated criteria,
287 /// however, and can override this behavior.
288 virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const {
289 return hasReservedCallFrame(MF) || hasFP(MF);
292 // needsFrameIndexResolution - Do we need to perform FI resolution for
293 // this function. Normally, this is required only when the function
294 // has any stack objects. However, targets may want to override this.
295 virtual bool needsFrameIndexResolution(const MachineFunction &MF) const;
297 /// getFrameIndexReference - This method should return the base register
298 /// and offset used to reference a frame index location. The offset is
299 /// returned directly, and the base register is returned via FrameReg.
300 virtual int getFrameIndexReference(const MachineFunction &MF, int FI,
301 Register &FrameReg) const;
303 /// Same as \c getFrameIndexReference, except that the stack pointer (as
304 /// opposed to the frame pointer) will be the preferred value for \p
305 /// FrameReg. This is generally used for emitting statepoint or EH tables that
306 /// use offsets from RSP. If \p IgnoreSPUpdates is true, the returned
307 /// offset is only guaranteed to be valid with respect to the value of SP at
308 /// the end of the prologue.
309 virtual int getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI,
311 bool IgnoreSPUpdates) const {
312 // Always safe to dispatch to getFrameIndexReference.
313 return getFrameIndexReference(MF, FI, FrameReg);
316 /// getNonLocalFrameIndexReference - This method returns the offset used to
317 /// reference a frame index location. The offset can be from either FP/BP/SP
318 /// based on which base register is returned by llvm.localaddress.
319 virtual int getNonLocalFrameIndexReference(const MachineFunction &MF,
321 // By default, dispatch to getFrameIndexReference. Interested targets can
324 return getFrameIndexReference(MF, FI, FrameReg);
327 /// Returns the callee-saved registers as computed by determineCalleeSaves
328 /// in the BitVector \p SavedRegs.
329 virtual void getCalleeSaves(const MachineFunction &MF,
330 BitVector &SavedRegs) const;
332 /// This method determines which of the registers reported by
333 /// TargetRegisterInfo::getCalleeSavedRegs() should actually get saved.
334 /// The default implementation checks populates the \p SavedRegs bitset with
335 /// all registers which are modified in the function, targets may override
336 /// this function to save additional registers.
337 /// This method also sets up the register scavenger ensuring there is a free
338 /// register or a frameindex available.
339 /// This method should not be called by any passes outside of PEI, because
340 /// it may change state passed in by \p MF and \p RS. The preferred
341 /// interface outside PEI is getCalleeSaves.
342 virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
343 RegScavenger *RS = nullptr) const;
345 /// processFunctionBeforeFrameFinalized - This method is called immediately
346 /// before the specified function's frame layout (MF.getFrameInfo()) is
347 /// finalized. Once the frame is finalized, MO_FrameIndex operands are
348 /// replaced with direct constants. This method is optional.
350 virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF,
351 RegScavenger *RS = nullptr) const {
354 /// processFunctionBeforeFrameIndicesReplaced - This method is called
355 /// immediately before MO_FrameIndex operands are eliminated, but after the
356 /// frame is finalized. This method is optional.
358 processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF,
359 RegScavenger *RS = nullptr) const {}
361 virtual unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const {
362 report_fatal_error("WinEH not implemented for this target");
365 /// This method is called during prolog/epilog code insertion to eliminate
366 /// call frame setup and destroy pseudo instructions (but only if the Target
367 /// is using them). It is responsible for eliminating these instructions,
368 /// replacing them with concrete instructions. This method need only be
369 /// implemented if using call frame setup/destroy pseudo instructions.
370 /// Returns an iterator pointing to the instruction after the replaced one.
371 virtual MachineBasicBlock::iterator
372 eliminateCallFramePseudoInstr(MachineFunction &MF,
373 MachineBasicBlock &MBB,
374 MachineBasicBlock::iterator MI) const {
375 llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
380 /// Order the symbols in the local stack frame.
381 /// The list of objects that we want to order is in \p objectsToAllocate as
382 /// indices into the MachineFrameInfo. The array can be reordered in any way
383 /// upon return. The contents of the array, however, may not be modified (i.e.
384 /// only their order may be changed).
385 /// By default, just maintain the original order.
387 orderFrameObjects(const MachineFunction &MF,
388 SmallVectorImpl<int> &objectsToAllocate) const {
391 /// Check whether or not the given \p MBB can be used as a prologue
393 /// The prologue will be inserted first in this basic block.
394 /// This method is used by the shrink-wrapping pass to decide if
395 /// \p MBB will be correctly handled by the target.
396 /// As soon as the target enable shrink-wrapping without overriding
397 /// this method, we assume that each basic block is a valid
399 virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const {
403 /// Check whether or not the given \p MBB can be used as a epilogue
405 /// The epilogue will be inserted before the first terminator of that block.
406 /// This method is used by the shrink-wrapping pass to decide if
407 /// \p MBB will be correctly handled by the target.
408 /// As soon as the target enable shrink-wrapping without overriding
409 /// this method, we assume that each basic block is a valid
411 virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const {
415 /// Returns the StackID that scalable vectors should be associated with.
416 virtual TargetStackID::Value getStackIDForScalableVectors() const {
417 return TargetStackID::Default;
420 virtual bool isSupportedStackID(TargetStackID::Value ID) const {
424 case TargetStackID::Default:
425 case TargetStackID::NoAlloc:
430 /// Check if given function is safe for not having callee saved registers.
431 /// This is used when interprocedural register allocation is enabled.
432 static bool isSafeForNoCSROpt(const Function &F);
434 /// Check if the no-CSR optimisation is profitable for the given function.
435 virtual bool isProfitableForNoCSROpt(const Function &F) const {
439 /// Return initial CFA offset value i.e. the one valid at the beginning of the
440 /// function (before any stack operations).
441 virtual int getInitialCFAOffset(const MachineFunction &MF) const;
443 /// Return initial CFA register value i.e. the one valid at the beginning of
444 /// the function (before any stack operations).
445 virtual Register getInitialCFARegister(const MachineFunction &MF) const;
447 /// Return the frame base information to be encoded in the DWARF subprogram
449 virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const;
452 } // End llvm namespace