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