#include "LiveDebugVariables.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntervalMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/LiveInterval.h"
#include "llvm/CodeGen/LiveIntervals.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/VirtRegMap.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <memory>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "livedebugvars"
static cl::opt<bool>
EnableLDV("live-debug-variables", cl::init(true),
cl::desc("Enable the live debug variables pass"), cl::Hidden);
STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
char LiveDebugVariables::ID = 0;
INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
"Debug Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
"Debug Variable Analysis", false, false)
void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<MachineDominatorTree>();
AU.addRequiredTransitive<LiveIntervals>();
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
}
enum : unsigned { UndefLocNo = ~0U };
namespace {
class DbgVariableValue {
public:
DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
const DIExpression &Expr)
: WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
assert(!(WasIndirect && WasList) &&
"DBG_VALUE_LISTs should not be indirect.");
SmallVector<unsigned> LocNoVec;
for (unsigned LocNo : NewLocs) {
auto It = find(LocNoVec, LocNo);
if (It == LocNoVec.end())
LocNoVec.push_back(LocNo);
else {
unsigned OpIdx = LocNoVec.size();
unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
Expression =
DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
}
}
if (LocNoVec.size() < 64) {
LocNoCount = LocNoVec.size();
if (LocNoCount > 0) {
LocNos = std::make_unique<unsigned[]>(LocNoCount);
std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
}
} else {
LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
"locations, dropping...\n");
LocNoCount = 1;
Expression =
DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0,
dwarf::DW_OP_stack_value});
if (auto FragmentInfoOpt = Expr.getFragmentInfo())
Expression = *DIExpression::createFragmentExpression(
Expression, FragmentInfoOpt->OffsetInBits,
FragmentInfoOpt->SizeInBits);
LocNos = std::make_unique<unsigned[]>(LocNoCount);
LocNos[0] = UndefLocNo;
}
}
DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
DbgVariableValue(const DbgVariableValue &Other)
: LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
WasList(Other.getWasList()), Expression(Other.getExpression()) {
if (Other.getLocNoCount()) {
LocNos.reset(new unsigned[Other.getLocNoCount()]);
std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
}
}
DbgVariableValue &operator=(const DbgVariableValue &Other) {
if (this == &Other)
return *this;
if (Other.getLocNoCount()) {
LocNos.reset(new unsigned[Other.getLocNoCount()]);
std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
} else {
LocNos.release();
}
LocNoCount = Other.getLocNoCount();
WasIndirect = Other.getWasIndirect();
WasList = Other.getWasList();
Expression = Other.getExpression();
return *this;
}
const DIExpression *getExpression() const { return Expression; }
uint8_t getLocNoCount() const { return LocNoCount; }
bool containsLocNo(unsigned LocNo) const {
return is_contained(loc_nos(), LocNo);
}
bool getWasIndirect() const { return WasIndirect; }
bool getWasList() const { return WasList; }
bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
SmallVector<unsigned, 4> NewLocNos;
for (unsigned LocNo : loc_nos())
NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
: LocNo);
return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
}
DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
SmallVector<unsigned> NewLocNos;
for (unsigned LocNo : loc_nos())
NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
}
DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
SmallVector<unsigned> NewLocNos;
NewLocNos.assign(loc_nos_begin(), loc_nos_end());
auto OldLocIt = find(NewLocNos, OldLocNo);
assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
*OldLocIt = NewLocNo;
return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
}
bool hasLocNoGreaterThan(unsigned LocNo) const {
return any_of(loc_nos(),
[LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
}
void printLocNos(llvm::raw_ostream &OS) const {
for (const unsigned &Loc : loc_nos())
OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
}
friend inline bool operator==(const DbgVariableValue &LHS,
const DbgVariableValue &RHS) {
if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
LHS.Expression) !=
std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
return false;
return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
RHS.loc_nos_begin());
}
friend inline bool operator!=(const DbgVariableValue &LHS,
const DbgVariableValue &RHS) {
return !(LHS == RHS);
}
unsigned *loc_nos_begin() { return LocNos.get(); }
const unsigned *loc_nos_begin() const { return LocNos.get(); }
unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
ArrayRef<unsigned> loc_nos() const {
return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
}
private:
std::unique_ptr<unsigned[]> LocNos;
uint8_t LocNoCount : 6;
bool WasIndirect : 1;
bool WasList : 1;
const DIExpression *Expression = nullptr;
};
}
using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
using SpillOffsetMap = DenseMap<unsigned, unsigned>;
using BlockSkipInstsMap =
DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
namespace {
class LDVImpl;
class UserValue {
const DILocalVariable *Variable; const Optional<DIExpression::FragmentInfo> Fragment;
DebugLoc dl; UserValue *leader; UserValue *next = nullptr;
SmallVector<MachineOperand, 4> locations;
LocMap locInts;
SmallSet<SlotIndex, 2> trimmedDefs;
void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
SlotIndex StopIdx, DbgVariableValue DbgValue,
ArrayRef<bool> LocSpills,
ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
BlockSkipInstsMap &BBSkipInstsMap);
bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
LiveIntervals &LIS);
public:
UserValue(const DILocalVariable *var,
Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
LocMap::Allocator &alloc)
: Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
locInts(alloc) {}
UserValue *getLeader() {
UserValue *l = leader;
while (l != l->leader)
l = l->leader;
return leader = l;
}
UserValue *getNext() const { return next; }
static UserValue *merge(UserValue *L1, UserValue *L2) {
L2 = L2->getLeader();
if (!L1)
return L2;
L1 = L1->getLeader();
if (L1 == L2)
return L1;
UserValue *End = L2;
while (End->next) {
End->leader = L1;
End = End->next;
}
End->leader = L1;
End->next = L1->next;
L1->next = L2;
return L1;
}
unsigned getLocationNo(const MachineOperand &LocMO) {
if (LocMO.isReg()) {
if (LocMO.getReg() == 0)
return UndefLocNo;
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (locations[i].isReg() &&
locations[i].getReg() == LocMO.getReg() &&
locations[i].getSubReg() == LocMO.getSubReg())
return i;
} else
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (LocMO.isIdenticalTo(locations[i]))
return i;
locations.push_back(LocMO);
locations.back().clearParent();
if (locations.back().isReg()) {
if (locations.back().isDef())
locations.back().setIsDead(false);
locations.back().setIsUse();
}
return locations.size() - 1;
}
void removeLocationIfUnused(unsigned LocNo) {
for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
const DbgVariableValue &DbgValue = I.value();
if (DbgValue.containsLocNo(LocNo))
return;
}
locations.erase(locations.begin() + LocNo);
for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
const DbgVariableValue &DbgValue = I.value();
if (DbgValue.hasLocNoGreaterThan(LocNo))
I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
}
}
void mapVirtRegs(LDVImpl *LDV);
void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
bool IsList, const DIExpression &Expr) {
SmallVector<unsigned> Locs;
for (const MachineOperand &Op : LocMOs)
Locs.push_back(getLocationNo(Op));
DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
LocMap::iterator I = locInts.find(Idx);
if (!I.valid() || I.start() != Idx)
I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
else
I.setValue(std::move(DbgValue));
}
void extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
&LiveIntervalInfo,
Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
LiveIntervals &LIS);
void addDefsFromCopies(
DbgVariableValue DbgValue,
SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
SlotIndex KilledAt,
SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
MachineRegisterInfo &MRI, LiveIntervals &LIS);
void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
LiveIntervals &LIS, LexicalScopes &LS);
bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
LiveIntervals &LIS);
void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
SpillOffsetMap &SpillOffsets);
void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
const SpillOffsetMap &SpillOffsets,
BlockSkipInstsMap &BBSkipInstsMap);
const DebugLoc &getDebugLoc() { return dl; }
void print(raw_ostream &, const TargetRegisterInfo *);
};
class UserLabel {
const DILabel *Label; DebugLoc dl; SlotIndex loc;
void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
LiveIntervals &LIS, const TargetInstrInfo &TII,
BlockSkipInstsMap &BBSkipInstsMap);
public:
UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
: Label(label), dl(std::move(L)), loc(Idx) {}
bool matches(const DILabel *L, const DILocation *IA,
const SlotIndex Index) const {
return Label == L && dl->getInlinedAt() == IA && loc == Index;
}
void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
BlockSkipInstsMap &BBSkipInstsMap);
const DebugLoc &getDebugLoc() { return dl; }
void print(raw_ostream &, const TargetRegisterInfo *);
};
class LDVImpl {
LiveDebugVariables &pass;
LocMap::Allocator allocator;
MachineFunction *MF = nullptr;
LiveIntervals *LIS;
const TargetRegisterInfo *TRI;
struct PHIValPos {
SlotIndex SI; Register Reg; unsigned SubReg; };
std::map<unsigned, PHIValPos> PHIValToPos;
DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
struct InstrPos {
MachineInstr *MI; SlotIndex Idx; MachineBasicBlock *MBB; };
SmallVector<InstrPos, 32> StashedDebugInstrs;
bool EmitDone = false;
bool ModifiedMF = false;
SmallVector<std::unique_ptr<UserValue>, 8> userValues;
SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
using VRMap = DenseMap<unsigned, UserValue *>;
VRMap virtRegToEqClass;
using UVMap = DenseMap<DebugVariable, UserValue *>;
UVMap userVarMap;
UserValue *getUserValue(const DILocalVariable *Var,
Optional<DIExpression::FragmentInfo> Fragment,
const DebugLoc &DL);
UserValue *lookupVirtReg(Register VirtReg);
bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
bool collectDebugValues(MachineFunction &mf, bool InstrRef);
void computeIntervals();
public:
LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
void clear() {
MF = nullptr;
PHIValToPos.clear();
RegToPHIIdx.clear();
StashedDebugInstrs.clear();
userValues.clear();
userLabels.clear();
virtRegToEqClass.clear();
userVarMap.clear();
assert((!ModifiedMF || EmitDone) &&
"Dbg values are not emitted in LDV");
EmitDone = false;
ModifiedMF = false;
}
void mapVirtReg(Register VirtReg, UserValue *EC);
void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
void emitDebugValues(VirtRegMap *VRM);
void print(raw_ostream&);
};
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
const LLVMContext &Ctx) {
if (!DL)
return;
auto *Scope = cast<DIScope>(DL.getScope());
CommentOS << Scope->getFilename();
CommentOS << ':' << DL.getLine();
if (DL.getCol() != 0)
CommentOS << ':' << DL.getCol();
DebugLoc InlinedAtDL = DL.getInlinedAt();
if (!InlinedAtDL)
return;
CommentOS << " @[ ";
printDebugLoc(InlinedAtDL, CommentOS, Ctx);
CommentOS << " ]";
}
static void printExtendedName(raw_ostream &OS, const DINode *Node,
const DILocation *DL) {
const LLVMContext &Ctx = Node->getContext();
StringRef Res;
unsigned Line = 0;
if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
Res = V->getName();
Line = V->getLine();
} else if (const auto *L = dyn_cast<const DILabel>(Node)) {
Res = L->getName();
Line = L->getLine();
}
if (!Res.empty())
OS << Res << "," << Line;
auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
if (InlinedAt) {
if (DebugLoc InlinedAtDL = InlinedAt) {
OS << " @[";
printDebugLoc(InlinedAtDL, OS, Ctx);
OS << "]";
}
}
}
void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
OS << "!\"";
printExtendedName(OS, Variable, dl);
OS << "\"\t";
for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
OS << " [" << I.start() << ';' << I.stop() << "):";
if (I.value().isUndef())
OS << " undef";
else {
I.value().printLocNos(OS);
if (I.value().getWasIndirect())
OS << " ind";
else if (I.value().getWasList())
OS << " list";
}
}
for (unsigned i = 0, e = locations.size(); i != e; ++i) {
OS << " Loc" << i << '=';
locations[i].print(OS, TRI);
}
OS << '\n';
}
void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
OS << "!\"";
printExtendedName(OS, Label, dl);
OS << "\"\t";
OS << loc;
OS << '\n';
}
void LDVImpl::print(raw_ostream &OS) {
OS << "********** DEBUG VARIABLES **********\n";
for (auto &userValue : userValues)
userValue->print(OS, TRI);
OS << "********** DEBUG LABELS **********\n";
for (auto &userLabel : userLabels)
userLabel->print(OS, TRI);
}
#endif
void UserValue::mapVirtRegs(LDVImpl *LDV) {
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (locations[i].isReg() &&
Register::isVirtualRegister(locations[i].getReg()))
LDV->mapVirtReg(locations[i].getReg(), this);
}
UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
Optional<DIExpression::FragmentInfo> Fragment,
const DebugLoc &DL) {
DebugVariable ID(Var, Fragment, DL->getInlinedAt());
UserValue *&UV = userVarMap[ID];
if (!UV) {
userValues.push_back(
std::make_unique<UserValue>(Var, Fragment, DL, allocator));
UV = userValues.back().get();
}
return UV;
}
void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs");
UserValue *&Leader = virtRegToEqClass[VirtReg];
Leader = UserValue::merge(Leader, EC);
}
UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
return UV->getLeader();
return nullptr;
}
bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
if (!MI.isDebugValue()) {
LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
return false;
}
if (!MI.getDebugVariableOp().isMetadata()) {
LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
<< MI);
return false;
}
if (MI.isNonListDebugValue() &&
(MI.getNumOperands() != 4 ||
!(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
return false;
}
bool Discard = false;
for (const MachineOperand &Op : MI.debug_operands()) {
if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) {
const Register Reg = Op.getReg();
if (!LIS->hasInterval(Reg)) {
Discard = true;
LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
<< " " << MI);
} else {
const LiveInterval &LI = LIS->getInterval(Reg);
LiveQueryResult LRQ = LI.Query(Idx);
if (!LRQ.valueOutOrDead()) {
Discard = true;
LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
<< " " << MI);
}
}
}
}
bool IsIndirect = MI.isDebugOffsetImm();
if (IsIndirect)
assert(MI.getDebugOffset().getImm() == 0 &&
"DBG_VALUE with nonzero offset");
bool IsList = MI.isDebugValueList();
const DILocalVariable *Var = MI.getDebugVariable();
const DIExpression *Expr = MI.getDebugExpression();
UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
if (!Discard)
UV->addDef(Idx,
ArrayRef<MachineOperand>(MI.debug_operands().begin(),
MI.debug_operands().end()),
IsIndirect, IsList, *Expr);
else {
MachineOperand MO = MachineOperand::CreateReg(0U, false);
MO.setIsDebug();
SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
}
return true;
}
MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
SlotIndex Idx) {
assert(MI.isDebugValue() || MI.isDebugRef() || MI.isDebugPHI());
if (MI.isDebugValue())
assert(!MI.getOperand(0).isReg() || !MI.getOperand(0).getReg().isVirtual());
auto NextInst = std::next(MI.getIterator());
auto *MBB = MI.getParent();
MI.removeFromParent();
StashedDebugInstrs.push_back({&MI, Idx, MBB});
return NextInst;
}
bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
LLVM_DEBUG(dbgs() << "Can't handle " << MI);
return false;
}
const DILabel *Label = MI.getDebugLabel();
const DebugLoc &DL = MI.getDebugLoc();
bool Found = false;
for (auto const &L : userLabels) {
if (L->matches(Label, DL->getInlinedAt(), Idx)) {
Found = true;
break;
}
}
if (!Found)
userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
return true;
}
bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
bool Changed = false;
for (MachineBasicBlock &MBB : mf) {
for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
MBBI != MBBE;) {
if (!MBBI->isDebugOrPseudoInstr()) {
++MBBI;
continue;
}
SlotIndex Idx =
MBBI == MBB.begin()
? LIS->getMBBStartIdx(&MBB)
: LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
do {
if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
MBBI->isDebugRef())) {
MBBI = handleDebugInstr(*MBBI, Idx);
Changed = true;
} else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
(MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
MBBI = MBB.erase(MBBI);
Changed = true;
} else
++MBBI;
} while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
}
}
return Changed;
}
void UserValue::extendDef(
SlotIndex Idx, DbgVariableValue DbgValue,
SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
&LiveIntervalInfo,
Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
LiveIntervals &LIS) {
SlotIndex Start = Idx;
MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
SlotIndex Stop = LIS.getMBBEndIdx(MBB);
LocMap::iterator I = locInts.find(Start);
for (auto &LII : LiveIntervalInfo) {
LiveRange *LR = LII.second.first;
assert(LR && LII.second.second && "Missing range info for Idx.");
LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
assert(Segment && Segment->valno == LII.second.second &&
"Invalid VNInfo for Idx given?");
if (Segment->end < Stop) {
Stop = Segment->end;
Kills = {Stop, {LII.first}};
} else if (Segment->end == Stop && Kills) {
Kills->second.push_back(LII.first);
}
}
if (I.valid() && I.start() <= Start) {
Start = Start.getNextSlot();
if (I.value() != DbgValue || I.stop() != Start) {
Kills = None;
return;
}
++I;
}
if (I.valid() && I.start() < Stop) {
Stop = I.start();
Kills = None;
}
if (Start < Stop) {
DbgVariableValue ExtDbgValue(DbgValue);
I.insert(Start, Stop, std::move(ExtDbgValue));
}
}
void UserValue::addDefsFromCopies(
DbgVariableValue DbgValue,
SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
SlotIndex KilledAt,
SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
MachineRegisterInfo &MRI, LiveIntervals &LIS) {
if (any_of(LocIntervals, [](auto LocI) {
return !Register::isVirtualRegister(LocI.second->reg());
}))
return;
SmallDenseMap<unsigned,
SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
CopyValues;
for (auto &LocInterval : LocIntervals) {
unsigned LocNo = LocInterval.first;
LiveInterval *LI = LocInterval.second;
for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
MachineInstr *MI = MO.getParent();
if (MO.getSubReg() || !MI->isCopy())
continue;
Register DstReg = MI->getOperand(0).getReg();
if (!Register::isVirtualRegister(DstReg))
continue;
SlotIndex Idx = LIS.getInstructionIndex(*MI);
LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
if (!I.valid() || I.value() != DbgValue)
continue;
if (!LIS.hasInterval(DstReg))
continue;
LiveInterval *DstLI = &LIS.getInterval(DstReg);
const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
}
}
if (CopyValues.empty())
return;
#if !defined(NDEBUG)
for (auto &LocInterval : LocIntervals)
LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
<< " copies of " << *LocInterval.second << '\n');
#endif
LocMap::iterator I = locInts.find(KilledAt);
if (I.valid() && I.start() <= KilledAt)
return;
DbgVariableValue NewValue(DbgValue);
for (auto &LocInterval : LocIntervals) {
unsigned LocNo = LocInterval.first;
bool FoundCopy = false;
for (auto &LIAndVNI : CopyValues[LocNo]) {
LiveInterval *DstLI = LIAndVNI.first;
const VNInfo *DstVNI = LIAndVNI.second;
if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
continue;
LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
<< DstVNI->id << " in " << *DstLI << '\n');
MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
FoundCopy = true;
break;
}
if (!FoundCopy)
return;
}
I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
NewDefs.push_back(std::make_pair(KilledAt, NewValue));
}
void UserValue::computeIntervals(MachineRegisterInfo &MRI,
const TargetRegisterInfo &TRI,
LiveIntervals &LIS, LexicalScopes &LS) {
SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
if (!I.value().isUndef())
Defs.push_back(std::make_pair(I.start(), I.value()));
for (unsigned i = 0; i != Defs.size(); ++i) {
SlotIndex Idx = Defs[i].first;
DbgVariableValue DbgValue = Defs[i].second;
SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
SmallVector<const VNInfo *, 4> VNIs;
bool ShouldExtendDef = false;
for (unsigned LocNo : DbgValue.loc_nos()) {
const MachineOperand &LocMO = locations[LocNo];
if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) {
ShouldExtendDef |= !LocMO.isReg();
continue;
}
ShouldExtendDef = true;
LiveInterval *LI = nullptr;
const VNInfo *VNI = nullptr;
if (LIS.hasInterval(LocMO.getReg())) {
LI = &LIS.getInterval(LocMO.getReg());
VNI = LI->getVNInfoAt(Idx);
}
if (LI && VNI)
LIs[LocNo] = {LI, VNI};
}
if (ShouldExtendDef) {
Optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
extendDef(Idx, DbgValue, LIs, Kills, LIS);
if (Kills) {
SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
bool AnySubreg = false;
for (unsigned LocNo : Kills->second) {
const MachineOperand &LocMO = this->locations[LocNo];
if (LocMO.getSubReg()) {
AnySubreg = true;
break;
}
LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
KilledLocIntervals.push_back({LocNo, LI});
}
if (!AnySubreg)
addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
MRI, LIS);
}
}
}
if (!dl.getInlinedAt())
return;
LexicalScope *Scope = LS.findLexicalScope(dl);
if (!Scope)
return;
SlotIndex PrevEnd;
LocMap::iterator I = locInts.begin();
for (const InsnRange &Range : Scope->getRanges()) {
SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
if (Range.first == Range.first->getParent()->begin())
RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
if (PrevEnd && I.start() < PrevEnd) {
SlotIndex IStop = I.stop();
DbgVariableValue DbgValue = I.value();
I.setStopUnchecked(PrevEnd);
++I;
if (RStart < IStop)
I.insert(RStart, IStop, DbgValue);
}
I.advanceTo(RStart);
if (!I.valid())
return;
if (I.start() < RStart) {
I.setStartUnchecked(RStart);
trimmedDefs.insert(RStart);
}
REnd = REnd.getNextIndex();
I.advanceTo(REnd);
if (!I.valid())
return;
PrevEnd = REnd;
}
if (PrevEnd && I.start() < PrevEnd)
I.setStopUnchecked(PrevEnd);
}
void LDVImpl::computeIntervals() {
LexicalScopes LS;
LS.initialize(*MF);
for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
userValues[i]->mapVirtRegs(this);
}
}
bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
clear();
MF = &mf;
LIS = &pass.getAnalysis<LiveIntervals>();
TRI = mf.getSubtarget().getRegisterInfo();
LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
<< mf.getName() << " **********\n");
bool Changed = collectDebugValues(mf, InstrRef);
computeIntervals();
LLVM_DEBUG(print(dbgs()));
SlotIndexes *Slots = LIS->getSlotIndexes();
for (const auto &PHIIt : MF->DebugPHIPositions) {
const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
MachineBasicBlock *MBB = Position.MBB;
Register Reg = Position.Reg;
unsigned SubReg = Position.SubReg;
SlotIndex SI = Slots->getMBBStartIdx(MBB);
PHIValPos VP = {SI, Reg, SubReg};
PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
RegToPHIIdx[Reg].push_back(PHIIt.first);
}
ModifiedMF = Changed;
return Changed;
}
static void removeDebugInstrs(MachineFunction &mf) {
for (MachineBasicBlock &MBB : mf) {
for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
if (MI.isDebugInstr())
MBB.erase(&MI);
}
}
bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
if (!EnableLDV)
return false;
if (!mf.getFunction().getSubprogram()) {
removeDebugInstrs(mf);
return false;
}
bool InstrRef = mf.useDebugInstrRef();
if (!pImpl)
pImpl = new LDVImpl(this);
return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
}
void LiveDebugVariables::releaseMemory() {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->clear();
}
LiveDebugVariables::~LiveDebugVariables() {
if (pImpl)
delete static_cast<LDVImpl*>(pImpl);
}
bool
UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
LiveIntervals& LIS) {
LLVM_DEBUG({
dbgs() << "Splitting Loc" << OldLocNo << '\t';
print(dbgs(), nullptr);
});
bool DidChange = false;
LocMap::iterator LocMapI;
LocMapI.setMap(locInts);
for (Register NewReg : NewRegs) {
LiveInterval *LI = &LIS.getInterval(NewReg);
if (LI->empty())
continue;
unsigned NewLocNo = UndefLocNo;
LocMapI.find(LI->beginIndex());
if (!LocMapI.valid())
continue;
LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
LiveInterval::iterator LIE = LI->end();
while (LocMapI.valid() && LII != LIE) {
LII = LI->advanceTo(LII, LocMapI.start());
if (LII == LIE)
break;
if (LocMapI.value().containsLocNo(OldLocNo) &&
LII->start < LocMapI.stop()) {
if (NewLocNo == UndefLocNo) {
MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
MO.setSubReg(locations[OldLocNo].getSubReg());
NewLocNo = getLocationNo(MO);
DidChange = true;
}
SlotIndex LStart = LocMapI.start();
SlotIndex LStop = LocMapI.stop();
DbgVariableValue OldDbgValue = LocMapI.value();
if (LStart < LII->start)
LocMapI.setStartUnchecked(LII->start);
if (LStop > LII->end)
LocMapI.setStopUnchecked(LII->end);
LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
if (LStart < LocMapI.start()) {
LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
++LocMapI;
assert(LocMapI.valid() && "Unexpected coalescing");
}
if (LStop > LocMapI.stop()) {
++LocMapI;
LocMapI.insert(LII->end, LStop, OldDbgValue);
--LocMapI;
}
}
if (LII->end < LocMapI.stop()) {
if (++LII == LIE)
break;
LocMapI.advanceTo(LII->start);
} else {
++LocMapI;
if (!LocMapI.valid())
break;
LII = LI->advanceTo(LII, LocMapI.start());
}
}
}
removeLocationIfUnused(OldLocNo);
LLVM_DEBUG({
dbgs() << "Split result: \t";
print(dbgs(), nullptr);
});
return DidChange;
}
bool
UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
LiveIntervals &LIS) {
bool DidChange = false;
for (unsigned i = locations.size(); i ; --i) {
unsigned LocNo = i-1;
const MachineOperand *Loc = &locations[LocNo];
if (!Loc->isReg() || Loc->getReg() != OldReg)
continue;
DidChange |= splitLocation(LocNo, NewRegs, LIS);
}
return DidChange;
}
void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
auto RegIt = RegToPHIIdx.find(OldReg);
if (RegIt == RegToPHIIdx.end())
return;
std::vector<std::pair<Register, unsigned>> NewRegIdxes;
for (unsigned InstrID : RegIt->second) {
auto PHIIt = PHIValToPos.find(InstrID);
assert(PHIIt != PHIValToPos.end());
const SlotIndex &Slot = PHIIt->second.SI;
assert(OldReg == PHIIt->second.Reg);
for (auto NewReg : NewRegs) {
const LiveInterval &LI = LIS->getInterval(NewReg);
auto LII = LI.find(Slot);
if (LII != LI.end() && LII->start <= Slot) {
NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
PHIIt->second.Reg = NewReg;
break;
}
}
}
RegToPHIIdx.erase(RegIt);
for (auto &RegAndInstr : NewRegIdxes)
RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
}
void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
splitPHIRegister(OldReg, NewRegs);
bool DidChange = false;
for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
if (!DidChange)
return;
UserValue *UV = lookupVirtReg(OldReg);
for (Register NewReg : NewRegs)
mapVirtReg(NewReg, UV);
}
void LiveDebugVariables::
splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
}
void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
SpillOffsetMap &SpillOffsets) {
MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
SmallVector<unsigned, 4> LocNoMap(locations.size());
for (unsigned I = 0, E = locations.size(); I != E; ++I) {
bool Spilled = false;
unsigned SpillOffset = 0;
MachineOperand Loc = locations[I];
if (Loc.isReg() && Loc.getReg() &&
Register::isVirtualRegister(Loc.getReg())) {
Register VirtReg = Loc.getReg();
if (VRM.isAssignedReg(VirtReg) &&
Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
} else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
unsigned SpillSize;
const MachineRegisterInfo &MRI = MF.getRegInfo();
const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
SpillOffset, MF);
(void)Success;
Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Spilled = true;
} else {
Loc.setReg(0);
Loc.setSubReg(0);
}
}
auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
LocNoMap[I] = NewLocNo;
}
locations.clear();
SpillOffsets.clear();
for (auto &Pair : NewLocations) {
bool Spilled;
unsigned SpillOffset;
std::tie(Spilled, SpillOffset) = Pair.second;
locations.push_back(Pair.first);
if (Spilled) {
unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
SpillOffsets[NewLocNo] = SpillOffset;
}
}
for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
I.setStart(I.start());
}
}
static MachineBasicBlock::iterator
findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
BlockSkipInstsMap &BBSkipInstsMap) {
SlotIndex Start = LIS.getMBBStartIdx(MBB);
Idx = Idx.getBaseIndex();
MachineInstr *MI;
while (!(MI = LIS.getInstructionFromIndex(Idx))) {
if (Idx == Start) {
MachineBasicBlock::iterator BeginIt;
auto MapIt = BBSkipInstsMap.find(MBB);
if (MapIt == BBSkipInstsMap.end())
BeginIt = MBB->begin();
else
BeginIt = std::next(MapIt->second);
auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
if (I != BeginIt)
BBSkipInstsMap[MBB] = std::prev(I);
return I;
}
Idx = Idx.getPrevIndex();
}
return MI->isTerminator() ? MBB->getFirstTerminator() :
std::next(MachineBasicBlock::iterator(MI));
}
static MachineBasicBlock::iterator
findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
SmallVector<Register, 4> Regs;
for (const MachineOperand &LocMO : LocMOs)
if (LocMO.isReg())
Regs.push_back(LocMO.getReg());
if (Regs.empty())
return MBB->instr_end();
while (I != MBB->end() && !I->isTerminator()) {
if (!LIS.isNotInMIMap(*I) &&
SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
break;
if (any_of(Regs, [&I, &TRI](Register &Reg) {
return I->definesRegister(Reg, &TRI);
}))
return std::next(I);
++I;
}
return MBB->end();
}
void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
SlotIndex StopIdx, DbgVariableValue DbgValue,
ArrayRef<bool> LocSpills,
ArrayRef<unsigned> SpillOffsets,
LiveIntervals &LIS, const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
BlockSkipInstsMap &BBSkipInstsMap) {
SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
MachineBasicBlock::iterator I =
findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
SmallVector<MachineOperand, 8> MOs;
if (DbgValue.isUndef()) {
MOs.assign(DbgValue.loc_nos().size(),
MachineOperand::CreateReg(
0, false, false,
false, false,
false, false,
0, true));
} else {
for (unsigned LocNo : DbgValue.loc_nos())
MOs.push_back(locations[LocNo]);
}
++NumInsertedDebugValues;
assert(cast<DILocalVariable>(Variable)
->isValidLocationForIntrinsic(getDebugLoc()) &&
"Expected inlined-at fields to agree");
const DIExpression *Expr = DbgValue.getExpression();
bool IsIndirect = DbgValue.getWasIndirect();
bool IsList = DbgValue.getWasList();
for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
if (LocSpills[I]) {
if (!IsList) {
uint8_t DIExprFlags = DIExpression::ApplyOffset;
if (IsIndirect)
DIExprFlags |= DIExpression::DerefAfter;
Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
IsIndirect = true;
} else {
SmallVector<uint64_t, 4> Ops;
DIExpression::appendOffset(Ops, SpillOffsets[I]);
Ops.push_back(dwarf::DW_OP_deref);
Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
}
}
assert((!LocSpills[I] || MOs[I].isFI()) &&
"a spilled location must be a frame index");
}
unsigned DbgValueOpcode =
IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
do {
BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
Variable, Expr);
I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
} while (I != MBB->end());
}
void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
LiveIntervals &LIS, const TargetInstrInfo &TII,
BlockSkipInstsMap &BBSkipInstsMap) {
MachineBasicBlock::iterator I =
findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
++NumInsertedDebugLabels;
BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
.addMetadata(Label);
}
void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
const TargetInstrInfo &TII,
const TargetRegisterInfo &TRI,
const SpillOffsetMap &SpillOffsets,
BlockSkipInstsMap &BBSkipInstsMap) {
MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
SlotIndex Start = I.start();
SlotIndex Stop = I.stop();
DbgVariableValue DbgValue = I.value();
SmallVector<bool> SpilledLocs;
SmallVector<unsigned> LocSpillOffsets;
for (unsigned LocNo : DbgValue.loc_nos()) {
auto SpillIt =
!DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
bool Spilled = SpillIt != SpillOffsets.end();
SpilledLocs.push_back(Spilled);
LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
}
if (trimmedDefs.count(Start))
Start = Start.getPrevIndex();
LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
DbgValue.printLocNos(dbg));
MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
LIS, TII, TRI, BBSkipInstsMap);
while (Stop > MBBEnd) {
Start = MBBEnd;
if (++MBB == MFEnd)
break;
MBBEnd = LIS.getMBBEndIdx(&*MBB);
LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
}
LLVM_DEBUG(dbgs() << '\n');
if (MBB == MFEnd)
break;
++I;
}
}
void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
BlockSkipInstsMap &BBSkipInstsMap) {
LLVM_DEBUG(dbgs() << "\t" << loc);
MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
LLVM_DEBUG(dbgs() << '\n');
}
void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
if (!MF)
return;
BlockSkipInstsMap BBSkipInstsMap;
const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
SpillOffsetMap SpillOffsets;
for (auto &userValue : userValues) {
LLVM_DEBUG(userValue->print(dbgs(), TRI));
userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
BBSkipInstsMap);
}
LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
for (auto &userLabel : userLabels) {
LLVM_DEBUG(userLabel->print(dbgs(), TRI));
userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
}
LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
auto Slots = LIS->getSlotIndexes();
for (auto &It : PHIValToPos) {
unsigned InstNum = It.first;
auto Slot = It.second.SI;
Register Reg = It.second.Reg;
unsigned SubReg = It.second.SubReg;
MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
if (VRM->isAssignedReg(Reg) &&
Register::isPhysicalRegister(VRM->getPhys(Reg))) {
unsigned PhysReg = VRM->getPhys(Reg);
if (SubReg != 0)
PhysReg = TRI->getSubReg(PhysReg, SubReg);
auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
TII->get(TargetOpcode::DBG_PHI));
Builder.addReg(PhysReg);
Builder.addImm(InstNum);
} else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
const MachineRegisterInfo &MRI = MF->getRegInfo();
const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
unsigned SpillSize, SpillOffset;
unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
if (SubReg)
regSizeInBits = TRI->getSubRegIdxSize(SubReg);
bool Success =
TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
if (Success && SpillOffset == 0) {
auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
TII->get(TargetOpcode::DBG_PHI));
Builder.addFrameIndex(VRM->getStackSlot(Reg));
Builder.addImm(InstNum);
Builder.addImm(regSizeInBits);
}
LLVM_DEBUG(
if (SpillOffset != 0) {
dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg <<
" has nonzero offset\n";
}
);
}
}
MF->DebugPHIPositions.clear();
LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
for (auto *StashIt = StashedDebugInstrs.begin();
StashIt != StashedDebugInstrs.end(); ++StashIt) {
SlotIndex Idx = StashIt->Idx;
MachineBasicBlock *MBB = StashIt->MBB;
MachineInstr *MI = StashIt->MI;
auto EmitInstsHere = [this, &StashIt, MBB, Idx,
MI](MachineBasicBlock::iterator InsertPos) {
MBB->insert(InsertPos, MI);
auto NextItem = std::next(StashIt);
while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
"in the same block");
MBB->insert(InsertPos, NextItem->MI);
StashIt = NextItem;
NextItem = std::next(StashIt);
};
};
if (Idx == Slots->getMBBStartIdx(MBB)) {
MachineBasicBlock::iterator InsertPos =
findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
EmitInstsHere(InsertPos);
continue;
}
if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
auto PostDebug = std::next(Pos->getIterator());
PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
EmitInstsHere(PostDebug);
} else {
SlotIndex End = Slots->getMBBEndIdx(MBB);
for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
Pos = Slots->getInstructionFromIndex(Idx);
if (Pos) {
EmitInstsHere(Pos->getIterator());
break;
}
}
if (Idx >= End) {
auto TermIt = MBB->getFirstTerminator();
EmitInstsHere(TermIt);
}
}
}
EmitDone = true;
BBSkipInstsMap.clear();
}
void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->print(dbgs());
}
#endif