blob: 1318d6212497f58243c7177ced9b7a3eaf86da96 [file] [log] [blame]
Jim Grosbach3d723672010-08-14 00:15:52 +00001//===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass assigns local frame indices to stack slots relative to one another
11// and allocates additional base registers to access them when the target
Bob Wilson67b067d2011-01-07 04:58:58 +000012// estimates they are likely to be out of range of stack pointer and frame
Jim Grosbach3d723672010-08-14 00:15:52 +000013// pointer relative addressing.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "localstackalloc"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
Jim Grosbach3d723672010-08-14 00:15:52 +000022#include "llvm/LLVMContext.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/ADT/SmallSet.h"
Jim Grosbach8708ead2010-08-17 18:13:53 +000026#include "llvm/ADT/Statistic.h"
Jim Grosbach864d22e2010-08-31 17:58:19 +000027#include "llvm/ADT/STLExtras.h"
Jim Grosbach3d723672010-08-14 00:15:52 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
Jim Grosbachdc140c62010-08-17 22:41:55 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Grosbach3d723672010-08-14 00:15:52 +000032#include "llvm/CodeGen/Passes.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/Target/TargetRegisterInfo.h"
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000037#include "llvm/Target/TargetFrameLowering.h"
Jim Grosbach3d723672010-08-14 00:15:52 +000038
39using namespace llvm;
40
Jim Grosbach8708ead2010-08-17 18:13:53 +000041STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
42STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
43STATISTIC(NumReplacements, "Number of frame indices references replaced");
Jim Grosbach3d723672010-08-14 00:15:52 +000044
45namespace {
Jim Grosbach864d22e2010-08-31 17:58:19 +000046 class FrameRef {
47 MachineBasicBlock::iterator MI; // Instr referencing the frame
48 int64_t LocalOffset; // Local offset of the frame idx referenced
49 public:
50 FrameRef(MachineBasicBlock::iterator I, int64_t Offset) :
51 MI(I), LocalOffset(Offset) {}
52 bool operator<(const FrameRef &RHS) const {
53 return LocalOffset < RHS.LocalOffset;
54 }
55 MachineBasicBlock::iterator getMachineInstr() { return MI; }
56 };
57
Jim Grosbach3d723672010-08-14 00:15:52 +000058 class LocalStackSlotPass: public MachineFunctionPass {
Jim Grosbach2b1e2022010-08-18 22:44:49 +000059 SmallVector<int64_t,16> LocalOffsets;
Jim Grosbach8708ead2010-08-17 18:13:53 +000060
Jim Grosbach2b1e2022010-08-18 22:44:49 +000061 void AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx, int64_t &Offset,
Jim Grosbach67ff81a2010-08-23 20:40:38 +000062 bool StackGrowsDown, unsigned &MaxAlign);
Jim Grosbach2b1e2022010-08-18 22:44:49 +000063 void calculateFrameObjectOffsets(MachineFunction &Fn);
Jim Grosbach2d16f5b2010-08-20 16:48:30 +000064 bool insertFrameReferenceRegisters(MachineFunction &Fn);
Jim Grosbach3d723672010-08-14 00:15:52 +000065 public:
66 static char ID; // Pass identification, replacement for typeid
67 explicit LocalStackSlotPass() : MachineFunctionPass(ID) { }
68 bool runOnMachineFunction(MachineFunction &MF);
69
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.setPreservesCFG();
72 MachineFunctionPass::getAnalysisUsage(AU);
73 }
74 const char *getPassName() const {
75 return "Local Stack Slot Allocation";
76 }
77
78 private:
79 };
80} // end anonymous namespace
81
82char LocalStackSlotPass::ID = 0;
83
84FunctionPass *llvm::createLocalStackSlotAllocationPass() {
85 return new LocalStackSlotPass();
86}
87
88bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
Jim Grosbach2b1e2022010-08-18 22:44:49 +000089 MachineFrameInfo *MFI = MF.getFrameInfo();
Jim Grosbacha2734422010-08-24 19:05:43 +000090 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
Jim Grosbach2b1e2022010-08-18 22:44:49 +000091 unsigned LocalObjectCount = MFI->getObjectIndexEnd();
92
Jim Grosbacha2734422010-08-24 19:05:43 +000093 // If the target doesn't want/need this pass, or if there are no locals
94 // to consider, early exit.
95 if (!TRI->requiresVirtualBaseRegisters(MF) || LocalObjectCount == 0)
Jim Grosbach2b1e2022010-08-18 22:44:49 +000096 return true;
97
98 // Make sure we have enough space to store the local offsets.
99 LocalOffsets.resize(MFI->getObjectIndexEnd());
100
Jim Grosbach8708ead2010-08-17 18:13:53 +0000101 // Lay out the local blob.
Jim Grosbach3d723672010-08-14 00:15:52 +0000102 calculateFrameObjectOffsets(MF);
Jim Grosbach8708ead2010-08-17 18:13:53 +0000103
104 // Insert virtual base registers to resolve frame index references.
Jim Grosbach2d16f5b2010-08-20 16:48:30 +0000105 bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000106
Jim Grosbacha0fc0052010-08-19 02:47:08 +0000107 // Tell MFI whether any base registers were allocated. PEI will only
108 // want to use the local block allocations from this pass if there were any.
109 // Otherwise, PEI can do a bit better job of getting the alignment right
110 // without a hole at the start since it knows the alignment of the stack
111 // at the start of local allocation, and this pass doesn't.
Jim Grosbach2d16f5b2010-08-20 16:48:30 +0000112 MFI->setUseLocalStackAllocationBlock(UsedBaseRegs);
Jim Grosbacha0fc0052010-08-19 02:47:08 +0000113
Jim Grosbach3d723672010-08-14 00:15:52 +0000114 return true;
115}
116
117/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000118void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo *MFI,
119 int FrameIdx, int64_t &Offset,
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000120 bool StackGrowsDown,
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000121 unsigned &MaxAlign) {
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000122 // If the stack grows down, add the object size to find the lowest address.
123 if (StackGrowsDown)
124 Offset += MFI->getObjectSize(FrameIdx);
125
Jim Grosbach3d723672010-08-14 00:15:52 +0000126 unsigned Align = MFI->getObjectAlignment(FrameIdx);
127
128 // If the alignment of this object is greater than that of the stack, then
129 // increase the stack alignment to match.
130 MaxAlign = std::max(MaxAlign, Align);
131
132 // Adjust to alignment boundary.
133 Offset = (Offset + Align - 1) / Align * Align;
134
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000135 int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
Jim Grosbach3d723672010-08-14 00:15:52 +0000136 DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000137 << LocalOffset << "\n");
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000138 // Keep the offset available for base register allocation
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000139 LocalOffsets[FrameIdx] = LocalOffset;
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000140 // And tell MFI about it for PEI to use later
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000141 MFI->mapLocalFrameObject(FrameIdx, LocalOffset);
142
143 if (!StackGrowsDown)
144 Offset += MFI->getObjectSize(FrameIdx);
Jim Grosbach3d723672010-08-14 00:15:52 +0000145
146 ++NumAllocations;
147}
148
149/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
150/// abstract stack objects.
151///
152void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
Jim Grosbach3d723672010-08-14 00:15:52 +0000153 // Loop over all of the stack objects, assigning sequential addresses...
154 MachineFrameInfo *MFI = Fn.getFrameInfo();
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000155 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000156 bool StackGrowsDown =
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000157 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
Jim Grosbach3d723672010-08-14 00:15:52 +0000158 int64_t Offset = 0;
Jim Grosbach4861ed62010-08-16 22:30:41 +0000159 unsigned MaxAlign = 0;
Jim Grosbach3d723672010-08-14 00:15:52 +0000160
161 // Make sure that the stack protector comes before the local variables on the
162 // stack.
163 SmallSet<int, 16> LargeStackObjs;
164 if (MFI->getStackProtectorIndex() >= 0) {
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000165 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), Offset,
166 StackGrowsDown, MaxAlign);
Jim Grosbach3d723672010-08-14 00:15:52 +0000167
168 // Assign large stack objects first.
169 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
170 if (MFI->isDeadObjectIndex(i))
171 continue;
172 if (MFI->getStackProtectorIndex() == (int)i)
173 continue;
174 if (!MFI->MayNeedStackProtector(i))
175 continue;
176
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000177 AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
Jim Grosbach3d723672010-08-14 00:15:52 +0000178 LargeStackObjs.insert(i);
179 }
180 }
181
182 // Then assign frame offsets to stack objects that are not used to spill
183 // callee saved registers.
184 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
185 if (MFI->isDeadObjectIndex(i))
186 continue;
187 if (MFI->getStackProtectorIndex() == (int)i)
188 continue;
189 if (LargeStackObjs.count(i))
190 continue;
191
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000192 AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
Jim Grosbach3d723672010-08-14 00:15:52 +0000193 }
194
Jim Grosbach3d723672010-08-14 00:15:52 +0000195 // Remember how big this blob of stack space is
Jim Grosbach63249342010-08-16 18:06:15 +0000196 MFI->setLocalFrameSize(Offset);
Jim Grosbach4861ed62010-08-16 22:30:41 +0000197 MFI->setLocalFrameMaxAlign(MaxAlign);
Jim Grosbach3d723672010-08-14 00:15:52 +0000198}
Jim Grosbach8708ead2010-08-17 18:13:53 +0000199
Jim Grosbach74d803a2010-08-18 17:57:37 +0000200static inline bool
201lookupCandidateBaseReg(const SmallVector<std::pair<unsigned, int64_t>, 8> &Regs,
202 std::pair<unsigned, int64_t> &RegOffset,
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000203 int64_t FrameSizeAdjust,
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000204 int64_t LocalFrameOffset,
Jim Grosbach74d803a2010-08-18 17:57:37 +0000205 const MachineInstr *MI,
206 const TargetRegisterInfo *TRI) {
207 unsigned e = Regs.size();
208 for (unsigned i = 0; i < e; ++i) {
209 RegOffset = Regs[i];
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000210 // Check if the relative offset from the where the base register references
211 // to the target address is in range for the instruction.
Jim Grosbach67ff81a2010-08-23 20:40:38 +0000212 int64_t Offset = FrameSizeAdjust + LocalFrameOffset - RegOffset.second;
Jim Grosbache2f55692010-08-19 23:52:25 +0000213 if (TRI->isFrameOffsetLegal(MI, Offset))
Jim Grosbach74d803a2010-08-18 17:57:37 +0000214 return true;
215 }
216 return false;
217}
218
Jim Grosbach2d16f5b2010-08-20 16:48:30 +0000219bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
Jim Grosbach8708ead2010-08-17 18:13:53 +0000220 // Scan the function's instructions looking for frame index references.
221 // For each, ask the target if it wants a virtual base register for it
222 // based on what we can tell it about where the local will end up in the
223 // stack frame. If it wants one, re-use a suitable one we've previously
224 // allocated, or if there isn't one that fits the bill, allocate a new one
225 // and ask the target to create a defining instruction for it.
Jim Grosbach2d16f5b2010-08-20 16:48:30 +0000226 bool UsedBaseReg = false;
Jim Grosbach8708ead2010-08-17 18:13:53 +0000227
228 MachineFrameInfo *MFI = Fn.getFrameInfo();
229 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000230 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
Jim Grosbach4c207c22010-08-20 20:25:31 +0000231 bool StackGrowsDown =
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000232 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
Jim Grosbach8708ead2010-08-17 18:13:53 +0000233
Jim Grosbach864d22e2010-08-31 17:58:19 +0000234 // Collect all of the instructions in the block that reference
235 // a frame index. Also store the frame index referenced to ease later
236 // lookup. (For any insn that has more than one FI reference, we arbitrarily
237 // choose the first one).
238 SmallVector<FrameRef, 64> FrameReferenceInsns;
Jim Grosbach2b1e2022010-08-18 22:44:49 +0000239
Bill Wendling976ef862010-12-17 23:09:14 +0000240 // A base register definition is a register + offset pair.
241 SmallVector<std::pair<unsigned, int64_t>, 8> BaseRegisters;
Jim Grosbach864d22e2010-08-31 17:58:19 +0000242
243 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Jim Grosbach8708ead2010-08-17 18:13:53 +0000244 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
245 MachineInstr *MI = I;
Bill Wendling976ef862010-12-17 23:09:14 +0000246
Jim Grosbachdc140c62010-08-17 22:41:55 +0000247 // Debug value instructions can't be out of range, so they don't need
248 // any updates.
Jim Grosbachdc140c62010-08-17 22:41:55 +0000249 if (MI->isDebugValue())
250 continue;
Bill Wendling976ef862010-12-17 23:09:14 +0000251
Jim Grosbach8708ead2010-08-17 18:13:53 +0000252 // For now, allocate the base register(s) within the basic block
253 // where they're used, and don't try to keep them around outside
254 // of that. It may be beneficial to try sharing them more broadly
255 // than that, but the increased register pressure makes that a
256 // tricky thing to balance. Investigate if re-materializing these
257 // becomes an issue.
258 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
259 // Consider replacing all frame index operands that reference
260 // an object allocated in the local block.
Jim Grosbachdc140c62010-08-17 22:41:55 +0000261 if (MI->getOperand(i).isFI()) {
Jim Grosbachdc140c62010-08-17 22:41:55 +0000262 // Don't try this with values not in the local block.
Jim Grosbach864d22e2010-08-31 17:58:19 +0000263 if (!MFI->isObjectPreAllocated(MI->getOperand(i).getIndex()))
264 break;
265 FrameReferenceInsns.
266 push_back(FrameRef(MI, LocalOffsets[MI->getOperand(i).getIndex()]));
267 break;
268 }
269 }
270 }
271 }
Bill Wendling976ef862010-12-17 23:09:14 +0000272
Jim Grosbach864d22e2010-08-31 17:58:19 +0000273 // Sort the frame references by local offset
274 array_pod_sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
Jim Grosbachdc140c62010-08-17 22:41:55 +0000275
Bill Wendling976ef862010-12-17 23:09:14 +0000276 MachineBasicBlock *Entry = Fn.begin();
Jim Grosbach74d803a2010-08-18 17:57:37 +0000277
Bill Wendling976ef862010-12-17 23:09:14 +0000278 // Loop through the frame references and allocate for them as necessary.
Jim Grosbach864d22e2010-08-31 17:58:19 +0000279 for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
280 MachineBasicBlock::iterator I =
281 FrameReferenceInsns[ref].getMachineInstr();
282 MachineInstr *MI = I;
283 for (unsigned idx = 0, e = MI->getNumOperands(); idx != e; ++idx) {
284 // Consider replacing all frame index operands that reference
285 // an object allocated in the local block.
286 if (MI->getOperand(idx).isFI()) {
287 int FrameIdx = MI->getOperand(idx).getIndex();
Jim Grosbach8708ead2010-08-17 18:13:53 +0000288
Jim Grosbach864d22e2010-08-31 17:58:19 +0000289 assert(MFI->isObjectPreAllocated(FrameIdx) &&
290 "Only pre-allocated locals expected!");
Jim Grosbachdc140c62010-08-17 22:41:55 +0000291
Jim Grosbach864d22e2010-08-31 17:58:19 +0000292 DEBUG(dbgs() << "Considering: " << *MI);
293 if (TRI->needsFrameBaseReg(MI, LocalOffsets[FrameIdx])) {
294 unsigned BaseReg = 0;
295 int64_t Offset = 0;
296 int64_t FrameSizeAdjust =
297 StackGrowsDown ? MFI->getLocalFrameSize() : 0;
Jim Grosbach74d803a2010-08-18 17:57:37 +0000298
Jim Grosbach864d22e2010-08-31 17:58:19 +0000299 DEBUG(dbgs() << " Replacing FI in: " << *MI);
Jim Grosbache2f55692010-08-19 23:52:25 +0000300
Jim Grosbach864d22e2010-08-31 17:58:19 +0000301 // If we have a suitable base register available, use it; otherwise
302 // create a new one. Note that any offset encoded in the
303 // instruction itself will be taken into account by the target,
304 // so we don't have to adjust for it here when reusing a base
305 // register.
306 std::pair<unsigned, int64_t> RegOffset;
307 if (lookupCandidateBaseReg(BaseRegisters, RegOffset,
308 FrameSizeAdjust,
309 LocalOffsets[FrameIdx],
310 MI, TRI)) {
311 DEBUG(dbgs() << " Reusing base register " <<
312 RegOffset.first << "\n");
313 // We found a register to reuse.
314 BaseReg = RegOffset.first;
315 Offset = FrameSizeAdjust + LocalOffsets[FrameIdx] -
316 RegOffset.second;
317 } else {
318 // No previously defined register was in range, so create a
319 // new one.
320 int64_t InstrOffset = TRI->getFrameIndexInstrOffset(MI, idx);
321 const TargetRegisterClass *RC = TRI->getPointerRegClass();
322 BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
Jim Grosbachdc140c62010-08-17 22:41:55 +0000323
Jim Grosbach864d22e2010-08-31 17:58:19 +0000324 DEBUG(dbgs() << " Materializing base register " << BaseReg <<
325 " at frame local offset " <<
326 LocalOffsets[FrameIdx] + InstrOffset << "\n");
Bill Wendling976ef862010-12-17 23:09:14 +0000327
Jim Grosbach864d22e2010-08-31 17:58:19 +0000328 // Tell the target to insert the instruction to initialize
329 // the base register.
Bill Wendling976ef862010-12-17 23:09:14 +0000330 // MachineBasicBlock::iterator InsertionPt = Entry->begin();
331 TRI->materializeFrameBaseRegister(Entry, BaseReg, FrameIdx,
332 InstrOffset);
Jim Grosbachdc140c62010-08-17 22:41:55 +0000333
Jim Grosbach864d22e2010-08-31 17:58:19 +0000334 // The base register already includes any offset specified
335 // by the instruction, so account for that so it doesn't get
336 // applied twice.
337 Offset = -InstrOffset;
338
339 int64_t BaseOffset = FrameSizeAdjust + LocalOffsets[FrameIdx] +
340 InstrOffset;
341 BaseRegisters.push_back(
342 std::pair<unsigned, int64_t>(BaseReg, BaseOffset));
343 ++NumBaseRegisters;
344 UsedBaseReg = true;
Jim Grosbach8708ead2010-08-17 18:13:53 +0000345 }
Jim Grosbach864d22e2010-08-31 17:58:19 +0000346 assert(BaseReg != 0 && "Unable to allocate virtual base register!");
347
348 // Modify the instruction to use the new base register rather
349 // than the frame index operand.
350 TRI->resolveFrameIndex(I, BaseReg, Offset);
351 DEBUG(dbgs() << "Resolved: " << *MI);
352
353 ++NumReplacements;
Jim Grosbach8708ead2010-08-17 18:13:53 +0000354 }
355 }
356 }
357 }
Jim Grosbach2d16f5b2010-08-20 16:48:30 +0000358 return UsedBaseReg;
Jim Grosbach8708ead2010-08-17 18:13:53 +0000359}