1 //===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The file defines the MachineFrameInfo class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
15 #define LLVM_CODEGEN_MACHINEFRAMEINFO_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/DataTypes.h"
25 class TargetRegisterClass;
27 class MachineFunction;
28 class MachineBasicBlock;
29 class TargetFrameLowering;
35 /// The CalleeSavedInfo class tracks the information need to locate where a
36 /// callee saved register is in the current frame.
37 class CalleeSavedInfo {
42 explicit CalleeSavedInfo(unsigned R, int FI = 0)
43 : Reg(R), FrameIdx(FI) {}
46 unsigned getReg() const { return Reg; }
47 int getFrameIdx() const { return FrameIdx; }
48 void setFrameIdx(int FI) { FrameIdx = FI; }
51 /// The MachineFrameInfo class represents an abstract stack frame until
52 /// prolog/epilog code is inserted. This class is key to allowing stack frame
53 /// representation optimizations, such as frame pointer elimination. It also
54 /// allows more mundane (but still important) optimizations, such as reordering
55 /// of abstract objects on the stack frame.
57 /// To support this, the class assigns unique integer identifiers to stack
58 /// objects requested clients. These identifiers are negative integers for
59 /// fixed stack objects (such as arguments passed on the stack) or nonnegative
60 /// for objects that may be reordered. Instructions which refer to stack
61 /// objects use a special MO_FrameIndex operand to represent these frame
64 /// Because this class keeps track of all references to the stack frame, it
65 /// knows when a variable sized object is allocated on the stack. This is the
66 /// sole condition which prevents frame pointer elimination, which is an
67 /// important optimization on register-poor architectures. Because original
68 /// variable sized alloca's in the source program are the only source of
69 /// variable sized stack objects, it is safe to decide whether there will be
70 /// any variable sized objects before all stack objects are known (for
71 /// example, register allocator spill code never needs variable sized
74 /// When prolog/epilog code emission is performed, the final stack frame is
75 /// built and the machine instructions are modified to refer to the actual
76 /// stack offsets of the object, eliminating all MO_FrameIndex operands from
79 /// @brief Abstract Stack Frame Information
80 class MachineFrameInfo {
82 // Represent a single object allocated on the stack.
84 // The offset of this object from the stack pointer on entry to
85 // the function. This field has no meaning for a variable sized element.
88 // The size of this object on the stack. 0 means a variable sized object,
89 // ~0ULL means a dead object.
92 // The required alignment of this stack slot.
95 // If true, the value of the stack object is set before
96 // entering the function and is not modified inside the function. By
97 // default, fixed objects are immutable unless marked otherwise.
100 // If true the stack object is used as spill slot. It
101 // cannot alias any other memory objects.
104 /// If this stack object is originated from an Alloca instruction
105 /// this value saves the original IR allocation. Can be NULL.
106 const AllocaInst *Alloca;
108 // If true, the object was mapped into the local frame
109 // block and doesn't need additional handling for allocation beyond that.
112 // If true, an LLVM IR value might point to this object.
113 // Normally, spill slots and fixed-offset objects don't alias IR-accessible
114 // objects, but there are exceptions (on PowerPC, for example, some byval
115 // arguments have ABI-prescribed offsets).
118 StackObject(uint64_t Sz, unsigned Al, int64_t SP, bool IM,
119 bool isSS, const AllocaInst *Val, bool A)
120 : SPOffset(SP), Size(Sz), Alignment(Al), isImmutable(IM),
121 isSpillSlot(isSS), Alloca(Val), PreAllocated(false), isAliased(A) {}
124 /// The alignment of the stack.
125 unsigned StackAlignment;
127 /// Can the stack be realigned.
128 bool StackRealignable;
130 /// The list of stack objects allocated.
131 std::vector<StackObject> Objects;
133 /// This contains the number of fixed objects contained on
134 /// the stack. Because fixed objects are stored at a negative index in the
135 /// Objects list, this is also the index to the 0th object in the list.
136 unsigned NumFixedObjects;
138 /// This boolean keeps track of whether any variable
139 /// sized objects have been allocated yet.
140 bool HasVarSizedObjects;
142 /// This boolean keeps track of whether there is a call
143 /// to builtin \@llvm.frameaddress.
144 bool FrameAddressTaken;
146 /// This boolean keeps track of whether there is a call
147 /// to builtin \@llvm.returnaddress.
148 bool ReturnAddressTaken;
150 /// This boolean keeps track of whether there is a call
151 /// to builtin \@llvm.experimental.stackmap.
154 /// This boolean keeps track of whether there is a call
155 /// to builtin \@llvm.experimental.patchpoint.
158 /// The prolog/epilog code inserter calculates the final stack
159 /// offsets for all of the fixed size objects, updating the Objects list
160 /// above. It then updates StackSize to contain the number of bytes that need
161 /// to be allocated on entry to the function.
164 /// The amount that a frame offset needs to be adjusted to
165 /// have the actual offset from the stack/frame pointer. The exact usage of
166 /// this is target-dependent, but it is typically used to adjust between
167 /// SP-relative and FP-relative offsets. E.G., if objects are accessed via
168 /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
169 /// to the distance between the initial SP and the value in FP. For many
170 /// targets, this value is only used when generating debug info (via
171 /// TargetRegisterInfo::getFrameIndexReference); when generating code, the
172 /// corresponding adjustments are performed directly.
173 int OffsetAdjustment;
175 /// The prolog/epilog code inserter may process objects that require greater
176 /// alignment than the default alignment the target provides.
177 /// To handle this, MaxAlignment is set to the maximum alignment
178 /// needed by the objects on the current frame. If this is greater than the
179 /// native alignment maintained by the compiler, dynamic alignment code will
182 unsigned MaxAlignment;
184 /// Set to true if this function adjusts the stack -- e.g.,
185 /// when calling another function. This is only valid during and after
186 /// prolog/epilog code insertion.
189 /// Set to true if this function has any function calls.
192 /// The frame index for the stack protector.
193 int StackProtectorIdx;
195 /// The frame index for the function context. Used for SjLj exceptions.
196 int FunctionContextIdx;
198 /// This contains the size of the largest call frame if the target uses frame
199 /// setup/destroy pseudo instructions (as defined in the TargetFrameInfo
200 /// class). This information is important for frame pointer elimination.
201 /// If is only valid during and after prolog/epilog code insertion.
202 unsigned MaxCallFrameSize;
204 /// The prolog/epilog code inserter fills in this vector with each
205 /// callee saved register saved in the frame. Beyond its use by the prolog/
206 /// epilog code inserter, this data used for debug info and exception
208 std::vector<CalleeSavedInfo> CSInfo;
210 /// Has CSInfo been set yet?
213 /// References to frame indices which are mapped
214 /// into the local frame allocation block. <FrameIdx, LocalOffset>
215 SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
217 /// Size of the pre-allocated local frame block.
218 int64_t LocalFrameSize;
220 /// Required alignment of the local object blob, which is the strictest
221 /// alignment of any object in it.
222 unsigned LocalFrameMaxAlign;
224 /// Whether the local object blob needs to be allocated together. If not,
225 /// PEI should ignore the isPreAllocated flags on the stack objects and
226 /// just allocate them normally.
227 bool UseLocalStackAllocationBlock;
229 /// Whether the "realign-stack" option is on.
232 /// True if the function dynamically adjusts the stack pointer through some
233 /// opaque mechanism like inline assembly or Win32 EH.
234 bool HasOpaqueSPAdjustment;
236 /// True if the function contains a call to the llvm.vastart intrinsic.
239 /// True if this is a varargs function that contains a musttail call.
240 bool HasMustTailInVarArgFunc;
242 /// True if this function contains a tail call. If so immutable objects like
243 /// function arguments are no longer so. A tail call *can* override fixed
244 /// stack objects like arguments so we can't treat them as immutable.
247 /// Not null, if shrink-wrapping found a better place for the prologue.
248 MachineBasicBlock *Save;
249 /// Not null, if shrink-wrapping found a better place for the epilogue.
250 MachineBasicBlock *Restore;
253 explicit MachineFrameInfo(unsigned StackAlign, bool isStackRealign,
255 : StackAlignment(StackAlign), StackRealignable(isStackRealign),
256 RealignOption(RealignOpt) {
257 StackSize = NumFixedObjects = OffsetAdjustment = MaxAlignment = 0;
258 HasVarSizedObjects = false;
259 FrameAddressTaken = false;
260 ReturnAddressTaken = false;
262 HasPatchPoint = false;
263 AdjustsStack = false;
265 StackProtectorIdx = -1;
266 FunctionContextIdx = -1;
267 MaxCallFrameSize = 0;
270 LocalFrameMaxAlign = 0;
271 UseLocalStackAllocationBlock = false;
272 HasOpaqueSPAdjustment = false;
274 HasMustTailInVarArgFunc = false;
280 /// Return true if there are any stack objects in this function.
281 bool hasStackObjects() const { return !Objects.empty(); }
283 /// This method may be called any time after instruction
284 /// selection is complete to determine if the stack frame for this function
285 /// contains any variable sized objects.
286 bool hasVarSizedObjects() const { return HasVarSizedObjects; }
288 /// Return the index for the stack protector object.
289 int getStackProtectorIndex() const { return StackProtectorIdx; }
290 void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
291 bool hasStackProtectorIndex() const { return StackProtectorIdx != -1; }
293 /// Return the index for the function context object.
294 /// This object is used for SjLj exceptions.
295 int getFunctionContextIndex() const { return FunctionContextIdx; }
296 void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
298 /// This method may be called any time after instruction
299 /// selection is complete to determine if there is a call to
300 /// \@llvm.frameaddress in this function.
301 bool isFrameAddressTaken() const { return FrameAddressTaken; }
302 void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
304 /// This method may be called any time after
305 /// instruction selection is complete to determine if there is a call to
306 /// \@llvm.returnaddress in this function.
307 bool isReturnAddressTaken() const { return ReturnAddressTaken; }
308 void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
310 /// This method may be called any time after instruction
311 /// selection is complete to determine if there is a call to builtin
312 /// \@llvm.experimental.stackmap.
313 bool hasStackMap() const { return HasStackMap; }
314 void setHasStackMap(bool s = true) { HasStackMap = s; }
316 /// This method may be called any time after instruction
317 /// selection is complete to determine if there is a call to builtin
318 /// \@llvm.experimental.patchpoint.
319 bool hasPatchPoint() const { return HasPatchPoint; }
320 void setHasPatchPoint(bool s = true) { HasPatchPoint = s; }
322 /// Return the minimum frame object index.
323 int getObjectIndexBegin() const { return -NumFixedObjects; }
325 /// Return one past the maximum frame object index.
326 int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
328 /// Return the number of fixed objects.
329 unsigned getNumFixedObjects() const { return NumFixedObjects; }
331 /// Return the number of objects.
332 unsigned getNumObjects() const { return Objects.size(); }
334 /// Map a frame index into the local object block
335 void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
336 LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
337 Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
340 /// Get the local offset mapping for a for an object.
341 std::pair<int, int64_t> getLocalFrameObjectMap(int i) const {
342 assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
343 "Invalid local object reference!");
344 return LocalFrameObjects[i];
347 /// Return the number of objects allocated into the local object block.
348 int64_t getLocalFrameObjectCount() const { return LocalFrameObjects.size(); }
350 /// Set the size of the local object blob.
351 void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
353 /// Get the size of the local object blob.
354 int64_t getLocalFrameSize() const { return LocalFrameSize; }
356 /// Required alignment of the local object blob,
357 /// which is the strictest alignment of any object in it.
358 void setLocalFrameMaxAlign(unsigned Align) { LocalFrameMaxAlign = Align; }
360 /// Return the required alignment of the local object blob.
361 unsigned getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
363 /// Get whether the local allocation blob should be allocated together or
364 /// let PEI allocate the locals in it directly.
365 bool getUseLocalStackAllocationBlock() const {
366 return UseLocalStackAllocationBlock;
369 /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
370 /// should be allocated together or let PEI allocate the locals in it
372 void setUseLocalStackAllocationBlock(bool v) {
373 UseLocalStackAllocationBlock = v;
376 /// Return true if the object was pre-allocated into the local block.
377 bool isObjectPreAllocated(int ObjectIdx) const {
378 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
379 "Invalid Object Idx!");
380 return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
383 /// Return the size of the specified object.
384 int64_t getObjectSize(int ObjectIdx) const {
385 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
386 "Invalid Object Idx!");
387 return Objects[ObjectIdx+NumFixedObjects].Size;
390 /// Change the size of the specified stack object.
391 void setObjectSize(int ObjectIdx, int64_t Size) {
392 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
393 "Invalid Object Idx!");
394 Objects[ObjectIdx+NumFixedObjects].Size = Size;
397 /// Return the alignment of the specified stack object.
398 unsigned getObjectAlignment(int ObjectIdx) const {
399 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
400 "Invalid Object Idx!");
401 return Objects[ObjectIdx+NumFixedObjects].Alignment;
404 /// setObjectAlignment - Change the alignment of the specified stack object.
405 void setObjectAlignment(int ObjectIdx, unsigned Align) {
406 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
407 "Invalid Object Idx!");
408 Objects[ObjectIdx+NumFixedObjects].Alignment = Align;
409 ensureMaxAlignment(Align);
412 /// Return the underlying Alloca of the specified
413 /// stack object if it exists. Returns 0 if none exists.
414 const AllocaInst* getObjectAllocation(int ObjectIdx) const {
415 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
416 "Invalid Object Idx!");
417 return Objects[ObjectIdx+NumFixedObjects].Alloca;
420 /// Return the assigned stack offset of the specified object
421 /// from the incoming stack pointer.
422 int64_t getObjectOffset(int ObjectIdx) const {
423 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
424 "Invalid Object Idx!");
425 assert(!isDeadObjectIndex(ObjectIdx) &&
426 "Getting frame offset for a dead object?");
427 return Objects[ObjectIdx+NumFixedObjects].SPOffset;
430 /// Set the stack frame offset of the specified object. The
431 /// offset is relative to the stack pointer on entry to the function.
432 void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
433 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
434 "Invalid Object Idx!");
435 assert(!isDeadObjectIndex(ObjectIdx) &&
436 "Setting frame offset for a dead object?");
437 Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
440 /// Return the number of bytes that must be allocated to hold
441 /// all of the fixed size frame objects. This is only valid after
442 /// Prolog/Epilog code insertion has finalized the stack frame layout.
443 uint64_t getStackSize() const { return StackSize; }
445 /// Set the size of the stack.
446 void setStackSize(uint64_t Size) { StackSize = Size; }
448 /// Estimate and return the size of the stack frame.
449 unsigned estimateStackSize(const MachineFunction &MF) const;
451 /// Return the correction for frame offsets.
452 int getOffsetAdjustment() const { return OffsetAdjustment; }
454 /// Set the correction for frame offsets.
455 void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
457 /// Return the alignment in bytes that this function must be aligned to,
458 /// which is greater than the default stack alignment provided by the target.
459 unsigned getMaxAlignment() const { return MaxAlignment; }
461 /// Make sure the function is at least Align bytes aligned.
462 void ensureMaxAlignment(unsigned Align);
464 /// Return true if this function adjusts the stack -- e.g.,
465 /// when calling another function. This is only valid during and after
466 /// prolog/epilog code insertion.
467 bool adjustsStack() const { return AdjustsStack; }
468 void setAdjustsStack(bool V) { AdjustsStack = V; }
470 /// Return true if the current function has any function calls.
471 bool hasCalls() const { return HasCalls; }
472 void setHasCalls(bool V) { HasCalls = V; }
474 /// Returns true if the function contains opaque dynamic stack adjustments.
475 bool hasOpaqueSPAdjustment() const { return HasOpaqueSPAdjustment; }
476 void setHasOpaqueSPAdjustment(bool B) { HasOpaqueSPAdjustment = B; }
478 /// Returns true if the function calls the llvm.va_start intrinsic.
479 bool hasVAStart() const { return HasVAStart; }
480 void setHasVAStart(bool B) { HasVAStart = B; }
482 /// Returns true if the function is variadic and contains a musttail call.
483 bool hasMustTailInVarArgFunc() const { return HasMustTailInVarArgFunc; }
484 void setHasMustTailInVarArgFunc(bool B) { HasMustTailInVarArgFunc = B; }
486 /// Returns true if the function contains a tail call.
487 bool hasTailCall() const { return HasTailCall; }
488 void setHasTailCall() { HasTailCall = true; }
490 /// Return the maximum size of a call frame that must be
491 /// allocated for an outgoing function call. This is only available if
492 /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
493 /// then only during or after prolog/epilog code insertion.
495 unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
496 void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
498 /// Create a new object at a fixed location on the stack.
499 /// All fixed objects should be created before other objects are created for
500 /// efficiency. By default, fixed objects are not pointed to by LLVM IR
501 /// values. This returns an index with a negative value.
502 int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable,
503 bool isAliased = false);
505 /// Create a spill slot at a fixed location on the stack.
506 /// Returns an index with a negative value.
507 int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset);
509 /// Returns true if the specified index corresponds to a fixed stack object.
510 bool isFixedObjectIndex(int ObjectIdx) const {
511 return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
514 /// Returns true if the specified index corresponds
515 /// to an object that might be pointed to by an LLVM IR value.
516 bool isAliasedObjectIndex(int ObjectIdx) const {
517 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
518 "Invalid Object Idx!");
519 return Objects[ObjectIdx+NumFixedObjects].isAliased;
522 /// isImmutableObjectIndex - Returns true if the specified index corresponds
523 /// to an immutable object.
524 bool isImmutableObjectIndex(int ObjectIdx) const {
525 // Tail calling functions can clobber their function arguments.
528 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
529 "Invalid Object Idx!");
530 return Objects[ObjectIdx+NumFixedObjects].isImmutable;
533 /// Returns true if the specified index corresponds to a spill slot.
534 bool isSpillSlotObjectIndex(int ObjectIdx) const {
535 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
536 "Invalid Object Idx!");
537 return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
540 /// Returns true if the specified index corresponds to a dead object.
541 bool isDeadObjectIndex(int ObjectIdx) const {
542 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
543 "Invalid Object Idx!");
544 return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
547 /// Returns true if the specified index corresponds to a variable sized
549 bool isVariableSizedObjectIndex(int ObjectIdx) const {
550 assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
551 "Invalid Object Idx!");
552 return Objects[ObjectIdx + NumFixedObjects].Size == 0;
555 /// Create a new statically sized stack object, returning
556 /// a nonnegative identifier to represent it.
557 int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS,
558 const AllocaInst *Alloca = nullptr);
560 /// Create a new statically sized stack object that represents a spill slot,
561 /// returning a nonnegative identifier to represent it.
562 int CreateSpillStackObject(uint64_t Size, unsigned Alignment);
564 /// Remove or mark dead a statically sized stack object.
565 void RemoveStackObject(int ObjectIdx) {
567 Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
570 /// Notify the MachineFrameInfo object that a variable sized object has been
571 /// created. This must be created whenever a variable sized object is
572 /// created, whether or not the index returned is actually used.
573 int CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca);
575 /// Returns a reference to call saved info vector for the current function.
576 const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
580 /// Used by prolog/epilog inserter to set the function's callee saved
582 void setCalleeSavedInfo(const std::vector<CalleeSavedInfo> &CSI) {
586 /// Has the callee saved info been calculated yet?
587 bool isCalleeSavedInfoValid() const { return CSIValid; }
589 void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
591 MachineBasicBlock *getSavePoint() const { return Save; }
592 void setSavePoint(MachineBasicBlock *NewSave) { Save = NewSave; }
593 MachineBasicBlock *getRestorePoint() const { return Restore; }
594 void setRestorePoint(MachineBasicBlock *NewRestore) { Restore = NewRestore; }
596 /// Return a set of physical registers that are pristine.
598 /// Pristine registers hold a value that is useless to the current function,
599 /// but that must be preserved - they are callee saved registers that are not
602 /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
603 /// method always returns an empty set.
604 BitVector getPristineRegs(const MachineFunction &MF) const;
606 /// Used by the MachineFunction printer to print information about
607 /// stack objects. Implemented in MachineFunction.cpp.
608 void print(const MachineFunction &MF, raw_ostream &OS) const;
610 /// dump - Print the function to stderr.
611 void dump(const MachineFunction &MF) const;
614 } // End llvm namespace