20#define DEBUG_TYPE "reaching-defs-analysis"
38 OS <<
"Reaching definitions for for machine function: " << MF.
getName()
45 "Reaching Definitions Analysis",
false,
true)
58 MachineFunctionAnalysisManager::Invalidator &) {
62 return !PAC.preserved() &&
105 int DefFrameIndex = 0;
106 int SrcFrameIndex = 0;
107 if (
TII->isStoreToStackSlot(
MI, DefFrameIndex) ||
108 TII->isStackSlotCopy(
MI, DefFrameIndex, SrcFrameIndex))
109 return DefFrameIndex == FrameIndex;
115 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
116 "Unexpected basic block number.");
117 assert(LiveRegs.empty() &&
"LiveRegs should be empty on BB entry");
118 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
125 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
127 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
131 if (LiveRegs[
static_cast<unsigned>(Unit)] != FunctionLiveInMarker) {
132 LiveRegs[
static_cast<unsigned>(
Unit)] = FunctionLiveInMarker;
133 MBBReachingDefs.append(MBBNumber, Unit, FunctionLiveInMarker);
142 bool Initialized =
false;
144 assert(
unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
145 "Should have pre-allocated MBBInfos for all MBBs");
146 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
149 if (Incoming.empty())
160 for (
unsigned Unit = 0;
Unit != NumRegUnits; ++
Unit)
161 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
165 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
168 for (
unsigned Unit = 0;
Unit != NumRegUnits; ++
Unit)
169 if (LiveRegs[Unit] != ReachingDefDefaultVal)
170 MBBReachingDefs.append(MBBNumber,
static_cast<MCRegUnit
>(Unit),
175 assert(!LiveRegs.empty() &&
"Must enter basic block first.");
177 assert(MBBNumber < MBBOutRegsInfos.size() &&
178 "Unexpected basic block number.");
180 MBBOutRegsInfos[MBBNumber] = LiveRegs;
186 for (
int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
187 if (OutLiveReg != ReachingDefDefaultVal)
188 OutLiveReg -= CurInstr;
193 assert(!
MI->isDebugInstr() &&
"Won't process debug instructions");
195 unsigned MBBNumber =
MI->getParent()->getNumber();
196 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
197 "Unexpected basic block number.");
199 for (
auto &MO :
MI->operands()) {
204 MBBFrameObjsReachingDefs[{MBBNumber,
FrameIndex}].push_back(CurInstr);
208 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
214 if (LiveRegs[
static_cast<unsigned>(Unit)] != CurInstr) {
215 LiveRegs[
static_cast<unsigned>(
Unit)] = CurInstr;
216 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
220 InstIds[
MI] = CurInstr;
226 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
227 "Unexpected basic block number.");
232 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
237 assert(
unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
238 "Should have pre-allocated MBBInfos for all MBBs");
239 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
241 if (Incoming.empty())
244 for (
unsigned Unit = 0;
Unit != NumRegUnits; ++
Unit) {
246 if (Def == ReachingDefDefaultVal)
249 auto Defs = MBBReachingDefs.defs(MBBNumber,
static_cast<MCRegUnit
>(Unit));
250 if (!Defs.empty() && Defs.front() < 0) {
251 if (Defs.front() >= Def)
255 MBBReachingDefs.replaceFront(MBBNumber,
static_cast<MCRegUnit
>(Unit),
259 MBBReachingDefs.prepend(MBBNumber,
static_cast<MCRegUnit
>(Unit), Def);
264 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
265 MBBOutRegsInfos[MBBNumber][
Unit] =
Def - NumInsts;
270void ReachingDefInfo::processBasicBlock(
272 MachineBasicBlock *
MBB = TraversedMBB.
MBB;
274 << (!TraversedMBB.
IsDone ?
": incomplete\n"
275 :
": all preds known\n"));
279 reprocessBasicBlock(
MBB);
283 enterBasicBlock(
MBB);
284 for (MachineInstr &
MI :
287 leaveBasicBlock(
MBB);
295 LLVM_DEBUG(
dbgs() <<
"********** REACHING DEFINITION ANALYSIS **********\n");
308 InstToNumMap[&
MI] = Num;
320 int FrameIndex = MO.getIndex();
322 }
else if (MO.isReg()) {
342 OS << InstToNumMap[&
MI] <<
": " <<
MI <<
"\n";
354 MBBOutRegsInfos.clear();
355 MBBReachingDefs.clear();
356 MBBFrameObjsReachingDefs.clear();
368 NumRegUnits = TRI->getNumRegUnits();
369 MBBReachingDefs.init(MF->getNumBlockIDs());
371 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
373 TraversedMBBOrder = Traversal.
traverse(*MF);
379 processBasicBlock(TraversedMBB);
382 for (
unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
383 MBBNumber != NumBlockIDs; ++MBBNumber) {
384 for (
unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
385 int LastDef = ReachingDefDefaultVal;
387 MBBReachingDefs.defs(MBBNumber,
static_cast<MCRegUnit
>(Unit))) {
388 assert(Def > LastDef &&
"Defs must be sorted and unique");
397 assert(InstIds.count(
MI) &&
"Unexpected machine instruction.");
398 int InstId = InstIds.lookup(
MI);
399 int DefRes = ReachingDefDefaultVal;
400 unsigned MBBNumber =
MI->getParent()->getNumber();
401 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
402 "Unexpected basic block number.");
403 int LatestDef = ReachingDefDefaultVal;
407 int FrameIndex = Reg.stackSlotIndex();
408 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
409 if (
Lookup == MBBFrameObjsReachingDefs.end())
411 auto &Defs =
Lookup->second;
412 for (
int Def : Defs) {
417 LatestDef = std::max(LatestDef, DefRes);
421 for (MCRegUnit Unit : TRI->regunits(Reg)) {
422 for (
int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
427 LatestDef = std::max(LatestDef, DefRes);
443 if (ParentA != ParentB)
451 assert(
static_cast<size_t>(
MBB->getNumber()) <
453 "Unexpected basic block number.");
454 assert(InstId <
static_cast<int>(
MBB->size()) &&
455 "Unexpected instruction id.");
460 for (
auto &
MI : *
MBB) {
461 auto F = InstIds.find(&
MI);
462 if (
F != InstIds.end() &&
F->second == InstId)
470 assert(InstIds.count(
MI) &&
"Unexpected machine instruction.");
479 InstSet &
Uses)
const {
482 while (++
MI !=
MBB->end()) {
483 if (
MI->isDebugInstr())
488 if (getReachingLocalMIDef(&*
MI, Reg) != Def)
491 for (
auto &MO :
MI->operands()) {
503 InstSet &
Uses)
const {
506 for (
auto &MO :
MI.operands()) {
514 auto Last =
MBB->getLastNonDebugInstr();
521 InstSet &
Uses)
const {
534 while (!ToVisit.
empty()) {
546 InstSet &Defs)
const {
552 for (
auto *
MBB :
MI->getParent()->predecessors())
557 InstSet &Defs)
const {
563 InstSet &Defs, BlockSet &VisitedBBs)
const {
569 LiveRegs.addLiveOuts(*
MBB);
570 if (Reg.isPhysical() && LiveRegs.available(Reg))
576 for (
auto *Pred :
MBB->predecessors())
584 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(
MI))
595 if (Incoming.
size() == 1 && (*Incoming.
begin())->getParent() != Parent)
596 return *Incoming.
begin();
601 unsigned Idx)
const {
602 assert(
MI->getOperand(Idx).isReg() &&
"Expected register operand");
615 LiveRegs.addLiveOuts(*
MBB);
618 if (!LiveRegs.available(Reg))
625 LiveRegs.stepBackward(
Last);
626 if (!LiveRegs.available(Reg))
627 return InstIds.lookup(&
Last) > InstIds.lookup(
MI);
634 auto Last =
MBB->getLastNonDebugInstr();
640 return Def == getReachingLocalMIDef(
MI, Reg);
649 LiveRegs.addLiveOuts(*
MBB);
650 if (Reg.isPhysical() && LiveRegs.available(Reg))
653 auto Last =
MBB->getLastNonDebugInstr();
659 for (
auto &MO :
Last->operands())
669 LiveRegs.addLiveOuts(*
MBB);
670 if (Reg.isPhysical() && LiveRegs.available(Reg))
673 auto Last =
MBB->getLastNonDebugInstr();
679 int FrameIndex = Reg.stackSlotIndex();
683 for (
auto &MO :
Last->operands())
689 return Def < 0 ? nullptr : getInstFromId(
MBB, Def);
693 return MI.mayLoadOrStore() ||
MI.mayRaiseFPException() ||
694 MI.hasUnmodeledSideEffects() ||
MI.isTerminator() ||
695 MI.isCall() ||
MI.isBarrier() ||
MI.isBranch() ||
MI.isReturn();
701template <
typename Iterator>
706 SmallSet<Register, 2> Defs;
723 for (
auto &MO :
I->operands())
724 if (MO.isReg() && MO.getReg() && Defs.
count(MO.getReg()))
734 for (
auto I = Iterator(From), E = From->
getParent()->
end();
I != E; ++
I)
736 return isSafeToMove<Iterator>(From, To);
746 return isSafeToMove<Iterator>(From, To);
774 for (
auto &MO :
MI->operands()) {
781 for (
auto *
I :
Uses) {
793 InstSet &
Dead)
const {
799 unsigned LiveDefs = 0;
800 for (
auto &MO : Def->operands()) {
815 for (
auto &MO :
MI->operands()) {
819 if (
IsDead(Def, MO.getReg()))
833 if (
auto *Def = getReachingLocalMIDef(
MI, Reg)) {
846 for (
auto E =
MBB->end();
I != E; ++
I) {
849 for (
auto &MO :
I->operands())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet InstSet & Ignore
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isValidRegUseOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool mayHaveSideEffects(MachineInstr &MI)
static bool isValidReg(const MachineOperand &MO)
static bool isFIDef(const MachineInstr &MI, int FrameIndex, const TargetInstrInfo *TII)
static bool isValidRegDef(const MachineOperand &MO)
static bool isValidRegDefOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool isValidRegUse(const MachineOperand &MO)
Remove Loads Into Fake Uses
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallSet class.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
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.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
A set of register units used to track register liveness.
This class provides the basic blocks traversal order used by passes like ReachingDefAnalysis and Exec...
LLVM_ABI TraversalOrder traverse(MachineFunction &MF)
unsigned numBlockIDs() const
An RAII based helper class to modify MachineFunctionProperties when running pass.
instr_iterator instr_begin()
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineBasicBlock & front() const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
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.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineFunctionProperties getRequiredProperties() const override
This class provides the reaching def analysis.
LLVM_ABI MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
LLVM_ABI bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
LLVM_ABI bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
LLVM_ABI int getReachingDef(MachineInstr *MI, Register Reg) const
Provides the instruction id of the closest reaching def instruction of Reg that reaches MI,...
LLVM_ABI void run(MachineFunction &mf)
LLVM_ABI void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
LLVM_ABI int getClearance(MachineInstr *MI, Register Reg) const
Provides the clearance - the number of instructions since the closest reaching def instruction of Reg...
LLVM_ABI bool isRegDefinedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is defined after MI.
LLVM_ABI void init()
Initialize data structures.
LLVM_ABI void print(raw_ostream &OS)
LLVM_ABI bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
LLVM_ABI void reset()
Re-run the analysis.
LLVM_ABI void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
LLVM_ABI void releaseMemory()
LLVM_ABI MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
LLVM_ABI void getLiveOuts(MachineBasicBlock *MBB, Register Reg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of Reg and insert it into Defs.
LLVM_ABI void traverse()
Traverse the machine function, mapping definitions.
LLVM_ABI ReachingDefInfo()
LLVM_ABI bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
LLVM_ABI void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const
Assuming MI is dead, recursively search the incoming operands which are killed by MI and collect thos...
LLVM_ABI ~ReachingDefInfo()
LLVM_ABI bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
LLVM_ABI bool isRegUsedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is used after MI, whether it's a local use or a live out.
LLVM_ABI void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
LLVM_ABI bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
LLVM_ABI MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, Register Reg) const
Return the local MI that produces the live out value for Reg, or nullptr for a non-live out or non-lo...
LLVM_ABI bool invalidate(MachineFunction &F, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI bool getLiveInUses(MachineBasicBlock *MBB, Register Reg, InstSet &Uses) const
For the given block, collect the instructions that use the live-in value of the provided register.
LLVM_ABI bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
static Register index2StackSlot(int FI)
Convert a frame index to a stack slot register value.
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.
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.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
This class implements an extremely fast bulk output stream that can only output to a stream.
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A special type used by analysis passes to provide an address that identifies that particular analysis...
MachineBasicBlock * MBB
The basic block.
bool IsDone
True if the block that is ready for its final round of processing.
bool PrimaryPass
True if this is the first time we process the basic block.