10b57cec5SDimitry Andric //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass assigns local frame indices to stack slots relative to one another
100b57cec5SDimitry Andric // and allocates additional base registers to access them when the target
110b57cec5SDimitry Andric // estimates they are likely to be out of range of stack pointer and frame
120b57cec5SDimitry Andric // pointer relative addressing.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric
16*0fca6ea1SDimitry Andric #include "llvm/CodeGen/LocalStackSlotAllocation.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
31480093f4SDimitry Andric #include "llvm/InitializePasses.h"
320b57cec5SDimitry Andric #include "llvm/Pass.h"
330b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
340b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
350b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
360b57cec5SDimitry Andric #include <algorithm>
370b57cec5SDimitry Andric #include <cassert>
380b57cec5SDimitry Andric #include <cstdint>
390b57cec5SDimitry Andric #include <tuple>
400b57cec5SDimitry Andric
410b57cec5SDimitry Andric using namespace llvm;
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric #define DEBUG_TYPE "localstackalloc"
440b57cec5SDimitry Andric
450b57cec5SDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
460b57cec5SDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
470b57cec5SDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
480b57cec5SDimitry Andric
490b57cec5SDimitry Andric namespace {
500b57cec5SDimitry Andric
510b57cec5SDimitry Andric class FrameRef {
520b57cec5SDimitry Andric MachineBasicBlock::iterator MI; // Instr referencing the frame
530b57cec5SDimitry Andric int64_t LocalOffset; // Local offset of the frame idx referenced
540b57cec5SDimitry Andric int FrameIdx; // The frame index
550b57cec5SDimitry Andric
560b57cec5SDimitry Andric // Order reference instruction appears in program. Used to ensure
570b57cec5SDimitry Andric // deterministic order when multiple instructions may reference the same
580b57cec5SDimitry Andric // location.
590b57cec5SDimitry Andric unsigned Order;
600b57cec5SDimitry Andric
610b57cec5SDimitry Andric public:
FrameRef(MachineInstr * I,int64_t Offset,int Idx,unsigned Ord)620b57cec5SDimitry Andric FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
630b57cec5SDimitry Andric MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
640b57cec5SDimitry Andric
operator <(const FrameRef & RHS) const650b57cec5SDimitry Andric bool operator<(const FrameRef &RHS) const {
660b57cec5SDimitry Andric return std::tie(LocalOffset, FrameIdx, Order) <
670b57cec5SDimitry Andric std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric
getMachineInstr() const700b57cec5SDimitry Andric MachineBasicBlock::iterator getMachineInstr() const { return MI; }
getLocalOffset() const710b57cec5SDimitry Andric int64_t getLocalOffset() const { return LocalOffset; }
getFrameIndex() const720b57cec5SDimitry Andric int getFrameIndex() const { return FrameIdx; }
730b57cec5SDimitry Andric };
740b57cec5SDimitry Andric
75*0fca6ea1SDimitry Andric class LocalStackSlotImpl {
760b57cec5SDimitry Andric SmallVector<int64_t, 16> LocalOffsets;
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric /// StackObjSet - A set of stack object indexes
790b57cec5SDimitry Andric using StackObjSet = SmallSetVector<int, 8>;
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
825ffd83dbSDimitry Andric bool StackGrowsDown, Align &MaxAlign);
830b57cec5SDimitry Andric void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
840b57cec5SDimitry Andric SmallSet<int, 16> &ProtectedObjs,
850b57cec5SDimitry Andric MachineFrameInfo &MFI, bool StackGrowsDown,
865ffd83dbSDimitry Andric int64_t &Offset, Align &MaxAlign);
870b57cec5SDimitry Andric void calculateFrameObjectOffsets(MachineFunction &Fn);
880b57cec5SDimitry Andric bool insertFrameReferenceRegisters(MachineFunction &Fn);
890b57cec5SDimitry Andric
900b57cec5SDimitry Andric public:
91*0fca6ea1SDimitry Andric bool runOnMachineFunction(MachineFunction &MF);
92*0fca6ea1SDimitry Andric };
93*0fca6ea1SDimitry Andric
94*0fca6ea1SDimitry Andric class LocalStackSlotPass : public MachineFunctionPass {
95*0fca6ea1SDimitry Andric public:
960b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid
970b57cec5SDimitry Andric
LocalStackSlotPass()980b57cec5SDimitry Andric explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
990b57cec5SDimitry Andric initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric
runOnMachineFunction(MachineFunction & MF)102*0fca6ea1SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override {
103*0fca6ea1SDimitry Andric return LocalStackSlotImpl().runOnMachineFunction(MF);
104*0fca6ea1SDimitry Andric }
1050b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const1060b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
1070b57cec5SDimitry Andric AU.setPreservesCFG();
1080b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric };
1110b57cec5SDimitry Andric
1120b57cec5SDimitry Andric } // end anonymous namespace
1130b57cec5SDimitry Andric
114*0fca6ea1SDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager &)115*0fca6ea1SDimitry Andric LocalStackSlotAllocationPass::run(MachineFunction &MF,
116*0fca6ea1SDimitry Andric MachineFunctionAnalysisManager &) {
117*0fca6ea1SDimitry Andric bool Changed = LocalStackSlotImpl().runOnMachineFunction(MF);
118*0fca6ea1SDimitry Andric if (!Changed)
119*0fca6ea1SDimitry Andric return PreservedAnalyses::all();
120*0fca6ea1SDimitry Andric auto PA = getMachineFunctionPassPreservedAnalyses();
121*0fca6ea1SDimitry Andric PA.preserveSet<CFGAnalyses>();
122*0fca6ea1SDimitry Andric return PA;
123*0fca6ea1SDimitry Andric }
124*0fca6ea1SDimitry Andric
1250b57cec5SDimitry Andric char LocalStackSlotPass::ID = 0;
1260b57cec5SDimitry Andric
1270b57cec5SDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
1280b57cec5SDimitry Andric INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
1290b57cec5SDimitry Andric "Local Stack Slot Allocation", false, false)
1300b57cec5SDimitry Andric
runOnMachineFunction(MachineFunction & MF)131*0fca6ea1SDimitry Andric bool LocalStackSlotImpl::runOnMachineFunction(MachineFunction &MF) {
1320b57cec5SDimitry Andric MachineFrameInfo &MFI = MF.getFrameInfo();
1330b57cec5SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1340b57cec5SDimitry Andric unsigned LocalObjectCount = MFI.getObjectIndexEnd();
1350b57cec5SDimitry Andric
1360b57cec5SDimitry Andric // If the target doesn't want/need this pass, or if there are no locals
1370b57cec5SDimitry Andric // to consider, early exit.
138e8d8bef9SDimitry Andric if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
13981ad6265SDimitry Andric return false;
1400b57cec5SDimitry Andric
1410b57cec5SDimitry Andric // Make sure we have enough space to store the local offsets.
1420b57cec5SDimitry Andric LocalOffsets.resize(MFI.getObjectIndexEnd());
1430b57cec5SDimitry Andric
1440b57cec5SDimitry Andric // Lay out the local blob.
1450b57cec5SDimitry Andric calculateFrameObjectOffsets(MF);
1460b57cec5SDimitry Andric
1470b57cec5SDimitry Andric // Insert virtual base registers to resolve frame index references.
1480b57cec5SDimitry Andric bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric // Tell MFI whether any base registers were allocated. PEI will only
1510b57cec5SDimitry Andric // want to use the local block allocations from this pass if there were any.
1520b57cec5SDimitry Andric // Otherwise, PEI can do a bit better job of getting the alignment right
1530b57cec5SDimitry Andric // without a hole at the start since it knows the alignment of the stack
1540b57cec5SDimitry Andric // at the start of local allocation, and this pass doesn't.
1550b57cec5SDimitry Andric MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
1560b57cec5SDimitry Andric
1570b57cec5SDimitry Andric return true;
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric
1600b57cec5SDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
AdjustStackOffset(MachineFrameInfo & MFI,int FrameIdx,int64_t & Offset,bool StackGrowsDown,Align & MaxAlign)161*0fca6ea1SDimitry Andric void LocalStackSlotImpl::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
1625ffd83dbSDimitry Andric int64_t &Offset, bool StackGrowsDown,
1635ffd83dbSDimitry Andric Align &MaxAlign) {
1640b57cec5SDimitry Andric // If the stack grows down, add the object size to find the lowest address.
1650b57cec5SDimitry Andric if (StackGrowsDown)
1660b57cec5SDimitry Andric Offset += MFI.getObjectSize(FrameIdx);
1670b57cec5SDimitry Andric
1685ffd83dbSDimitry Andric Align Alignment = MFI.getObjectAlign(FrameIdx);
1690b57cec5SDimitry Andric
1700b57cec5SDimitry Andric // If the alignment of this object is greater than that of the stack, then
1710b57cec5SDimitry Andric // increase the stack alignment to match.
1725ffd83dbSDimitry Andric MaxAlign = std::max(MaxAlign, Alignment);
1730b57cec5SDimitry Andric
1740b57cec5SDimitry Andric // Adjust to alignment boundary.
1755ffd83dbSDimitry Andric Offset = alignTo(Offset, Alignment);
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
1780b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
1790b57cec5SDimitry Andric << LocalOffset << "\n");
1800b57cec5SDimitry Andric // Keep the offset available for base register allocation
1810b57cec5SDimitry Andric LocalOffsets[FrameIdx] = LocalOffset;
1820b57cec5SDimitry Andric // And tell MFI about it for PEI to use later
1830b57cec5SDimitry Andric MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
1840b57cec5SDimitry Andric
1850b57cec5SDimitry Andric if (!StackGrowsDown)
1860b57cec5SDimitry Andric Offset += MFI.getObjectSize(FrameIdx);
1870b57cec5SDimitry Andric
1880b57cec5SDimitry Andric ++NumAllocations;
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric
1910b57cec5SDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
1920b57cec5SDimitry Andric /// those required to be close to the Stack Protector) to stack offsets.
AssignProtectedObjSet(const StackObjSet & UnassignedObjs,SmallSet<int,16> & ProtectedObjs,MachineFrameInfo & MFI,bool StackGrowsDown,int64_t & Offset,Align & MaxAlign)193*0fca6ea1SDimitry Andric void LocalStackSlotImpl::AssignProtectedObjSet(
1945ffd83dbSDimitry Andric const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
1955ffd83dbSDimitry Andric MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
1965ffd83dbSDimitry Andric Align &MaxAlign) {
197fe6060f1SDimitry Andric for (int i : UnassignedObjs) {
1980b57cec5SDimitry Andric AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
1990b57cec5SDimitry Andric ProtectedObjs.insert(i);
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
2040b57cec5SDimitry Andric /// abstract stack objects.
calculateFrameObjectOffsets(MachineFunction & Fn)205*0fca6ea1SDimitry Andric void LocalStackSlotImpl::calculateFrameObjectOffsets(MachineFunction &Fn) {
2060b57cec5SDimitry Andric // Loop over all of the stack objects, assigning sequential addresses...
2070b57cec5SDimitry Andric MachineFrameInfo &MFI = Fn.getFrameInfo();
2080b57cec5SDimitry Andric const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
2090b57cec5SDimitry Andric bool StackGrowsDown =
2100b57cec5SDimitry Andric TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
2110b57cec5SDimitry Andric int64_t Offset = 0;
2125ffd83dbSDimitry Andric Align MaxAlign;
2130b57cec5SDimitry Andric
2140b57cec5SDimitry Andric // Make sure that the stack protector comes before the local variables on the
2150b57cec5SDimitry Andric // stack.
2160b57cec5SDimitry Andric SmallSet<int, 16> ProtectedObjs;
2170b57cec5SDimitry Andric if (MFI.hasStackProtectorIndex()) {
2180b57cec5SDimitry Andric int StackProtectorFI = MFI.getStackProtectorIndex();
2190b57cec5SDimitry Andric
2200b57cec5SDimitry Andric // We need to make sure we didn't pre-allocate the stack protector when
2210b57cec5SDimitry Andric // doing this.
2220b57cec5SDimitry Andric // If we already have a stack protector, this will re-assign it to a slot
2230b57cec5SDimitry Andric // that is **not** covering the protected objects.
2240b57cec5SDimitry Andric assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
2250b57cec5SDimitry Andric "Stack protector pre-allocated in LocalStackSlotAllocation");
2260b57cec5SDimitry Andric
2270b57cec5SDimitry Andric StackObjSet LargeArrayObjs;
2280b57cec5SDimitry Andric StackObjSet SmallArrayObjs;
2290b57cec5SDimitry Andric StackObjSet AddrOfObjs;
2300b57cec5SDimitry Andric
2310eae32dcSDimitry Andric // Only place the stack protector in the local stack area if the target
2320eae32dcSDimitry Andric // allows it.
2330eae32dcSDimitry Andric if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
2340eae32dcSDimitry Andric AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
2350eae32dcSDimitry Andric MaxAlign);
2360b57cec5SDimitry Andric
2370b57cec5SDimitry Andric // Assign large stack objects first.
2380b57cec5SDimitry Andric for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
2390b57cec5SDimitry Andric if (MFI.isDeadObjectIndex(i))
2400b57cec5SDimitry Andric continue;
2410b57cec5SDimitry Andric if (StackProtectorFI == (int)i)
2420b57cec5SDimitry Andric continue;
243979e22ffSDimitry Andric if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
244979e22ffSDimitry Andric continue;
2450b57cec5SDimitry Andric
2460b57cec5SDimitry Andric switch (MFI.getObjectSSPLayout(i)) {
2470b57cec5SDimitry Andric case MachineFrameInfo::SSPLK_None:
2480b57cec5SDimitry Andric continue;
2490b57cec5SDimitry Andric case MachineFrameInfo::SSPLK_SmallArray:
2500b57cec5SDimitry Andric SmallArrayObjs.insert(i);
2510b57cec5SDimitry Andric continue;
2520b57cec5SDimitry Andric case MachineFrameInfo::SSPLK_AddrOf:
2530b57cec5SDimitry Andric AddrOfObjs.insert(i);
2540b57cec5SDimitry Andric continue;
2550b57cec5SDimitry Andric case MachineFrameInfo::SSPLK_LargeArray:
2560b57cec5SDimitry Andric LargeArrayObjs.insert(i);
2570b57cec5SDimitry Andric continue;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric llvm_unreachable("Unexpected SSPLayoutKind.");
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2630b57cec5SDimitry Andric Offset, MaxAlign);
2640b57cec5SDimitry Andric AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2650b57cec5SDimitry Andric Offset, MaxAlign);
2660b57cec5SDimitry Andric AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
2670b57cec5SDimitry Andric Offset, MaxAlign);
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric
2700b57cec5SDimitry Andric // Then assign frame offsets to stack objects that are not used to spill
2710b57cec5SDimitry Andric // callee saved registers.
2720b57cec5SDimitry Andric for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
2730b57cec5SDimitry Andric if (MFI.isDeadObjectIndex(i))
2740b57cec5SDimitry Andric continue;
2750b57cec5SDimitry Andric if (MFI.getStackProtectorIndex() == (int)i)
2760b57cec5SDimitry Andric continue;
2770b57cec5SDimitry Andric if (ProtectedObjs.count(i))
2780b57cec5SDimitry Andric continue;
279979e22ffSDimitry Andric if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
280979e22ffSDimitry Andric continue;
2810b57cec5SDimitry Andric
2820b57cec5SDimitry Andric AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric
2850b57cec5SDimitry Andric // Remember how big this blob of stack space is
2860b57cec5SDimitry Andric MFI.setLocalFrameSize(Offset);
2875ffd83dbSDimitry Andric MFI.setLocalFrameMaxAlign(MaxAlign);
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric
2900b57cec5SDimitry Andric static inline bool
lookupCandidateBaseReg(unsigned BaseReg,int64_t BaseOffset,int64_t FrameSizeAdjust,int64_t LocalFrameOffset,const MachineInstr & MI,const TargetRegisterInfo * TRI)2910b57cec5SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
2920b57cec5SDimitry Andric int64_t BaseOffset,
2930b57cec5SDimitry Andric int64_t FrameSizeAdjust,
2940b57cec5SDimitry Andric int64_t LocalFrameOffset,
2950b57cec5SDimitry Andric const MachineInstr &MI,
2960b57cec5SDimitry Andric const TargetRegisterInfo *TRI) {
2970b57cec5SDimitry Andric // Check if the relative offset from the where the base register references
2980b57cec5SDimitry Andric // to the target address is in range for the instruction.
2990b57cec5SDimitry Andric int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
3000b57cec5SDimitry Andric return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric
insertFrameReferenceRegisters(MachineFunction & Fn)303*0fca6ea1SDimitry Andric bool LocalStackSlotImpl::insertFrameReferenceRegisters(MachineFunction &Fn) {
3040b57cec5SDimitry Andric // Scan the function's instructions looking for frame index references.
3050b57cec5SDimitry Andric // For each, ask the target if it wants a virtual base register for it
3060b57cec5SDimitry Andric // based on what we can tell it about where the local will end up in the
3070b57cec5SDimitry Andric // stack frame. If it wants one, re-use a suitable one we've previously
3080b57cec5SDimitry Andric // allocated, or if there isn't one that fits the bill, allocate a new one
3090b57cec5SDimitry Andric // and ask the target to create a defining instruction for it.
3100b57cec5SDimitry Andric
3110b57cec5SDimitry Andric MachineFrameInfo &MFI = Fn.getFrameInfo();
3120b57cec5SDimitry Andric const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
3130b57cec5SDimitry Andric const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
3140b57cec5SDimitry Andric bool StackGrowsDown =
3150b57cec5SDimitry Andric TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric // Collect all of the instructions in the block that reference
3180b57cec5SDimitry Andric // a frame index. Also store the frame index referenced to ease later
3190b57cec5SDimitry Andric // lookup. (For any insn that has more than one FI reference, we arbitrarily
3200b57cec5SDimitry Andric // choose the first one).
3210b57cec5SDimitry Andric SmallVector<FrameRef, 64> FrameReferenceInsns;
3220b57cec5SDimitry Andric
3230b57cec5SDimitry Andric unsigned Order = 0;
3240b57cec5SDimitry Andric
3250b57cec5SDimitry Andric for (MachineBasicBlock &BB : Fn) {
3260b57cec5SDimitry Andric for (MachineInstr &MI : BB) {
3270b57cec5SDimitry Andric // Debug value, stackmap and patchpoint instructions can't be out of
3280b57cec5SDimitry Andric // range, so they don't need any updates.
3290b57cec5SDimitry Andric if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
3300b57cec5SDimitry Andric MI.getOpcode() == TargetOpcode::STACKMAP ||
3310b57cec5SDimitry Andric MI.getOpcode() == TargetOpcode::PATCHPOINT)
3320b57cec5SDimitry Andric continue;
3330b57cec5SDimitry Andric
3340b57cec5SDimitry Andric // For now, allocate the base register(s) within the basic block
3350b57cec5SDimitry Andric // where they're used, and don't try to keep them around outside
3360b57cec5SDimitry Andric // of that. It may be beneficial to try sharing them more broadly
3370b57cec5SDimitry Andric // than that, but the increased register pressure makes that a
3380b57cec5SDimitry Andric // tricky thing to balance. Investigate if re-materializing these
3390b57cec5SDimitry Andric // becomes an issue.
3404824e7fdSDimitry Andric for (const MachineOperand &MO : MI.operands()) {
3410b57cec5SDimitry Andric // Consider replacing all frame index operands that reference
3420b57cec5SDimitry Andric // an object allocated in the local block.
3434824e7fdSDimitry Andric if (MO.isFI()) {
3440b57cec5SDimitry Andric // Don't try this with values not in the local block.
3454824e7fdSDimitry Andric if (!MFI.isObjectPreAllocated(MO.getIndex()))
3460b57cec5SDimitry Andric break;
3474824e7fdSDimitry Andric int Idx = MO.getIndex();
3480b57cec5SDimitry Andric int64_t LocalOffset = LocalOffsets[Idx];
3490b57cec5SDimitry Andric if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
3500b57cec5SDimitry Andric break;
3510b57cec5SDimitry Andric FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
3520b57cec5SDimitry Andric break;
3530b57cec5SDimitry Andric }
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric
3580b57cec5SDimitry Andric // Sort the frame references by local offset.
3590b57cec5SDimitry Andric // Use frame index as a tie-breaker in case MI's have the same offset.
3600b57cec5SDimitry Andric llvm::sort(FrameReferenceInsns);
3610b57cec5SDimitry Andric
3620b57cec5SDimitry Andric MachineBasicBlock *Entry = &Fn.front();
3630b57cec5SDimitry Andric
36481ad6265SDimitry Andric Register BaseReg;
3650b57cec5SDimitry Andric int64_t BaseOffset = 0;
3660b57cec5SDimitry Andric
3670b57cec5SDimitry Andric // Loop through the frame references and allocate for them as necessary.
3680b57cec5SDimitry Andric for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
3690b57cec5SDimitry Andric FrameRef &FR = FrameReferenceInsns[ref];
3700b57cec5SDimitry Andric MachineInstr &MI = *FR.getMachineInstr();
3710b57cec5SDimitry Andric int64_t LocalOffset = FR.getLocalOffset();
3720b57cec5SDimitry Andric int FrameIdx = FR.getFrameIndex();
3730b57cec5SDimitry Andric assert(MFI.isObjectPreAllocated(FrameIdx) &&
3740b57cec5SDimitry Andric "Only pre-allocated locals expected!");
3750b57cec5SDimitry Andric
3760b57cec5SDimitry Andric // We need to keep the references to the stack protector slot through frame
3770b57cec5SDimitry Andric // index operands so that it gets resolved by PEI rather than this pass.
3780b57cec5SDimitry Andric // This avoids accesses to the stack protector though virtual base
3790b57cec5SDimitry Andric // registers, and forces PEI to address it using fp/sp/bp.
3800b57cec5SDimitry Andric if (MFI.hasStackProtectorIndex() &&
3810b57cec5SDimitry Andric FrameIdx == MFI.getStackProtectorIndex())
3820b57cec5SDimitry Andric continue;
3830b57cec5SDimitry Andric
3840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Considering: " << MI);
3850b57cec5SDimitry Andric
3860b57cec5SDimitry Andric unsigned idx = 0;
3870b57cec5SDimitry Andric for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
3880b57cec5SDimitry Andric if (!MI.getOperand(idx).isFI())
3890b57cec5SDimitry Andric continue;
3900b57cec5SDimitry Andric
3910b57cec5SDimitry Andric if (FrameIdx == MI.getOperand(idx).getIndex())
3920b57cec5SDimitry Andric break;
3930b57cec5SDimitry Andric }
3940b57cec5SDimitry Andric
3950b57cec5SDimitry Andric assert(idx < MI.getNumOperands() && "Cannot find FI operand");
3960b57cec5SDimitry Andric
3970b57cec5SDimitry Andric int64_t Offset = 0;
3980b57cec5SDimitry Andric int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
3990b57cec5SDimitry Andric
4000b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Replacing FI in: " << MI);
4010b57cec5SDimitry Andric
4020b57cec5SDimitry Andric // If we have a suitable base register available, use it; otherwise
4030b57cec5SDimitry Andric // create a new one. Note that any offset encoded in the
4040b57cec5SDimitry Andric // instruction itself will be taken into account by the target,
4050b57cec5SDimitry Andric // so we don't have to adjust for it here when reusing a base
4060b57cec5SDimitry Andric // register.
407bdd1243dSDimitry Andric if (BaseReg.isValid() &&
4080b57cec5SDimitry Andric lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
4090b57cec5SDimitry Andric LocalOffset, MI, TRI)) {
4100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Reusing base register " << BaseReg << "\n");
4110b57cec5SDimitry Andric // We found a register to reuse.
4120b57cec5SDimitry Andric Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
4130b57cec5SDimitry Andric } else {
4140b57cec5SDimitry Andric // No previously defined register was in range, so create a new one.
4150b57cec5SDimitry Andric int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
4160b57cec5SDimitry Andric
417bdd1243dSDimitry Andric int64_t CandBaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
4180b57cec5SDimitry Andric
4190b57cec5SDimitry Andric // We'd like to avoid creating single-use virtual base registers.
4200b57cec5SDimitry Andric // Because the FrameRefs are in sorted order, and we've already
4210b57cec5SDimitry Andric // processed all FrameRefs before this one, just check whether or not
4220b57cec5SDimitry Andric // the next FrameRef will be able to reuse this new register. If not,
4230b57cec5SDimitry Andric // then don't bother creating it.
4240b57cec5SDimitry Andric if (ref + 1 >= e ||
4250b57cec5SDimitry Andric !lookupCandidateBaseReg(
426bdd1243dSDimitry Andric BaseReg, CandBaseOffset, FrameSizeAdjust,
4270b57cec5SDimitry Andric FrameReferenceInsns[ref + 1].getLocalOffset(),
428bdd1243dSDimitry Andric *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI))
4290b57cec5SDimitry Andric continue;
430bdd1243dSDimitry Andric
431bdd1243dSDimitry Andric // Save the base offset.
432bdd1243dSDimitry Andric BaseOffset = CandBaseOffset;
4330b57cec5SDimitry Andric
4340b57cec5SDimitry Andric // Tell the target to insert the instruction to initialize
4350b57cec5SDimitry Andric // the base register.
4360b57cec5SDimitry Andric // MachineBasicBlock::iterator InsertionPt = Entry->begin();
437e8d8bef9SDimitry Andric BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
438e8d8bef9SDimitry Andric
43981ad6265SDimitry Andric LLVM_DEBUG(dbgs() << " Materialized base register at frame local offset "
44081ad6265SDimitry Andric << LocalOffset + InstrOffset
44181ad6265SDimitry Andric << " into " << printReg(BaseReg, TRI) << '\n');
4420b57cec5SDimitry Andric
4430b57cec5SDimitry Andric // The base register already includes any offset specified
4440b57cec5SDimitry Andric // by the instruction, so account for that so it doesn't get
4450b57cec5SDimitry Andric // applied twice.
4460b57cec5SDimitry Andric Offset = -InstrOffset;
4470b57cec5SDimitry Andric
4480b57cec5SDimitry Andric ++NumBaseRegisters;
4490b57cec5SDimitry Andric }
45081ad6265SDimitry Andric assert(BaseReg && "Unable to allocate virtual base register!");
4510b57cec5SDimitry Andric
4520b57cec5SDimitry Andric // Modify the instruction to use the new base register rather
4530b57cec5SDimitry Andric // than the frame index operand.
4540b57cec5SDimitry Andric TRI->resolveFrameIndex(MI, BaseReg, Offset);
4550b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Resolved: " << MI);
4560b57cec5SDimitry Andric
4570b57cec5SDimitry Andric ++NumReplacements;
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric
460bdd1243dSDimitry Andric return BaseReg.isValid();
4610b57cec5SDimitry Andric }
462