xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
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 
160b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
30480093f4SDimitry Andric #include "llvm/InitializePasses.h"
310b57cec5SDimitry Andric #include "llvm/Pass.h"
320b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
330b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
340b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
350b57cec5SDimitry Andric #include <algorithm>
360b57cec5SDimitry Andric #include <cassert>
370b57cec5SDimitry Andric #include <cstdint>
380b57cec5SDimitry Andric #include <tuple>
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric using namespace llvm;
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric #define DEBUG_TYPE "localstackalloc"
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
450b57cec5SDimitry Andric STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
460b57cec5SDimitry Andric STATISTIC(NumReplacements, "Number of frame indices references replaced");
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric namespace {
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   class FrameRef {
510b57cec5SDimitry Andric     MachineBasicBlock::iterator MI; // Instr referencing the frame
520b57cec5SDimitry Andric     int64_t LocalOffset;            // Local offset of the frame idx referenced
530b57cec5SDimitry Andric     int FrameIdx;                   // The frame index
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric     // Order reference instruction appears in program. Used to ensure
560b57cec5SDimitry Andric     // deterministic order when multiple instructions may reference the same
570b57cec5SDimitry Andric     // location.
580b57cec5SDimitry Andric     unsigned Order;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric   public:
610b57cec5SDimitry Andric     FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
620b57cec5SDimitry Andric       MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric     bool operator<(const FrameRef &RHS) const {
650b57cec5SDimitry Andric       return std::tie(LocalOffset, FrameIdx, Order) <
660b57cec5SDimitry Andric              std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
670b57cec5SDimitry Andric     }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric     MachineBasicBlock::iterator getMachineInstr() const { return MI; }
700b57cec5SDimitry Andric     int64_t getLocalOffset() const { return LocalOffset; }
710b57cec5SDimitry Andric     int getFrameIndex() const { return FrameIdx; }
720b57cec5SDimitry Andric   };
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric   class LocalStackSlotPass: public MachineFunctionPass {
750b57cec5SDimitry Andric     SmallVector<int64_t, 16> LocalOffsets;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric     /// StackObjSet - A set of stack object indexes
780b57cec5SDimitry Andric     using StackObjSet = SmallSetVector<int, 8>;
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric     void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
815ffd83dbSDimitry Andric                            bool StackGrowsDown, Align &MaxAlign);
820b57cec5SDimitry Andric     void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
830b57cec5SDimitry Andric                                SmallSet<int, 16> &ProtectedObjs,
840b57cec5SDimitry Andric                                MachineFrameInfo &MFI, bool StackGrowsDown,
855ffd83dbSDimitry Andric                                int64_t &Offset, Align &MaxAlign);
860b57cec5SDimitry Andric     void calculateFrameObjectOffsets(MachineFunction &Fn);
870b57cec5SDimitry Andric     bool insertFrameReferenceRegisters(MachineFunction &Fn);
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   public:
900b57cec5SDimitry Andric     static char ID; // Pass identification, replacement for typeid
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric     explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
930b57cec5SDimitry Andric       initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
940b57cec5SDimitry Andric     }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
990b57cec5SDimitry Andric       AU.setPreservesCFG();
1000b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
1010b57cec5SDimitry Andric     }
1020b57cec5SDimitry Andric   };
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric } // end anonymous namespace
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric char LocalStackSlotPass::ID = 0;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
1090b57cec5SDimitry Andric INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
1100b57cec5SDimitry Andric                 "Local Stack Slot Allocation", false, false)
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
1130b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
1140b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1150b57cec5SDimitry Andric   unsigned LocalObjectCount = MFI.getObjectIndexEnd();
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   // If the target doesn't want/need this pass, or if there are no locals
1180b57cec5SDimitry Andric   // to consider, early exit.
119e8d8bef9SDimitry Andric   if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
120*81ad6265SDimitry Andric     return false;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   // Make sure we have enough space to store the local offsets.
1230b57cec5SDimitry Andric   LocalOffsets.resize(MFI.getObjectIndexEnd());
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Lay out the local blob.
1260b57cec5SDimitry Andric   calculateFrameObjectOffsets(MF);
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   // Insert virtual base registers to resolve frame index references.
1290b57cec5SDimitry Andric   bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   // Tell MFI whether any base registers were allocated. PEI will only
1320b57cec5SDimitry Andric   // want to use the local block allocations from this pass if there were any.
1330b57cec5SDimitry Andric   // Otherwise, PEI can do a bit better job of getting the alignment right
1340b57cec5SDimitry Andric   // without a hole at the start since it knows the alignment of the stack
1350b57cec5SDimitry Andric   // at the start of local allocation, and this pass doesn't.
1360b57cec5SDimitry Andric   MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   return true;
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
1425ffd83dbSDimitry Andric void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
1435ffd83dbSDimitry Andric                                            int64_t &Offset, bool StackGrowsDown,
1445ffd83dbSDimitry Andric                                            Align &MaxAlign) {
1450b57cec5SDimitry Andric   // If the stack grows down, add the object size to find the lowest address.
1460b57cec5SDimitry Andric   if (StackGrowsDown)
1470b57cec5SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
1480b57cec5SDimitry Andric 
1495ffd83dbSDimitry Andric   Align Alignment = MFI.getObjectAlign(FrameIdx);
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   // If the alignment of this object is greater than that of the stack, then
1520b57cec5SDimitry Andric   // increase the stack alignment to match.
1535ffd83dbSDimitry Andric   MaxAlign = std::max(MaxAlign, Alignment);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   // Adjust to alignment boundary.
1565ffd83dbSDimitry Andric   Offset = alignTo(Offset, Alignment);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
1590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
1600b57cec5SDimitry Andric                     << LocalOffset << "\n");
1610b57cec5SDimitry Andric   // Keep the offset available for base register allocation
1620b57cec5SDimitry Andric   LocalOffsets[FrameIdx] = LocalOffset;
1630b57cec5SDimitry Andric   // And tell MFI about it for PEI to use later
1640b57cec5SDimitry Andric   MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   if (!StackGrowsDown)
1670b57cec5SDimitry Andric     Offset += MFI.getObjectSize(FrameIdx);
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   ++NumAllocations;
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
1730b57cec5SDimitry Andric /// those required to be close to the Stack Protector) to stack offsets.
1745ffd83dbSDimitry Andric void LocalStackSlotPass::AssignProtectedObjSet(
1755ffd83dbSDimitry Andric     const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
1765ffd83dbSDimitry Andric     MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
1775ffd83dbSDimitry Andric     Align &MaxAlign) {
178fe6060f1SDimitry Andric   for (int i : UnassignedObjs) {
1790b57cec5SDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
1800b57cec5SDimitry Andric     ProtectedObjs.insert(i);
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
1850b57cec5SDimitry Andric /// abstract stack objects.
1860b57cec5SDimitry Andric void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
1870b57cec5SDimitry Andric   // Loop over all of the stack objects, assigning sequential addresses...
1880b57cec5SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
1890b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
1900b57cec5SDimitry Andric   bool StackGrowsDown =
1910b57cec5SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
1920b57cec5SDimitry Andric   int64_t Offset = 0;
1935ffd83dbSDimitry Andric   Align MaxAlign;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   // Make sure that the stack protector comes before the local variables on the
1960b57cec5SDimitry Andric   // stack.
1970b57cec5SDimitry Andric   SmallSet<int, 16> ProtectedObjs;
1980b57cec5SDimitry Andric   if (MFI.hasStackProtectorIndex()) {
1990b57cec5SDimitry Andric     int StackProtectorFI = MFI.getStackProtectorIndex();
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric     // We need to make sure we didn't pre-allocate the stack protector when
2020b57cec5SDimitry Andric     // doing this.
2030b57cec5SDimitry Andric     // If we already have a stack protector, this will re-assign it to a slot
2040b57cec5SDimitry Andric     // that is **not** covering the protected objects.
2050b57cec5SDimitry Andric     assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
2060b57cec5SDimitry Andric            "Stack protector pre-allocated in LocalStackSlotAllocation");
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric     StackObjSet LargeArrayObjs;
2090b57cec5SDimitry Andric     StackObjSet SmallArrayObjs;
2100b57cec5SDimitry Andric     StackObjSet AddrOfObjs;
2110b57cec5SDimitry Andric 
2120eae32dcSDimitry Andric     // Only place the stack protector in the local stack area if the target
2130eae32dcSDimitry Andric     // allows it.
2140eae32dcSDimitry Andric     if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
2150eae32dcSDimitry Andric       AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
2160eae32dcSDimitry Andric                         MaxAlign);
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     // Assign large stack objects first.
2190b57cec5SDimitry Andric     for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
2200b57cec5SDimitry Andric       if (MFI.isDeadObjectIndex(i))
2210b57cec5SDimitry Andric         continue;
2220b57cec5SDimitry Andric       if (StackProtectorFI == (int)i)
2230b57cec5SDimitry Andric         continue;
224979e22ffSDimitry Andric       if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
225979e22ffSDimitry Andric         continue;
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric       switch (MFI.getObjectSSPLayout(i)) {
2280b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_None:
2290b57cec5SDimitry Andric         continue;
2300b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_SmallArray:
2310b57cec5SDimitry Andric         SmallArrayObjs.insert(i);
2320b57cec5SDimitry Andric         continue;
2330b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_AddrOf:
2340b57cec5SDimitry Andric         AddrOfObjs.insert(i);
2350b57cec5SDimitry Andric         continue;
2360b57cec5SDimitry Andric       case MachineFrameInfo::SSPLK_LargeArray:
2370b57cec5SDimitry Andric         LargeArrayObjs.insert(i);
2380b57cec5SDimitry Andric         continue;
2390b57cec5SDimitry Andric       }
2400b57cec5SDimitry Andric       llvm_unreachable("Unexpected SSPLayoutKind.");
2410b57cec5SDimitry Andric     }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2440b57cec5SDimitry Andric                           Offset, MaxAlign);
2450b57cec5SDimitry Andric     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
2460b57cec5SDimitry Andric                           Offset, MaxAlign);
2470b57cec5SDimitry Andric     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
2480b57cec5SDimitry Andric                           Offset, MaxAlign);
2490b57cec5SDimitry Andric   }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   // Then assign frame offsets to stack objects that are not used to spill
2520b57cec5SDimitry Andric   // callee saved registers.
2530b57cec5SDimitry Andric   for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
2540b57cec5SDimitry Andric     if (MFI.isDeadObjectIndex(i))
2550b57cec5SDimitry Andric       continue;
2560b57cec5SDimitry Andric     if (MFI.getStackProtectorIndex() == (int)i)
2570b57cec5SDimitry Andric       continue;
2580b57cec5SDimitry Andric     if (ProtectedObjs.count(i))
2590b57cec5SDimitry Andric       continue;
260979e22ffSDimitry Andric     if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
261979e22ffSDimitry Andric       continue;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   // Remember how big this blob of stack space is
2670b57cec5SDimitry Andric   MFI.setLocalFrameSize(Offset);
2685ffd83dbSDimitry Andric   MFI.setLocalFrameMaxAlign(MaxAlign);
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric static inline bool
2720b57cec5SDimitry Andric lookupCandidateBaseReg(unsigned BaseReg,
2730b57cec5SDimitry Andric                        int64_t BaseOffset,
2740b57cec5SDimitry Andric                        int64_t FrameSizeAdjust,
2750b57cec5SDimitry Andric                        int64_t LocalFrameOffset,
2760b57cec5SDimitry Andric                        const MachineInstr &MI,
2770b57cec5SDimitry Andric                        const TargetRegisterInfo *TRI) {
2780b57cec5SDimitry Andric   // Check if the relative offset from the where the base register references
2790b57cec5SDimitry Andric   // to the target address is in range for the instruction.
2800b57cec5SDimitry Andric   int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
2810b57cec5SDimitry Andric   return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
2850b57cec5SDimitry Andric   // Scan the function's instructions looking for frame index references.
2860b57cec5SDimitry Andric   // For each, ask the target if it wants a virtual base register for it
2870b57cec5SDimitry Andric   // based on what we can tell it about where the local will end up in the
2880b57cec5SDimitry Andric   // stack frame. If it wants one, re-use a suitable one we've previously
2890b57cec5SDimitry Andric   // allocated, or if there isn't one that fits the bill, allocate a new one
2900b57cec5SDimitry Andric   // and ask the target to create a defining instruction for it.
2910b57cec5SDimitry Andric   bool UsedBaseReg = false;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   MachineFrameInfo &MFI = Fn.getFrameInfo();
2940b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
2950b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
2960b57cec5SDimitry Andric   bool StackGrowsDown =
2970b57cec5SDimitry Andric     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // Collect all of the instructions in the block that reference
3000b57cec5SDimitry Andric   // a frame index. Also store the frame index referenced to ease later
3010b57cec5SDimitry Andric   // lookup. (For any insn that has more than one FI reference, we arbitrarily
3020b57cec5SDimitry Andric   // choose the first one).
3030b57cec5SDimitry Andric   SmallVector<FrameRef, 64> FrameReferenceInsns;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   unsigned Order = 0;
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   for (MachineBasicBlock &BB : Fn) {
3080b57cec5SDimitry Andric     for (MachineInstr &MI : BB) {
3090b57cec5SDimitry Andric       // Debug value, stackmap and patchpoint instructions can't be out of
3100b57cec5SDimitry Andric       // range, so they don't need any updates.
3110b57cec5SDimitry Andric       if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
3120b57cec5SDimitry Andric           MI.getOpcode() == TargetOpcode::STACKMAP ||
3130b57cec5SDimitry Andric           MI.getOpcode() == TargetOpcode::PATCHPOINT)
3140b57cec5SDimitry Andric         continue;
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric       // For now, allocate the base register(s) within the basic block
3170b57cec5SDimitry Andric       // where they're used, and don't try to keep them around outside
3180b57cec5SDimitry Andric       // of that. It may be beneficial to try sharing them more broadly
3190b57cec5SDimitry Andric       // than that, but the increased register pressure makes that a
3200b57cec5SDimitry Andric       // tricky thing to balance. Investigate if re-materializing these
3210b57cec5SDimitry Andric       // becomes an issue.
3224824e7fdSDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
3230b57cec5SDimitry Andric         // Consider replacing all frame index operands that reference
3240b57cec5SDimitry Andric         // an object allocated in the local block.
3254824e7fdSDimitry Andric         if (MO.isFI()) {
3260b57cec5SDimitry Andric           // Don't try this with values not in the local block.
3274824e7fdSDimitry Andric           if (!MFI.isObjectPreAllocated(MO.getIndex()))
3280b57cec5SDimitry Andric             break;
3294824e7fdSDimitry Andric           int Idx = MO.getIndex();
3300b57cec5SDimitry Andric           int64_t LocalOffset = LocalOffsets[Idx];
3310b57cec5SDimitry Andric           if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
3320b57cec5SDimitry Andric             break;
3330b57cec5SDimitry Andric           FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
3340b57cec5SDimitry Andric           break;
3350b57cec5SDimitry Andric         }
3360b57cec5SDimitry Andric       }
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Sort the frame references by local offset.
3410b57cec5SDimitry Andric   // Use frame index as a tie-breaker in case MI's have the same offset.
3420b57cec5SDimitry Andric   llvm::sort(FrameReferenceInsns);
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   MachineBasicBlock *Entry = &Fn.front();
3450b57cec5SDimitry Andric 
346*81ad6265SDimitry Andric   Register BaseReg;
3470b57cec5SDimitry Andric   int64_t BaseOffset = 0;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Loop through the frame references and allocate for them as necessary.
3500b57cec5SDimitry Andric   for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
3510b57cec5SDimitry Andric     FrameRef &FR = FrameReferenceInsns[ref];
3520b57cec5SDimitry Andric     MachineInstr &MI = *FR.getMachineInstr();
3530b57cec5SDimitry Andric     int64_t LocalOffset = FR.getLocalOffset();
3540b57cec5SDimitry Andric     int FrameIdx = FR.getFrameIndex();
3550b57cec5SDimitry Andric     assert(MFI.isObjectPreAllocated(FrameIdx) &&
3560b57cec5SDimitry Andric            "Only pre-allocated locals expected!");
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric     // We need to keep the references to the stack protector slot through frame
3590b57cec5SDimitry Andric     // index operands so that it gets resolved by PEI rather than this pass.
3600b57cec5SDimitry Andric     // This avoids accesses to the stack protector though virtual base
3610b57cec5SDimitry Andric     // registers, and forces PEI to address it using fp/sp/bp.
3620b57cec5SDimitry Andric     if (MFI.hasStackProtectorIndex() &&
3630b57cec5SDimitry Andric         FrameIdx == MFI.getStackProtectorIndex())
3640b57cec5SDimitry Andric       continue;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Considering: " << MI);
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     unsigned idx = 0;
3690b57cec5SDimitry Andric     for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
3700b57cec5SDimitry Andric       if (!MI.getOperand(idx).isFI())
3710b57cec5SDimitry Andric         continue;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric       if (FrameIdx == MI.getOperand(idx).getIndex())
3740b57cec5SDimitry Andric         break;
3750b57cec5SDimitry Andric     }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     assert(idx < MI.getNumOperands() && "Cannot find FI operand");
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     int64_t Offset = 0;
3800b57cec5SDimitry Andric     int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Replacing FI in: " << MI);
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     // If we have a suitable base register available, use it; otherwise
3850b57cec5SDimitry Andric     // create a new one. Note that any offset encoded in the
3860b57cec5SDimitry Andric     // instruction itself will be taken into account by the target,
3870b57cec5SDimitry Andric     // so we don't have to adjust for it here when reusing a base
3880b57cec5SDimitry Andric     // register.
3890b57cec5SDimitry Andric     if (UsedBaseReg &&
3900b57cec5SDimitry Andric         lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
3910b57cec5SDimitry Andric                                LocalOffset, MI, TRI)) {
3920b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Reusing base register " << BaseReg << "\n");
3930b57cec5SDimitry Andric       // We found a register to reuse.
3940b57cec5SDimitry Andric       Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
3950b57cec5SDimitry Andric     } else {
3960b57cec5SDimitry Andric       // No previously defined register was in range, so create a new one.
3970b57cec5SDimitry Andric       int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric       int64_t PrevBaseOffset = BaseOffset;
4000b57cec5SDimitry Andric       BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric       // We'd like to avoid creating single-use virtual base registers.
4030b57cec5SDimitry Andric       // Because the FrameRefs are in sorted order, and we've already
4040b57cec5SDimitry Andric       // processed all FrameRefs before this one, just check whether or not
4050b57cec5SDimitry Andric       // the next FrameRef will be able to reuse this new register. If not,
4060b57cec5SDimitry Andric       // then don't bother creating it.
4070b57cec5SDimitry Andric       if (ref + 1 >= e ||
4080b57cec5SDimitry Andric           !lookupCandidateBaseReg(
4090b57cec5SDimitry Andric               BaseReg, BaseOffset, FrameSizeAdjust,
4100b57cec5SDimitry Andric               FrameReferenceInsns[ref + 1].getLocalOffset(),
4110b57cec5SDimitry Andric               *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
4120b57cec5SDimitry Andric         BaseOffset = PrevBaseOffset;
4130b57cec5SDimitry Andric         continue;
4140b57cec5SDimitry Andric       }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric       // Tell the target to insert the instruction to initialize
4170b57cec5SDimitry Andric       // the base register.
4180b57cec5SDimitry Andric       //            MachineBasicBlock::iterator InsertionPt = Entry->begin();
419e8d8bef9SDimitry Andric       BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
420e8d8bef9SDimitry Andric 
421*81ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "  Materialized base register at frame local offset "
422*81ad6265SDimitry Andric                         << LocalOffset + InstrOffset
423*81ad6265SDimitry Andric                         << " into " << printReg(BaseReg, TRI) << '\n');
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric       // The base register already includes any offset specified
4260b57cec5SDimitry Andric       // by the instruction, so account for that so it doesn't get
4270b57cec5SDimitry Andric       // applied twice.
4280b57cec5SDimitry Andric       Offset = -InstrOffset;
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric       ++NumBaseRegisters;
4310b57cec5SDimitry Andric       UsedBaseReg = true;
4320b57cec5SDimitry Andric     }
433*81ad6265SDimitry Andric     assert(BaseReg && "Unable to allocate virtual base register!");
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric     // Modify the instruction to use the new base register rather
4360b57cec5SDimitry Andric     // than the frame index operand.
4370b57cec5SDimitry Andric     TRI->resolveFrameIndex(MI, BaseReg, Offset);
4380b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Resolved: " << MI);
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     ++NumReplacements;
4410b57cec5SDimitry Andric   }
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   return UsedBaseReg;
4440b57cec5SDimitry Andric }
445