LiveIntervalAnalysis.cpp [plain text]
#define DEBUG_TYPE "regalloc"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "LiveRangeCalc.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/VirtRegMap.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include <algorithm>
#include <cmath>
#include <limits>
using namespace llvm;
static cl::opt<bool>
NewLiveIntervals("new-live-intervals", cl::Hidden,
cl::desc("Use new algorithm forcomputing live intervals"));
char LiveIntervals::ID = 0;
char &llvm::LiveIntervalsID = LiveIntervals::ID;
INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
"Live Interval Analysis", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(LiveVariables)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
"Live Interval Analysis", false, false)
void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<AliasAnalysis>();
AU.addPreserved<AliasAnalysis>();
AU.addRequired<LiveVariables>();
AU.addPreserved<LiveVariables>();
AU.addPreservedID(MachineLoopInfoID);
AU.addRequiredTransitiveID(MachineDominatorsID);
AU.addPreservedID(MachineDominatorsID);
AU.addPreserved<SlotIndexes>();
AU.addRequiredTransitive<SlotIndexes>();
MachineFunctionPass::getAnalysisUsage(AU);
}
LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
DomTree(0), LRCalc(0) {
initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
}
LiveIntervals::~LiveIntervals() {
delete LRCalc;
}
void LiveIntervals::releaseMemory() {
for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
VirtRegIntervals.clear();
RegMaskSlots.clear();
RegMaskBits.clear();
RegMaskBlocks.clear();
for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
delete RegUnitIntervals[i];
RegUnitIntervals.clear();
VNInfoAllocator.Reset();
}
bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
MF = &fn;
MRI = &MF->getRegInfo();
TM = &fn.getTarget();
TRI = TM->getRegisterInfo();
TII = TM->getInstrInfo();
AA = &getAnalysis<AliasAnalysis>();
LV = &getAnalysis<LiveVariables>();
Indexes = &getAnalysis<SlotIndexes>();
DomTree = &getAnalysis<MachineDominatorTree>();
if (!LRCalc)
LRCalc = new LiveRangeCalc();
VirtRegIntervals.resize(MRI->getNumVirtRegs());
if (NewLiveIntervals) {
computeVirtRegs();
computeRegMasks();
} else {
computeIntervals();
}
computeLiveInRegUnits();
DEBUG(dump());
return true;
}
void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
OS << "********** INTERVALS **********\n";
for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
if (LiveInterval *LI = RegUnitIntervals[i])
OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
if (hasInterval(Reg))
OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
}
OS << "RegMasks:";
for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
OS << ' ' << RegMaskSlots[i];
OS << '\n';
printInstrs(OS);
}
void LiveIntervals::printInstrs(raw_ostream &OS) const {
OS << "********** MACHINEINSTRS **********\n";
MF->print(OS, Indexes);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void LiveIntervals::dumpInstrs() const {
printInstrs(dbgs());
}
#endif
static
bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
unsigned Reg = MI.getOperand(MOIdx).getReg();
for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (!MO.isReg())
continue;
if (MO.getReg() == Reg && MO.isDef()) {
assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
MI.getOperand(MOIdx).getSubReg() &&
(MO.getSubReg() || MO.isImplicit()));
return true;
}
}
return false;
}
bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
LiveInterval &interval) {
if (!MO.getSubReg() || MO.isEarlyClobber())
return false;
SlotIndex RedefIndex = MIIdx.getRegSlot();
const LiveRange *OldLR =
interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
if (DefMI != 0) {
return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
}
return false;
}
void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
MachineBasicBlock::iterator mi,
SlotIndex MIIdx,
MachineOperand& MO,
unsigned MOIdx,
LiveInterval &interval) {
DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, TRI));
LiveVariables::VarInfo& vi = LV->getVarInfo(interval.reg);
if (interval.empty()) {
SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
assert(!MO.readsReg() && "First def cannot also read virtual register "
"missing <undef> flag?");
VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
assert(ValNo->id == 0 && "First value in interval is not 0?");
if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
SlotIndex killIdx;
if (vi.Kills[0] != mi)
killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
else
killIdx = defIndex.getDeadSlot();
if (killIdx > defIndex) {
assert(vi.AliveBlocks.empty() &&
"Shouldn't be alive across any blocks!");
LiveRange LR(defIndex, killIdx, ValNo);
interval.addRange(LR);
DEBUG(dbgs() << " +" << LR << "\n");
return;
}
}
LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
DEBUG(dbgs() << " +" << NewLR);
interval.addRange(NewLR);
bool PHIJoin = LV->isPHIJoin(interval.reg);
if (PHIJoin) {
assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
DEBUG(dbgs() << " phi-join");
} else {
for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
E = vi.AliveBlocks.end(); I != E; ++I) {
MachineBasicBlock *aliveBlock = MF->getBlockNumbered(*I);
LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock),
ValNo);
interval.addRange(LR);
DEBUG(dbgs() << " +" << LR);
}
}
for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
MachineInstr *Kill = vi.Kills[i];
SlotIndex Start = getMBBStartIdx(Kill->getParent());
SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
if (PHIJoin) {
assert(getInstructionFromIndex(Start) == 0 &&
"PHI def index points at actual instruction.");
ValNo = interval.getNextValue(Start, VNInfoAllocator);
}
LiveRange LR(Start, killIdx, ValNo);
interval.addRange(LR);
DEBUG(dbgs() << " +" << LR);
}
} else {
if (MultipleDefsBySameMI(*mi, MOIdx))
return;
bool PartReDef = isPartialRedef(MIIdx, MO, interval);
if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
const LiveRange *OldLR =
interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
VNInfo *OldValNo = OldLR->valno;
SlotIndex DefIndex = OldValNo->def.getRegSlot();
interval.removeRange(DefIndex, RedefIndex);
VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
OldValNo->def = RedefIndex;
LiveRange LR(DefIndex, RedefIndex, ValNo);
DEBUG(dbgs() << " replace range with " << LR);
interval.addRange(LR);
if (MO.isDead())
interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
OldValNo));
DEBUG(dbgs() << " RESULT: " << interval);
} else if (LV->isPHIJoin(interval.reg)) {
SlotIndex defIndex = MIIdx.getRegSlot();
if (MO.isEarlyClobber())
defIndex = MIIdx.getRegSlot(true);
VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
SlotIndex killIndex = getMBBEndIdx(mbb);
LiveRange LR(defIndex, killIndex, ValNo);
interval.addRange(LR);
DEBUG(dbgs() << " phi-join +" << LR);
} else {
llvm_unreachable("Multiply defined register");
}
}
DEBUG(dbgs() << '\n');
}
void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
MachineBasicBlock::iterator MI,
SlotIndex MIIdx,
MachineOperand& MO,
unsigned MOIdx) {
if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
getOrCreateInterval(MO.getReg()));
}
void LiveIntervals::computeIntervals() {
DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
<< "********** Function: " << MF->getName() << '\n');
RegMaskBlocks.resize(MF->getNumBlockIDs());
SmallVector<unsigned, 8> UndefUses;
for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
MBBI != E; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
RegMaskBlocks[MBB->getNumber()].first = RegMaskSlots.size();
if (MBB->empty())
continue;
SlotIndex MIIndex = getMBBStartIdx(MBB);
DEBUG(dbgs() << "BB#" << MBB->getNumber()
<< ":\t\t# derived from " << MBB->getName() << "\n");
if (getInstructionFromIndex(MIIndex) == 0)
MIIndex = Indexes->getNextNonNullIndex(MIIndex);
for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
MI != miEnd; ++MI) {
DEBUG(dbgs() << MIIndex << "\t" << *MI);
if (MI->isDebugValue())
continue;
assert(Indexes->getInstructionFromIndex(MIIndex) == MI &&
"Lost SlotIndex synchronization");
for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
MachineOperand &MO = MI->getOperand(i);
if (MO.isRegMask()) {
RegMaskSlots.push_back(MIIndex.getRegSlot());
RegMaskBits.push_back(MO.getRegMask());
continue;
}
if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
continue;
if (MO.isDef())
handleRegisterDef(MBB, MI, MIIndex, MO, i);
else if (MO.isUndef())
UndefUses.push_back(MO.getReg());
}
MIIndex = Indexes->getNextNonNullIndex(MIIndex);
}
std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
RMB.second = RegMaskSlots.size() - RMB.first;
}
for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
unsigned UndefReg = UndefUses[i];
(void)getOrCreateInterval(UndefReg);
}
}
LiveInterval* LiveIntervals::createInterval(unsigned reg) {
float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
return new LiveInterval(reg, Weight);
}
void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
assert(LRCalc && "LRCalc not initialized.");
assert(LI->empty() && "Should only compute empty intervals.");
LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
LRCalc->createDeadDefs(LI);
LRCalc->extendToUses(LI);
}
void LiveIntervals::computeVirtRegs() {
for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
if (MRI->reg_nodbg_empty(Reg))
continue;
LiveInterval *LI = createInterval(Reg);
VirtRegIntervals[Reg] = LI;
computeVirtRegInterval(LI);
}
}
void LiveIntervals::computeRegMasks() {
RegMaskBlocks.resize(MF->getNumBlockIDs());
for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
MBBI != E; ++MBBI) {
MachineBasicBlock *MBB = MBBI;
std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
RMB.first = RegMaskSlots.size();
for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
MI != ME; ++MI)
for (MIOperands MO(MI); MO.isValid(); ++MO) {
if (!MO->isRegMask())
continue;
RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
RegMaskBits.push_back(MO->getRegMask());
}
RMB.second = RegMaskSlots.size() - RMB.first;
}
}
void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
unsigned Unit = LI->reg;
assert(LRCalc && "LRCalc not initialized.");
LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
unsigned Root = *Roots;
if (!MRI->reg_empty(Root))
LRCalc->createDeadDefs(LI, Root);
for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
if (!MRI->reg_empty(*Supers))
LRCalc->createDeadDefs(LI, *Supers);
}
}
for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
unsigned Root = *Roots;
if (!MRI->isReserved(Root) && !MRI->reg_empty(Root))
LRCalc->extendToUses(LI, Root);
for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
unsigned Reg = *Supers;
if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
LRCalc->extendToUses(LI, Reg);
}
}
}
void LiveIntervals::computeLiveInRegUnits() {
RegUnitIntervals.resize(TRI->getNumRegUnits());
DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
SmallVector<LiveInterval*, 8> NewIntvs;
for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
MFI != MFE; ++MFI) {
const MachineBasicBlock *MBB = MFI;
if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
continue;
SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
LIE = MBB->livein_end(); LII != LIE; ++LII) {
for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
unsigned Unit = *Units;
LiveInterval *Intv = RegUnitIntervals[Unit];
if (!Intv) {
Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
NewIntvs.push_back(Intv);
}
VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
(void)VNI;
DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
}
}
DEBUG(dbgs() << '\n');
}
DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
computeRegUnitInterval(NewIntvs[i]);
}
bool LiveIntervals::shrinkToUses(LiveInterval *li,
SmallVectorImpl<MachineInstr*> *dead) {
DEBUG(dbgs() << "Shrink: " << *li << '\n');
assert(TargetRegisterInfo::isVirtualRegister(li->reg)
&& "Can only shrink virtual registers");
SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
MachineInstr *UseMI = I.skipInstruction();) {
if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
continue;
SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
LiveRangeQuery LRQ(*li, Idx);
VNInfo *VNI = LRQ.valueIn();
if (!VNI) {
DEBUG(dbgs() << Idx << '\t' << *UseMI
<< "Warning: Instr claims to read non-existent value in "
<< *li << '\n');
continue;
}
if (VNInfo *DefVNI = LRQ.valueDefined())
Idx = DefVNI->def;
WorkList.push_back(std::make_pair(Idx, VNI));
}
LiveInterval NewLI(li->reg, 0);
for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
}
SmallPtrSet<VNInfo*, 8> UsedPHIs;
while (!WorkList.empty()) {
SlotIndex Idx = WorkList.back().first;
VNInfo *VNI = WorkList.back().second;
WorkList.pop_back();
const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
SlotIndex BlockStart = getMBBStartIdx(MBB);
if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
(void)ExtVNI;
assert(ExtVNI == VNI && "Unexpected existing value number");
if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
continue;
for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
PE = MBB->pred_end(); PI != PE; ++PI) {
if (!LiveOut.insert(*PI))
continue;
SlotIndex Stop = getMBBEndIdx(*PI);
if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
WorkList.push_back(std::make_pair(Stop, PVNI));
}
continue;
}
DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
PE = MBB->pred_end(); PI != PE; ++PI) {
if (!LiveOut.insert(*PI))
continue;
SlotIndex Stop = getMBBEndIdx(*PI);
assert(li->getVNInfoBefore(Stop) == VNI &&
"Wrong value out of predecessor");
WorkList.push_back(std::make_pair(Stop, VNI));
}
}
bool CanSeparate = false;
for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
assert(LII != NewLI.end() && "Missing live range for PHI");
if (LII->end != VNI->def.getDeadSlot())
continue;
if (VNI->isPHIDef()) {
VNI->markUnused();
NewLI.removeRange(*LII);
DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
CanSeparate = true;
} else {
MachineInstr *MI = getInstructionFromIndex(VNI->def);
assert(MI && "No instruction defining live value");
MI->addRegisterDead(li->reg, TRI);
if (dead && MI->allDefsAreDead()) {
DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
dead->push_back(MI);
}
}
}
li->ranges.swap(NewLI.ranges);
DEBUG(dbgs() << "Shrunk: " << *li << '\n');
return CanSeparate;
}
void LiveIntervals::extendToIndices(LiveInterval *LI,
ArrayRef<SlotIndex> Indices) {
assert(LRCalc && "LRCalc not initialized.");
LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
for (unsigned i = 0, e = Indices.size(); i != e; ++i)
LRCalc->extend(LI, Indices[i]);
}
void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
SmallVectorImpl<SlotIndex> *EndPoints) {
LiveRangeQuery LRQ(*LI, Kill);
VNInfo *VNI = LRQ.valueOut();
if (!VNI)
return;
MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
SlotIndex MBBStart, MBBEnd;
tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
if (LRQ.endPoint() < MBBEnd) {
LI->removeRange(Kill, LRQ.endPoint());
if (EndPoints) EndPoints->push_back(LRQ.endPoint());
return;
}
LI->removeRange(Kill, MBBEnd);
if (EndPoints) EndPoints->push_back(MBBEnd);
typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
VisitedTy Visited;
for (MachineBasicBlock::succ_iterator
SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
SuccI != SuccE; ++SuccI) {
for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
I != E;) {
MachineBasicBlock *MBB = *I;
tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
LiveRangeQuery LRQ(*LI, MBBStart);
if (LRQ.valueIn() != VNI) {
I.skipChildren();
continue;
}
if (LRQ.endPoint() < MBBEnd) {
LI->removeRange(MBBStart, LRQ.endPoint());
if (EndPoints) EndPoints->push_back(LRQ.endPoint());
I.skipChildren();
continue;
}
LI->removeRange(MBBStart, MBBEnd);
if (EndPoints) EndPoints->push_back(MBBEnd);
++I;
}
}
}
void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
if (MRI->reg_nodbg_empty(Reg))
continue;
LiveInterval *LI = &getInterval(Reg);
if (LI->empty())
continue;
RU.clear();
for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
++Units) {
LiveInterval *RUInt = &getRegUnit(*Units);
if (RUInt->empty())
continue;
RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
}
for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
++RI) {
if (RI->end.isBlock())
continue;
MachineInstr *MI = getInstructionFromIndex(RI->end);
if (!MI)
continue;
bool CancelKill = false;
for (unsigned u = 0, e = RU.size(); u != e; ++u) {
LiveInterval *RInt = RU[u].first;
LiveInterval::iterator &I = RU[u].second;
if (I == RInt->end())
continue;
I = RInt->advanceTo(I, RI->end);
if (I == RInt->end() || I->start >= RI->end)
continue;
CancelKill = true;
break;
}
if (CancelKill)
MI->clearRegisterKills(Reg, NULL);
else
MI->addRegisterKilled(Reg, NULL);
}
}
}
MachineBasicBlock*
LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
SlotIndex Start = LI.beginIndex();
if (Start.isBlock())
return NULL;
SlotIndex Stop = LI.endIndex();
if (Stop.isBlock())
return NULL;
MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
return MBB1 == MBB2 ? MBB1 : NULL;
}
bool
LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
I != E; ++I) {
const VNInfo *PHI = *I;
if (PHI->isUnused() || !PHI->isPHIDef())
continue;
const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
if (PHIMBB->pred_size() > 100)
return true;
for (MachineBasicBlock::const_pred_iterator
PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
return true;
}
return false;
}
float
LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
if (loopDepth > 200)
loopDepth = 200;
float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
return (isDef + isUse) * lc;
}
LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
MachineInstr* startInst) {
LiveInterval& Interval = getOrCreateInterval(reg);
VNInfo* VN = Interval.getNextValue(
SlotIndex(getInstructionIndex(startInst).getRegSlot()),
getVNInfoAllocator());
LiveRange LR(
SlotIndex(getInstructionIndex(startInst).getRegSlot()),
getMBBEndIdx(startInst->getParent()), VN);
Interval.addRange(LR);
return LR;
}
bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
BitVector &UsableRegs) {
if (LI.empty())
return false;
LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
ArrayRef<SlotIndex> Slots;
ArrayRef<const uint32_t*> Bits;
if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
Slots = getRegMaskSlotsInBlock(MBB->getNumber());
Bits = getRegMaskBitsInBlock(MBB->getNumber());
} else {
Slots = getRegMaskSlots();
Bits = getRegMaskBits();
}
ArrayRef<SlotIndex>::iterator SlotI =
std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
if (SlotI == SlotE)
return false;
bool Found = false;
for (;;) {
assert(*SlotI >= LiveI->start);
while (*SlotI < LiveI->end) {
if (!Found) {
UsableRegs.clear();
UsableRegs.resize(TRI->getNumRegs(), true);
Found = true;
}
UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
if (++SlotI == SlotE)
return Found;
}
LiveI = LI.advanceTo(LiveI, *SlotI);
if (LiveI == LiveE)
return Found;
while (*SlotI < LiveI->start)
if (++SlotI == SlotE)
return Found;
}
}
class LiveIntervals::HMEditor {
private:
LiveIntervals& LIS;
const MachineRegisterInfo& MRI;
const TargetRegisterInfo& TRI;
SlotIndex OldIdx;
SlotIndex NewIdx;
SmallPtrSet<LiveInterval*, 8> Updated;
bool UpdateFlags;
public:
HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
const TargetRegisterInfo& TRI,
SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
: LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
UpdateFlags(UpdateFlags) {}
LiveInterval *getRegUnitLI(unsigned Unit) {
if (UpdateFlags)
return &LIS.getRegUnit(Unit);
return LIS.getCachedRegUnit(Unit);
}
void updateAllRanges(MachineInstr *MI) {
DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
bool hasRegMask = false;
for (MIOperands MO(MI); MO.isValid(); ++MO) {
if (MO->isRegMask())
hasRegMask = true;
if (!MO->isReg())
continue;
if (MO->isUse())
MO->setIsKill(false);
unsigned Reg = MO->getReg();
if (!Reg)
continue;
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
updateRange(LIS.getInterval(Reg));
continue;
}
for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
if (LiveInterval *LI = getRegUnitLI(*Units))
updateRange(*LI);
}
if (hasRegMask)
updateRegMaskSlots();
}
private:
void updateRange(LiveInterval &LI) {
if (!Updated.insert(&LI))
return;
DEBUG({
dbgs() << " ";
if (TargetRegisterInfo::isVirtualRegister(LI.reg))
dbgs() << PrintReg(LI.reg);
else
dbgs() << PrintRegUnit(LI.reg, &TRI);
dbgs() << ":\t" << LI << '\n';
});
if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
handleMoveDown(LI);
else
handleMoveUp(LI);
DEBUG(dbgs() << " -->\t" << LI << '\n');
LI.verify();
}
void handleMoveDown(LiveInterval &LI) {
LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
LiveInterval::iterator E = LI.end();
if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
return;
if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
return;
if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
if (MO->isReg() && MO->isUse())
MO->setIsKill(false);
I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
if (!isKill)
return;
++I;
}
if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
return;
VNInfo *DefVNI = I->valno;
assert(DefVNI->def == I->start && "Inconsistent def");
DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
I->start = DefVNI->def;
return;
}
assert((I->end == OldIdx.getDeadSlot() ||
SlotIndex::isSameInstr(I->end, NewIdx)) &&
"Cannot move def below kill");
LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
assert(NewI->valno != DefVNI && "Multiple defs of value?");
LI.removeValNo(DefVNI);
return;
}
assert(NewI != I && "Inconsistent iterators");
std::copy(llvm::next(I), NewI, I);
*llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
}
void handleMoveUp(LiveInterval &LI) {
LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
LiveInterval::iterator E = LI.end();
if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
return;
if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
if (!SlotIndex::isSameInstr(OldIdx, I->end))
return;
I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
++I;
if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
return;
}
}
assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
VNInfo *DefVNI = I->valno;
assert(DefVNI->def == I->start && "Inconsistent def");
DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
assert(NewI->valno != DefVNI && "Same value defined more than once?");
if (I->end.isDead()) {
LI.removeValNo(DefVNI);
return;
}
I->start = DefVNI->def;
LI.removeValNo(NewI->valno);
return;
}
if (!I->end.isDead()) {
I->start = DefVNI->def;
return;
}
std::copy_backward(NewI, I, llvm::next(I));
*NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
}
void updateRegMaskSlots() {
SmallVectorImpl<SlotIndex>::iterator RI =
std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
OldIdx);
assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
"No RegMask at OldIdx.");
*RI = NewIdx.getRegSlot();
assert((RI == LIS.RegMaskSlots.begin() ||
SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
"Cannot move regmask instruction above another call");
assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
"Cannot move regmask instruction below another call");
}
SlotIndex findLastUseBefore(unsigned Reg) {
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
SlotIndex LastUse = NewIdx;
for (MachineRegisterInfo::use_nodbg_iterator
UI = MRI.use_nodbg_begin(Reg),
UE = MRI.use_nodbg_end();
UI != UE; UI.skipInstruction()) {
const MachineInstr* MI = &*UI;
SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
if (InstSlot > LastUse && InstSlot < OldIdx)
LastUse = InstSlot;
}
return LastUse;
}
assert(NewIdx < OldIdx && "Expected upwards move");
SlotIndexes *Indexes = LIS.getSlotIndexes();
MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
MachineBasicBlock::iterator MII = MBB->end();
if (MachineInstr *MI = Indexes->getInstructionFromIndex(
Indexes->getNextNonNullIndex(OldIdx)))
if (MI->getParent() == MBB)
MII = MI;
MachineBasicBlock::iterator Begin = MBB->begin();
while (MII != Begin) {
if ((--MII)->isDebugValue())
continue;
SlotIndex Idx = Indexes->getInstructionIndex(MII);
if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
return NewIdx;
for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
if (MO->isReg() &&
TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
TRI.hasRegUnit(MO->getReg(), Reg))
return Idx;
}
return NewIdx;
}
};
void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Indexes->removeMachineInstrFromMaps(MI);
SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
OldIndex < getMBBEndIdx(MI->getParent()) &&
"Cannot handle moves across basic block boundaries.");
HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
HME.updateAllRanges(MI);
}
void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
MachineInstr* BundleStart,
bool UpdateFlags) {
SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
HME.updateAllRanges(MI);
}