#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/Optional.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/MCDwarf.h"
using namespace llvm;
static cl::opt<bool> VerifyCFI("verify-cfiinstrs",
cl::desc("Verify Call Frame Information instructions"),
cl::init(false),
cl::Hidden);
namespace {
class CFIInstrInserter : public MachineFunctionPass {
public:
static char ID;
CFIInstrInserter() : MachineFunctionPass(ID) {
initializeCFIInstrInserterPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override {
if (!MF.needsFrameMoves())
return false;
MBBVector.resize(MF.getNumBlockIDs());
calculateCFAInfo(MF);
if (VerifyCFI) {
if (unsigned ErrorNum = verify(MF))
report_fatal_error("Found " + Twine(ErrorNum) +
" in/out CFI information errors.");
}
bool insertedCFI = insertCFIInstrs(MF);
MBBVector.clear();
return insertedCFI;
}
private:
struct MBBCFAInfo {
MachineBasicBlock *MBB;
int IncomingCFAOffset = -1;
int OutgoingCFAOffset = -1;
unsigned IncomingCFARegister = 0;
unsigned OutgoingCFARegister = 0;
BitVector IncomingCSRSaved;
BitVector OutgoingCSRSaved;
bool Processed = false;
};
#define INVALID_REG UINT_MAX
#define INVALID_OFFSET INT_MAX
struct CSRSavedLocation {
CSRSavedLocation(Optional<unsigned> R, Optional<int> O)
: Reg(R), Offset(O) {}
Optional<unsigned> Reg;
Optional<int> Offset;
};
std::vector<MBBCFAInfo> MBBVector;
SmallDenseMap<unsigned, CSRSavedLocation, 16> CSRLocMap;
void calculateCFAInfo(MachineFunction &MF);
void calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo);
void updateSuccCFAInfo(MBBCFAInfo &MBBInfo);
bool insertCFIInstrs(MachineFunction &MF);
int getCorrectCFAOffset(MachineBasicBlock *MBB) {
return MBBVector[MBB->getNumber()].IncomingCFAOffset;
}
void reportCFAError(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
void reportCSRError(const MBBCFAInfo &Pred, const MBBCFAInfo &Succ);
unsigned verify(MachineFunction &MF);
};
}
char CFIInstrInserter::ID = 0;
INITIALIZE_PASS(CFIInstrInserter, "cfi-instr-inserter",
"Check CFA info and insert CFI instructions if needed", false,
false)
FunctionPass *llvm::createCFIInstrInserter() { return new CFIInstrInserter(); }
void CFIInstrInserter::calculateCFAInfo(MachineFunction &MF) {
int InitialOffset =
MF.getSubtarget().getFrameLowering()->getInitialCFAOffset(MF);
unsigned InitialRegister =
MF.getSubtarget().getFrameLowering()->getInitialCFARegister(MF);
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
unsigned NumRegs = TRI.getNumRegs();
for (MachineBasicBlock &MBB : MF) {
MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
MBBInfo.MBB = &MBB;
MBBInfo.IncomingCFAOffset = InitialOffset;
MBBInfo.OutgoingCFAOffset = InitialOffset;
MBBInfo.IncomingCFARegister = InitialRegister;
MBBInfo.OutgoingCFARegister = InitialRegister;
MBBInfo.IncomingCSRSaved.resize(NumRegs);
MBBInfo.OutgoingCSRSaved.resize(NumRegs);
}
CSRLocMap.clear();
updateSuccCFAInfo(MBBVector[MF.front().getNumber()]);
}
void CFIInstrInserter::calculateOutgoingCFAInfo(MBBCFAInfo &MBBInfo) {
int SetOffset = MBBInfo.IncomingCFAOffset;
unsigned SetRegister = MBBInfo.IncomingCFARegister;
MachineFunction *MF = MBBInfo.MBB->getParent();
const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
unsigned NumRegs = TRI.getNumRegs();
BitVector CSRSaved(NumRegs), CSRRestored(NumRegs);
for (MachineInstr &MI : *MBBInfo.MBB) {
if (MI.isCFIInstruction()) {
Optional<unsigned> CSRReg;
Optional<int> CSROffset;
unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
const MCCFIInstruction &CFI = Instrs[CFIIndex];
switch (CFI.getOperation()) {
case MCCFIInstruction::OpDefCfaRegister:
SetRegister = CFI.getRegister();
break;
case MCCFIInstruction::OpDefCfaOffset:
SetOffset = CFI.getOffset();
break;
case MCCFIInstruction::OpAdjustCfaOffset:
SetOffset += CFI.getOffset();
break;
case MCCFIInstruction::OpDefCfa:
SetRegister = CFI.getRegister();
SetOffset = CFI.getOffset();
break;
case MCCFIInstruction::OpOffset:
CSROffset = CFI.getOffset();
break;
case MCCFIInstruction::OpRegister:
CSRReg = CFI.getRegister2();
break;
case MCCFIInstruction::OpRelOffset:
CSROffset = CFI.getOffset() - SetOffset;
break;
case MCCFIInstruction::OpRestore:
CSRRestored.set(CFI.getRegister());
break;
case MCCFIInstruction::OpLLVMDefAspaceCfa:
#ifndef NDEBUG
report_fatal_error(
"Support for cfi_llvm_def_aspace_cfa not implemented! Value of CFA "
"may be incorrect!\n");
#endif
break;
case MCCFIInstruction::OpRememberState:
#ifndef NDEBUG
report_fatal_error(
"Support for cfi_remember_state not implemented! Value of CFA "
"may be incorrect!\n");
#endif
break;
case MCCFIInstruction::OpRestoreState:
#ifndef NDEBUG
report_fatal_error(
"Support for cfi_restore_state not implemented! Value of CFA may "
"be incorrect!\n");
#endif
break;
case MCCFIInstruction::OpUndefined:
case MCCFIInstruction::OpSameValue:
case MCCFIInstruction::OpEscape:
case MCCFIInstruction::OpWindowSave:
case MCCFIInstruction::OpNegateRAState:
case MCCFIInstruction::OpGnuArgsSize:
break;
}
if (CSRReg || CSROffset) {
auto It = CSRLocMap.find(CFI.getRegister());
if (It == CSRLocMap.end()) {
CSRLocMap.insert(
{CFI.getRegister(), CSRSavedLocation(CSRReg, CSROffset)});
} else if (It->second.Reg != CSRReg || It->second.Offset != CSROffset) {
llvm_unreachable("Different saved locations for the same CSR");
}
CSRSaved.set(CFI.getRegister());
}
}
}
MBBInfo.Processed = true;
MBBInfo.OutgoingCFAOffset = SetOffset;
MBBInfo.OutgoingCFARegister = SetRegister;
BitVector::apply([](auto x, auto y, auto z) { return (x | y) & ~z; },
MBBInfo.OutgoingCSRSaved, MBBInfo.IncomingCSRSaved, CSRSaved,
CSRRestored);
}
void CFIInstrInserter::updateSuccCFAInfo(MBBCFAInfo &MBBInfo) {
SmallVector<MachineBasicBlock *, 4> Stack;
Stack.push_back(MBBInfo.MBB);
do {
MachineBasicBlock *Current = Stack.pop_back_val();
MBBCFAInfo &CurrentInfo = MBBVector[Current->getNumber()];
calculateOutgoingCFAInfo(CurrentInfo);
for (auto *Succ : CurrentInfo.MBB->successors()) {
MBBCFAInfo &SuccInfo = MBBVector[Succ->getNumber()];
if (!SuccInfo.Processed) {
SuccInfo.IncomingCFAOffset = CurrentInfo.OutgoingCFAOffset;
SuccInfo.IncomingCFARegister = CurrentInfo.OutgoingCFARegister;
SuccInfo.IncomingCSRSaved = CurrentInfo.OutgoingCSRSaved;
Stack.push_back(Succ);
}
}
} while (!Stack.empty());
}
bool CFIInstrInserter::insertCFIInstrs(MachineFunction &MF) {
const MBBCFAInfo *PrevMBBInfo = &MBBVector[MF.front().getNumber()];
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
bool InsertedCFIInstr = false;
BitVector SetDifference;
for (MachineBasicBlock &MBB : MF) {
if (MBB.getNumber() == MF.front().getNumber()) continue;
const MBBCFAInfo &MBBInfo = MBBVector[MBB.getNumber()];
auto MBBI = MBBInfo.MBB->begin();
DebugLoc DL = MBBInfo.MBB->findDebugLoc(MBBI);
const bool ForceFullCFA = MBB.isBeginSection();
if ((PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset &&
PrevMBBInfo->OutgoingCFARegister != MBBInfo.IncomingCFARegister) ||
ForceFullCFA) {
unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
nullptr, MBBInfo.IncomingCFARegister, getCorrectCFAOffset(&MBB)));
BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
InsertedCFIInstr = true;
} else if (PrevMBBInfo->OutgoingCFAOffset != MBBInfo.IncomingCFAOffset) {
unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
nullptr, getCorrectCFAOffset(&MBB)));
BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
InsertedCFIInstr = true;
} else if (PrevMBBInfo->OutgoingCFARegister !=
MBBInfo.IncomingCFARegister) {
unsigned CFIIndex =
MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
nullptr, MBBInfo.IncomingCFARegister));
BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
InsertedCFIInstr = true;
}
if (ForceFullCFA) {
MF.getSubtarget().getFrameLowering()->emitCalleeSavedFrameMovesFullCFA(
*MBBInfo.MBB, MBBI);
InsertedCFIInstr = true;
PrevMBBInfo = &MBBInfo;
continue;
}
BitVector::apply([](auto x, auto y) { return x & ~y; }, SetDifference,
PrevMBBInfo->OutgoingCSRSaved, MBBInfo.IncomingCSRSaved);
for (int Reg : SetDifference.set_bits()) {
unsigned CFIIndex =
MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
InsertedCFIInstr = true;
}
BitVector::apply([](auto x, auto y) { return x & ~y; }, SetDifference,
MBBInfo.IncomingCSRSaved, PrevMBBInfo->OutgoingCSRSaved);
for (int Reg : SetDifference.set_bits()) {
auto it = CSRLocMap.find(Reg);
assert(it != CSRLocMap.end() && "Reg should have an entry in CSRLocMap");
unsigned CFIIndex;
CSRSavedLocation RO = it->second;
if (!RO.Reg && RO.Offset) {
CFIIndex = MF.addFrameInst(
MCCFIInstruction::createOffset(nullptr, Reg, *RO.Offset));
} else if (RO.Reg && !RO.Offset) {
CFIIndex = MF.addFrameInst(
MCCFIInstruction::createRegister(nullptr, Reg, *RO.Reg));
} else {
llvm_unreachable("RO.Reg and RO.Offset cannot both be valid/invalid");
}
BuildMI(*MBBInfo.MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex);
InsertedCFIInstr = true;
}
PrevMBBInfo = &MBBInfo;
}
return InsertedCFIInstr;
}
void CFIInstrInserter::reportCFAError(const MBBCFAInfo &Pred,
const MBBCFAInfo &Succ) {
errs() << "*** Inconsistent CFA register and/or offset between pred and succ "
"***\n";
errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
<< " in " << Pred.MBB->getParent()->getName()
<< " outgoing CFA Reg:" << Pred.OutgoingCFARegister << "\n";
errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
<< " in " << Pred.MBB->getParent()->getName()
<< " outgoing CFA Offset:" << Pred.OutgoingCFAOffset << "\n";
errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
<< " incoming CFA Reg:" << Succ.IncomingCFARegister << "\n";
errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
<< " incoming CFA Offset:" << Succ.IncomingCFAOffset << "\n";
}
void CFIInstrInserter::reportCSRError(const MBBCFAInfo &Pred,
const MBBCFAInfo &Succ) {
errs() << "*** Inconsistent CSR Saved between pred and succ in function "
<< Pred.MBB->getParent()->getName() << " ***\n";
errs() << "Pred: " << Pred.MBB->getName() << " #" << Pred.MBB->getNumber()
<< " outgoing CSR Saved: ";
for (int Reg : Pred.OutgoingCSRSaved.set_bits())
errs() << Reg << " ";
errs() << "\n";
errs() << "Succ: " << Succ.MBB->getName() << " #" << Succ.MBB->getNumber()
<< " incoming CSR Saved: ";
for (int Reg : Succ.IncomingCSRSaved.set_bits())
errs() << Reg << " ";
errs() << "\n";
}
unsigned CFIInstrInserter::verify(MachineFunction &MF) {
unsigned ErrorNum = 0;
for (auto *CurrMBB : depth_first(&MF)) {
const MBBCFAInfo &CurrMBBInfo = MBBVector[CurrMBB->getNumber()];
for (MachineBasicBlock *Succ : CurrMBB->successors()) {
const MBBCFAInfo &SuccMBBInfo = MBBVector[Succ->getNumber()];
if (SuccMBBInfo.IncomingCFAOffset != CurrMBBInfo.OutgoingCFAOffset ||
SuccMBBInfo.IncomingCFARegister != CurrMBBInfo.OutgoingCFARegister) {
if (SuccMBBInfo.MBB->succ_empty() && !SuccMBBInfo.MBB->isReturnBlock())
continue;
reportCFAError(CurrMBBInfo, SuccMBBInfo);
ErrorNum++;
}
if (SuccMBBInfo.IncomingCSRSaved != CurrMBBInfo.OutgoingCSRSaved) {
reportCSRError(CurrMBBInfo, SuccMBBInfo);
ErrorNum++;
}
}
}
return ErrorNum;
}