1e580952dSDimitry Andric //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
2e580952dSDimitry Andric //
3e580952dSDimitry Andric //                     The LLVM Compiler Infrastructure
4e580952dSDimitry Andric //
5e580952dSDimitry Andric // This file is distributed under the University of Illinois Open Source
6e580952dSDimitry Andric // License. See LICENSE.TXT for details.
7e580952dSDimitry Andric //
8e580952dSDimitry Andric //===----------------------------------------------------------------------===//
9e580952dSDimitry Andric //
10e580952dSDimitry Andric // This pass assigns local frame indices to stack slots relative to one another
11e580952dSDimitry Andric // and allocates additional base registers to access them when the target
122754fe60SDimitry Andric // estimates they are likely to be out of range of stack pointer and frame
13e580952dSDimitry Andric // pointer relative addressing.
14e580952dSDimitry Andric //
15e580952dSDimitry Andric //===----------------------------------------------------------------------===//
16e580952dSDimitry Andric 
17139f7f9bSDimitry Andric #include "llvm/CodeGen/Passes.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
1991bc56edSDimitry Andric #include "llvm/ADT/SetVector.h"
20e580952dSDimitry Andric #include "llvm/ADT/SmallSet.h"
21e580952dSDimitry Andric #include "llvm/ADT/Statistic.h"
22e580952dSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
23e580952dSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
24e580952dSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
25e580952dSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
2691bc56edSDimitry Andric #include "llvm/CodeGen/StackProtector.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
28139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
30139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
31139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
32139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
33139f7f9bSDimitry Andric #include "llvm/Pass.h"
34e580952dSDimitry Andric #include "llvm/Support/Debug.h"
35e580952dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
36e580952dSDimitry Andric #include "llvm/Support/raw_ostream.h"
372754fe60SDimitry Andric #include "llvm/Target/TargetFrameLowering.h"
38139f7f9bSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
3939d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
40e580952dSDimitry Andric 
41e580952dSDimitry Andric using namespace llvm;
42e580952dSDimitry Andric 
4391bc56edSDimitry Andric #define DEBUG_TYPE "localstackalloc"
4491bc56edSDimitry Andric 
45e580952dSDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
46e580952dSDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
47e580952dSDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
48e580952dSDimitry Andric 
49e580952dSDimitry Andric namespace {
50e580952dSDimitry Andric   class FrameRef {
51e580952dSDimitry Andric     MachineBasicBlock::iterator MI; // Instr referencing the frame
52e580952dSDimitry Andric     int64_t LocalOffset;            // Local offset of the frame idx referenced
53284c1978SDimitry Andric     int FrameIdx;                   // The frame index
54d88c1a5aSDimitry Andric 
55d88c1a5aSDimitry Andric     // Order reference instruction appears in program. Used to ensure
56d88c1a5aSDimitry Andric     // deterministic order when multiple instructions may reference the same
57d88c1a5aSDimitry Andric     // location.
58d88c1a5aSDimitry Andric     unsigned Order;
59d88c1a5aSDimitry Andric 
60e580952dSDimitry Andric   public:
61d88c1a5aSDimitry Andric     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
62d88c1a5aSDimitry Andric       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
63d88c1a5aSDimitry Andric 
64e580952dSDimitry Andric     bool operator<(const FrameRef &RHS) const {
65d88c1a5aSDimitry Andric       return std::tie(LocalOffset, FrameIdx, Order) <
66d88c1a5aSDimitry Andric              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
67e580952dSDimitry Andric     }
68d88c1a5aSDimitry Andric 
69284c1978SDimitry Andric     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
70284c1978SDimitry Andric     int64_t getLocalOffset() const { return LocalOffset; }
71284c1978SDimitry Andric     int getFrameIndex() const { return FrameIdx; }
72e580952dSDimitry Andric   };
73e580952dSDimitry Andric 
74e580952dSDimitry Andric   class LocalStackSlotPass: public MachineFunctionPass {
75e580952dSDimitry Andric     SmallVector<int64_t,16> LocalOffsets;
7691bc56edSDimitry Andric     /// StackObjSet - A set of stack object indexes
7791bc56edSDimitry Andric     typedef SmallSetVector<int, 8> StackObjSet;
78e580952dSDimitry Andric 
79d88c1a5aSDimitry Andric     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
80e580952dSDimitry Andric                            bool StackGrowsDown, unsigned &MaxAlign);
8191bc56edSDimitry Andric     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
8291bc56edSDimitry Andric                                SmallSet<int, 16> &ProtectedObjs,
83d88c1a5aSDimitry Andric                                MachineFrameInfo &MFI, bool StackGrowsDown,
8491bc56edSDimitry Andric                                int64_t &Offset, unsigned &MaxAlign);
85e580952dSDimitry Andric     void calculateFrameObjectOffsets(MachineFunction &Fn);
86e580952dSDimitry Andric     bool insertFrameReferenceRegisters(MachineFunction &Fn);
87e580952dSDimitry Andric   public:
88e580952dSDimitry Andric     static char ID; // Pass identification, replacement for typeid
8991bc56edSDimitry Andric     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
9091bc56edSDimitry Andric       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
9191bc56edSDimitry Andric     }
9291bc56edSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
93e580952dSDimitry Andric 
9491bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
95e580952dSDimitry Andric       AU.setPreservesCFG();
9691bc56edSDimitry Andric       AU.addRequired<StackProtector>();
97e580952dSDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
98e580952dSDimitry Andric     }
99e580952dSDimitry Andric 
100e580952dSDimitry Andric   private:
101e580952dSDimitry Andric   };
102e580952dSDimitry Andric } // end anonymous namespace
103e580952dSDimitry Andric 
104e580952dSDimitry Andric char LocalStackSlotPass::ID = 0;
105dff0c46cSDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
106302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(LocalStackSlotPass, DEBUG_TYPE,
107dff0c46cSDimitry Andric                       "Local Stack Slot Allocation", false, false)
10891bc56edSDimitry Andric INITIALIZE_PASS_DEPENDENCY(StackProtector)
109302affcbSDimitry Andric INITIALIZE_PASS_END(LocalStackSlotPass, DEBUG_TYPE,
11091bc56edSDimitry Andric                     "Local Stack Slot Allocation", false, false)
11191bc56edSDimitry Andric 
112e580952dSDimitry Andric 
113e580952dSDimitry Andric bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
114d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
11539d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
116d88c1a5aSDimitry Andric   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
117e580952dSDimitry Andric 
118e580952dSDimitry Andric   // If the target doesn't want/need this pass, or if there are no locals
119e580952dSDimitry Andric   // to consider, early exit.
120e580952dSDimitry Andric   if (!TRI->requiresVirtualBaseRegisters(MF) || LocalObjectCount == 0)
121e580952dSDimitry Andric     return true;
122e580952dSDimitry Andric 
123e580952dSDimitry Andric   // Make sure we have enough space to store the local offsets.
124d88c1a5aSDimitry Andric   LocalOffsets.resize(MFI.getObjectIndexEnd());
125e580952dSDimitry Andric 
126e580952dSDimitry Andric   // Lay out the local blob.
127e580952dSDimitry Andric   calculateFrameObjectOffsets(MF);
128e580952dSDimitry Andric 
129e580952dSDimitry Andric   // Insert virtual base registers to resolve frame index references.
130e580952dSDimitry Andric   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
131e580952dSDimitry Andric 
132e580952dSDimitry Andric   // Tell MFI whether any base registers were allocated. PEI will only
133e580952dSDimitry Andric   // want to use the local block allocations from this pass if there were any.
134e580952dSDimitry Andric   // Otherwise, PEI can do a bit better job of getting the alignment right
135e580952dSDimitry Andric   // without a hole at the start since it knows the alignment of the stack
136e580952dSDimitry Andric   // at the start of local allocation, and this pass doesn't.
137d88c1a5aSDimitry Andric   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
138e580952dSDimitry Andric 
139e580952dSDimitry Andric   return true;
140e580952dSDimitry Andric }
141e580952dSDimitry Andric 
142e580952dSDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
143d88c1a5aSDimitry Andric void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI,
144e580952dSDimitry Andric                                            int FrameIdx, int64_t &Offset,
145e580952dSDimitry Andric                                            bool StackGrowsDown,
146e580952dSDimitry Andric                                            unsigned &MaxAlign) {
147e580952dSDimitry Andric   // If the stack grows down, add the object size to find the lowest address.
148e580952dSDimitry Andric   if (StackGrowsDown)
149d88c1a5aSDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
150e580952dSDimitry Andric 
151d88c1a5aSDimitry Andric   unsigned Align = MFI.getObjectAlignment(FrameIdx);
152e580952dSDimitry Andric 
153e580952dSDimitry Andric   // If the alignment of this object is greater than that of the stack, then
154e580952dSDimitry Andric   // increase the stack alignment to match.
155e580952dSDimitry Andric   MaxAlign = std::max(MaxAlign, Align);
156e580952dSDimitry Andric 
157e580952dSDimitry Andric   // Adjust to alignment boundary.
158e580952dSDimitry Andric   Offset = (Offset + Align - 1) / Align * Align;
159e580952dSDimitry Andric 
160e580952dSDimitry Andric   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
161e580952dSDimitry Andric   DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
162e580952dSDimitry Andric         << LocalOffset << "\n");
163e580952dSDimitry Andric   // Keep the offset available for base register allocation
164e580952dSDimitry Andric   LocalOffsets[FrameIdx] = LocalOffset;
165e580952dSDimitry Andric   // And tell MFI about it for PEI to use later
166d88c1a5aSDimitry Andric   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
167e580952dSDimitry Andric 
168e580952dSDimitry Andric   if (!StackGrowsDown)
169d88c1a5aSDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
170e580952dSDimitry Andric 
171e580952dSDimitry Andric   ++NumAllocations;
172e580952dSDimitry Andric }
173e580952dSDimitry Andric 
17491bc56edSDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
17591bc56edSDimitry Andric /// those required to be close to the Stack Protector) to stack offsets.
17691bc56edSDimitry Andric void LocalStackSlotPass::AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
17791bc56edSDimitry Andric                                            SmallSet<int, 16> &ProtectedObjs,
178d88c1a5aSDimitry Andric                                            MachineFrameInfo &MFI,
17991bc56edSDimitry Andric                                            bool StackGrowsDown, int64_t &Offset,
18091bc56edSDimitry Andric                                            unsigned &MaxAlign) {
18191bc56edSDimitry Andric 
18291bc56edSDimitry Andric   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
18391bc56edSDimitry Andric         E = UnassignedObjs.end(); I != E; ++I) {
18491bc56edSDimitry Andric     int i = *I;
18591bc56edSDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
18691bc56edSDimitry Andric     ProtectedObjs.insert(i);
18791bc56edSDimitry Andric   }
18891bc56edSDimitry Andric }
18991bc56edSDimitry Andric 
190e580952dSDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
191e580952dSDimitry Andric /// abstract stack objects.
192e580952dSDimitry Andric ///
193e580952dSDimitry Andric void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
194e580952dSDimitry Andric   // Loop over all of the stack objects, assigning sequential addresses...
195d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
19639d628a0SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
197e580952dSDimitry Andric   bool StackGrowsDown =
1982754fe60SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
199e580952dSDimitry Andric   int64_t Offset = 0;
200e580952dSDimitry Andric   unsigned MaxAlign = 0;
20191bc56edSDimitry Andric   StackProtector *SP = &getAnalysis<StackProtector>();
202e580952dSDimitry Andric 
203e580952dSDimitry Andric   // Make sure that the stack protector comes before the local variables on the
204e580952dSDimitry Andric   // stack.
20591bc56edSDimitry Andric   SmallSet<int, 16> ProtectedObjs;
206d88c1a5aSDimitry Andric   if (MFI.getStackProtectorIndex() >= 0) {
20791bc56edSDimitry Andric     StackObjSet LargeArrayObjs;
20891bc56edSDimitry Andric     StackObjSet SmallArrayObjs;
20991bc56edSDimitry Andric     StackObjSet AddrOfObjs;
21091bc56edSDimitry Andric 
211d88c1a5aSDimitry Andric     AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), Offset,
212e580952dSDimitry Andric                       StackGrowsDown, MaxAlign);
213e580952dSDimitry Andric 
214e580952dSDimitry Andric     // Assign large stack objects first.
215d88c1a5aSDimitry Andric     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
216d88c1a5aSDimitry Andric       if (MFI.isDeadObjectIndex(i))
217e580952dSDimitry Andric         continue;
218d88c1a5aSDimitry Andric       if (MFI.getStackProtectorIndex() == (int)i)
219e580952dSDimitry Andric         continue;
220e580952dSDimitry Andric 
221d88c1a5aSDimitry Andric       switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) {
22291bc56edSDimitry Andric       case StackProtector::SSPLK_None:
22391bc56edSDimitry Andric         continue;
22491bc56edSDimitry Andric       case StackProtector::SSPLK_SmallArray:
22591bc56edSDimitry Andric         SmallArrayObjs.insert(i);
22691bc56edSDimitry Andric         continue;
22791bc56edSDimitry Andric       case StackProtector::SSPLK_AddrOf:
22891bc56edSDimitry Andric         AddrOfObjs.insert(i);
22991bc56edSDimitry Andric         continue;
23091bc56edSDimitry Andric       case StackProtector::SSPLK_LargeArray:
23191bc56edSDimitry Andric         LargeArrayObjs.insert(i);
23291bc56edSDimitry Andric         continue;
233e580952dSDimitry Andric       }
23491bc56edSDimitry Andric       llvm_unreachable("Unexpected SSPLayoutKind.");
23591bc56edSDimitry Andric     }
23691bc56edSDimitry Andric 
23791bc56edSDimitry Andric     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
23891bc56edSDimitry Andric                           Offset, MaxAlign);
23991bc56edSDimitry Andric     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
24091bc56edSDimitry Andric                           Offset, MaxAlign);
24191bc56edSDimitry Andric     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
24291bc56edSDimitry Andric                           Offset, MaxAlign);
243e580952dSDimitry Andric   }
244e580952dSDimitry Andric 
245e580952dSDimitry Andric   // Then assign frame offsets to stack objects that are not used to spill
246e580952dSDimitry Andric   // callee saved registers.
247d88c1a5aSDimitry Andric   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
248d88c1a5aSDimitry Andric     if (MFI.isDeadObjectIndex(i))
249e580952dSDimitry Andric       continue;
250d88c1a5aSDimitry Andric     if (MFI.getStackProtectorIndex() == (int)i)
251e580952dSDimitry Andric       continue;
25291bc56edSDimitry Andric     if (ProtectedObjs.count(i))
253e580952dSDimitry Andric       continue;
254e580952dSDimitry Andric 
255e580952dSDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
256e580952dSDimitry Andric   }
257e580952dSDimitry Andric 
258e580952dSDimitry Andric   // Remember how big this blob of stack space is
259d88c1a5aSDimitry Andric   MFI.setLocalFrameSize(Offset);
260d88c1a5aSDimitry Andric   MFI.setLocalFrameMaxAlign(MaxAlign);
261e580952dSDimitry Andric }
262e580952dSDimitry Andric 
263e580952dSDimitry Andric static inline bool
264ff0cc061SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
265ff0cc061SDimitry Andric                        int64_t BaseOffset,
266e580952dSDimitry Andric                        int64_t FrameSizeAdjust,
267e580952dSDimitry Andric                        int64_t LocalFrameOffset,
2683ca95b02SDimitry Andric                        const MachineInstr &MI,
269e580952dSDimitry Andric                        const TargetRegisterInfo *TRI) {
270e580952dSDimitry Andric   // Check if the relative offset from the where the base register references
271e580952dSDimitry Andric   // to the target address is in range for the instruction.
272284c1978SDimitry Andric   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
2733ca95b02SDimitry Andric   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
274e580952dSDimitry Andric }
275e580952dSDimitry Andric 
276e580952dSDimitry Andric bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
277e580952dSDimitry Andric   // Scan the function's instructions looking for frame index references.
278e580952dSDimitry Andric   // For each, ask the target if it wants a virtual base register for it
279e580952dSDimitry Andric   // based on what we can tell it about where the local will end up in the
280e580952dSDimitry Andric   // stack frame. If it wants one, re-use a suitable one we've previously
281e580952dSDimitry Andric   // allocated, or if there isn't one that fits the bill, allocate a new one
282e580952dSDimitry Andric   // and ask the target to create a defining instruction for it.
283e580952dSDimitry Andric   bool UsedBaseReg = false;
284e580952dSDimitry Andric 
285d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
28639d628a0SDimitry Andric   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
28739d628a0SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
288e580952dSDimitry Andric   bool StackGrowsDown =
2892754fe60SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
290e580952dSDimitry Andric 
291e580952dSDimitry Andric   // Collect all of the instructions in the block that reference
292e580952dSDimitry Andric   // a frame index. Also store the frame index referenced to ease later
293e580952dSDimitry Andric   // lookup. (For any insn that has more than one FI reference, we arbitrarily
294e580952dSDimitry Andric   // choose the first one).
295e580952dSDimitry Andric   SmallVector<FrameRef, 64> FrameReferenceInsns;
2962754fe60SDimitry Andric 
297d88c1a5aSDimitry Andric   unsigned Order = 0;
298d88c1a5aSDimitry Andric 
2993ca95b02SDimitry Andric   for (MachineBasicBlock &BB : Fn) {
3003ca95b02SDimitry Andric     for (MachineInstr &MI : BB) {
30191bc56edSDimitry Andric       // Debug value, stackmap and patchpoint instructions can't be out of
30291bc56edSDimitry Andric       // range, so they don't need any updates.
3033ca95b02SDimitry Andric       if (MI.isDebugValue() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
3043ca95b02SDimitry Andric           MI.getOpcode() == TargetOpcode::STACKMAP ||
3053ca95b02SDimitry Andric           MI.getOpcode() == TargetOpcode::PATCHPOINT)
306e580952dSDimitry Andric         continue;
3072754fe60SDimitry Andric 
308e580952dSDimitry Andric       // For now, allocate the base register(s) within the basic block
309e580952dSDimitry Andric       // where they're used, and don't try to keep them around outside
310e580952dSDimitry Andric       // of that. It may be beneficial to try sharing them more broadly
311e580952dSDimitry Andric       // than that, but the increased register pressure makes that a
312e580952dSDimitry Andric       // tricky thing to balance. Investigate if re-materializing these
313e580952dSDimitry Andric       // becomes an issue.
3143ca95b02SDimitry Andric       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
315e580952dSDimitry Andric         // Consider replacing all frame index operands that reference
316e580952dSDimitry Andric         // an object allocated in the local block.
3173ca95b02SDimitry Andric         if (MI.getOperand(i).isFI()) {
318e580952dSDimitry Andric           // Don't try this with values not in the local block.
319d88c1a5aSDimitry Andric           if (!MFI.isObjectPreAllocated(MI.getOperand(i).getIndex()))
320e580952dSDimitry Andric             break;
3213ca95b02SDimitry Andric           int Idx = MI.getOperand(i).getIndex();
322284c1978SDimitry Andric           int64_t LocalOffset = LocalOffsets[Idx];
3233ca95b02SDimitry Andric           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
324284c1978SDimitry Andric             break;
325d88c1a5aSDimitry Andric           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
326e580952dSDimitry Andric           break;
327e580952dSDimitry Andric         }
328e580952dSDimitry Andric       }
329e580952dSDimitry Andric     }
330e580952dSDimitry Andric   }
3312754fe60SDimitry Andric 
332d88c1a5aSDimitry Andric   // Sort the frame references by local offset.
333d88c1a5aSDimitry Andric   // Use frame index as a tie-breaker in case MI's have the same offset.
334d88c1a5aSDimitry Andric   std::sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
335e580952dSDimitry Andric 
3367d523365SDimitry Andric   MachineBasicBlock *Entry = &Fn.front();
337e580952dSDimitry Andric 
338284c1978SDimitry Andric   unsigned BaseReg = 0;
339284c1978SDimitry Andric   int64_t BaseOffset = 0;
340284c1978SDimitry Andric 
3412754fe60SDimitry Andric   // Loop through the frame references and allocate for them as necessary.
342e580952dSDimitry Andric   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
343284c1978SDimitry Andric     FrameRef &FR = FrameReferenceInsns[ref];
3443ca95b02SDimitry Andric     MachineInstr &MI = *FR.getMachineInstr();
345284c1978SDimitry Andric     int64_t LocalOffset = FR.getLocalOffset();
346284c1978SDimitry Andric     int FrameIdx = FR.getFrameIndex();
347d88c1a5aSDimitry Andric     assert(MFI.isObjectPreAllocated(FrameIdx) &&
348e580952dSDimitry Andric            "Only pre-allocated locals expected!");
349e580952dSDimitry Andric 
3503ca95b02SDimitry Andric     DEBUG(dbgs() << "Considering: " << MI);
351284c1978SDimitry Andric 
352284c1978SDimitry Andric     unsigned idx = 0;
3533ca95b02SDimitry Andric     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
3543ca95b02SDimitry Andric       if (!MI.getOperand(idx).isFI())
355284c1978SDimitry Andric         continue;
356284c1978SDimitry Andric 
3573ca95b02SDimitry Andric       if (FrameIdx == MI.getOperand(idx).getIndex())
358284c1978SDimitry Andric         break;
359284c1978SDimitry Andric     }
360284c1978SDimitry Andric 
3613ca95b02SDimitry Andric     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
362284c1978SDimitry Andric 
363e580952dSDimitry Andric     int64_t Offset = 0;
364d88c1a5aSDimitry Andric     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
365e580952dSDimitry Andric 
3663ca95b02SDimitry Andric     DEBUG(dbgs() << "  Replacing FI in: " << MI);
367e580952dSDimitry Andric 
368e580952dSDimitry Andric     // If we have a suitable base register available, use it; otherwise
369e580952dSDimitry Andric     // create a new one. Note that any offset encoded in the
370e580952dSDimitry Andric     // instruction itself will be taken into account by the target,
371e580952dSDimitry Andric     // so we don't have to adjust for it here when reusing a base
372e580952dSDimitry Andric     // register.
3733ca95b02SDimitry Andric     if (UsedBaseReg &&
3743ca95b02SDimitry Andric         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
3753ca95b02SDimitry Andric                                LocalOffset, MI, TRI)) {
376284c1978SDimitry Andric       DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
377e580952dSDimitry Andric       // We found a register to reuse.
378284c1978SDimitry Andric       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
379e580952dSDimitry Andric     } else {
3803ca95b02SDimitry Andric       // No previously defined register was in range, so create a new one.
3813ca95b02SDimitry Andric       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
382284c1978SDimitry Andric 
383284c1978SDimitry Andric       int64_t PrevBaseOffset = BaseOffset;
384284c1978SDimitry Andric       BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
385284c1978SDimitry Andric 
386284c1978SDimitry Andric       // We'd like to avoid creating single-use virtual base registers.
387284c1978SDimitry Andric       // Because the FrameRefs are in sorted order, and we've already
388284c1978SDimitry Andric       // processed all FrameRefs before this one, just check whether or not
389284c1978SDimitry Andric       // the next FrameRef will be able to reuse this new register. If not,
390284c1978SDimitry Andric       // then don't bother creating it.
39191bc56edSDimitry Andric       if (ref + 1 >= e ||
39291bc56edSDimitry Andric           !lookupCandidateBaseReg(
393ff0cc061SDimitry Andric               BaseReg, BaseOffset, FrameSizeAdjust,
39491bc56edSDimitry Andric               FrameReferenceInsns[ref + 1].getLocalOffset(),
3953ca95b02SDimitry Andric               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
396284c1978SDimitry Andric         BaseOffset = PrevBaseOffset;
397284c1978SDimitry Andric         continue;
398284c1978SDimitry Andric       }
399284c1978SDimitry Andric 
4003ca95b02SDimitry Andric       const MachineFunction *MF = MI.getParent()->getParent();
4017ae0e2c9SDimitry Andric       const TargetRegisterClass *RC = TRI->getPointerRegClass(*MF);
402e580952dSDimitry Andric       BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
403e580952dSDimitry Andric 
404e580952dSDimitry Andric       DEBUG(dbgs() << "  Materializing base register " << BaseReg <<
405284c1978SDimitry Andric             " at frame local offset " << LocalOffset + InstrOffset << "\n");
4062754fe60SDimitry Andric 
407e580952dSDimitry Andric       // Tell the target to insert the instruction to initialize
408e580952dSDimitry Andric       // the base register.
4092754fe60SDimitry Andric       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
4102754fe60SDimitry Andric       TRI->materializeFrameBaseRegister(Entry, BaseReg, FrameIdx,
4112754fe60SDimitry Andric                                         InstrOffset);
412e580952dSDimitry Andric 
413e580952dSDimitry Andric       // The base register already includes any offset specified
414e580952dSDimitry Andric       // by the instruction, so account for that so it doesn't get
415e580952dSDimitry Andric       // applied twice.
416e580952dSDimitry Andric       Offset = -InstrOffset;
417e580952dSDimitry Andric 
418e580952dSDimitry Andric       ++NumBaseRegisters;
419e580952dSDimitry Andric       UsedBaseReg = true;
420e580952dSDimitry Andric     }
421e580952dSDimitry Andric     assert(BaseReg != 0 && "Unable to allocate virtual base register!");
422e580952dSDimitry Andric 
423e580952dSDimitry Andric     // Modify the instruction to use the new base register rather
424e580952dSDimitry Andric     // than the frame index operand.
4253ca95b02SDimitry Andric     TRI->resolveFrameIndex(MI, BaseReg, Offset);
4263ca95b02SDimitry Andric     DEBUG(dbgs() << "Resolved: " << MI);
427e580952dSDimitry Andric 
428e580952dSDimitry Andric     ++NumReplacements;
429e580952dSDimitry Andric   }
430284c1978SDimitry Andric 
431e580952dSDimitry Andric   return UsedBaseReg;
432e580952dSDimitry Andric }
433