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