37#include "llvm/Config/llvm-config.h"
55 OS <<
"Live variables in machine function: " << MF.
getName() <<
'\n';
63 "Live Variable Analysis",
false,
false)
75 : MF(&MF), MRI(&MF.getRegInfo()), TRI(MF.getSubtarget().getRegisterInfo()) {
80 for (
size_t I = 0, E = VirtRegInfo.size();
I != E; ++
I) {
82 OS <<
"Virtual register '%" <<
I <<
"':\n";
83 VirtRegInfo[Reg].print(OS);
90 if (
MI->getParent() ==
MBB)
96 OS <<
" Alive in blocks: ";
99 OS <<
"\n Killed by:";
101 OS <<
" No instructions.\n\n";
103 for (
unsigned i = 0, e =
Kills.size(); i != e; ++i)
104 OS <<
"\n #" << i <<
": " << *
Kills[i];
109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
115 assert(Reg.isVirtual() &&
"getVarInfo: not a virtual register!");
116 VirtRegInfo.grow(Reg);
117 return VirtRegInfo[Reg];
123 unsigned BBNum =
MBB->getNumber();
127 for (
unsigned i = 0, e = VRInfo.
Kills.size(); i != e; ++i)
128 if (VRInfo.
Kills[i]->getParent() ==
MBB) {
133 if (
MBB == DefBlock)
return;
141 assert(
MBB != &MF->front() &&
"Can't find reaching def for virtreg");
151 while (!WorkList.
empty()) {
159 assert(MRI->getVRegDef(Reg) &&
"Register use before def!");
161 unsigned BBNum =
MBB->getNumber();
166 if (!VRInfo.
Kills.empty() && VRInfo.
Kills.back()->getParent() ==
MBB) {
175 assert(
Kill->getParent() !=
MBB &&
"entry should be at end!");
194 if (
MBB == MRI->getVRegDef(Reg)->getParent())
218 unsigned LastDefDist = 0;
224 unsigned Dist = DistanceMap[Def];
225 if (Dist > LastDefDist) {
240void LiveVariables::HandlePhysRegUse(
Register Reg, MachineInstr &
MI) {
241 MachineInstr *LastDef = PhysRegDef[
Reg.
id()];
243 if (!LastDef && !PhysRegUse[
Reg.
id()]) {
252 MachineInstr *LastPartialDef = FindLastPartialDef(
Reg);
254 if (LastPartialDef) {
258 }
else if (LastDef && !PhysRegUse[
Reg.
id()] &&
271MachineInstr *LiveVariables::FindLastRefOrPartRef(
Register Reg) {
272 MachineInstr *LastDef = PhysRegDef[
Reg.
id()];
273 MachineInstr *LastUse = PhysRegUse[
Reg.
id()];
274 if (!LastDef && !LastUse)
277 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
278 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
279 unsigned LastPartDefDist = 0;
282 if (Def && Def != LastDef) {
285 unsigned Dist = DistanceMap[
Def];
286 if (Dist > LastPartDefDist)
287 LastPartDefDist = Dist;
288 }
else if (MachineInstr *Use = PhysRegUse[
SubReg]) {
289 unsigned Dist = DistanceMap[
Use];
290 if (Dist > LastRefOrPartRefDist) {
291 LastRefOrPartRefDist = Dist;
292 LastRefOrPartRef =
Use;
297 return LastRefOrPartRef;
300bool LiveVariables::HandlePhysRegKill(
Register Reg, MachineInstr *
MI) {
301 MachineInstr *LastDef = PhysRegDef[
Reg.
id()];
302 MachineInstr *LastUse = PhysRegUse[
Reg.
id()];
303 if (!LastDef && !LastUse)
306 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
307 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
325 MachineInstr *LastPartDef =
nullptr;
326 unsigned LastPartDefDist = 0;
327 SmallSet<unsigned, 8> PartUses;
330 if (Def && Def != LastDef) {
333 unsigned Dist = DistanceMap[
Def];
334 if (Dist > LastPartDefDist) {
335 LastPartDefDist = Dist;
340 if (MachineInstr *Use = PhysRegUse[
SubReg]) {
342 unsigned Dist = DistanceMap[
Use];
343 if (Dist > LastRefOrPartRefDist) {
344 LastRefOrPartRefDist = Dist;
345 LastRefOrPartRef =
Use;
350 if (!PhysRegUse[
Reg.
id()]) {
355 PhysRegDef[
Reg.
id()]->addRegisterDead(
Reg, TRI,
true);
361 MachineOperand *MO = PhysRegDef[
Reg.
id()]->findRegisterDefOperand(
369 PhysRegDef[
Reg.
id()]->addOperand(
371 MachineInstr *LastSubRef = FindLastRefOrPartRef(
SubReg);
377 PhysRegUse[
SS] = LastRefOrPartRef;
382 }
else if (LastRefOrPartRef == PhysRegDef[
Reg.
id()] &&
383 LastRefOrPartRef !=
MI) {
408void LiveVariables::HandleRegMask(
const MachineOperand &MO,
unsigned NumRegs) {
412 for (
unsigned Reg = 1;
Reg != NumRegs; ++
Reg) {
414 if (!PhysRegDef[
Reg] && !PhysRegUse[
Reg])
421 unsigned Super =
Reg;
423 if (SR < NumRegs && (PhysRegDef[SR] || PhysRegUse[SR]) &&
426 HandlePhysRegKill(Super,
nullptr);
430void LiveVariables::HandlePhysRegDef(
Register Reg, MachineInstr *
MI,
431 SmallVectorImpl<Register> &Defs) {
433 SmallSet<unsigned, 32> Live;
434 if (PhysRegDef[
Reg.
id()] || PhysRegUse[
Reg.
id()]) {
453 HandlePhysRegKill(
Reg,
MI);
466void LiveVariables::UpdatePhysRegDefs(MachineInstr &
MI,
467 SmallVectorImpl<Register> &Defs) {
468 while (!Defs.
empty()) {
472 PhysRegUse[
SubReg] =
nullptr;
477void LiveVariables::runOnInstr(MachineInstr &
MI,
478 SmallVectorImpl<Register> &Defs,
482 unsigned NumOperandsToProcess =
MI.getNumOperands();
487 NumOperandsToProcess = 1;
493 for (
unsigned i = 0; i != NumOperandsToProcess; ++i) {
494 MachineOperand &MO =
MI.getOperand(i);
503 if (!(MOReg.
isPhysical() && MRI->isReserved(MOReg)))
511 if (MOReg.
isPhysical() && !MRI->isReserved(MOReg))
517 MachineBasicBlock *
MBB =
MI.getParent();
522 else if (!MRI->isReserved(MOReg))
523 HandlePhysRegUse(MOReg,
MI);
527 for (
unsigned Mask : RegMasks)
528 HandleRegMask(
MI.getOperand(Mask), NumRegs);
534 else if (!MRI->isReserved(MOReg))
535 HandlePhysRegDef(MOReg, &
MI, Defs);
537 UpdatePhysRegDefs(
MI, Defs);
540void LiveVariables::runOnBlock(MachineBasicBlock *
MBB,
unsigned NumRegs) {
544 assert(LI.PhysReg.isPhysical() &&
545 "Cannot have a live-in virtual register!");
546 HandlePhysRegDef(LI.PhysReg,
nullptr, Defs);
552 for (MachineInstr &
MI : *
MBB) {
553 if (
MI.isDebugOrPseudoInstr())
555 DistanceMap.insert(std::make_pair(&
MI, Dist++));
557 runOnInstr(
MI, Defs, NumRegs);
565 SmallVectorImpl<Register> &VarInfoVec = PHIVarInfo[
MBB->
getNumber()];
575 SmallSet<unsigned, 4> LiveOuts;
577 if (SuccMBB->isEHPad())
579 for (
const auto &LI : SuccMBB->liveins()) {
580 if (!TRI->isInAllocatableClass(LI.PhysReg))
582 LiveOuts.
insert(LI.PhysReg);
588 for (
unsigned i = 0; i != NumRegs; ++i)
589 if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.
count(i))
590 HandlePhysRegDef(i,
nullptr, Defs);
593void LiveVariables::analyze(MachineFunction &mf) {
596 TRI = MF->getSubtarget().getRegisterInfo();
598 const unsigned NumRegs = TRI->getNumSupportedRegs(mf);
599 PhysRegDef.assign(NumRegs,
nullptr);
600 PhysRegUse.assign(NumRegs,
nullptr);
601 PHIVarInfo.resize(MF->getNumBlockIDs());
615 MachineBasicBlock *
Entry = &MF->front();
616 df_iterator_default_set<MachineBasicBlock*,16> Visited;
619 runOnBlock(
MBB, NumRegs);
621 PhysRegDef.assign(NumRegs,
nullptr);
622 PhysRegUse.assign(NumRegs,
nullptr);
627 for (
unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
629 for (
unsigned j = 0, e2 = VirtRegInfo[
Reg].Kills.size(); j != e2; ++j)
630 if (VirtRegInfo[
Reg].Kills[j] == MRI->getVRegDef(
Reg))
631 VirtRegInfo[
Reg].Kills[
j]->addRegisterDead(
Reg, TRI);
633 VirtRegInfo[
Reg].Kills[
j]->addRegisterKilled(
Reg, TRI);
640 for (
const MachineBasicBlock &
MBB : *MF)
653 VI.AliveBlocks.clear();
665 unsigned NumRealUses = 0;
666 for (
auto &UseMO : MRI->use_nodbg_operands(Reg)) {
667 UseMO.setIsKill(
false);
668 if (!UseMO.readsReg())
677 unsigned Idx = UseMO.getOperandNo();
679 }
else if (&UseBB == &DefBB) {
688 if (NumRealUses == 0) {
689 VI.Kills.push_back(&
DefMI);
690 DefMI.addRegisterDead(Reg,
nullptr);
693 DefMI.clearRegisterDeads(Reg);
696 bool LiveToEndOfDefBB =
false;
697 while (!LiveToEndBlocks.
empty()) {
700 LiveToEndOfDefBB =
true;
712 for (
unsigned UseBBNum : UseBlocks) {
713 if (VI.AliveBlocks.test(UseBBNum))
716 if (&UseBB == &DefBB && LiveToEndOfDefBB)
719 if (
MI.isDebugOrPseudoInstr())
723 if (
MI.readsVirtualRegister(Reg)) {
724 assert(!
MI.killsRegister(Reg,
nullptr));
725 MI.addRegisterKilled(Reg,
nullptr);
726 VI.Kills.push_back(&
MI);
748 if (Reg.isVirtual()) {
750 assert(removed &&
"kill not in register's VarInfo?");
762 for (
const auto &
MBB : Fn)
763 for (
const auto &BBI :
MBB) {
766 for (
unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
767 if (BBI.getOperand(i).readsReg())
768 PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
769 .push_back(BBI.getOperand(i).getReg());
775 unsigned Num =
MBB.getNumber();
783 if (Def && Def->getParent() == &
MBB)
801 unsigned SuccIdx = SuccMBB->getNumber();
802 if (VI.AliveBlocks.test(SuccIdx))
805 if (Kills.
count(SuccMBB))
823 for (; BBI != BBE && BBI->isPHI(); ++BBI) {
825 Defs.
insert(BBI->getOperand(0).getReg());
828 for (
unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
829 if (BBI->getOperand(i+1).getMBB() == BB)
834 for (; BBI != BBE; ++BBI) {
836 if (
Op.isReg() &&
Op.getReg().isVirtual()) {
839 else if (
Op.isKill())
846 for (
unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
857 VI.AliveBlocks.set(NumNew);
872 for (
unsigned R : BV) {
875 VI.AliveBlocks.set(NumNew);
880 BBI != BBE && BBI->isPHI(); ++BBI) {
881 for (
unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
882 if (BBI->getOperand(i + 1).getMBB() == BB &&
883 BBI->getOperand(i).readsReg())
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Implements a dense probed hash-table based set.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LiveVariablesWrapperPass()
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
LLVM_ABI void MarkVirtRegAliveInBlock(VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *BB)
LLVM_ABI void removeVirtualRegistersKilled(MachineInstr &MI)
removeVirtualRegistersKilled - Remove all killed info for the specified instruction.
LLVM_ABI bool isLiveOut(Register Reg, const MachineBasicBlock &MBB)
isLiveOut - Determine if Reg is live out from MBB, when not considering PHI nodes.
LLVM_ABI void HandleVirtRegDef(Register reg, MachineInstr &MI)
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
LLVM_ABI void HandleVirtRegUse(Register reg, MachineBasicBlock *MBB, MachineInstr &MI)
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
LLVM_ABI void addNewBlock(MachineBasicBlock *BB, MachineBasicBlock *DomBB, MachineBasicBlock *SuccBB)
addNewBlock - Add a new basic block BB between DomBB and SuccBB.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
pred_iterator pred_begin()
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsDead(bool Val=true)
void setIsKill(bool Val=true)
void setIsEarlyClobber(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr unsigned id() const
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool test(unsigned Idx) const
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
This class implements an extremely fast bulk output stream that can only output to a stream.
NodeAddr< DefNode * > Def
NodeAddr< UseNode * > Use
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
@ Kill
The last use of a register.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto reverse(ContainerTy &&C)
LLVM_ABI char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
LLVM_ABI char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
A special type used by analysis passes to provide an address that identifies that particular analysis...
VarInfo - This represents the regions where a virtual register is live in the program.
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
LLVM_ABI void dump() const
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
LLVM_ABI MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI bool isLiveIn(const MachineBasicBlock &MBB, Register Reg, MachineRegisterInfo &MRI)
isLiveIn - Is Reg live in to MBB?