xref: /freebsd/contrib/llvm-project/llvm/lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 //===-- NVPTXPrologEpilogPass.cpp - NVPTX prolog/epilog inserter ----------===//
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 // This file is a copy of the generic LLVM PrologEpilogInserter pass, modified
10 // to remove unneeded functionality and to handle virtual registers. Most code
11 // here is a copy of PrologEpilogInserter.cpp.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "NVPTX.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/TargetFrameLowering.h"
20 #include "llvm/CodeGen/TargetRegisterInfo.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "nvptx-prolog-epilog"
30 
31 namespace {
32 class NVPTXPrologEpilogPass : public MachineFunctionPass {
33 public:
34   static char ID;
35   NVPTXPrologEpilogPass() : MachineFunctionPass(ID) {}
36 
37   bool runOnMachineFunction(MachineFunction &MF) override;
38 
39 private:
40   void calculateFrameObjectOffsets(MachineFunction &Fn);
41 };
42 }
43 
44 MachineFunctionPass *llvm::createNVPTXPrologEpilogPass() {
45   return new NVPTXPrologEpilogPass();
46 }
47 
48 char NVPTXPrologEpilogPass::ID = 0;
49 
50 bool NVPTXPrologEpilogPass::runOnMachineFunction(MachineFunction &MF) {
51   const TargetSubtargetInfo &STI = MF.getSubtarget();
52   const TargetFrameLowering &TFI = *STI.getFrameLowering();
53   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
54   bool Modified = false;
55 
56   calculateFrameObjectOffsets(MF);
57 
58   for (MachineBasicBlock &MBB : MF) {
59     for (MachineInstr &MI : MBB) {
60       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
61         if (!MI.getOperand(i).isFI())
62           continue;
63 
64         // Frame indices in debug values are encoded in a target independent
65         // way with simply the frame index and offset rather than any
66         // target-specific addressing mode.
67         if (MI.isDebugValue()) {
68           MachineOperand &Op = MI.getOperand(i);
69           assert(
70               MI.isDebugOperand(&Op) &&
71               "Frame indices can only appear as a debug operand in a DBG_VALUE*"
72               " machine instruction");
73           Register Reg;
74           auto Offset =
75               TFI.getFrameIndexReference(MF, Op.getIndex(), Reg);
76           Op.ChangeToRegister(Reg, /*isDef=*/false);
77           const DIExpression *DIExpr = MI.getDebugExpression();
78           if (MI.isNonListDebugValue()) {
79             DIExpr = TRI.prependOffsetExpression(MI.getDebugExpression(), DIExpression::ApplyOffset, Offset);
80           } else {
81 	    SmallVector<uint64_t, 3> Ops;
82             TRI.getOffsetOpcodes(Offset, Ops);
83             unsigned OpIdx = MI.getDebugOperandIndex(&Op);
84             DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, OpIdx);
85           }
86           MI.getDebugExpressionOp().setMetadata(DIExpr);
87           continue;
88         }
89 
90         TRI.eliminateFrameIndex(MI, 0, i, nullptr);
91         Modified = true;
92       }
93     }
94   }
95 
96   // Add function prolog/epilog
97   TFI.emitPrologue(MF, MF.front());
98 
99   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
100     // If last instruction is a return instruction, add an epilogue
101     if (I->isReturnBlock())
102       TFI.emitEpilogue(MF, *I);
103   }
104 
105   return Modified;
106 }
107 
108 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
109 static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
110                                      bool StackGrowsDown, int64_t &Offset,
111                                      Align &MaxAlign) {
112   // If the stack grows down, add the object size to find the lowest address.
113   if (StackGrowsDown)
114     Offset += MFI.getObjectSize(FrameIdx);
115 
116   Align Alignment = MFI.getObjectAlign(FrameIdx);
117 
118   // If the alignment of this object is greater than that of the stack, then
119   // increase the stack alignment to match.
120   MaxAlign = std::max(MaxAlign, Alignment);
121 
122   // Adjust to alignment boundary.
123   Offset = alignTo(Offset, Alignment);
124 
125   if (StackGrowsDown) {
126     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
127                       << "]\n");
128     MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
129   } else {
130     LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
131                       << "]\n");
132     MFI.setObjectOffset(FrameIdx, Offset);
133     Offset += MFI.getObjectSize(FrameIdx);
134   }
135 }
136 
137 void
138 NVPTXPrologEpilogPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
139   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
140   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
141 
142   bool StackGrowsDown =
143     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
144 
145   // Loop over all of the stack objects, assigning sequential addresses...
146   MachineFrameInfo &MFI = Fn.getFrameInfo();
147 
148   // Start at the beginning of the local area.
149   // The Offset is the distance from the stack top in the direction
150   // of stack growth -- so it's always nonnegative.
151   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
152   if (StackGrowsDown)
153     LocalAreaOffset = -LocalAreaOffset;
154   assert(LocalAreaOffset >= 0
155          && "Local area offset should be in direction of stack growth");
156   int64_t Offset = LocalAreaOffset;
157 
158   // If there are fixed sized objects that are preallocated in the local area,
159   // non-fixed objects can't be allocated right at the start of local area.
160   // We currently don't support filling in holes in between fixed sized
161   // objects, so we adjust 'Offset' to point to the end of last fixed sized
162   // preallocated object.
163   for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
164     int64_t FixedOff;
165     if (StackGrowsDown) {
166       // The maximum distance from the stack pointer is at lower address of
167       // the object -- which is given by offset. For down growing stack
168       // the offset is negative, so we negate the offset to get the distance.
169       FixedOff = -MFI.getObjectOffset(i);
170     } else {
171       // The maximum distance from the start pointer is at the upper
172       // address of the object.
173       FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
174     }
175     if (FixedOff > Offset) Offset = FixedOff;
176   }
177 
178   // NOTE: We do not have a call stack
179 
180   Align MaxAlign = MFI.getMaxAlign();
181 
182   // No scavenger
183 
184   // FIXME: Once this is working, then enable flag will change to a target
185   // check for whether the frame is large enough to want to use virtual
186   // frame index registers. Functions which don't want/need this optimization
187   // will continue to use the existing code path.
188   if (MFI.getUseLocalStackAllocationBlock()) {
189     Align Alignment = MFI.getLocalFrameMaxAlign();
190 
191     // Adjust to alignment boundary.
192     Offset = alignTo(Offset, Alignment);
193 
194     LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
195 
196     // Resolve offsets for objects in the local block.
197     for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
198       std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
199       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
200       LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
201                         << "]\n");
202       MFI.setObjectOffset(Entry.first, FIOffset);
203     }
204     // Allocate the local block
205     Offset += MFI.getLocalFrameSize();
206 
207     MaxAlign = std::max(Alignment, MaxAlign);
208   }
209 
210   // No stack protector
211 
212   // Then assign frame offsets to stack objects that are not used to spill
213   // callee saved registers.
214   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
215     if (MFI.isObjectPreAllocated(i) &&
216         MFI.getUseLocalStackAllocationBlock())
217       continue;
218     if (MFI.isDeadObjectIndex(i))
219       continue;
220 
221     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
222   }
223 
224   // No scavenger
225 
226   if (!TFI.targetHandlesStackFrameRounding()) {
227     // If we have reserved argument space for call sites in the function
228     // immediately on entry to the current function, count it as part of the
229     // overall stack size.
230     if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn))
231       Offset += MFI.getMaxCallFrameSize();
232 
233     // Round up the size to a multiple of the alignment.  If the function has
234     // any calls or alloca's, align to the target's StackAlignment value to
235     // ensure that the callee's frame or the alloca data is suitably aligned;
236     // otherwise, for leaf functions, align to the TransientStackAlignment
237     // value.
238     Align StackAlign;
239     if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
240         (RegInfo->hasStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0))
241       StackAlign = TFI.getStackAlign();
242     else
243       StackAlign = TFI.getTransientStackAlign();
244 
245     // If the frame pointer is eliminated, all frame offsets will be relative to
246     // SP not FP. Align to MaxAlign so this works.
247     Offset = alignTo(Offset, std::max(StackAlign, MaxAlign));
248   }
249 
250   // Update frame info to pretend that this is part of the stack...
251   int64_t StackSize = Offset - LocalAreaOffset;
252   MFI.setStackSize(StackSize);
253 }
254