#include "llvm/CodeGen/RDFLiveness.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominanceFrontier.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/RDFGraph.h"
#include "llvm/CodeGen/RDFRegisters.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <map>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace llvm;
using namespace rdf;
static cl::opt<unsigned> MaxRecNest("rdf-liveness-max-rec", cl::init(25),
cl::Hidden, cl::desc("Maximum recursion level"));
namespace llvm {
namespace rdf {
raw_ostream &operator<< (raw_ostream &OS, const Print<Liveness::RefMap> &P) {
OS << '{';
for (const auto &I : P.Obj) {
OS << ' ' << printReg(I.first, &P.G.getTRI()) << '{';
for (auto J = I.second.begin(), E = I.second.end(); J != E; ) {
OS << Print<NodeId>(J->first, P.G) << PrintLaneMaskOpt(J->second);
if (++J != E)
OS << ',';
}
OS << '}';
}
OS << " }";
return OS;
}
} }
NodeList Liveness::getAllReachingDefs(RegisterRef RefRR,
NodeAddr<RefNode*> RefA, bool TopShadows, bool FullChain,
const RegisterAggr &DefRRs) {
NodeList RDefs; SetVector<NodeId> DefQ;
DenseMap<MachineInstr*, uint32_t> OrdMap;
if (RefA.Addr->getFlags() & NodeAttrs::Undef)
return RDefs;
NodeId Start = RefA.Id;
auto SNA = DFG.addr<RefNode*>(Start);
if (NodeId RD = SNA.Addr->getReachingDef())
DefQ.insert(RD);
if (TopShadows) {
for (auto S : DFG.getRelatedRefs(RefA.Addr->getOwner(DFG), RefA))
if (NodeId RD = NodeAddr<RefNode*>(S).Addr->getReachingDef())
DefQ.insert(RD);
}
for (unsigned i = 0; i < DefQ.size(); ++i) {
auto TA = DFG.addr<DefNode*>(DefQ[i]);
if (TA.Addr->getFlags() & NodeAttrs::PhiRef)
continue;
RegisterRef RR = TA.Addr->getRegRef(DFG);
if (!DFG.IsPreservingDef(TA))
if (RegisterAggr::isCoverOf(RR, RefRR, PRI))
continue;
for (auto S : DFG.getRelatedRefs(TA.Addr->getOwner(DFG), TA))
if (NodeId RD = NodeAddr<RefNode*>(S).Addr->getReachingDef())
DefQ.insert(RD);
}
auto Block = [this] (NodeAddr<InstrNode*> IA) -> MachineBasicBlock* {
if (IA.Addr->getKind() == NodeAttrs::Stmt)
return NodeAddr<StmtNode*>(IA).Addr->getCode()->getParent();
assert(IA.Addr->getKind() == NodeAttrs::Phi);
NodeAddr<PhiNode*> PA = IA;
NodeAddr<BlockNode*> BA = PA.Addr->getOwner(DFG);
return BA.Addr->getCode();
};
SmallSet<NodeId,32> Defs;
std::map<NodeId, NodeAddr<InstrNode*>> Owners;
std::map<MachineBasicBlock*, SmallVector<NodeId,32>> Blocks;
for (NodeId N : DefQ) {
auto TA = DFG.addr<DefNode*>(N);
bool IsPhi = TA.Addr->getFlags() & NodeAttrs::PhiRef;
if (!IsPhi && !PRI.alias(RefRR, TA.Addr->getRegRef(DFG)))
continue;
Defs.insert(TA.Id);
NodeAddr<InstrNode*> IA = TA.Addr->getOwner(DFG);
Owners[TA.Id] = IA;
Blocks[Block(IA)].push_back(IA.Id);
}
auto Precedes = [this,&OrdMap] (NodeId A, NodeId B) {
if (A == B)
return false;
NodeAddr<InstrNode*> OA = DFG.addr<InstrNode*>(A);
NodeAddr<InstrNode*> OB = DFG.addr<InstrNode*>(B);
bool StmtA = OA.Addr->getKind() == NodeAttrs::Stmt;
bool StmtB = OB.Addr->getKind() == NodeAttrs::Stmt;
if (StmtA && StmtB) {
const MachineInstr *InA = NodeAddr<StmtNode*>(OA).Addr->getCode();
const MachineInstr *InB = NodeAddr<StmtNode*>(OB).Addr->getCode();
assert(InA->getParent() == InB->getParent());
auto FA = OrdMap.find(InA);
if (FA != OrdMap.end())
return FA->second < OrdMap.find(InB)->second;
const MachineBasicBlock *BB = InA->getParent();
for (auto It = BB->begin(), E = BB->end(); It != E; ++It) {
if (It == InA->getIterator())
return true;
if (It == InB->getIterator())
return false;
}
llvm_unreachable("InA and InB should be in the same block");
}
if (!StmtA && !StmtB) {
return A < B;
}
return !StmtA;
};
auto GetOrder = [&OrdMap] (MachineBasicBlock &B) {
uint32_t Pos = 0;
for (MachineInstr &In : B)
OrdMap.insert({&In, ++Pos});
};
std::vector<MachineBasicBlock*> TmpBB;
for (auto &Bucket : Blocks) {
TmpBB.push_back(Bucket.first);
if (Bucket.second.size() > 2)
GetOrder(*Bucket.first);
llvm::sort(Bucket.second, Precedes);
}
llvm::sort(TmpBB,
[this](auto A, auto B) { return MDT.properlyDominates(A, B); });
std::vector<NodeId> TmpInst;
for (MachineBasicBlock *MBB : llvm::reverse(TmpBB)) {
auto &Bucket = Blocks[MBB];
TmpInst.insert(TmpInst.end(), Bucket.rbegin(), Bucket.rend());
}
RegisterAggr RRs(DefRRs);
auto DefInSet = [&Defs] (NodeAddr<RefNode*> TA) -> bool {
return TA.Addr->getKind() == NodeAttrs::Def &&
Defs.count(TA.Id);
};
for (NodeId T : TmpInst) {
if (!FullChain && RRs.hasCoverOf(RefRR))
break;
auto TA = DFG.addr<InstrNode*>(T);
bool IsPhi = DFG.IsCode<NodeAttrs::Phi>(TA);
NodeList Ds;
for (NodeAddr<DefNode*> DA : TA.Addr->members_if(DefInSet, DFG)) {
RegisterRef QR = DA.Addr->getRegRef(DFG);
if (FullChain || IsPhi || !RRs.hasCoverOf(QR))
Ds.push_back(DA);
}
llvm::append_range(RDefs, Ds);
for (NodeAddr<DefNode*> DA : Ds) {
uint16_t Flags = DA.Addr->getFlags();
if (!FullChain || !(Flags & NodeAttrs::PhiRef))
if (!(Flags & NodeAttrs::Preserving)) RRs.insert(DA.Addr->getRegRef(DFG));
}
}
auto DeadP = [](const NodeAddr<DefNode*> DA) -> bool {
return DA.Addr->getFlags() & NodeAttrs::Dead;
};
llvm::erase_if(RDefs, DeadP);
return RDefs;
}
std::pair<NodeSet,bool>
Liveness::getAllReachingDefsRec(RegisterRef RefRR, NodeAddr<RefNode*> RefA,
NodeSet &Visited, const NodeSet &Defs) {
return getAllReachingDefsRecImpl(RefRR, RefA, Visited, Defs, 0, MaxRecNest);
}
std::pair<NodeSet,bool>
Liveness::getAllReachingDefsRecImpl(RegisterRef RefRR, NodeAddr<RefNode*> RefA,
NodeSet &Visited, const NodeSet &Defs, unsigned Nest, unsigned MaxNest) {
if (Nest > MaxNest)
return { NodeSet(), false };
RegisterAggr DefRRs(PRI);
for (NodeId D : Defs) {
const auto DA = DFG.addr<const DefNode*>(D);
if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
DefRRs.insert(DA.Addr->getRegRef(DFG));
}
NodeList RDs = getAllReachingDefs(RefRR, RefA, false, true, DefRRs);
if (RDs.empty())
return { Defs, true };
NodeSet TmpDefs = Defs;
for (NodeAddr<NodeBase*> R : RDs)
TmpDefs.insert(R.Id);
NodeSet Result = Defs;
for (NodeAddr<DefNode*> DA : RDs) {
Result.insert(DA.Id);
if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
continue;
NodeAddr<PhiNode*> PA = DA.Addr->getOwner(DFG);
if (!Visited.insert(PA.Id).second)
continue;
for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
const auto &T = getAllReachingDefsRecImpl(RefRR, U, Visited, TmpDefs,
Nest+1, MaxNest);
if (!T.second)
return { T.first, false };
Result.insert(T.first.begin(), T.first.end());
}
}
return { Result, true };
}
NodeAddr<RefNode*> Liveness::getNearestAliasedRef(RegisterRef RefRR,
NodeAddr<InstrNode*> IA) {
NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
NodeList Ins = BA.Addr->members(DFG);
NodeId FindId = IA.Id;
auto E = Ins.rend();
auto B = std::find_if(Ins.rbegin(), E,
[FindId] (const NodeAddr<InstrNode*> T) {
return T.Id == FindId;
});
if (B != E)
++B;
do {
for (NodeAddr<InstrNode*> I : make_range(B, E)) {
NodeList Refs = I.Addr->members(DFG);
NodeAddr<RefNode*> Clob, Use;
for (NodeAddr<RefNode*> R : Refs) {
if (!PRI.alias(R.Addr->getRegRef(DFG), RefRR))
continue;
if (DFG.IsDef(R)) {
if (!(R.Addr->getFlags() & NodeAttrs::Clobbering))
return R;
Clob = R;
} else {
Use = R;
}
}
if (Clob.Id != 0)
return Clob;
if (Use.Id != 0)
return Use;
}
MachineBasicBlock *BB = BA.Addr->getCode();
BA = NodeAddr<BlockNode*>();
if (MachineDomTreeNode *N = MDT.getNode(BB)) {
if ((N = N->getIDom()))
BA = DFG.findBlock(N->getBlock());
}
if (!BA.Id)
break;
Ins = BA.Addr->members(DFG);
B = Ins.rbegin();
E = Ins.rend();
} while (true);
return NodeAddr<RefNode*>();
}
NodeSet Liveness::getAllReachedUses(RegisterRef RefRR,
NodeAddr<DefNode*> DefA, const RegisterAggr &DefRRs) {
NodeSet Uses;
if (DefRRs.hasCoverOf(RefRR))
return Uses;
bool IsDead = DefA.Addr->getFlags() & NodeAttrs::Dead;
NodeId U = !IsDead ? DefA.Addr->getReachedUse() : 0;
while (U != 0) {
auto UA = DFG.addr<UseNode*>(U);
if (!(UA.Addr->getFlags() & NodeAttrs::Undef)) {
RegisterRef UR = UA.Addr->getRegRef(DFG);
if (PRI.alias(RefRR, UR) && !DefRRs.hasCoverOf(UR))
Uses.insert(U);
}
U = UA.Addr->getSibling();
}
for (NodeId D = DefA.Addr->getReachedDef(), NextD; D != 0; D = NextD) {
auto DA = DFG.addr<DefNode*>(D);
NextD = DA.Addr->getSibling();
RegisterRef DR = DA.Addr->getRegRef(DFG);
if (DefRRs.hasCoverOf(DR) || !PRI.alias(RefRR, DR))
continue;
NodeSet T;
if (DFG.IsPreservingDef(DA)) {
T = getAllReachedUses(RefRR, DA, DefRRs);
} else {
RegisterAggr NewDefRRs = DefRRs;
NewDefRRs.insert(DR);
T = getAllReachedUses(RefRR, DA, NewDefRRs);
}
Uses.insert(T.begin(), T.end());
}
return Uses;
}
void Liveness::computePhiInfo() {
RealUseMap.clear();
NodeList Phis;
NodeAddr<FuncNode*> FA = DFG.getFunc();
NodeList Blocks = FA.Addr->members(DFG);
for (NodeAddr<BlockNode*> BA : Blocks) {
auto Ps = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
llvm::append_range(Phis, Ps);
}
std::map<NodeId,std::map<NodeId,RegisterAggr>> PhiUp;
std::vector<NodeId> PhiUQ; std::unordered_map<NodeId,RegisterAggr> PhiDRs;
for (NodeAddr<PhiNode*> PhiA : Phis) {
RefMap &RealUses = RealUseMap[PhiA.Id];
NodeList PhiRefs = PhiA.Addr->members(DFG);
SetVector<NodeId> DefQ;
NodeSet PhiDefs;
RegisterAggr DRs(PRI);
for (NodeAddr<RefNode*> R : PhiRefs) {
if (!DFG.IsRef<NodeAttrs::Def>(R))
continue;
DRs.insert(R.Addr->getRegRef(DFG));
DefQ.insert(R.Id);
PhiDefs.insert(R.Id);
}
PhiDRs.insert(std::make_pair(PhiA.Id, DRs));
for (unsigned i = 0; i < DefQ.size(); ++i) {
NodeAddr<DefNode*> DA = DFG.addr<DefNode*>(DefQ[i]);
bool IsDead = DA.Addr->getFlags() & NodeAttrs::Dead;
NodeId UN = !IsDead ? DA.Addr->getReachedUse() : 0;
while (UN != 0) {
NodeAddr<UseNode*> A = DFG.addr<UseNode*>(UN);
uint16_t F = A.Addr->getFlags();
if ((F & (NodeAttrs::Undef | NodeAttrs::PhiRef)) == 0) {
RegisterRef R = A.Addr->getRegRef(DFG);
RealUses[R.Reg].insert({A.Id,R.Mask});
}
UN = A.Addr->getSibling();
}
NodeId DN = DA.Addr->getReachedDef();
while (DN != 0) {
NodeAddr<DefNode*> A = DFG.addr<DefNode*>(DN);
for (auto T : DFG.getRelatedRefs(A.Addr->getOwner(DFG), A)) {
uint16_t Flags = NodeAddr<DefNode*>(T).Addr->getFlags();
if (!(Flags & NodeAttrs::PhiRef))
DefQ.insert(T.Id);
}
DN = A.Addr->getSibling();
}
}
for (auto UI = RealUses.begin(), UE = RealUses.end(); UI != UE; ) {
NodeRefSet Uses = UI->second;
UI->second.clear();
for (std::pair<NodeId,LaneBitmask> I : Uses) {
auto UA = DFG.addr<UseNode*>(I.first);
assert((UA.Addr->getFlags() & NodeAttrs::Undef) == 0);
RegisterRef R(UI->first, I.second);
RegisterAggr Covered(PRI);
for (NodeAddr<DefNode*> DA : getAllReachingDefs(R, UA)) {
if (PhiDefs.count(DA.Id))
break;
Covered.insert(DA.Addr->getRegRef(DFG));
}
if (RegisterRef RC = Covered.clearIn(R)) {
RegisterRef S = PRI.mapTo(RC, UI->first);
UI->second.insert({I.first, S.Mask});
}
}
UI = UI->second.empty() ? RealUses.erase(UI) : std::next(UI);
}
if (!RealUses.empty())
PhiUQ.push_back(PhiA.Id);
NodeSet SeenUses;
for (auto I : PhiRefs) {
if (!DFG.IsRef<NodeAttrs::Use>(I) || SeenUses.count(I.Id))
continue;
NodeAddr<PhiUseNode*> PUA = I;
if (PUA.Addr->getReachingDef() == 0)
continue;
RegisterRef UR = PUA.Addr->getRegRef(DFG);
NodeList Ds = getAllReachingDefs(UR, PUA, true, false, NoRegs);
RegisterAggr DefRRs(PRI);
for (NodeAddr<DefNode*> D : Ds) {
if (D.Addr->getFlags() & NodeAttrs::PhiRef) {
NodeId RP = D.Addr->getOwner(DFG).Id;
std::map<NodeId,RegisterAggr> &M = PhiUp[PUA.Id];
auto F = M.find(RP);
if (F == M.end())
M.insert(std::make_pair(RP, DefRRs));
else
F->second.insert(DefRRs);
}
DefRRs.insert(D.Addr->getRegRef(DFG));
}
for (NodeAddr<PhiUseNode*> T : DFG.getRelatedRefs(PhiA, PUA))
SeenUses.insert(T.Id);
}
}
if (Trace) {
dbgs() << "Phi-up-to-phi map with intervening defs:\n";
for (auto I : PhiUp) {
dbgs() << "phi " << Print<NodeId>(I.first, DFG) << " -> {";
for (auto R : I.second)
dbgs() << ' ' << Print<NodeId>(R.first, DFG)
<< Print<RegisterAggr>(R.second, DFG);
dbgs() << " }\n";
}
}
using SubMap = std::unordered_map<RegisterRef, RegisterRef>;
std::unordered_map<RegisterAggr, SubMap> Subs;
auto ClearIn = [] (RegisterRef RR, const RegisterAggr &Mid, SubMap &SM) {
if (Mid.empty())
return RR;
auto F = SM.find(RR);
if (F != SM.end())
return F->second;
RegisterRef S = Mid.clearIn(RR);
SM.insert({RR, S});
return S;
};
for (unsigned i = 0; i < PhiUQ.size(); ++i) {
auto PA = DFG.addr<PhiNode*>(PhiUQ[i]);
NodeList PUs = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG);
RefMap &RUM = RealUseMap[PA.Id];
for (NodeAddr<UseNode*> UA : PUs) {
std::map<NodeId,RegisterAggr> &PUM = PhiUp[UA.Id];
RegisterRef UR = UA.Addr->getRegRef(DFG);
for (const std::pair<const NodeId, RegisterAggr> &P : PUM) {
bool Changed = false;
const RegisterAggr &MidDefs = P.second;
if (MidDefs.hasCoverOf(UR))
continue;
SubMap &SM = Subs[MidDefs];
for (const std::pair<const RegisterId, NodeRefSet> &T : RUM) {
RegisterRef R(T.first);
const RegisterAggr &DRs = PhiDRs.at(P.first);
if (!DRs.hasAliasOf(R))
continue;
R = PRI.mapTo(DRs.intersectWith(R), T.first);
for (std::pair<NodeId,LaneBitmask> V : T.second) {
LaneBitmask M = R.Mask & V.second;
if (M.none())
continue;
if (RegisterRef SS = ClearIn(RegisterRef(R.Reg, M), MidDefs, SM)) {
NodeRefSet &RS = RealUseMap[P.first][SS.Reg];
Changed |= RS.insert({V.first,SS.Mask}).second;
}
}
}
if (Changed)
PhiUQ.push_back(P.first);
}
}
}
if (Trace) {
dbgs() << "Real use map:\n";
for (auto I : RealUseMap) {
dbgs() << "phi " << Print<NodeId>(I.first, DFG);
NodeAddr<PhiNode*> PA = DFG.addr<PhiNode*>(I.first);
NodeList Ds = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Def>, DFG);
if (!Ds.empty()) {
RegisterRef RR = NodeAddr<DefNode*>(Ds[0]).Addr->getRegRef(DFG);
dbgs() << '<' << Print<RegisterRef>(RR, DFG) << '>';
} else {
dbgs() << "<noreg>";
}
dbgs() << " -> " << Print<RefMap>(I.second, DFG) << '\n';
}
}
}
void Liveness::computeLiveIns() {
NBMap.clear();
for (NodeAddr<BlockNode*> BA : DFG.getFunc().Addr->members(DFG)) {
MachineBasicBlock *BB = BA.Addr->getCode();
for (NodeAddr<InstrNode*> IA : BA.Addr->members(DFG)) {
for (NodeAddr<RefNode*> RA : IA.Addr->members(DFG))
NBMap.insert(std::make_pair(RA.Id, BB));
NBMap.insert(std::make_pair(IA.Id, BB));
}
}
MachineFunction &MF = DFG.getMF();
decltype(IIDF) IDF;
for (MachineBasicBlock &B : MF) {
auto F1 = MDF.find(&B);
if (F1 == MDF.end())
continue;
SetVector<MachineBasicBlock*> IDFB(F1->second.begin(), F1->second.end());
for (unsigned i = 0; i < IDFB.size(); ++i) {
auto F2 = MDF.find(IDFB[i]);
if (F2 != MDF.end())
IDFB.insert(F2->second.begin(), F2->second.end());
}
IDFB.insert(&B);
IDF[&B].insert(IDFB.begin(), IDFB.end());
}
for (auto I : IDF)
for (auto *S : I.second)
IIDF[S].insert(I.first);
computePhiInfo();
NodeAddr<FuncNode*> FA = DFG.getFunc();
NodeList Blocks = FA.Addr->members(DFG);
for (NodeAddr<BlockNode*> BA : Blocks) {
MachineBasicBlock *MB = BA.Addr->getCode();
RefMap &LON = PhiLON[MB];
for (auto P : BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG))
for (const RefMap::value_type &S : RealUseMap[P.Id])
LON[S.first].insert(S.second.begin(), S.second.end());
}
if (Trace) {
dbgs() << "Phi live-on-entry map:\n";
for (auto &I : PhiLON)
dbgs() << "block #" << I.first->getNumber() << " -> "
<< Print<RefMap>(I.second, DFG) << '\n';
}
for (NodeAddr<BlockNode*> BA : Blocks) {
NodeList Phis = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
for (NodeAddr<PhiNode*> PA : Phis) {
RefMap &RUs = RealUseMap[PA.Id];
if (RUs.empty())
continue;
NodeSet SeenUses;
for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
if (!SeenUses.insert(U.Id).second)
continue;
NodeAddr<PhiUseNode*> PUA = U;
if (PUA.Addr->getReachingDef() == 0)
continue;
auto PrA = DFG.addr<BlockNode*>(PUA.Addr->getPredecessor());
RefMap &LOX = PhiLOX[PrA.Addr->getCode()];
for (const std::pair<const RegisterId, NodeRefSet> &RS : RUs) {
for (std::pair<NodeId,LaneBitmask> P : RS.second) {
RegisterRef S(RS.first, P.second);
NodeList Ds = getAllReachingDefs(S, PUA, true, false, NoRegs);
for (NodeAddr<DefNode*> D : Ds) {
RegisterAggr TA(PRI);
TA.insert(D.Addr->getRegRef(DFG)).intersect(S);
LaneBitmask TM = TA.makeRegRef().Mask;
LOX[S.Reg].insert({D.Id, TM});
}
}
}
for (NodeAddr<PhiUseNode*> T : DFG.getRelatedRefs(PA, PUA))
SeenUses.insert(T.Id);
} } }
if (Trace) {
dbgs() << "Phi live-on-exit map:\n";
for (auto &I : PhiLOX)
dbgs() << "block #" << I.first->getNumber() << " -> "
<< Print<RefMap>(I.second, DFG) << '\n';
}
RefMap LiveIn;
traverse(&MF.front(), LiveIn);
LiveMap[&MF.front()].insert(DFG.getLiveIns());
if (Trace) {
for (MachineBasicBlock &B : MF) {
std::vector<RegisterRef> LV;
for (const MachineBasicBlock::RegisterMaskPair &LI : B.liveins())
LV.push_back(RegisterRef(LI.PhysReg, LI.LaneMask));
llvm::sort(LV);
dbgs() << printMBBReference(B) << "\t rec = {";
for (auto I : LV)
dbgs() << ' ' << Print<RegisterRef>(I, DFG);
dbgs() << " }\n";
LV.clear();
const RegisterAggr &LG = LiveMap[&B];
for (auto I = LG.rr_begin(), E = LG.rr_end(); I != E; ++I)
LV.push_back(*I);
llvm::sort(LV);
dbgs() << "\tcomp = {";
for (auto I : LV)
dbgs() << ' ' << Print<RegisterRef>(I, DFG);
dbgs() << " }\n";
}
}
}
void Liveness::resetLiveIns() {
for (auto &B : DFG.getMF()) {
std::vector<unsigned> T;
for (const MachineBasicBlock::RegisterMaskPair &LI : B.liveins())
T.push_back(LI.PhysReg);
for (auto I : T)
B.removeLiveIn(I);
const RegisterAggr &LiveIns = LiveMap[&B];
for (const RegisterRef R : make_range(LiveIns.rr_begin(), LiveIns.rr_end()))
B.addLiveIn({MCPhysReg(R.Reg), R.Mask});
}
}
void Liveness::resetKills() {
for (auto &B : DFG.getMF())
resetKills(&B);
}
void Liveness::resetKills(MachineBasicBlock *B) {
auto CopyLiveIns = [this] (MachineBasicBlock *B, BitVector &LV) -> void {
for (auto I : B->liveins()) {
MCSubRegIndexIterator S(I.PhysReg, &TRI);
if (!S.isValid()) {
LV.set(I.PhysReg);
continue;
}
do {
LaneBitmask M = TRI.getSubRegIndexLaneMask(S.getSubRegIndex());
if ((M & I.LaneMask).any())
LV.set(S.getSubReg());
++S;
} while (S.isValid());
}
};
BitVector LiveIn(TRI.getNumRegs()), Live(TRI.getNumRegs());
CopyLiveIns(B, LiveIn);
for (auto *SI : B->successors())
CopyLiveIns(SI, Live);
for (MachineInstr &MI : llvm::reverse(*B)) {
if (MI.isDebugInstr())
continue;
MI.clearKillInfo();
for (auto &Op : MI.operands()) {
if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
continue;
Register R = Op.getReg();
if (!Register::isPhysicalRegister(R))
continue;
for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
Live.reset(*SR);
}
for (auto &Op : MI.operands()) {
if (!Op.isReg() || !Op.isUse() || Op.isUndef())
continue;
Register R = Op.getReg();
if (!Register::isPhysicalRegister(R))
continue;
bool IsLive = false;
for (MCRegAliasIterator AR(R, &TRI, true); AR.isValid(); ++AR) {
if (!Live[*AR])
continue;
IsLive = true;
break;
}
if (!IsLive)
Op.setIsKill(true);
for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
Live.set(*SR);
}
}
}
MachineBasicBlock *Liveness::getBlockWithRef(NodeId RN) const {
auto F = NBMap.find(RN);
if (F != NBMap.end())
return F->second;
llvm_unreachable("Node id not in map");
}
void Liveness::traverse(MachineBasicBlock *B, RefMap &LiveIn) {
MachineDomTreeNode *N = MDT.getNode(B);
for (auto *I : *N) {
RefMap L;
MachineBasicBlock *SB = I->getBlock();
traverse(SB, L);
for (auto S : L)
LiveIn[S.first].insert(S.second.begin(), S.second.end());
}
if (Trace) {
dbgs() << "\n-- " << printMBBReference(*B) << ": " << __func__
<< " after recursion into: {";
for (auto *I : *N)
dbgs() << ' ' << I->getBlock()->getNumber();
dbgs() << " }\n";
dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
dbgs() << " Local: " << Print<RegisterAggr>(LiveMap[B], DFG) << '\n';
}
RefMap &PUs = PhiLOX[B];
for (auto &S : PUs)
LiveIn[S.first].insert(S.second.begin(), S.second.end());
if (Trace) {
dbgs() << "after LOX\n";
dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
dbgs() << " Local: " << Print<RegisterAggr>(LiveMap[B], DFG) << '\n';
}
RefMap LiveInCopy = LiveIn;
LiveIn.clear();
for (const std::pair<const RegisterId, NodeRefSet> &LE : LiveInCopy) {
RegisterRef LRef(LE.first);
NodeRefSet &NewDefs = LiveIn[LRef.Reg]; const NodeRefSet &OldDefs = LE.second;
for (NodeRef OR : OldDefs) {
auto DA = DFG.addr<DefNode*>(OR.first);
NodeAddr<InstrNode*> IA = DA.Addr->getOwner(DFG);
NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
if (B != BA.Addr->getCode()) {
NewDefs.insert(OR);
continue;
}
RegisterAggr RRs(PRI);
LRef.Mask = OR.second;
if (!DFG.IsPreservingDef(DA)) {
assert(!(IA.Addr->getFlags() & NodeAttrs::Phi));
if (RRs.insert(DA.Addr->getRegRef(DFG)).hasCoverOf(LRef))
continue;
}
for (NodeAddr<DefNode*> TA : getAllReachingDefs(DA)) {
NodeAddr<InstrNode*> ITA = TA.Addr->getOwner(DFG);
NodeAddr<BlockNode*> BTA = ITA.Addr->getOwner(DFG);
if (BTA.Addr->getCode() != B) {
RegisterRef T = RRs.clearIn(LRef);
assert(T);
NewDefs.insert({TA.Id,T.Mask});
break;
}
if (!(TA.Addr->getFlags() & NodeAttrs::Preserving))
RRs.insert(TA.Addr->getRegRef(DFG));
if (RRs.hasCoverOf(LRef))
break;
}
}
}
emptify(LiveIn);
if (Trace) {
dbgs() << "after defs in block\n";
dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
dbgs() << " Local: " << Print<RegisterAggr>(LiveMap[B], DFG) << '\n';
}
for (auto I : DFG.getFunc().Addr->findBlock(B, DFG).Addr->members(DFG)) {
NodeAddr<InstrNode*> IA = I;
if (IA.Addr->getKind() != NodeAttrs::Stmt)
continue;
for (NodeAddr<UseNode*> UA : IA.Addr->members_if(DFG.IsUse, DFG)) {
if (UA.Addr->getFlags() & NodeAttrs::Undef)
continue;
RegisterRef RR = UA.Addr->getRegRef(DFG);
for (NodeAddr<DefNode*> D : getAllReachingDefs(UA))
if (getBlockWithRef(D.Id) != B)
LiveIn[RR.Reg].insert({D.Id,RR.Mask});
}
}
if (Trace) {
dbgs() << "after uses in block\n";
dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
dbgs() << " Local: " << Print<RegisterAggr>(LiveMap[B], DFG) << '\n';
}
RegisterAggr &Local = LiveMap[B];
RefMap &LON = PhiLON[B];
for (auto &R : LON) {
LaneBitmask M;
for (auto P : R.second)
M |= P.second;
Local.insert(RegisterRef(R.first,M));
}
if (Trace) {
dbgs() << "after phi uses in block\n";
dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
dbgs() << " Local: " << Print<RegisterAggr>(Local, DFG) << '\n';
}
for (auto *C : IIDF[B]) {
RegisterAggr &LiveC = LiveMap[C];
for (const std::pair<const RegisterId, NodeRefSet> &S : LiveIn)
for (auto R : S.second)
if (MDT.properlyDominates(getBlockWithRef(R.first), C))
LiveC.insert(RegisterRef(S.first, R.second));
}
}
void Liveness::emptify(RefMap &M) {
for (auto I = M.begin(), E = M.end(); I != E; )
I = I->second.empty() ? M.erase(I) : std::next(I);
}