#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <tuple>
using namespace llvm;
#define DEBUG_TYPE "localstackalloc"
STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
STATISTIC(NumReplacements, "Number of frame indices references replaced");
namespace {
class FrameRef {
MachineBasicBlock::iterator MI; int64_t LocalOffset; int FrameIdx;
unsigned Order;
public:
FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
bool operator<(const FrameRef &RHS) const {
return std::tie(LocalOffset, FrameIdx, Order) <
std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
}
MachineBasicBlock::iterator getMachineInstr() const { return MI; }
int64_t getLocalOffset() const { return LocalOffset; }
int getFrameIndex() const { return FrameIdx; }
};
class LocalStackSlotPass: public MachineFunctionPass {
SmallVector<int64_t, 16> LocalOffsets;
using StackObjSet = SmallSetVector<int, 8>;
void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
bool StackGrowsDown, Align &MaxAlign);
void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
SmallSet<int, 16> &ProtectedObjs,
MachineFrameInfo &MFI, bool StackGrowsDown,
int64_t &Offset, Align &MaxAlign);
void calculateFrameObjectOffsets(MachineFunction &Fn);
bool insertFrameReferenceRegisters(MachineFunction &Fn);
public:
static char ID;
explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
};
}
char LocalStackSlotPass::ID = 0;
char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
"Local Stack Slot Allocation", false, false)
bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
unsigned LocalObjectCount = MFI.getObjectIndexEnd();
if (LocalObjectCount == 0 || !TRI->requiresVirtualBaseRegisters(MF))
return false;
LocalOffsets.resize(MFI.getObjectIndexEnd());
calculateFrameObjectOffsets(MF);
bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
return true;
}
void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
int64_t &Offset, bool StackGrowsDown,
Align &MaxAlign) {
if (StackGrowsDown)
Offset += MFI.getObjectSize(FrameIdx);
Align Alignment = MFI.getObjectAlign(FrameIdx);
MaxAlign = std::max(MaxAlign, Alignment);
Offset = alignTo(Offset, Alignment);
int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
<< LocalOffset << "\n");
LocalOffsets[FrameIdx] = LocalOffset;
MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
if (!StackGrowsDown)
Offset += MFI.getObjectSize(FrameIdx);
++NumAllocations;
}
void LocalStackSlotPass::AssignProtectedObjSet(
const StackObjSet &UnassignedObjs, SmallSet<int, 16> &ProtectedObjs,
MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset,
Align &MaxAlign) {
for (int i : UnassignedObjs) {
AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
ProtectedObjs.insert(i);
}
}
void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
MachineFrameInfo &MFI = Fn.getFrameInfo();
const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
int64_t Offset = 0;
Align MaxAlign;
SmallSet<int, 16> ProtectedObjs;
if (MFI.hasStackProtectorIndex()) {
int StackProtectorFI = MFI.getStackProtectorIndex();
assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
"Stack protector pre-allocated in LocalStackSlotAllocation");
StackObjSet LargeArrayObjs;
StackObjSet SmallArrayObjs;
StackObjSet AddrOfObjs;
if (TFI.isStackIdSafeForLocalArea(MFI.getStackID(StackProtectorFI)))
AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown,
MaxAlign);
for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
if (MFI.isDeadObjectIndex(i))
continue;
if (StackProtectorFI == (int)i)
continue;
if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
continue;
switch (MFI.getObjectSSPLayout(i)) {
case MachineFrameInfo::SSPLK_None:
continue;
case MachineFrameInfo::SSPLK_SmallArray:
SmallArrayObjs.insert(i);
continue;
case MachineFrameInfo::SSPLK_AddrOf:
AddrOfObjs.insert(i);
continue;
case MachineFrameInfo::SSPLK_LargeArray:
LargeArrayObjs.insert(i);
continue;
}
llvm_unreachable("Unexpected SSPLayoutKind.");
}
AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
Offset, MaxAlign);
AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
Offset, MaxAlign);
AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
Offset, MaxAlign);
}
for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
if (MFI.isDeadObjectIndex(i))
continue;
if (MFI.getStackProtectorIndex() == (int)i)
continue;
if (ProtectedObjs.count(i))
continue;
if (!TFI.isStackIdSafeForLocalArea(MFI.getStackID(i)))
continue;
AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
}
MFI.setLocalFrameSize(Offset);
MFI.setLocalFrameMaxAlign(MaxAlign);
}
static inline bool
lookupCandidateBaseReg(unsigned BaseReg,
int64_t BaseOffset,
int64_t FrameSizeAdjust,
int64_t LocalFrameOffset,
const MachineInstr &MI,
const TargetRegisterInfo *TRI) {
int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
}
bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
bool UsedBaseReg = false;
MachineFrameInfo &MFI = Fn.getFrameInfo();
const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
bool StackGrowsDown =
TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
SmallVector<FrameRef, 64> FrameReferenceInsns;
unsigned Order = 0;
for (MachineBasicBlock &BB : Fn) {
for (MachineInstr &MI : BB) {
if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
MI.getOpcode() == TargetOpcode::STACKMAP ||
MI.getOpcode() == TargetOpcode::PATCHPOINT)
continue;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isFI()) {
if (!MFI.isObjectPreAllocated(MO.getIndex()))
break;
int Idx = MO.getIndex();
int64_t LocalOffset = LocalOffsets[Idx];
if (!TRI->needsFrameBaseReg(&MI, LocalOffset))
break;
FrameReferenceInsns.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
break;
}
}
}
}
llvm::sort(FrameReferenceInsns);
MachineBasicBlock *Entry = &Fn.front();
Register BaseReg;
int64_t BaseOffset = 0;
for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
FrameRef &FR = FrameReferenceInsns[ref];
MachineInstr &MI = *FR.getMachineInstr();
int64_t LocalOffset = FR.getLocalOffset();
int FrameIdx = FR.getFrameIndex();
assert(MFI.isObjectPreAllocated(FrameIdx) &&
"Only pre-allocated locals expected!");
if (MFI.hasStackProtectorIndex() &&
FrameIdx == MFI.getStackProtectorIndex())
continue;
LLVM_DEBUG(dbgs() << "Considering: " << MI);
unsigned idx = 0;
for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
if (!MI.getOperand(idx).isFI())
continue;
if (FrameIdx == MI.getOperand(idx).getIndex())
break;
}
assert(idx < MI.getNumOperands() && "Cannot find FI operand");
int64_t Offset = 0;
int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
LLVM_DEBUG(dbgs() << " Replacing FI in: " << MI);
if (UsedBaseReg &&
lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
LocalOffset, MI, TRI)) {
LLVM_DEBUG(dbgs() << " Reusing base register " << BaseReg << "\n");
Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
} else {
int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
int64_t PrevBaseOffset = BaseOffset;
BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
if (ref + 1 >= e ||
!lookupCandidateBaseReg(
BaseReg, BaseOffset, FrameSizeAdjust,
FrameReferenceInsns[ref + 1].getLocalOffset(),
*FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
BaseOffset = PrevBaseOffset;
continue;
}
BaseReg = TRI->materializeFrameBaseRegister(Entry, FrameIdx, InstrOffset);
LLVM_DEBUG(dbgs() << " Materialized base register at frame local offset "
<< LocalOffset + InstrOffset
<< " into " << printReg(BaseReg, TRI) << '\n');
Offset = -InstrOffset;
++NumBaseRegisters;
UsedBaseReg = true;
}
assert(BaseReg && "Unable to allocate virtual base register!");
TRI->resolveFrameIndex(MI, BaseReg, Offset);
LLVM_DEBUG(dbgs() << "Resolved: " << MI);
++NumReplacements;
}
return UsedBaseReg;
}