xref: /llvm-project/llvm/lib/CodeGen/MachineFrameInfo.cpp (revision c3df69faa03404ad912f4f613edc19c067ab91f6)
1 //===-- MachineFrameInfo.cpp ---------------------------------------------===//
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 /// \file Implements MachineFrameInfo that manages the stack frame.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineFrameInfo.h"
14 
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetFrameLowering.h"
19 #include "llvm/CodeGen/TargetInstrInfo.h"
20 #include "llvm/CodeGen/TargetRegisterInfo.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <cassert>
26 
27 #define DEBUG_TYPE "codegen"
28 
29 using namespace llvm;
30 
31 void MachineFrameInfo::ensureMaxAlignment(Align Alignment) {
32   if (!StackRealignable)
33     assert(Alignment <= StackAlignment &&
34            "For targets without stack realignment, Alignment is out of limit!");
35   if (MaxAlignment < Alignment)
36     MaxAlignment = Alignment;
37 }
38 
39 /// Clamp the alignment if requested and emit a warning.
40 static inline Align clampStackAlignment(bool ShouldClamp, Align Alignment,
41                                         Align StackAlignment) {
42   if (!ShouldClamp || Alignment <= StackAlignment)
43     return Alignment;
44   LLVM_DEBUG(dbgs() << "Warning: requested alignment " << Alignment.value()
45                     << " exceeds the stack alignment " << StackAlignment.value()
46                     << " when stack realignment is off" << '\n');
47   return StackAlignment;
48 }
49 
50 int MachineFrameInfo::CreateStackObject(uint64_t Size, Align Alignment,
51                                         bool IsSpillSlot,
52                                         const AllocaInst *Alloca,
53                                         uint8_t StackID) {
54   assert(Size != 0 && "Cannot allocate zero size stack objects!");
55   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
56   Objects.push_back(StackObject(Size, Alignment, 0, false, IsSpillSlot, Alloca,
57                                 !IsSpillSlot, StackID));
58   int Index = (int)Objects.size() - NumFixedObjects - 1;
59   assert(Index >= 0 && "Bad frame index!");
60   if (StackID == 0)
61     ensureMaxAlignment(Alignment);
62   return Index;
63 }
64 
65 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size, Align Alignment) {
66   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
67   CreateStackObject(Size, Alignment, true);
68   int Index = (int)Objects.size() - NumFixedObjects - 1;
69   ensureMaxAlignment(Alignment);
70   return Index;
71 }
72 
73 int MachineFrameInfo::CreateVariableSizedObject(Align Alignment,
74                                                 const AllocaInst *Alloca) {
75   HasVarSizedObjects = true;
76   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
77   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
78   ensureMaxAlignment(Alignment);
79   return (int)Objects.size()-NumFixedObjects-1;
80 }
81 
82 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
83                                         bool IsImmutable, bool IsAliased) {
84   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
85   // The alignment of the frame index can be determined from its offset from
86   // the incoming frame position.  If the frame object is at offset 32 and
87   // the stack is guaranteed to be 16-byte aligned, then we know that the
88   // object is 16-byte aligned. Note that unlike the non-fixed case, if the
89   // stack needs realignment, we can't assume that the stack will in fact be
90   // aligned.
91   Align Alignment =
92       commonAlignment(ForcedRealign ? Align(1) : StackAlignment, SPOffset);
93   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
94   Objects.insert(Objects.begin(),
95                  StackObject(Size, Alignment, SPOffset, IsImmutable,
96                              /*IsSpillSlot=*/false, /*Alloca=*/nullptr,
97                              IsAliased));
98   return -++NumFixedObjects;
99 }
100 
101 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
102                                                   int64_t SPOffset,
103                                                   bool IsImmutable) {
104   Align Alignment =
105       commonAlignment(ForcedRealign ? Align(1) : StackAlignment, SPOffset);
106   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
107   Objects.insert(Objects.begin(),
108                  StackObject(Size, Alignment, SPOffset, IsImmutable,
109                              /*IsSpillSlot=*/true, /*Alloca=*/nullptr,
110                              /*IsAliased=*/false));
111   return -++NumFixedObjects;
112 }
113 
114 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
115   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
116   BitVector BV(TRI->getNumRegs());
117 
118   // Before CSI is calculated, no registers are considered pristine. They can be
119   // freely used and PEI will make sure they are saved.
120   if (!isCalleeSavedInfoValid())
121     return BV;
122 
123   const MachineRegisterInfo &MRI = MF.getRegInfo();
124   for (const MCPhysReg *CSR = MRI.getCalleeSavedRegs(); CSR && *CSR;
125        ++CSR)
126     BV.set(*CSR);
127 
128   // Saved CSRs are not pristine.
129   for (auto &I : getCalleeSavedInfo())
130     for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S)
131       BV.reset(*S);
132 
133   return BV;
134 }
135 
136 uint64_t MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
137   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
138   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
139   Align MaxAlign = getMaxAlign();
140   int64_t Offset = 0;
141 
142   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
143   // It really should be refactored to share code. Until then, changes
144   // should keep in mind that there's tight coupling between the two.
145 
146   for (int i = getObjectIndexBegin(); i != 0; ++i) {
147     // Only estimate stack size of default stack.
148     if (getStackID(i) != TargetStackID::Default)
149       continue;
150     int64_t FixedOff = -getObjectOffset(i);
151     if (FixedOff > Offset) Offset = FixedOff;
152   }
153   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
154     // Only estimate stack size of live objects on default stack.
155     if (isDeadObjectIndex(i) || getStackID(i) != TargetStackID::Default)
156       continue;
157     Offset += getObjectSize(i);
158     Align Alignment = getObjectAlign(i);
159     // Adjust to alignment boundary
160     Offset = alignTo(Offset, Alignment);
161 
162     MaxAlign = std::max(Alignment, MaxAlign);
163   }
164 
165   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
166     Offset += getMaxCallFrameSize();
167 
168   // Round up the size to a multiple of the alignment.  If the function has
169   // any calls or alloca's, align to the target's StackAlignment value to
170   // ensure that the callee's frame or the alloca data is suitably aligned;
171   // otherwise, for leaf functions, align to the TransientStackAlignment
172   // value.
173   Align StackAlign;
174   if (adjustsStack() || hasVarSizedObjects() ||
175       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
176     StackAlign = TFI->getStackAlign();
177   else
178     StackAlign = TFI->getTransientStackAlign();
179 
180   // If the frame pointer is eliminated, all frame offsets will be relative to
181   // SP not FP. Align to MaxAlign so this works.
182   StackAlign = std::max(StackAlign, MaxAlign);
183   return alignTo(Offset, StackAlign);
184 }
185 
186 void MachineFrameInfo::computeMaxCallFrameSize(const MachineFunction &MF) {
187   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
188   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
189   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
190   assert(FrameSetupOpcode != ~0u && FrameDestroyOpcode != ~0u &&
191          "Can only compute MaxCallFrameSize if Setup/Destroy opcode are known");
192 
193   MaxCallFrameSize = 0;
194   for (const MachineBasicBlock &MBB : MF) {
195     for (const MachineInstr &MI : MBB) {
196       unsigned Opcode = MI.getOpcode();
197       if (Opcode == FrameSetupOpcode || Opcode == FrameDestroyOpcode) {
198         unsigned Size = TII.getFrameSize(MI);
199         MaxCallFrameSize = std::max(MaxCallFrameSize, Size);
200         AdjustsStack = true;
201       } else if (MI.isInlineAsm()) {
202         // Some inline asm's need a stack frame, as indicated by operand 1.
203         unsigned ExtraInfo = MI.getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
204         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
205           AdjustsStack = true;
206       }
207     }
208   }
209 }
210 
211 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
212   if (Objects.empty()) return;
213 
214   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
215   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
216 
217   OS << "Frame Objects:\n";
218 
219   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
220     const StackObject &SO = Objects[i];
221     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
222 
223     if (SO.StackID != 0)
224       OS << "id=" << static_cast<unsigned>(SO.StackID) << ' ';
225 
226     if (SO.Size == ~0ULL) {
227       OS << "dead\n";
228       continue;
229     }
230     if (SO.Size == 0)
231       OS << "variable sized";
232     else
233       OS << "size=" << SO.Size;
234     OS << ", align=" << SO.Alignment.value();
235 
236     if (i < NumFixedObjects)
237       OS << ", fixed";
238     if (i < NumFixedObjects || SO.SPOffset != -1) {
239       int64_t Off = SO.SPOffset - ValOffset;
240       OS << ", at location [SP";
241       if (Off > 0)
242         OS << "+" << Off;
243       else if (Off < 0)
244         OS << Off;
245       OS << "]";
246     }
247     OS << "\n";
248   }
249 }
250 
251 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
252 LLVM_DUMP_METHOD void MachineFrameInfo::dump(const MachineFunction &MF) const {
253   print(MF, dbgs());
254 }
255 #endif
256