1 //===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- 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 // The file defines the MachineFrameInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
14 #define LLVM_CODEGEN_MACHINEFRAMEINFO_H
15 
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/Register.h"
18 #include "llvm/Support/Alignment.h"
19 #include "llvm/Support/DataTypes.h"
20 #include <cassert>
21 #include <vector>
22 
23 namespace llvm {
24 class raw_ostream;
25 class MachineFunction;
26 class MachineBasicBlock;
27 class BitVector;
28 class AllocaInst;
29 
30 /// The CalleeSavedInfo class tracks the information need to locate where a
31 /// callee saved register is in the current frame.
32 /// Callee saved reg can also be saved to a different register rather than
33 /// on the stack by setting DstReg instead of FrameIdx.
34 class CalleeSavedInfo {
35   Register Reg;
36   union {
37     int FrameIdx;
38     unsigned DstReg;
39   };
40   /// Flag indicating whether the register is actually restored in the epilog.
41   /// In most cases, if a register is saved, it is also restored. There are
42   /// some situations, though, when this is not the case. For example, the
43   /// LR register on ARM is usually saved, but on exit from the function its
44   /// saved value may be loaded directly into PC. Since liveness tracking of
45   /// physical registers treats callee-saved registers are live outside of
46   /// the function, LR would be treated as live-on-exit, even though in these
47   /// scenarios it is not. This flag is added to indicate that the saved
48   /// register described by this object is not restored in the epilog.
49   /// The long-term solution is to model the liveness of callee-saved registers
50   /// by implicit uses on the return instructions, however, the required
51   /// changes in the ARM backend would be quite extensive.
52   bool Restored;
53   /// Flag indicating whether the register is spilled to stack or another
54   /// register.
55   bool SpilledToReg;
56 
57 public:
58   explicit CalleeSavedInfo(unsigned R, int FI = 0)
Reg(R)59   : Reg(R), FrameIdx(FI), Restored(true), SpilledToReg(false) {}
60 
61   // Accessors.
getReg()62   Register getReg()                        const { return Reg; }
getFrameIdx()63   int getFrameIdx()                        const { return FrameIdx; }
getDstReg()64   unsigned getDstReg()                     const { return DstReg; }
setFrameIdx(int FI)65   void setFrameIdx(int FI) {
66     FrameIdx = FI;
67     SpilledToReg = false;
68   }
setDstReg(Register SpillReg)69   void setDstReg(Register SpillReg) {
70     DstReg = SpillReg;
71     SpilledToReg = true;
72   }
isRestored()73   bool isRestored()                        const { return Restored; }
setRestored(bool R)74   void setRestored(bool R)                       { Restored = R; }
isSpilledToReg()75   bool isSpilledToReg()                    const { return SpilledToReg; }
76 };
77 
78 /// The MachineFrameInfo class represents an abstract stack frame until
79 /// prolog/epilog code is inserted.  This class is key to allowing stack frame
80 /// representation optimizations, such as frame pointer elimination.  It also
81 /// allows more mundane (but still important) optimizations, such as reordering
82 /// of abstract objects on the stack frame.
83 ///
84 /// To support this, the class assigns unique integer identifiers to stack
85 /// objects requested clients.  These identifiers are negative integers for
86 /// fixed stack objects (such as arguments passed on the stack) or nonnegative
87 /// for objects that may be reordered.  Instructions which refer to stack
88 /// objects use a special MO_FrameIndex operand to represent these frame
89 /// indexes.
90 ///
91 /// Because this class keeps track of all references to the stack frame, it
92 /// knows when a variable sized object is allocated on the stack.  This is the
93 /// sole condition which prevents frame pointer elimination, which is an
94 /// important optimization on register-poor architectures.  Because original
95 /// variable sized alloca's in the source program are the only source of
96 /// variable sized stack objects, it is safe to decide whether there will be
97 /// any variable sized objects before all stack objects are known (for
98 /// example, register allocator spill code never needs variable sized
99 /// objects).
100 ///
101 /// When prolog/epilog code emission is performed, the final stack frame is
102 /// built and the machine instructions are modified to refer to the actual
103 /// stack offsets of the object, eliminating all MO_FrameIndex operands from
104 /// the program.
105 ///
106 /// Abstract Stack Frame Information
107 class MachineFrameInfo {
108 public:
109   /// Stack Smashing Protection (SSP) rules require that vulnerable stack
110   /// allocations are located close the stack protector.
111   enum SSPLayoutKind {
112     SSPLK_None,       ///< Did not trigger a stack protector.  No effect on data
113                       ///< layout.
114     SSPLK_LargeArray, ///< Array or nested array >= SSP-buffer-size.  Closest
115                       ///< to the stack protector.
116     SSPLK_SmallArray, ///< Array or nested array < SSP-buffer-size. 2nd closest
117                       ///< to the stack protector.
118     SSPLK_AddrOf      ///< The address of this allocation is exposed and
119                       ///< triggered protection.  3rd closest to the protector.
120   };
121 
122 private:
123   // Represent a single object allocated on the stack.
124   struct StackObject {
125     // The offset of this object from the stack pointer on entry to
126     // the function.  This field has no meaning for a variable sized element.
127     int64_t SPOffset;
128 
129     // The size of this object on the stack. 0 means a variable sized object,
130     // ~0ULL means a dead object.
131     uint64_t Size;
132 
133     // The required alignment of this stack slot.
134     Align Alignment;
135 
136     // If true, the value of the stack object is set before
137     // entering the function and is not modified inside the function. By
138     // default, fixed objects are immutable unless marked otherwise.
139     bool isImmutable;
140 
141     // If true the stack object is used as spill slot. It
142     // cannot alias any other memory objects.
143     bool isSpillSlot;
144 
145     /// If true, this stack slot is used to spill a value (could be deopt
146     /// and/or GC related) over a statepoint. We know that the address of the
147     /// slot can't alias any LLVM IR value.  This is very similar to a Spill
148     /// Slot, but is created by statepoint lowering is SelectionDAG, not the
149     /// register allocator.
150     bool isStatepointSpillSlot = false;
151 
152     /// Identifier for stack memory type analagous to address space. If this is
153     /// non-0, the meaning is target defined. Offsets cannot be directly
154     /// compared between objects with different stack IDs. The object may not
155     /// necessarily reside in the same contiguous memory block as other stack
156     /// objects. Objects with differing stack IDs should not be merged or
157     /// replaced substituted for each other.
158     //
159     /// It is assumed a target uses consecutive, increasing stack IDs starting
160     /// from 1.
161     uint8_t StackID;
162 
163     /// If this stack object is originated from an Alloca instruction
164     /// this value saves the original IR allocation. Can be NULL.
165     const AllocaInst *Alloca;
166 
167     // If true, the object was mapped into the local frame
168     // block and doesn't need additional handling for allocation beyond that.
169     bool PreAllocated = false;
170 
171     // If true, an LLVM IR value might point to this object.
172     // Normally, spill slots and fixed-offset objects don't alias IR-accessible
173     // objects, but there are exceptions (on PowerPC, for example, some byval
174     // arguments have ABI-prescribed offsets).
175     bool isAliased;
176 
177     /// If true, the object has been zero-extended.
178     bool isZExt = false;
179 
180     /// If true, the object has been sign-extended.
181     bool isSExt = false;
182 
183     uint8_t SSPLayout;
184 
185     StackObject(uint64_t Size, Align Alignment, int64_t SPOffset,
186                 bool IsImmutable, bool IsSpillSlot, const AllocaInst *Alloca,
187                 bool IsAliased, uint8_t StackID = 0)
SPOffsetStackObject188         : SPOffset(SPOffset), Size(Size), Alignment(Alignment),
189           isImmutable(IsImmutable), isSpillSlot(IsSpillSlot), StackID(StackID),
190           Alloca(Alloca), isAliased(IsAliased), SSPLayout(SSPLK_None) {}
191   };
192 
193   /// The alignment of the stack.
194   Align StackAlignment;
195 
196   /// Can the stack be realigned. This can be false if the target does not
197   /// support stack realignment, or if the user asks us not to realign the
198   /// stack. In this situation, overaligned allocas are all treated as dynamic
199   /// allocations and the target must handle them as part of DYNAMIC_STACKALLOC
200   /// lowering. All non-alloca stack objects have their alignment clamped to the
201   /// base ABI stack alignment.
202   /// FIXME: There is room for improvement in this case, in terms of
203   /// grouping overaligned allocas into a "secondary stack frame" and
204   /// then only use a single alloca to allocate this frame and only a
205   /// single virtual register to access it. Currently, without such an
206   /// optimization, each such alloca gets its own dynamic realignment.
207   bool StackRealignable;
208 
209   /// Whether the function has the \c alignstack attribute.
210   bool ForcedRealign;
211 
212   /// The list of stack objects allocated.
213   std::vector<StackObject> Objects;
214 
215   /// This contains the number of fixed objects contained on
216   /// the stack.  Because fixed objects are stored at a negative index in the
217   /// Objects list, this is also the index to the 0th object in the list.
218   unsigned NumFixedObjects = 0;
219 
220   /// This boolean keeps track of whether any variable
221   /// sized objects have been allocated yet.
222   bool HasVarSizedObjects = false;
223 
224   /// This boolean keeps track of whether there is a call
225   /// to builtin \@llvm.frameaddress.
226   bool FrameAddressTaken = false;
227 
228   /// This boolean keeps track of whether there is a call
229   /// to builtin \@llvm.returnaddress.
230   bool ReturnAddressTaken = false;
231 
232   /// This boolean keeps track of whether there is a call
233   /// to builtin \@llvm.experimental.stackmap.
234   bool HasStackMap = false;
235 
236   /// This boolean keeps track of whether there is a call
237   /// to builtin \@llvm.experimental.patchpoint.
238   bool HasPatchPoint = false;
239 
240   /// The prolog/epilog code inserter calculates the final stack
241   /// offsets for all of the fixed size objects, updating the Objects list
242   /// above.  It then updates StackSize to contain the number of bytes that need
243   /// to be allocated on entry to the function.
244   uint64_t StackSize = 0;
245 
246   /// The amount that a frame offset needs to be adjusted to
247   /// have the actual offset from the stack/frame pointer.  The exact usage of
248   /// this is target-dependent, but it is typically used to adjust between
249   /// SP-relative and FP-relative offsets.  E.G., if objects are accessed via
250   /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
251   /// to the distance between the initial SP and the value in FP.  For many
252   /// targets, this value is only used when generating debug info (via
253   /// TargetRegisterInfo::getFrameIndexReference); when generating code, the
254   /// corresponding adjustments are performed directly.
255   int OffsetAdjustment = 0;
256 
257   /// The prolog/epilog code inserter may process objects that require greater
258   /// alignment than the default alignment the target provides.
259   /// To handle this, MaxAlignment is set to the maximum alignment
260   /// needed by the objects on the current frame.  If this is greater than the
261   /// native alignment maintained by the compiler, dynamic alignment code will
262   /// be needed.
263   ///
264   Align MaxAlignment;
265 
266   /// Set to true if this function adjusts the stack -- e.g.,
267   /// when calling another function. This is only valid during and after
268   /// prolog/epilog code insertion.
269   bool AdjustsStack = false;
270 
271   /// Set to true if this function has any function calls.
272   bool HasCalls = false;
273 
274   /// The frame index for the stack protector.
275   int StackProtectorIdx = -1;
276 
277   /// The frame index for the function context. Used for SjLj exceptions.
278   int FunctionContextIdx = -1;
279 
280   /// This contains the size of the largest call frame if the target uses frame
281   /// setup/destroy pseudo instructions (as defined in the TargetFrameInfo
282   /// class).  This information is important for frame pointer elimination.
283   /// It is only valid during and after prolog/epilog code insertion.
284   unsigned MaxCallFrameSize = ~0u;
285 
286   /// The number of bytes of callee saved registers that the target wants to
287   /// report for the current function in the CodeView S_FRAMEPROC record.
288   unsigned CVBytesOfCalleeSavedRegisters = 0;
289 
290   /// The prolog/epilog code inserter fills in this vector with each
291   /// callee saved register saved in either the frame or a different
292   /// register.  Beyond its use by the prolog/ epilog code inserter,
293   /// this data is used for debug info and exception handling.
294   std::vector<CalleeSavedInfo> CSInfo;
295 
296   /// Has CSInfo been set yet?
297   bool CSIValid = false;
298 
299   /// References to frame indices which are mapped
300   /// into the local frame allocation block. <FrameIdx, LocalOffset>
301   SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
302 
303   /// Size of the pre-allocated local frame block.
304   int64_t LocalFrameSize = 0;
305 
306   /// Required alignment of the local object blob, which is the strictest
307   /// alignment of any object in it.
308   Align LocalFrameMaxAlign;
309 
310   /// Whether the local object blob needs to be allocated together. If not,
311   /// PEI should ignore the isPreAllocated flags on the stack objects and
312   /// just allocate them normally.
313   bool UseLocalStackAllocationBlock = false;
314 
315   /// True if the function dynamically adjusts the stack pointer through some
316   /// opaque mechanism like inline assembly or Win32 EH.
317   bool HasOpaqueSPAdjustment = false;
318 
319   /// True if the function contains operations which will lower down to
320   /// instructions which manipulate the stack pointer.
321   bool HasCopyImplyingStackAdjustment = false;
322 
323   /// True if the function contains a call to the llvm.vastart intrinsic.
324   bool HasVAStart = false;
325 
326   /// True if this is a varargs function that contains a musttail call.
327   bool HasMustTailInVarArgFunc = false;
328 
329   /// True if this function contains a tail call. If so immutable objects like
330   /// function arguments are no longer so. A tail call *can* override fixed
331   /// stack objects like arguments so we can't treat them as immutable.
332   bool HasTailCall = false;
333 
334   /// Not null, if shrink-wrapping found a better place for the prologue.
335   MachineBasicBlock *Save = nullptr;
336   /// Not null, if shrink-wrapping found a better place for the epilogue.
337   MachineBasicBlock *Restore = nullptr;
338 
339 public:
MachineFrameInfo(unsigned StackAlignment,bool StackRealignable,bool ForcedRealign)340   explicit MachineFrameInfo(unsigned StackAlignment, bool StackRealignable,
341                             bool ForcedRealign)
342       : StackAlignment(assumeAligned(StackAlignment)),
343         StackRealignable(StackRealignable), ForcedRealign(ForcedRealign) {}
344 
345   MachineFrameInfo(const MachineFrameInfo &) = delete;
346 
347   /// Return true if there are any stack objects in this function.
hasStackObjects()348   bool hasStackObjects() const { return !Objects.empty(); }
349 
350   /// This method may be called any time after instruction
351   /// selection is complete to determine if the stack frame for this function
352   /// contains any variable sized objects.
hasVarSizedObjects()353   bool hasVarSizedObjects() const { return HasVarSizedObjects; }
354 
355   /// Return the index for the stack protector object.
getStackProtectorIndex()356   int getStackProtectorIndex() const { return StackProtectorIdx; }
setStackProtectorIndex(int I)357   void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
hasStackProtectorIndex()358   bool hasStackProtectorIndex() const { return StackProtectorIdx != -1; }
359 
360   /// Return the index for the function context object.
361   /// This object is used for SjLj exceptions.
getFunctionContextIndex()362   int getFunctionContextIndex() const { return FunctionContextIdx; }
setFunctionContextIndex(int I)363   void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
364 
365   /// This method may be called any time after instruction
366   /// selection is complete to determine if there is a call to
367   /// \@llvm.frameaddress in this function.
isFrameAddressTaken()368   bool isFrameAddressTaken() const { return FrameAddressTaken; }
setFrameAddressIsTaken(bool T)369   void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
370 
371   /// This method may be called any time after
372   /// instruction selection is complete to determine if there is a call to
373   /// \@llvm.returnaddress in this function.
isReturnAddressTaken()374   bool isReturnAddressTaken() const { return ReturnAddressTaken; }
setReturnAddressIsTaken(bool s)375   void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
376 
377   /// This method may be called any time after instruction
378   /// selection is complete to determine if there is a call to builtin
379   /// \@llvm.experimental.stackmap.
hasStackMap()380   bool hasStackMap() const { return HasStackMap; }
381   void setHasStackMap(bool s = true) { HasStackMap = s; }
382 
383   /// This method may be called any time after instruction
384   /// selection is complete to determine if there is a call to builtin
385   /// \@llvm.experimental.patchpoint.
hasPatchPoint()386   bool hasPatchPoint() const { return HasPatchPoint; }
387   void setHasPatchPoint(bool s = true) { HasPatchPoint = s; }
388 
389   /// Return the minimum frame object index.
getObjectIndexBegin()390   int getObjectIndexBegin() const { return -NumFixedObjects; }
391 
392   /// Return one past the maximum frame object index.
getObjectIndexEnd()393   int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
394 
395   /// Return the number of fixed objects.
getNumFixedObjects()396   unsigned getNumFixedObjects() const { return NumFixedObjects; }
397 
398   /// Return the number of objects.
getNumObjects()399   unsigned getNumObjects() const { return Objects.size(); }
400 
401   /// Map a frame index into the local object block
mapLocalFrameObject(int ObjectIndex,int64_t Offset)402   void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
403     LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
404     Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
405   }
406 
407   /// Get the local offset mapping for a for an object.
getLocalFrameObjectMap(int i)408   std::pair<int, int64_t> getLocalFrameObjectMap(int i) const {
409     assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
410             "Invalid local object reference!");
411     return LocalFrameObjects[i];
412   }
413 
414   /// Return the number of objects allocated into the local object block.
getLocalFrameObjectCount()415   int64_t getLocalFrameObjectCount() const { return LocalFrameObjects.size(); }
416 
417   /// Set the size of the local object blob.
setLocalFrameSize(int64_t sz)418   void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
419 
420   /// Get the size of the local object blob.
getLocalFrameSize()421   int64_t getLocalFrameSize() const { return LocalFrameSize; }
422 
423   /// Required alignment of the local object blob,
424   /// which is the strictest alignment of any object in it.
setLocalFrameMaxAlign(Align Alignment)425   void setLocalFrameMaxAlign(Align Alignment) {
426     LocalFrameMaxAlign = Alignment;
427   }
428 
429   /// Return the required alignment of the local object blob.
getLocalFrameMaxAlign()430   Align getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
431 
432   /// Get whether the local allocation blob should be allocated together or
433   /// let PEI allocate the locals in it directly.
getUseLocalStackAllocationBlock()434   bool getUseLocalStackAllocationBlock() const {
435     return UseLocalStackAllocationBlock;
436   }
437 
438   /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
439   /// should be allocated together or let PEI allocate the locals in it
440   /// directly.
setUseLocalStackAllocationBlock(bool v)441   void setUseLocalStackAllocationBlock(bool v) {
442     UseLocalStackAllocationBlock = v;
443   }
444 
445   /// Return true if the object was pre-allocated into the local block.
isObjectPreAllocated(int ObjectIdx)446   bool isObjectPreAllocated(int ObjectIdx) const {
447     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
448            "Invalid Object Idx!");
449     return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
450   }
451 
452   /// Return the size of the specified object.
getObjectSize(int ObjectIdx)453   int64_t getObjectSize(int ObjectIdx) const {
454     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
455            "Invalid Object Idx!");
456     return Objects[ObjectIdx+NumFixedObjects].Size;
457   }
458 
459   /// Change the size of the specified stack object.
setObjectSize(int ObjectIdx,int64_t Size)460   void setObjectSize(int ObjectIdx, int64_t Size) {
461     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
462            "Invalid Object Idx!");
463     Objects[ObjectIdx+NumFixedObjects].Size = Size;
464   }
465 
466   /// Return the alignment of the specified stack object.
getObjectAlign(int ObjectIdx)467   Align getObjectAlign(int ObjectIdx) const {
468     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
469            "Invalid Object Idx!");
470     return Objects[ObjectIdx + NumFixedObjects].Alignment;
471   }
472 
473   /// setObjectAlignment - Change the alignment of the specified stack object.
setObjectAlignment(int ObjectIdx,Align Alignment)474   void setObjectAlignment(int ObjectIdx, Align Alignment) {
475     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
476            "Invalid Object Idx!");
477     Objects[ObjectIdx + NumFixedObjects].Alignment = Alignment;
478 
479     // Only ensure max alignment for the default stack.
480     if (getStackID(ObjectIdx) == 0)
481       ensureMaxAlignment(Alignment);
482   }
483 
484   /// Return the underlying Alloca of the specified
485   /// stack object if it exists. Returns 0 if none exists.
getObjectAllocation(int ObjectIdx)486   const AllocaInst* getObjectAllocation(int ObjectIdx) const {
487     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
488            "Invalid Object Idx!");
489     return Objects[ObjectIdx+NumFixedObjects].Alloca;
490   }
491 
492   /// Return the assigned stack offset of the specified object
493   /// from the incoming stack pointer.
getObjectOffset(int ObjectIdx)494   int64_t getObjectOffset(int ObjectIdx) const {
495     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
496            "Invalid Object Idx!");
497     assert(!isDeadObjectIndex(ObjectIdx) &&
498            "Getting frame offset for a dead object?");
499     return Objects[ObjectIdx+NumFixedObjects].SPOffset;
500   }
501 
isObjectZExt(int ObjectIdx)502   bool isObjectZExt(int ObjectIdx) const {
503     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
504            "Invalid Object Idx!");
505     return Objects[ObjectIdx+NumFixedObjects].isZExt;
506   }
507 
setObjectZExt(int ObjectIdx,bool IsZExt)508   void setObjectZExt(int ObjectIdx, bool IsZExt) {
509     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
510            "Invalid Object Idx!");
511     Objects[ObjectIdx+NumFixedObjects].isZExt = IsZExt;
512   }
513 
isObjectSExt(int ObjectIdx)514   bool isObjectSExt(int ObjectIdx) const {
515     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
516            "Invalid Object Idx!");
517     return Objects[ObjectIdx+NumFixedObjects].isSExt;
518   }
519 
setObjectSExt(int ObjectIdx,bool IsSExt)520   void setObjectSExt(int ObjectIdx, bool IsSExt) {
521     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
522            "Invalid Object Idx!");
523     Objects[ObjectIdx+NumFixedObjects].isSExt = IsSExt;
524   }
525 
526   /// Set the stack frame offset of the specified object. The
527   /// offset is relative to the stack pointer on entry to the function.
setObjectOffset(int ObjectIdx,int64_t SPOffset)528   void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
529     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
530            "Invalid Object Idx!");
531     assert(!isDeadObjectIndex(ObjectIdx) &&
532            "Setting frame offset for a dead object?");
533     Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
534   }
535 
getObjectSSPLayout(int ObjectIdx)536   SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const {
537     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
538            "Invalid Object Idx!");
539     return (SSPLayoutKind)Objects[ObjectIdx+NumFixedObjects].SSPLayout;
540   }
541 
setObjectSSPLayout(int ObjectIdx,SSPLayoutKind Kind)542   void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind) {
543     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
544            "Invalid Object Idx!");
545     assert(!isDeadObjectIndex(ObjectIdx) &&
546            "Setting SSP layout for a dead object?");
547     Objects[ObjectIdx+NumFixedObjects].SSPLayout = Kind;
548   }
549 
550   /// Return the number of bytes that must be allocated to hold
551   /// all of the fixed size frame objects.  This is only valid after
552   /// Prolog/Epilog code insertion has finalized the stack frame layout.
getStackSize()553   uint64_t getStackSize() const { return StackSize; }
554 
555   /// Set the size of the stack.
setStackSize(uint64_t Size)556   void setStackSize(uint64_t Size) { StackSize = Size; }
557 
558   /// Estimate and return the size of the stack frame.
559   uint64_t estimateStackSize(const MachineFunction &MF) const;
560 
561   /// Return the correction for frame offsets.
getOffsetAdjustment()562   int getOffsetAdjustment() const { return OffsetAdjustment; }
563 
564   /// Set the correction for frame offsets.
setOffsetAdjustment(int Adj)565   void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
566 
567   /// Return the alignment in bytes that this function must be aligned to,
568   /// which is greater than the default stack alignment provided by the target.
getMaxAlign()569   Align getMaxAlign() const { return MaxAlignment; }
570 
571   /// Make sure the function is at least Align bytes aligned.
572   void ensureMaxAlignment(Align Alignment);
573 
574   /// Return true if this function adjusts the stack -- e.g.,
575   /// when calling another function. This is only valid during and after
576   /// prolog/epilog code insertion.
adjustsStack()577   bool adjustsStack() const { return AdjustsStack; }
setAdjustsStack(bool V)578   void setAdjustsStack(bool V) { AdjustsStack = V; }
579 
580   /// Return true if the current function has any function calls.
hasCalls()581   bool hasCalls() const { return HasCalls; }
setHasCalls(bool V)582   void setHasCalls(bool V) { HasCalls = V; }
583 
584   /// Returns true if the function contains opaque dynamic stack adjustments.
hasOpaqueSPAdjustment()585   bool hasOpaqueSPAdjustment() const { return HasOpaqueSPAdjustment; }
setHasOpaqueSPAdjustment(bool B)586   void setHasOpaqueSPAdjustment(bool B) { HasOpaqueSPAdjustment = B; }
587 
588   /// Returns true if the function contains operations which will lower down to
589   /// instructions which manipulate the stack pointer.
hasCopyImplyingStackAdjustment()590   bool hasCopyImplyingStackAdjustment() const {
591     return HasCopyImplyingStackAdjustment;
592   }
setHasCopyImplyingStackAdjustment(bool B)593   void setHasCopyImplyingStackAdjustment(bool B) {
594     HasCopyImplyingStackAdjustment = B;
595   }
596 
597   /// Returns true if the function calls the llvm.va_start intrinsic.
hasVAStart()598   bool hasVAStart() const { return HasVAStart; }
setHasVAStart(bool B)599   void setHasVAStart(bool B) { HasVAStart = B; }
600 
601   /// Returns true if the function is variadic and contains a musttail call.
hasMustTailInVarArgFunc()602   bool hasMustTailInVarArgFunc() const { return HasMustTailInVarArgFunc; }
setHasMustTailInVarArgFunc(bool B)603   void setHasMustTailInVarArgFunc(bool B) { HasMustTailInVarArgFunc = B; }
604 
605   /// Returns true if the function contains a tail call.
hasTailCall()606   bool hasTailCall() const { return HasTailCall; }
607   void setHasTailCall(bool V = true) { HasTailCall = V; }
608 
609   /// Computes the maximum size of a callframe and the AdjustsStack property.
610   /// This only works for targets defining
611   /// TargetInstrInfo::getCallFrameSetupOpcode(), getCallFrameDestroyOpcode(),
612   /// and getFrameSize().
613   /// This is usually computed by the prologue epilogue inserter but some
614   /// targets may call this to compute it earlier.
615   void computeMaxCallFrameSize(const MachineFunction &MF);
616 
617   /// Return the maximum size of a call frame that must be
618   /// allocated for an outgoing function call.  This is only available if
619   /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
620   /// then only during or after prolog/epilog code insertion.
621   ///
getMaxCallFrameSize()622   unsigned getMaxCallFrameSize() const {
623     // TODO: Enable this assert when targets are fixed.
624     //assert(isMaxCallFrameSizeComputed() && "MaxCallFrameSize not computed yet");
625     if (!isMaxCallFrameSizeComputed())
626       return 0;
627     return MaxCallFrameSize;
628   }
isMaxCallFrameSizeComputed()629   bool isMaxCallFrameSizeComputed() const {
630     return MaxCallFrameSize != ~0u;
631   }
setMaxCallFrameSize(unsigned S)632   void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
633 
634   /// Returns how many bytes of callee-saved registers the target pushed in the
635   /// prologue. Only used for debug info.
getCVBytesOfCalleeSavedRegisters()636   unsigned getCVBytesOfCalleeSavedRegisters() const {
637     return CVBytesOfCalleeSavedRegisters;
638   }
setCVBytesOfCalleeSavedRegisters(unsigned S)639   void setCVBytesOfCalleeSavedRegisters(unsigned S) {
640     CVBytesOfCalleeSavedRegisters = S;
641   }
642 
643   /// Create a new object at a fixed location on the stack.
644   /// All fixed objects should be created before other objects are created for
645   /// efficiency. By default, fixed objects are not pointed to by LLVM IR
646   /// values. This returns an index with a negative value.
647   int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable,
648                         bool isAliased = false);
649 
650   /// Create a spill slot at a fixed location on the stack.
651   /// Returns an index with a negative value.
652   int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset,
653                                   bool IsImmutable = false);
654 
655   /// Returns true if the specified index corresponds to a fixed stack object.
isFixedObjectIndex(int ObjectIdx)656   bool isFixedObjectIndex(int ObjectIdx) const {
657     return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
658   }
659 
660   /// Returns true if the specified index corresponds
661   /// to an object that might be pointed to by an LLVM IR value.
isAliasedObjectIndex(int ObjectIdx)662   bool isAliasedObjectIndex(int ObjectIdx) const {
663     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
664            "Invalid Object Idx!");
665     return Objects[ObjectIdx+NumFixedObjects].isAliased;
666   }
667 
668   /// Returns true if the specified index corresponds to an immutable object.
isImmutableObjectIndex(int ObjectIdx)669   bool isImmutableObjectIndex(int ObjectIdx) const {
670     // Tail calling functions can clobber their function arguments.
671     if (HasTailCall)
672       return false;
673     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
674            "Invalid Object Idx!");
675     return Objects[ObjectIdx+NumFixedObjects].isImmutable;
676   }
677 
678   /// Marks the immutability of an object.
setIsImmutableObjectIndex(int ObjectIdx,bool IsImmutable)679   void setIsImmutableObjectIndex(int ObjectIdx, bool IsImmutable) {
680     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
681            "Invalid Object Idx!");
682     Objects[ObjectIdx+NumFixedObjects].isImmutable = IsImmutable;
683   }
684 
685   /// Returns true if the specified index corresponds to a spill slot.
isSpillSlotObjectIndex(int ObjectIdx)686   bool isSpillSlotObjectIndex(int ObjectIdx) const {
687     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
688            "Invalid Object Idx!");
689     return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
690   }
691 
isStatepointSpillSlotObjectIndex(int ObjectIdx)692   bool isStatepointSpillSlotObjectIndex(int ObjectIdx) const {
693     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
694            "Invalid Object Idx!");
695     return Objects[ObjectIdx+NumFixedObjects].isStatepointSpillSlot;
696   }
697 
698   /// \see StackID
getStackID(int ObjectIdx)699   uint8_t getStackID(int ObjectIdx) const {
700     return Objects[ObjectIdx+NumFixedObjects].StackID;
701   }
702 
703   /// \see StackID
setStackID(int ObjectIdx,uint8_t ID)704   void setStackID(int ObjectIdx, uint8_t ID) {
705     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
706            "Invalid Object Idx!");
707     Objects[ObjectIdx+NumFixedObjects].StackID = ID;
708     // If ID > 0, MaxAlignment may now be overly conservative.
709     // If ID == 0, MaxAlignment will need to be updated separately.
710   }
711 
712   /// Returns true if the specified index corresponds to a dead object.
isDeadObjectIndex(int ObjectIdx)713   bool isDeadObjectIndex(int ObjectIdx) const {
714     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
715            "Invalid Object Idx!");
716     return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
717   }
718 
719   /// Returns true if the specified index corresponds to a variable sized
720   /// object.
isVariableSizedObjectIndex(int ObjectIdx)721   bool isVariableSizedObjectIndex(int ObjectIdx) const {
722     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
723            "Invalid Object Idx!");
724     return Objects[ObjectIdx + NumFixedObjects].Size == 0;
725   }
726 
markAsStatepointSpillSlotObjectIndex(int ObjectIdx)727   void markAsStatepointSpillSlotObjectIndex(int ObjectIdx) {
728     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
729            "Invalid Object Idx!");
730     Objects[ObjectIdx+NumFixedObjects].isStatepointSpillSlot = true;
731     assert(isStatepointSpillSlotObjectIndex(ObjectIdx) && "inconsistent");
732   }
733 
734   /// Create a new statically sized stack object, returning
735   /// a nonnegative identifier to represent it.
736   int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot,
737                         const AllocaInst *Alloca = nullptr, uint8_t ID = 0);
738 
739   /// Create a new statically sized stack object that represents a spill slot,
740   /// returning a nonnegative identifier to represent it.
741   int CreateSpillStackObject(uint64_t Size, Align Alignment);
742 
743   /// Remove or mark dead a statically sized stack object.
RemoveStackObject(int ObjectIdx)744   void RemoveStackObject(int ObjectIdx) {
745     // Mark it dead.
746     Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
747   }
748 
749   /// Notify the MachineFrameInfo object that a variable sized object has been
750   /// created.  This must be created whenever a variable sized object is
751   /// created, whether or not the index returned is actually used.
752   int CreateVariableSizedObject(Align Alignment, const AllocaInst *Alloca);
753 
754   /// Returns a reference to call saved info vector for the current function.
getCalleeSavedInfo()755   const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
756     return CSInfo;
757   }
758   /// \copydoc getCalleeSavedInfo()
getCalleeSavedInfo()759   std::vector<CalleeSavedInfo> &getCalleeSavedInfo() { return CSInfo; }
760 
761   /// Used by prolog/epilog inserter to set the function's callee saved
762   /// information.
setCalleeSavedInfo(std::vector<CalleeSavedInfo> CSI)763   void setCalleeSavedInfo(std::vector<CalleeSavedInfo> CSI) {
764     CSInfo = std::move(CSI);
765   }
766 
767   /// Has the callee saved info been calculated yet?
isCalleeSavedInfoValid()768   bool isCalleeSavedInfoValid() const { return CSIValid; }
769 
setCalleeSavedInfoValid(bool v)770   void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
771 
getSavePoint()772   MachineBasicBlock *getSavePoint() const { return Save; }
setSavePoint(MachineBasicBlock * NewSave)773   void setSavePoint(MachineBasicBlock *NewSave) { Save = NewSave; }
getRestorePoint()774   MachineBasicBlock *getRestorePoint() const { return Restore; }
setRestorePoint(MachineBasicBlock * NewRestore)775   void setRestorePoint(MachineBasicBlock *NewRestore) { Restore = NewRestore; }
776 
777   /// Return a set of physical registers that are pristine.
778   ///
779   /// Pristine registers hold a value that is useless to the current function,
780   /// but that must be preserved - they are callee saved registers that are not
781   /// saved.
782   ///
783   /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
784   /// method always returns an empty set.
785   BitVector getPristineRegs(const MachineFunction &MF) const;
786 
787   /// Used by the MachineFunction printer to print information about
788   /// stack objects. Implemented in MachineFunction.cpp.
789   void print(const MachineFunction &MF, raw_ostream &OS) const;
790 
791   /// dump - Print the function to stderr.
792   void dump(const MachineFunction &MF) const;
793 };
794 
795 } // End llvm namespace
796 
797 #endif
798