1 //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
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 pass assigns local frame indices to stack slots relative to one another
10 // and allocates additional base registers to access them when the target
11 // estimates they are likely to be out of range of stack pointer and frame
12 // pointer relative addressing.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetFrameLowering.h"
28 #include "llvm/CodeGen/TargetOpcodes.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 #include <tuple>
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "localstackalloc"
44 
45 STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
46 STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
47 STATISTIC(NumReplacements, "Number of frame indices references replaced");
48 
49 namespace {
50 
51   class FrameRef {
52     MachineBasicBlock::iterator MI; // Instr referencing the frame
53     int64_t LocalOffset;            // Local offset of the frame idx referenced
54     int FrameIdx;                   // The frame index
55 
56     // Order reference instruction appears in program. Used to ensure
57     // deterministic order when multiple instructions may reference the same
58     // location.
59     unsigned Order;
60 
61   public:
62     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
63       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
64 
65     bool operator<(const FrameRef &RHS) const {
66       return std::tie(LocalOffset, FrameIdx, Order) <
67              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
68     }
69 
70     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
71     int64_t getLocalOffset() const { return LocalOffset; }
72     int getFrameIndex() const { return FrameIdx; }
73   };
74 
75   class LocalStackSlotPass: public MachineFunctionPass {
76     SmallVector<int64_t, 16> LocalOffsets;
77 
78     /// StackObjSet - A set of stack object indexes
79     using StackObjSet = SmallSetVector<int, 8>;
80 
81     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
82                            bool StackGrowsDown, Align &MaxAlign);
83     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
84                                SmallSet<int, 16> &ProtectedObjs,
85                                MachineFrameInfo &MFI, bool StackGrowsDown,
86                                int64_t &Offset, Align &MaxAlign);
87     void calculateFrameObjectOffsets(MachineFunction &Fn);
88     bool insertFrameReferenceRegisters(MachineFunction &Fn);
89 
90   public:
91     static char ID; // Pass identification, replacement for typeid
92 
93     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
94       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
95     }
96 
97     bool runOnMachineFunction(MachineFunction &MF) override;
98 
99     void getAnalysisUsage(AnalysisUsage &AU) const override {
100       AU.setPreservesCFG();
101       MachineFunctionPass::getAnalysisUsage(AU);
102     }
103   };
104 
105 } // end anonymous namespace
106 
107 char LocalStackSlotPass::ID = 0;
108 
109 char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
110 INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
111                 "Local Stack Slot Allocation", false, false)
112 
113 bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
114   MachineFrameInfo &MFI = MF.getFrameInfo();
115   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
116   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
117 
118   // If the target doesn't want/need this pass, or if there are no locals
119   // to consider, early exit.
120   if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
121     return true;
122 
123   // Make sure we have enough space to store the local offsets.
124   LocalOffsets.resize(MFI.getObjectIndexEnd());
125 
126   // Lay out the local blob.
127   calculateFrameObjectOffsets(MF);
128 
129   // Insert virtual base registers to resolve frame index references.
130   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
131 
132   // Tell MFI whether any base registers were allocated. PEI will only
133   // want to use the local block allocations from this pass if there were any.
134   // Otherwise, PEI can do a bit better job of getting the alignment right
135   // without a hole at the start since it knows the alignment of the stack
136   // at the start of local allocation, and this pass doesn't.
137   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
138 
139   return true;
140 }
141 
142 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
143 void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
144                                            int64_t &Offset, bool StackGrowsDown,
145                                            Align &MaxAlign) {
146   // If the stack grows down, add the object size to find the lowest address.
147   if (StackGrowsDown)
148     Offset += MFI.getObjectSize(FrameIdx);
149 
150   Align Alignment = MFI.getObjectAlign(FrameIdx);
151 
152   // If the alignment of this object is greater than that of the stack, then
153   // increase the stack alignment to match.
154   MaxAlign = std::max(MaxAlign, Alignment);
155 
156   // Adjust to alignment boundary.
157   Offset = alignTo(Offset, Alignment);
158 
159   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
160   LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
161                     << LocalOffset << "\n");
162   // Keep the offset available for base register allocation
163   LocalOffsets[FrameIdx] = LocalOffset;
164   // And tell MFI about it for PEI to use later
165   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
166 
167   if (!StackGrowsDown)
168     Offset += MFI.getObjectSize(FrameIdx);
169 
170   ++NumAllocations;
171 }
172 
173 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
174 /// those required to be close to the Stack Protector) to stack offsets.
175 void LocalStackSlotPass::AssignProtectedObjSet(
176     const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
177     MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
178     Align &MaxAlign) {
179   for (int i : UnassignedObjs) {
180     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
181     ProtectedObjs.insert(i);
182   }
183 }
184 
185 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
186 /// abstract stack objects.
187 void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
188   // Loop over all of the stack objects, assigning sequential addresses...
189   MachineFrameInfo &MFI = Fn.getFrameInfo();
190   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
191   bool StackGrowsDown =
192     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
193   int64_t Offset = 0;
194   Align MaxAlign;
195 
196   // Make sure that the stack protector comes before the local variables on the
197   // stack.
198   SmallSet<int, 16> ProtectedObjs;
199   if (MFI.hasStackProtectorIndex()) {
200     int StackProtectorFI = MFI.getStackProtectorIndex();
201 
202     // We need to make sure we didn't pre-allocate the stack protector when
203     // doing this.
204     // If we already have a stack protector, this will re-assign it to a slot
205     // that is **not** covering the protected objects.
206     assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
207            "Stack protector pre-allocated in LocalStackSlotAllocation");
208 
209     StackObjSet LargeArrayObjs;
210     StackObjSet SmallArrayObjs;
211     StackObjSet AddrOfObjs;
212 
213     // Only place the stack protector in the local stack area if the target
214     // allows it.
215     if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
216       AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
217                         MaxAlign);
218 
219     // Assign large stack objects first.
220     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
221       if (MFI.isDeadObjectIndex(i))
222         continue;
223       if (StackProtectorFI == (int)i)
224         continue;
225       if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
226         continue;
227 
228       switch (MFI.getObjectSSPLayout(i)) {
229       case MachineFrameInfo::SSPLK_None:
230         continue;
231       case MachineFrameInfo::SSPLK_SmallArray:
232         SmallArrayObjs.insert(i);
233         continue;
234       case MachineFrameInfo::SSPLK_AddrOf:
235         AddrOfObjs.insert(i);
236         continue;
237       case MachineFrameInfo::SSPLK_LargeArray:
238         LargeArrayObjs.insert(i);
239         continue;
240       }
241       llvm_unreachable("Unexpected SSPLayoutKind.");
242     }
243 
244     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
245                           Offset, MaxAlign);
246     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
247                           Offset, MaxAlign);
248     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
249                           Offset, MaxAlign);
250   }
251 
252   // Then assign frame offsets to stack objects that are not used to spill
253   // callee saved registers.
254   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
255     if (MFI.isDeadObjectIndex(i))
256       continue;
257     if (MFI.getStackProtectorIndex() == (int)i)
258       continue;
259     if (ProtectedObjs.count(i))
260       continue;
261     if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
262       continue;
263 
264     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
265   }
266 
267   // Remember how big this blob of stack space is
268   MFI.setLocalFrameSize(Offset);
269   MFI.setLocalFrameMaxAlign(MaxAlign);
270 }
271 
272 static inline bool
273 lookupCandidateBaseReg(unsigned BaseReg,
274                        int64_t BaseOffset,
275                        int64_t FrameSizeAdjust,
276                        int64_t LocalFrameOffset,
277                        const MachineInstr &MI,
278                        const TargetRegisterInfo *TRI) {
279   // Check if the relative offset from the where the base register references
280   // to the target address is in range for the instruction.
281   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
282   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
283 }
284 
285 bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
286   // Scan the function's instructions looking for frame index references.
287   // For each, ask the target if it wants a virtual base register for it
288   // based on what we can tell it about where the local will end up in the
289   // stack frame. If it wants one, re-use a suitable one we've previously
290   // allocated, or if there isn't one that fits the bill, allocate a new one
291   // and ask the target to create a defining instruction for it.
292   bool UsedBaseReg = false;
293 
294   MachineFrameInfo &MFI = Fn.getFrameInfo();
295   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
296   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
297   bool StackGrowsDown =
298     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
299 
300   // Collect all of the instructions in the block that reference
301   // a frame index. Also store the frame index referenced to ease later
302   // lookup. (For any insn that has more than one FI reference, we arbitrarily
303   // choose the first one).
304   SmallVector<FrameRef, 64> FrameReferenceInsns;
305 
306   unsigned Order = 0;
307 
308   for (MachineBasicBlock &BB : Fn) {
309     for (MachineInstr &MI : BB) {
310       // Debug value, stackmap and patchpoint instructions can't be out of
311       // range, so they don't need any updates.
312       if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
313           MI.getOpcode() == TargetOpcode::STACKMAP ||
314           MI.getOpcode() == TargetOpcode::PATCHPOINT)
315         continue;
316 
317       // For now, allocate the base register(s) within the basic block
318       // where they're used, and don't try to keep them around outside
319       // of that. It may be beneficial to try sharing them more broadly
320       // than that, but the increased register pressure makes that a
321       // tricky thing to balance. Investigate if re-materializing these
322       // becomes an issue.
323       for (const MachineOperand &MO : MI.operands()) {
324         // Consider replacing all frame index operands that reference
325         // an object allocated in the local block.
326         if (MO.isFI()) {
327           // Don't try this with values not in the local block.
328           if (!MFI.isObjectPreAllocated(MO.getIndex()))
329             break;
330           int Idx = MO.getIndex();
331           int64_t LocalOffset = LocalOffsets[Idx];
332           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
333             break;
334           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
335           break;
336         }
337       }
338     }
339   }
340 
341   // Sort the frame references by local offset.
342   // Use frame index as a tie-breaker in case MI's have the same offset.
343   llvm::sort(FrameReferenceInsns);
344 
345   MachineBasicBlock *Entry = &Fn.front();
346 
347   unsigned BaseReg = 0;
348   int64_t BaseOffset = 0;
349 
350   // Loop through the frame references and allocate for them as necessary.
351   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
352     FrameRef &FR = FrameReferenceInsns[ref];
353     MachineInstr &MI = *FR.getMachineInstr();
354     int64_t LocalOffset = FR.getLocalOffset();
355     int FrameIdx = FR.getFrameIndex();
356     assert(MFI.isObjectPreAllocated(FrameIdx) &&
357            "Only pre-allocated locals expected!");
358 
359     // We need to keep the references to the stack protector slot through frame
360     // index operands so that it gets resolved by PEI rather than this pass.
361     // This avoids accesses to the stack protector though virtual base
362     // registers, and forces PEI to address it using fp/sp/bp.
363     if (MFI.hasStackProtectorIndex() &&
364         FrameIdx == MFI.getStackProtectorIndex())
365       continue;
366 
367     LLVM_DEBUG(dbgs() << "Considering: " << MI);
368 
369     unsigned idx = 0;
370     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
371       if (!MI.getOperand(idx).isFI())
372         continue;
373 
374       if (FrameIdx == MI.getOperand(idx).getIndex())
375         break;
376     }
377 
378     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
379 
380     int64_t Offset = 0;
381     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
382 
383     LLVM_DEBUG(dbgs() << "  Replacing FI in: " << MI);
384 
385     // If we have a suitable base register available, use it; otherwise
386     // create a new one. Note that any offset encoded in the
387     // instruction itself will be taken into account by the target,
388     // so we don't have to adjust for it here when reusing a base
389     // register.
390     if (UsedBaseReg &&
391         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
392                                LocalOffset, MI, TRI)) {
393       LLVM_DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
394       // We found a register to reuse.
395       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
396     } else {
397       // No previously defined register was in range, so create a new one.
398       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
399 
400       int64_t PrevBaseOffset = BaseOffset;
401       BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
402 
403       // We'd like to avoid creating single-use virtual base registers.
404       // Because the FrameRefs are in sorted order, and we've already
405       // processed all FrameRefs before this one, just check whether or not
406       // the next FrameRef will be able to reuse this new register. If not,
407       // then don't bother creating it.
408       if (ref + 1 >= e ||
409           !lookupCandidateBaseReg(
410               BaseReg, BaseOffset, FrameSizeAdjust,
411               FrameReferenceInsns[ref + 1].getLocalOffset(),
412               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
413         BaseOffset = PrevBaseOffset;
414         continue;
415       }
416 
417       const MachineFunction *MF = MI.getMF();
418       const TargetRegisterClass *RC = TRI->getPointerRegClass(*MF);
419       BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
420 
421       LLVM_DEBUG(dbgs() << "  Materializing base register"
422                         << " at frame local offset "
423                         << LocalOffset + InstrOffset);
424 
425       // Tell the target to insert the instruction to initialize
426       // the base register.
427       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
428       BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
429 
430       LLVM_DEBUG(dbgs() << " into " << printReg(BaseReg, TRI) << '\n');
431 
432       // The base register already includes any offset specified
433       // by the instruction, so account for that so it doesn't get
434       // applied twice.
435       Offset = -InstrOffset;
436 
437       ++NumBaseRegisters;
438       UsedBaseReg = true;
439     }
440     assert(BaseReg != 0 && "Unable to allocate virtual base register!");
441 
442     // Modify the instruction to use the new base register rather
443     // than the frame index operand.
444     TRI->resolveFrameIndex(MI, BaseReg, Offset);
445     LLVM_DEBUG(dbgs() << "Resolved: " << MI);
446 
447     ++NumReplacements;
448   }
449 
450   return UsedBaseReg;
451 }
452