Home | History | Annotate | Line # | Download | only in CodeGen
      1 //===-- llvm/CodeGen/TargetFrameLowering.h ----------------------*- C++ -*-===//
      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 // Interface to describe the layout of a stack frame on the target machine.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #ifndef LLVM_CODEGEN_TARGETFRAMELOWERING_H
     14 #define LLVM_CODEGEN_TARGETFRAMELOWERING_H
     15 
     16 #include "llvm/CodeGen/MachineBasicBlock.h"
     17 #include "llvm/Support/TypeSize.h"
     18 #include <vector>
     19 
     20 namespace llvm {
     21   class BitVector;
     22   class CalleeSavedInfo;
     23   class MachineFunction;
     24   class RegScavenger;
     25 
     26 namespace TargetStackID {
     27   enum Value {
     28     Default = 0,
     29     SGPRSpill = 1,
     30     ScalableVector = 2,
     31     NoAlloc = 255
     32   };
     33 }
     34 
     35 /// Information about stack frame layout on the target.  It holds the direction
     36 /// of stack growth, the known stack alignment on entry to each function, and
     37 /// the offset to the locals area.
     38 ///
     39 /// The offset to the local area is the offset from the stack pointer on
     40 /// function entry to the first location where function data (local variables,
     41 /// spill locations) can be stored.
     42 class TargetFrameLowering {
     43 public:
     44   enum StackDirection {
     45     StackGrowsUp,        // Adding to the stack increases the stack address
     46     StackGrowsDown       // Adding to the stack decreases the stack address
     47   };
     48 
     49   // Maps a callee saved register to a stack slot with a fixed offset.
     50   struct SpillSlot {
     51     unsigned Reg;
     52     int Offset; // Offset relative to stack pointer on function entry.
     53   };
     54 
     55   struct DwarfFrameBase {
     56     // The frame base may be either a register (the default), the CFA,
     57     // or a WebAssembly-specific location description.
     58     enum FrameBaseKind { Register, CFA, WasmFrameBase } Kind;
     59     struct WasmFrameBase {
     60       unsigned Kind; // Wasm local, global, or value stack
     61       unsigned Index;
     62     };
     63     union {
     64       unsigned Reg;
     65       struct WasmFrameBase WasmLoc;
     66     } Location;
     67   };
     68 
     69 private:
     70   StackDirection StackDir;
     71   Align StackAlignment;
     72   Align TransientStackAlignment;
     73   int LocalAreaOffset;
     74   bool StackRealignable;
     75 public:
     76   TargetFrameLowering(StackDirection D, Align StackAl, int LAO,
     77                       Align TransAl = Align(1), bool StackReal = true)
     78       : StackDir(D), StackAlignment(StackAl), TransientStackAlignment(TransAl),
     79         LocalAreaOffset(LAO), StackRealignable(StackReal) {}
     80 
     81   virtual ~TargetFrameLowering();
     82 
     83   // These methods return information that describes the abstract stack layout
     84   // of the target machine.
     85 
     86   /// getStackGrowthDirection - Return the direction the stack grows
     87   ///
     88   StackDirection getStackGrowthDirection() const { return StackDir; }
     89 
     90   /// getStackAlignment - This method returns the number of bytes to which the
     91   /// stack pointer must be aligned on entry to a function.  Typically, this
     92   /// is the largest alignment for any data object in the target.
     93   ///
     94   unsigned getStackAlignment() const { return StackAlignment.value(); }
     95   /// getStackAlignment - This method returns the number of bytes to which the
     96   /// stack pointer must be aligned on entry to a function.  Typically, this
     97   /// is the largest alignment for any data object in the target.
     98   ///
     99   Align getStackAlign() const { return StackAlignment; }
    100 
    101   /// alignSPAdjust - This method aligns the stack adjustment to the correct
    102   /// alignment.
    103   ///
    104   int alignSPAdjust(int SPAdj) const {
    105     if (SPAdj < 0) {
    106       SPAdj = -alignTo(-SPAdj, StackAlignment);
    107     } else {
    108       SPAdj = alignTo(SPAdj, StackAlignment);
    109     }
    110     return SPAdj;
    111   }
    112 
    113   /// getTransientStackAlignment - This method returns the number of bytes to
    114   /// which the stack pointer must be aligned at all times, even between
    115   /// calls.
    116   ///
    117   Align getTransientStackAlign() const { return TransientStackAlignment; }
    118 
    119   /// isStackRealignable - This method returns whether the stack can be
    120   /// realigned.
    121   bool isStackRealignable() const {
    122     return StackRealignable;
    123   }
    124 
    125   /// Return the skew that has to be applied to stack alignment under
    126   /// certain conditions (e.g. stack was adjusted before function \p MF
    127   /// was called).
    128   virtual unsigned getStackAlignmentSkew(const MachineFunction &MF) const;
    129 
    130   /// This method returns whether or not it is safe for an object with the
    131   /// given stack id to be bundled into the local area.
    132   virtual bool isStackIdSafeForLocalArea(unsigned StackId) const {
    133     return true;
    134   }
    135 
    136   /// getOffsetOfLocalArea - This method returns the offset of the local area
    137   /// from the stack pointer on entrance to a function.
    138   ///
    139   int getOffsetOfLocalArea() const { return LocalAreaOffset; }
    140 
    141   /// isFPCloseToIncomingSP - Return true if the frame pointer is close to
    142   /// the incoming stack pointer, false if it is close to the post-prologue
    143   /// stack pointer.
    144   virtual bool isFPCloseToIncomingSP() const { return true; }
    145 
    146   /// assignCalleeSavedSpillSlots - Allows target to override spill slot
    147   /// assignment logic.  If implemented, assignCalleeSavedSpillSlots() should
    148   /// assign frame slots to all CSI entries and return true.  If this method
    149   /// returns false, spill slots will be assigned using generic implementation.
    150   /// assignCalleeSavedSpillSlots() may add, delete or rearrange elements of
    151   /// CSI.
    152   virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF,
    153                                            const TargetRegisterInfo *TRI,
    154                                            std::vector<CalleeSavedInfo> &CSI,
    155                                            unsigned &MinCSFrameIndex,
    156                                            unsigned &MaxCSFrameIndex) const {
    157     return assignCalleeSavedSpillSlots(MF, TRI, CSI);
    158   }
    159 
    160   virtual bool
    161   assignCalleeSavedSpillSlots(MachineFunction &MF,
    162                               const TargetRegisterInfo *TRI,
    163                               std::vector<CalleeSavedInfo> &CSI) const {
    164     return false;
    165   }
    166 
    167   /// getCalleeSavedSpillSlots - This method returns a pointer to an array of
    168   /// pairs, that contains an entry for each callee saved register that must be
    169   /// spilled to a particular stack location if it is spilled.
    170   ///
    171   /// Each entry in this array contains a <register,offset> pair, indicating the
    172   /// fixed offset from the incoming stack pointer that each register should be
    173   /// spilled at. If a register is not listed here, the code generator is
    174   /// allowed to spill it anywhere it chooses.
    175   ///
    176   virtual const SpillSlot *
    177   getCalleeSavedSpillSlots(unsigned &NumEntries) const {
    178     NumEntries = 0;
    179     return nullptr;
    180   }
    181 
    182   /// targetHandlesStackFrameRounding - Returns true if the target is
    183   /// responsible for rounding up the stack frame (probably at emitPrologue
    184   /// time).
    185   virtual bool targetHandlesStackFrameRounding() const {
    186     return false;
    187   }
    188 
    189   /// Returns true if the target will correctly handle shrink wrapping.
    190   virtual bool enableShrinkWrapping(const MachineFunction &MF) const {
    191     return false;
    192   }
    193 
    194   /// Returns true if the stack slot holes in the fixed and callee-save stack
    195   /// area should be used when allocating other stack locations to reduce stack
    196   /// size.
    197   virtual bool enableStackSlotScavenging(const MachineFunction &MF) const {
    198     return false;
    199   }
    200 
    201   /// Returns true if the target can safely skip saving callee-saved registers
    202   /// for noreturn nounwind functions.
    203   virtual bool enableCalleeSaveSkip(const MachineFunction &MF) const;
    204 
    205   /// emitProlog/emitEpilog - These methods insert prolog and epilog code into
    206   /// the function.
    207   virtual void emitPrologue(MachineFunction &MF,
    208                             MachineBasicBlock &MBB) const = 0;
    209   virtual void emitEpilogue(MachineFunction &MF,
    210                             MachineBasicBlock &MBB) const = 0;
    211 
    212   /// With basic block sections, emit callee saved frame moves for basic blocks
    213   /// that are in a different section.
    214   virtual void
    215   emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
    216                             MachineBasicBlock::iterator MBBI) const {}
    217 
    218   virtual void emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
    219                                          MachineBasicBlock::iterator MBBI,
    220                                          const DebugLoc &DL,
    221                                          bool IsPrologue) const {}
    222 
    223   /// Replace a StackProbe stub (if any) with the actual probe code inline
    224   virtual void inlineStackProbe(MachineFunction &MF,
    225                                 MachineBasicBlock &PrologueMBB) const {}
    226 
    227   /// Adjust the prologue to have the function use segmented stacks. This works
    228   /// by adding a check even before the "normal" function prologue.
    229   virtual void adjustForSegmentedStacks(MachineFunction &MF,
    230                                         MachineBasicBlock &PrologueMBB) const {}
    231 
    232   /// Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in
    233   /// the assembly prologue to explicitly handle the stack.
    234   virtual void adjustForHiPEPrologue(MachineFunction &MF,
    235                                      MachineBasicBlock &PrologueMBB) const {}
    236 
    237   /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
    238   /// saved registers and returns true if it isn't possible / profitable to do
    239   /// so by issuing a series of store instructions via
    240   /// storeRegToStackSlot(). Returns false otherwise.
    241   virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
    242                                          MachineBasicBlock::iterator MI,
    243                                          ArrayRef<CalleeSavedInfo> CSI,
    244                                          const TargetRegisterInfo *TRI) const {
    245     return false;
    246   }
    247 
    248   /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
    249   /// saved registers and returns true if it isn't possible / profitable to do
    250   /// so by issuing a series of load instructions via loadRegToStackSlot().
    251   /// If it returns true, and any of the registers in CSI is not restored,
    252   /// it sets the corresponding Restored flag in CSI to false.
    253   /// Returns false otherwise.
    254   virtual bool
    255   restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
    256                               MachineBasicBlock::iterator MI,
    257                               MutableArrayRef<CalleeSavedInfo> CSI,
    258                               const TargetRegisterInfo *TRI) const {
    259     return false;
    260   }
    261 
    262   /// Return true if the target wants to keep the frame pointer regardless of
    263   /// the function attribute "frame-pointer".
    264   virtual bool keepFramePointer(const MachineFunction &MF) const {
    265     return false;
    266   }
    267 
    268   /// hasFP - Return true if the specified function should have a dedicated
    269   /// frame pointer register. For most targets this is true only if the function
    270   /// has variable sized allocas or if frame pointer elimination is disabled.
    271   virtual bool hasFP(const MachineFunction &MF) const = 0;
    272 
    273   /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
    274   /// not required, we reserve argument space for call sites in the function
    275   /// immediately on entry to the current function. This eliminates the need for
    276   /// add/sub sp brackets around call sites. Returns true if the call frame is
    277   /// included as part of the stack frame.
    278   virtual bool hasReservedCallFrame(const MachineFunction &MF) const {
    279     return !hasFP(MF);
    280   }
    281 
    282   /// canSimplifyCallFramePseudos - When possible, it's best to simplify the
    283   /// call frame pseudo ops before doing frame index elimination. This is
    284   /// possible only when frame index references between the pseudos won't
    285   /// need adjusting for the call frame adjustments. Normally, that's true
    286   /// if the function has a reserved call frame or a frame pointer. Some
    287   /// targets (Thumb2, for example) may have more complicated criteria,
    288   /// however, and can override this behavior.
    289   virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const {
    290     return hasReservedCallFrame(MF) || hasFP(MF);
    291   }
    292 
    293   // needsFrameIndexResolution - Do we need to perform FI resolution for
    294   // this function. Normally, this is required only when the function
    295   // has any stack objects. However, targets may want to override this.
    296   virtual bool needsFrameIndexResolution(const MachineFunction &MF) const;
    297 
    298   /// getFrameIndexReference - This method should return the base register
    299   /// and offset used to reference a frame index location. The offset is
    300   /// returned directly, and the base register is returned via FrameReg.
    301   virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI,
    302                                              Register &FrameReg) const;
    303 
    304   /// Same as \c getFrameIndexReference, except that the stack pointer (as
    305   /// opposed to the frame pointer) will be the preferred value for \p
    306   /// FrameReg. This is generally used for emitting statepoint or EH tables that
    307   /// use offsets from RSP.  If \p IgnoreSPUpdates is true, the returned
    308   /// offset is only guaranteed to be valid with respect to the value of SP at
    309   /// the end of the prologue.
    310   virtual StackOffset
    311   getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI,
    312                                  Register &FrameReg,
    313                                  bool IgnoreSPUpdates) const {
    314     // Always safe to dispatch to getFrameIndexReference.
    315     return getFrameIndexReference(MF, FI, FrameReg);
    316   }
    317 
    318   /// getNonLocalFrameIndexReference - This method returns the offset used to
    319   /// reference a frame index location. The offset can be from either FP/BP/SP
    320   /// based on which base register is returned by llvm.localaddress.
    321   virtual StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF,
    322                                                      int FI) const {
    323     // By default, dispatch to getFrameIndexReference. Interested targets can
    324     // override this.
    325     Register FrameReg;
    326     return getFrameIndexReference(MF, FI, FrameReg);
    327   }
    328 
    329   /// Returns the callee-saved registers as computed by determineCalleeSaves
    330   /// in the BitVector \p SavedRegs.
    331   virtual void getCalleeSaves(const MachineFunction &MF,
    332                                   BitVector &SavedRegs) const;
    333 
    334   /// This method determines which of the registers reported by
    335   /// TargetRegisterInfo::getCalleeSavedRegs() should actually get saved.
    336   /// The default implementation checks populates the \p SavedRegs bitset with
    337   /// all registers which are modified in the function, targets may override
    338   /// this function to save additional registers.
    339   /// This method also sets up the register scavenger ensuring there is a free
    340   /// register or a frameindex available.
    341   /// This method should not be called by any passes outside of PEI, because
    342   /// it may change state passed in by \p MF and \p RS. The preferred
    343   /// interface outside PEI is getCalleeSaves.
    344   virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
    345                                     RegScavenger *RS = nullptr) const;
    346 
    347   /// processFunctionBeforeFrameFinalized - This method is called immediately
    348   /// before the specified function's frame layout (MF.getFrameInfo()) is
    349   /// finalized.  Once the frame is finalized, MO_FrameIndex operands are
    350   /// replaced with direct constants.  This method is optional.
    351   ///
    352   virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF,
    353                                              RegScavenger *RS = nullptr) const {
    354   }
    355 
    356   /// processFunctionBeforeFrameIndicesReplaced - This method is called
    357   /// immediately before MO_FrameIndex operands are eliminated, but after the
    358   /// frame is finalized. This method is optional.
    359   virtual void
    360   processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF,
    361                                             RegScavenger *RS = nullptr) const {}
    362 
    363   virtual unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const {
    364     report_fatal_error("WinEH not implemented for this target");
    365   }
    366 
    367   /// This method is called during prolog/epilog code insertion to eliminate
    368   /// call frame setup and destroy pseudo instructions (but only if the Target
    369   /// is using them).  It is responsible for eliminating these instructions,
    370   /// replacing them with concrete instructions.  This method need only be
    371   /// implemented if using call frame setup/destroy pseudo instructions.
    372   /// Returns an iterator pointing to the instruction after the replaced one.
    373   virtual MachineBasicBlock::iterator
    374   eliminateCallFramePseudoInstr(MachineFunction &MF,
    375                                 MachineBasicBlock &MBB,
    376                                 MachineBasicBlock::iterator MI) const {
    377     llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
    378                      "target!");
    379   }
    380 
    381 
    382   /// Order the symbols in the local stack frame.
    383   /// The list of objects that we want to order is in \p objectsToAllocate as
    384   /// indices into the MachineFrameInfo. The array can be reordered in any way
    385   /// upon return. The contents of the array, however, may not be modified (i.e.
    386   /// only their order may be changed).
    387   /// By default, just maintain the original order.
    388   virtual void
    389   orderFrameObjects(const MachineFunction &MF,
    390                     SmallVectorImpl<int> &objectsToAllocate) const {
    391   }
    392 
    393   /// Check whether or not the given \p MBB can be used as a prologue
    394   /// for the target.
    395   /// The prologue will be inserted first in this basic block.
    396   /// This method is used by the shrink-wrapping pass to decide if
    397   /// \p MBB will be correctly handled by the target.
    398   /// As soon as the target enable shrink-wrapping without overriding
    399   /// this method, we assume that each basic block is a valid
    400   /// prologue.
    401   virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const {
    402     return true;
    403   }
    404 
    405   /// Check whether or not the given \p MBB can be used as a epilogue
    406   /// for the target.
    407   /// The epilogue will be inserted before the first terminator of that block.
    408   /// This method is used by the shrink-wrapping pass to decide if
    409   /// \p MBB will be correctly handled by the target.
    410   /// As soon as the target enable shrink-wrapping without overriding
    411   /// this method, we assume that each basic block is a valid
    412   /// epilogue.
    413   virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const {
    414     return true;
    415   }
    416 
    417   /// Returns the StackID that scalable vectors should be associated with.
    418   virtual TargetStackID::Value getStackIDForScalableVectors() const {
    419     return TargetStackID::Default;
    420   }
    421 
    422   virtual bool isSupportedStackID(TargetStackID::Value ID) const {
    423     switch (ID) {
    424     default:
    425       return false;
    426     case TargetStackID::Default:
    427     case TargetStackID::NoAlloc:
    428       return true;
    429     }
    430   }
    431 
    432   /// Check if given function is safe for not having callee saved registers.
    433   /// This is used when interprocedural register allocation is enabled.
    434   static bool isSafeForNoCSROpt(const Function &F);
    435 
    436   /// Check if the no-CSR optimisation is profitable for the given function.
    437   virtual bool isProfitableForNoCSROpt(const Function &F) const {
    438     return true;
    439   }
    440 
    441   /// Return initial CFA offset value i.e. the one valid at the beginning of the
    442   /// function (before any stack operations).
    443   virtual int getInitialCFAOffset(const MachineFunction &MF) const;
    444 
    445   /// Return initial CFA register value i.e. the one valid at the beginning of
    446   /// the function (before any stack operations).
    447   virtual Register getInitialCFARegister(const MachineFunction &MF) const;
    448 
    449   /// Return the frame base information to be encoded in the DWARF subprogram
    450   /// debug info.
    451   virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const;
    452 };
    453 
    454 } // End llvm namespace
    455 
    456 #endif
    457