#include "MCTargetDesc/X86BaseInfo.h"
#include "X86.h"
#include "X86FrameLowering.h"
#include "X86InstrInfo.h"
#include "X86MachineFunctionInfo.h"
#include "X86RegisterInfo.h"
#include "X86Subtarget.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.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/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
using namespace llvm;
#define DEBUG_TYPE "x86-cf-opt"
static cl::opt<bool>
NoX86CFOpt("no-x86-call-frame-opt",
cl::desc("Avoid optimizing x86 call frames for size"),
cl::init(false), cl::Hidden);
namespace {
class X86CallFrameOptimization : public MachineFunctionPass {
public:
X86CallFrameOptimization() : MachineFunctionPass(ID) { }
bool runOnMachineFunction(MachineFunction &MF) override;
static char ID;
private:
struct CallContext {
CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
MachineBasicBlock::iterator FrameSetup;
MachineInstr *Call = nullptr;
MachineInstr *SPCopy = nullptr;
int64_t ExpectedDist = 0;
SmallVector<MachineInstr *, 4> ArgStoreVector;
bool NoStackParams = false;
bool UsePush = false;
};
typedef SmallVector<CallContext, 8> ContextVector;
bool isLegal(MachineFunction &MF);
bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I, CallContext &Context);
void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
Register Reg);
enum InstClassification { Convert, Skip, Exit };
InstClassification classifyInstruction(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const X86RegisterInfo &RegInfo,
DenseSet<unsigned int> &UsedRegs);
StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
const X86InstrInfo *TII = nullptr;
const X86FrameLowering *TFL = nullptr;
const X86Subtarget *STI = nullptr;
MachineRegisterInfo *MRI = nullptr;
unsigned SlotSize = 0;
unsigned Log2SlotSize = 0;
};
} char X86CallFrameOptimization::ID = 0;
INITIALIZE_PASS(X86CallFrameOptimization, DEBUG_TYPE,
"X86 Call Frame Optimization", false, false)
bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
if (NoX86CFOpt.getValue())
return false;
if (STI->isTargetDarwin() &&
(!MF.getLandingPads().empty() ||
(MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
return false;
if (STI->isTargetWin64())
return false;
unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
bool EmitStackProbeCall = STI->getTargetLowering()->hasStackProbeSymbol(MF);
unsigned StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
for (MachineBasicBlock &BB : MF) {
bool InsideFrameSequence = false;
for (MachineInstr &MI : BB) {
if (MI.getOpcode() == FrameSetupOpcode) {
if (TII->getFrameSize(MI) >= StackProbeSize && EmitStackProbeCall)
return false;
if (InsideFrameSequence)
return false;
InsideFrameSequence = true;
} else if (MI.getOpcode() == FrameDestroyOpcode) {
if (!InsideFrameSequence)
return false;
InsideFrameSequence = false;
}
}
if (InsideFrameSequence)
return false;
}
return true;
}
bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
ContextVector &CallSeqVector) {
bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
if (CannotReserveFrame)
return true;
Align StackAlign = TFL->getStackAlign();
int64_t Advantage = 0;
for (const auto &CC : CallSeqVector) {
if (CC.NoStackParams)
continue;
if (!CC.UsePush) {
Advantage -= 6;
} else {
Advantage -= 3;
if (!isAligned(StackAlign, CC.ExpectedDist))
Advantage -= 3;
Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
}
}
return Advantage >= 0;
}
bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
STI = &MF.getSubtarget<X86Subtarget>();
TII = STI->getInstrInfo();
TFL = STI->getFrameLowering();
MRI = &MF.getRegInfo();
const X86RegisterInfo &RegInfo =
*static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
SlotSize = RegInfo.getSlotSize();
assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
Log2SlotSize = Log2_32(SlotSize);
if (skipFunction(MF.getFunction()) || !isLegal(MF))
return false;
unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
bool Changed = false;
ContextVector CallSeqVector;
for (auto &MBB : MF)
for (auto &MI : MBB)
if (MI.getOpcode() == FrameSetupOpcode) {
CallContext Context;
collectCallInfo(MF, MBB, MI, Context);
CallSeqVector.push_back(Context);
}
if (!isProfitable(MF, CallSeqVector))
return false;
for (const auto &CC : CallSeqVector) {
if (CC.UsePush) {
adjustCallSequence(MF, CC);
Changed = true;
}
}
return Changed;
}
X86CallFrameOptimization::InstClassification
X86CallFrameOptimization::classifyInstruction(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
if (MI == MBB.end())
return Exit;
switch (MI->getOpcode()) {
case X86::AND16mi8:
case X86::AND32mi8:
case X86::AND64mi8: {
const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
return ImmOp.getImm() == 0 ? Convert : Exit;
}
case X86::OR16mi8:
case X86::OR32mi8:
case X86::OR64mi8: {
const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
return ImmOp.getImm() == -1 ? Convert : Exit;
}
case X86::MOV32mi:
case X86::MOV32mr:
case X86::MOV64mi32:
case X86::MOV64mr:
return Convert;
}
if (MI->isCall() || MI->mayStore())
return Exit;
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg.isPhysical())
continue;
if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
return Exit;
if (MO.isDef()) {
for (unsigned int U : UsedRegs)
if (RegInfo.regsOverlap(Reg, U))
return Exit;
}
}
return Skip;
}
void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
CallContext &Context) {
const X86RegisterInfo &RegInfo =
*static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
MachineBasicBlock::iterator FrameSetup = I++;
Context.FrameSetup = FrameSetup;
unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
if (!MaxAdjust) {
Context.NoStackParams = true;
return;
}
while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
++I;
Register StackPtr = RegInfo.getStackRegister();
auto StackPtrCopyInst = MBB.end();
for (auto J = I; !J->isCall(); ++J)
if (J->isCopy() && J->getOperand(0).isReg() && J->getOperand(1).isReg() &&
J->getOperand(1).getReg() == StackPtr) {
StackPtrCopyInst = J;
Context.SPCopy = &*J++;
StackPtr = Context.SPCopy->getOperand(0).getReg();
break;
}
if (MaxAdjust > 4)
Context.ArgStoreVector.resize(MaxAdjust, nullptr);
DenseSet<unsigned int> UsedRegs;
for (InstClassification Classification = Skip; Classification != Exit; ++I) {
if (I == StackPtrCopyInst)
continue;
Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs);
if (Classification != Convert)
continue;
if (!I->getOperand(X86::AddrBaseReg).isReg() ||
(I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
!I->getOperand(X86::AddrScaleAmt).isImm() ||
(I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
(I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
(I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
!I->getOperand(X86::AddrDisp).isImm())
return;
int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
assert(StackDisp >= 0 &&
"Negative stack displacement when passing parameters");
if (StackDisp & (SlotSize - 1))
return;
StackDisp >>= Log2SlotSize;
assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
"Function call has more parameters than the stack is adjusted for.");
if (Context.ArgStoreVector[StackDisp] != nullptr)
return;
Context.ArgStoreVector[StackDisp] = &*I;
for (const MachineOperand &MO : I->uses()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (Reg.isPhysical())
UsedRegs.insert(Reg);
}
}
--I;
if (I == MBB.end() || !I->isCall())
return;
Context.Call = &*I;
if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
return;
auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
if (*MMI == nullptr)
break;
if (MMI == Context.ArgStoreVector.begin())
return;
for (; MMI != MME; ++MMI)
if (*MMI != nullptr)
return;
Context.UsePush = true;
}
void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
const CallContext &Context) {
MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
MachineBasicBlock &MBB = *(FrameSetup->getParent());
TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
const DebugLoc &DL = FrameSetup->getDebugLoc();
bool Is64Bit = STI->is64Bit();
for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
const MachineOperand &PushOp = Store->getOperand(X86::AddrNumOperands);
MachineBasicBlock::iterator Push = nullptr;
unsigned PushOpcode;
switch (Store->getOpcode()) {
default:
llvm_unreachable("Unexpected Opcode!");
case X86::AND16mi8:
case X86::AND32mi8:
case X86::AND64mi8:
case X86::OR16mi8:
case X86::OR32mi8:
case X86::OR64mi8:
case X86::MOV32mi:
case X86::MOV64mi32:
PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
if (PushOp.isImm()) {
int64_t Val = PushOp.getImm();
if (isInt<8>(Val))
PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
}
Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
Push->cloneMemRefs(MF, *Store);
break;
case X86::MOV32mr:
case X86::MOV64mr: {
Register Reg = PushOp.getReg();
if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
Register UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
.addReg(UndefReg)
.add(PushOp)
.addImm(X86::sub_32bit);
}
bool SlowPUSHrmm = STI->slowTwoMemOps();
MachineInstr *DefMov = nullptr;
if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
unsigned NumOps = DefMov->getDesc().getNumOperands();
for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
Push->addOperand(DefMov->getOperand(i));
Push->cloneMergedMemRefs(MF, {DefMov, &*Store});
DefMov->eraseFromParent();
} else {
PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
.addReg(Reg)
.getInstr();
Push->cloneMemRefs(MF, *Store);
}
break;
}
}
if (!TFL->hasFP(MF))
TFL->BuildCFI(
MBB, std::next(Push), DL,
MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
MBB.erase(Store);
}
if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
Context.SPCopy->eraseFromParent();
X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
FuncInfo->setHasPushSequences(true);
}
MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
MachineBasicBlock::iterator FrameSetup, Register Reg) {
if (!Reg.isVirtual())
return nullptr;
if (!MRI->hasOneNonDBGUse(Reg))
return nullptr;
MachineInstr &DefMI = *MRI->getVRegDef(Reg);
if ((DefMI.getOpcode() != X86::MOV32rm &&
DefMI.getOpcode() != X86::MOV64rm) ||
DefMI.getParent() != FrameSetup->getParent())
return nullptr;
for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
if (I->isLoadFoldBarrier())
return nullptr;
return &DefMI;
}
FunctionPass *llvm::createX86CallFrameOptimization() {
return new X86CallFrameOptimization();
}