Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:36

0001 //===-- llvm/CodeGen/TargetFrameLowering.h ----------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // Interface to describe the layout of a stack frame on the target machine.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_CODEGEN_TARGETFRAMELOWERING_H
0014 #define LLVM_CODEGEN_TARGETFRAMELOWERING_H
0015 
0016 #include "llvm/ADT/BitVector.h"
0017 #include "llvm/CodeGen/MachineBasicBlock.h"
0018 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
0019 #include "llvm/Support/TypeSize.h"
0020 #include <vector>
0021 
0022 namespace llvm {
0023   class BitVector;
0024   class CalleeSavedInfo;
0025   class MachineFunction;
0026   class RegScavenger;
0027 
0028 namespace TargetStackID {
0029 enum Value {
0030   Default = 0,
0031   SGPRSpill = 1,
0032   ScalableVector = 2,
0033   WasmLocal = 3,
0034   NoAlloc = 255
0035 };
0036 }
0037 
0038 /// Information about stack frame layout on the target.  It holds the direction
0039 /// of stack growth, the known stack alignment on entry to each function, and
0040 /// the offset to the locals area.
0041 ///
0042 /// The offset to the local area is the offset from the stack pointer on
0043 /// function entry to the first location where function data (local variables,
0044 /// spill locations) can be stored.
0045 class TargetFrameLowering {
0046 public:
0047   enum StackDirection {
0048     StackGrowsUp,        // Adding to the stack increases the stack address
0049     StackGrowsDown       // Adding to the stack decreases the stack address
0050   };
0051 
0052   // Maps a callee saved register to a stack slot with a fixed offset.
0053   struct SpillSlot {
0054     unsigned Reg;
0055     int64_t Offset; // Offset relative to stack pointer on function entry.
0056   };
0057 
0058   struct DwarfFrameBase {
0059     // The frame base may be either a register (the default), the CFA with an
0060     // offset, or a WebAssembly-specific location description.
0061     enum FrameBaseKind { Register, CFA, WasmFrameBase } Kind;
0062     struct WasmFrameBase {
0063       unsigned Kind; // Wasm local, global, or value stack
0064       unsigned Index;
0065     };
0066     union {
0067       // Used with FrameBaseKind::Register.
0068       unsigned Reg;
0069       // Used with FrameBaseKind::CFA.
0070       int64_t Offset;
0071       struct WasmFrameBase WasmLoc;
0072     } Location;
0073   };
0074 
0075 private:
0076   StackDirection StackDir;
0077   Align StackAlignment;
0078   Align TransientStackAlignment;
0079   int LocalAreaOffset;
0080   bool StackRealignable;
0081 public:
0082   TargetFrameLowering(StackDirection D, Align StackAl, int LAO,
0083                       Align TransAl = Align(1), bool StackReal = true)
0084       : StackDir(D), StackAlignment(StackAl), TransientStackAlignment(TransAl),
0085         LocalAreaOffset(LAO), StackRealignable(StackReal) {}
0086 
0087   virtual ~TargetFrameLowering();
0088 
0089   // These methods return information that describes the abstract stack layout
0090   // of the target machine.
0091 
0092   /// getStackGrowthDirection - Return the direction the stack grows
0093   ///
0094   StackDirection getStackGrowthDirection() const { return StackDir; }
0095 
0096   /// getStackAlignment - This method returns the number of bytes to which the
0097   /// stack pointer must be aligned on entry to a function.  Typically, this
0098   /// is the largest alignment for any data object in the target.
0099   ///
0100   unsigned getStackAlignment() const { return StackAlignment.value(); }
0101   /// getStackAlignment - This method returns the number of bytes to which the
0102   /// stack pointer must be aligned on entry to a function.  Typically, this
0103   /// is the largest alignment for any data object in the target.
0104   ///
0105   Align getStackAlign() const { return StackAlignment; }
0106 
0107   /// getStackThreshold - Return the maximum stack size
0108   ///
0109   virtual uint64_t getStackThreshold() const { return UINT_MAX; }
0110 
0111   /// alignSPAdjust - This method aligns the stack adjustment to the correct
0112   /// alignment.
0113   ///
0114   int alignSPAdjust(int SPAdj) const {
0115     if (SPAdj < 0) {
0116       SPAdj = -alignTo(-SPAdj, StackAlignment);
0117     } else {
0118       SPAdj = alignTo(SPAdj, StackAlignment);
0119     }
0120     return SPAdj;
0121   }
0122 
0123   /// getTransientStackAlignment - This method returns the number of bytes to
0124   /// which the stack pointer must be aligned at all times, even between
0125   /// calls.
0126   ///
0127   Align getTransientStackAlign() const { return TransientStackAlignment; }
0128 
0129   /// isStackRealignable - This method returns whether the stack can be
0130   /// realigned.
0131   bool isStackRealignable() const {
0132     return StackRealignable;
0133   }
0134 
0135   /// This method returns whether or not it is safe for an object with the
0136   /// given stack id to be bundled into the local area.
0137   virtual bool isStackIdSafeForLocalArea(unsigned StackId) const {
0138     return true;
0139   }
0140 
0141   /// getOffsetOfLocalArea - This method returns the offset of the local area
0142   /// from the stack pointer on entrance to a function.
0143   ///
0144   int getOffsetOfLocalArea() const { return LocalAreaOffset; }
0145 
0146   /// Control the placement of special register scavenging spill slots when
0147   /// allocating a stack frame.
0148   ///
0149   /// If this returns true, the frame indexes used by the RegScavenger will be
0150   /// allocated closest to the incoming stack pointer.
0151   virtual bool allocateScavengingFrameIndexesNearIncomingSP(
0152     const MachineFunction &MF) const;
0153 
0154   /// assignCalleeSavedSpillSlots - Allows target to override spill slot
0155   /// assignment logic.  If implemented, assignCalleeSavedSpillSlots() should
0156   /// assign frame slots to all CSI entries and return true.  If this method
0157   /// returns false, spill slots will be assigned using generic implementation.
0158   /// assignCalleeSavedSpillSlots() may add, delete or rearrange elements of
0159   /// CSI.
0160   virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF,
0161                                            const TargetRegisterInfo *TRI,
0162                                            std::vector<CalleeSavedInfo> &CSI,
0163                                            unsigned &MinCSFrameIndex,
0164                                            unsigned &MaxCSFrameIndex) const {
0165     return assignCalleeSavedSpillSlots(MF, TRI, CSI);
0166   }
0167 
0168   virtual bool
0169   assignCalleeSavedSpillSlots(MachineFunction &MF,
0170                               const TargetRegisterInfo *TRI,
0171                               std::vector<CalleeSavedInfo> &CSI) const {
0172     return false;
0173   }
0174 
0175   /// getCalleeSavedSpillSlots - This method returns a pointer to an array of
0176   /// pairs, that contains an entry for each callee saved register that must be
0177   /// spilled to a particular stack location if it is spilled.
0178   ///
0179   /// Each entry in this array contains a <register,offset> pair, indicating the
0180   /// fixed offset from the incoming stack pointer that each register should be
0181   /// spilled at. If a register is not listed here, the code generator is
0182   /// allowed to spill it anywhere it chooses.
0183   ///
0184   virtual const SpillSlot *
0185   getCalleeSavedSpillSlots(unsigned &NumEntries) const {
0186     NumEntries = 0;
0187     return nullptr;
0188   }
0189 
0190   /// targetHandlesStackFrameRounding - Returns true if the target is
0191   /// responsible for rounding up the stack frame (probably at emitPrologue
0192   /// time).
0193   virtual bool targetHandlesStackFrameRounding() const {
0194     return false;
0195   }
0196 
0197   /// Returns true if the target will correctly handle shrink wrapping.
0198   virtual bool enableShrinkWrapping(const MachineFunction &MF) const {
0199     return false;
0200   }
0201 
0202   /// Returns true if the stack slot holes in the fixed and callee-save stack
0203   /// area should be used when allocating other stack locations to reduce stack
0204   /// size.
0205   virtual bool enableStackSlotScavenging(const MachineFunction &MF) const {
0206     return false;
0207   }
0208 
0209   /// Returns true if the target can safely skip saving callee-saved registers
0210   /// for noreturn nounwind functions.
0211   virtual bool enableCalleeSaveSkip(const MachineFunction &MF) const;
0212 
0213   /// emitProlog/emitEpilog - These methods insert prolog and epilog code into
0214   /// the function.
0215   virtual void emitPrologue(MachineFunction &MF,
0216                             MachineBasicBlock &MBB) const = 0;
0217   virtual void emitEpilogue(MachineFunction &MF,
0218                             MachineBasicBlock &MBB) const = 0;
0219 
0220   /// emitZeroCallUsedRegs - Zeros out call used registers.
0221   virtual void emitZeroCallUsedRegs(BitVector RegsToZero,
0222                                     MachineBasicBlock &MBB) const {}
0223 
0224   /// With basic block sections, emit callee saved frame moves for basic blocks
0225   /// that are in a different section.
0226   virtual void
0227   emitCalleeSavedFrameMovesFullCFA(MachineBasicBlock &MBB,
0228                                    MachineBasicBlock::iterator MBBI) const {}
0229 
0230   /// Returns true if we may need to fix the unwind information for the
0231   /// function.
0232   virtual bool enableCFIFixup(MachineFunction &MF) const;
0233 
0234   /// Emit CFI instructions that recreate the state of the unwind information
0235   /// upon fucntion entry.
0236   virtual void resetCFIToInitialState(MachineBasicBlock &MBB) const {}
0237 
0238   /// Replace a StackProbe stub (if any) with the actual probe code inline
0239   virtual void inlineStackProbe(MachineFunction &MF,
0240                                 MachineBasicBlock &PrologueMBB) const {}
0241 
0242   /// Does the stack probe function call return with a modified stack pointer?
0243   virtual bool stackProbeFunctionModifiesSP() const { return false; }
0244 
0245   /// Adjust the prologue to have the function use segmented stacks. This works
0246   /// by adding a check even before the "normal" function prologue.
0247   virtual void adjustForSegmentedStacks(MachineFunction &MF,
0248                                         MachineBasicBlock &PrologueMBB) const {}
0249 
0250   /// Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in
0251   /// the assembly prologue to explicitly handle the stack.
0252   virtual void adjustForHiPEPrologue(MachineFunction &MF,
0253                                      MachineBasicBlock &PrologueMBB) const {}
0254 
0255   /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
0256   /// saved registers and returns true if it isn't possible / profitable to do
0257   /// so by issuing a series of store instructions via
0258   /// storeRegToStackSlot(). Returns false otherwise.
0259   virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
0260                                          MachineBasicBlock::iterator MI,
0261                                          ArrayRef<CalleeSavedInfo> CSI,
0262                                          const TargetRegisterInfo *TRI) const {
0263     return false;
0264   }
0265 
0266   /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
0267   /// saved registers and returns true if it isn't possible / profitable to do
0268   /// so by issuing a series of load instructions via loadRegToStackSlot().
0269   /// If it returns true, and any of the registers in CSI is not restored,
0270   /// it sets the corresponding Restored flag in CSI to false.
0271   /// Returns false otherwise.
0272   virtual bool
0273   restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
0274                               MachineBasicBlock::iterator MI,
0275                               MutableArrayRef<CalleeSavedInfo> CSI,
0276                               const TargetRegisterInfo *TRI) const {
0277     return false;
0278   }
0279 
0280   /// hasFP - Return true if the specified function should have a dedicated
0281   /// frame pointer register. For most targets this is true only if the function
0282   /// has variable sized allocas or if frame pointer elimination is disabled.
0283   /// For all targets, this is false if the function has the naked attribute
0284   /// since there is no prologue to set up the frame pointer.
0285   bool hasFP(const MachineFunction &MF) const {
0286     return !MF.getFunction().hasFnAttribute(Attribute::Naked) && hasFPImpl(MF);
0287   }
0288 
0289   /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
0290   /// not required, we reserve argument space for call sites in the function
0291   /// immediately on entry to the current function. This eliminates the need for
0292   /// add/sub sp brackets around call sites. Returns true if the call frame is
0293   /// included as part of the stack frame.
0294   virtual bool hasReservedCallFrame(const MachineFunction &MF) const {
0295     return !hasFP(MF);
0296   }
0297 
0298   /// canSimplifyCallFramePseudos - When possible, it's best to simplify the
0299   /// call frame pseudo ops before doing frame index elimination. This is
0300   /// possible only when frame index references between the pseudos won't
0301   /// need adjusting for the call frame adjustments. Normally, that's true
0302   /// if the function has a reserved call frame or a frame pointer. Some
0303   /// targets (Thumb2, for example) may have more complicated criteria,
0304   /// however, and can override this behavior.
0305   virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const {
0306     return hasReservedCallFrame(MF) || hasFP(MF);
0307   }
0308 
0309   // needsFrameIndexResolution - Do we need to perform FI resolution for
0310   // this function. Normally, this is required only when the function
0311   // has any stack objects. However, targets may want to override this.
0312   virtual bool needsFrameIndexResolution(const MachineFunction &MF) const;
0313 
0314   /// getFrameIndexReference - This method should return the base register
0315   /// and offset used to reference a frame index location. The offset is
0316   /// returned directly, and the base register is returned via FrameReg.
0317   virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI,
0318                                              Register &FrameReg) const;
0319 
0320   /// Same as \c getFrameIndexReference, except that the stack pointer (as
0321   /// opposed to the frame pointer) will be the preferred value for \p
0322   /// FrameReg. This is generally used for emitting statepoint or EH tables that
0323   /// use offsets from RSP.  If \p IgnoreSPUpdates is true, the returned
0324   /// offset is only guaranteed to be valid with respect to the value of SP at
0325   /// the end of the prologue.
0326   virtual StackOffset
0327   getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI,
0328                                  Register &FrameReg,
0329                                  bool IgnoreSPUpdates) const {
0330     // Always safe to dispatch to getFrameIndexReference.
0331     return getFrameIndexReference(MF, FI, FrameReg);
0332   }
0333 
0334   /// getNonLocalFrameIndexReference - This method returns the offset used to
0335   /// reference a frame index location. The offset can be from either FP/BP/SP
0336   /// based on which base register is returned by llvm.localaddress.
0337   virtual StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF,
0338                                                      int FI) const {
0339     // By default, dispatch to getFrameIndexReference. Interested targets can
0340     // override this.
0341     Register FrameReg;
0342     return getFrameIndexReference(MF, FI, FrameReg);
0343   }
0344 
0345   /// getFrameIndexReferenceFromSP - This method returns the offset from the
0346   /// stack pointer to the slot of the specified index. This function serves to
0347   /// provide a comparable offset from a single reference point (the value of
0348   /// the stack-pointer at function entry) that can be used for analysis.
0349   virtual StackOffset getFrameIndexReferenceFromSP(const MachineFunction &MF,
0350                                                    int FI) const;
0351 
0352   /// Returns the callee-saved registers as computed by determineCalleeSaves
0353   /// in the BitVector \p SavedRegs.
0354   virtual void getCalleeSaves(const MachineFunction &MF,
0355                                   BitVector &SavedRegs) const;
0356 
0357   /// This method determines which of the registers reported by
0358   /// TargetRegisterInfo::getCalleeSavedRegs() should actually get saved.
0359   /// The default implementation checks populates the \p SavedRegs bitset with
0360   /// all registers which are modified in the function, targets may override
0361   /// this function to save additional registers.
0362   /// This method also sets up the register scavenger ensuring there is a free
0363   /// register or a frameindex available.
0364   /// This method should not be called by any passes outside of PEI, because
0365   /// it may change state passed in by \p MF and \p RS. The preferred
0366   /// interface outside PEI is getCalleeSaves.
0367   virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
0368                                     RegScavenger *RS = nullptr) const;
0369 
0370   /// processFunctionBeforeFrameFinalized - This method is called immediately
0371   /// before the specified function's frame layout (MF.getFrameInfo()) is
0372   /// finalized.  Once the frame is finalized, MO_FrameIndex operands are
0373   /// replaced with direct constants.  This method is optional.
0374   ///
0375   virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF,
0376                                              RegScavenger *RS = nullptr) const {
0377   }
0378 
0379   /// processFunctionBeforeFrameIndicesReplaced - This method is called
0380   /// immediately before MO_FrameIndex operands are eliminated, but after the
0381   /// frame is finalized. This method is optional.
0382   virtual void
0383   processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF,
0384                                             RegScavenger *RS = nullptr) const {}
0385 
0386   virtual unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const {
0387     report_fatal_error("WinEH not implemented for this target");
0388   }
0389 
0390   /// This method is called during prolog/epilog code insertion to eliminate
0391   /// call frame setup and destroy pseudo instructions (but only if the Target
0392   /// is using them).  It is responsible for eliminating these instructions,
0393   /// replacing them with concrete instructions.  This method need only be
0394   /// implemented if using call frame setup/destroy pseudo instructions.
0395   /// Returns an iterator pointing to the instruction after the replaced one.
0396   virtual MachineBasicBlock::iterator
0397   eliminateCallFramePseudoInstr(MachineFunction &MF,
0398                                 MachineBasicBlock &MBB,
0399                                 MachineBasicBlock::iterator MI) const {
0400     llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
0401                      "target!");
0402   }
0403 
0404 
0405   /// Order the symbols in the local stack frame.
0406   /// The list of objects that we want to order is in \p objectsToAllocate as
0407   /// indices into the MachineFrameInfo. The array can be reordered in any way
0408   /// upon return. The contents of the array, however, may not be modified (i.e.
0409   /// only their order may be changed).
0410   /// By default, just maintain the original order.
0411   virtual void
0412   orderFrameObjects(const MachineFunction &MF,
0413                     SmallVectorImpl<int> &objectsToAllocate) const {
0414   }
0415 
0416   /// Check whether or not the given \p MBB can be used as a prologue
0417   /// for the target.
0418   /// The prologue will be inserted first in this basic block.
0419   /// This method is used by the shrink-wrapping pass to decide if
0420   /// \p MBB will be correctly handled by the target.
0421   /// As soon as the target enable shrink-wrapping without overriding
0422   /// this method, we assume that each basic block is a valid
0423   /// prologue.
0424   virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const {
0425     return true;
0426   }
0427 
0428   /// Check whether or not the given \p MBB can be used as a epilogue
0429   /// for the target.
0430   /// The epilogue will be inserted before the first terminator of that block.
0431   /// This method is used by the shrink-wrapping pass to decide if
0432   /// \p MBB will be correctly handled by the target.
0433   /// As soon as the target enable shrink-wrapping without overriding
0434   /// this method, we assume that each basic block is a valid
0435   /// epilogue.
0436   virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const {
0437     return true;
0438   }
0439 
0440   /// Returns the StackID that scalable vectors should be associated with.
0441   virtual TargetStackID::Value getStackIDForScalableVectors() const {
0442     return TargetStackID::Default;
0443   }
0444 
0445   virtual bool isSupportedStackID(TargetStackID::Value ID) const {
0446     switch (ID) {
0447     default:
0448       return false;
0449     case TargetStackID::Default:
0450     case TargetStackID::NoAlloc:
0451       return true;
0452     }
0453   }
0454 
0455   /// Check if given function is safe for not having callee saved registers.
0456   /// This is used when interprocedural register allocation is enabled.
0457   static bool isSafeForNoCSROpt(const Function &F);
0458 
0459   /// Check if the no-CSR optimisation is profitable for the given function.
0460   virtual bool isProfitableForNoCSROpt(const Function &F) const {
0461     return true;
0462   }
0463 
0464   /// Return initial CFA offset value i.e. the one valid at the beginning of the
0465   /// function (before any stack operations).
0466   virtual int getInitialCFAOffset(const MachineFunction &MF) const;
0467 
0468   /// Return initial CFA register value i.e. the one valid at the beginning of
0469   /// the function (before any stack operations).
0470   virtual Register getInitialCFARegister(const MachineFunction &MF) const;
0471 
0472   /// Return the frame base information to be encoded in the DWARF subprogram
0473   /// debug info.
0474   virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const;
0475 
0476   /// If frame pointer or base pointer is clobbered by an instruction, we should
0477   /// spill/restore it around that instruction.
0478   virtual void spillFPBP(MachineFunction &MF) const {}
0479 
0480   /// This method is called at the end of prolog/epilog code insertion, so
0481   /// targets can emit remarks based on the final frame layout.
0482   virtual void emitRemarks(const MachineFunction &MF,
0483                            MachineOptimizationRemarkEmitter *ORE) const {};
0484 
0485 protected:
0486   virtual bool hasFPImpl(const MachineFunction &MF) const = 0;
0487 };
0488 
0489 } // End llvm namespace
0490 
0491 #endif