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/MachineBlockFrequencyInfo.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/BlockFrequency.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;
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)
#ifndef NDEBUG
static cl::opt<bool> EnablePrecomputePhysRegs(
"precompute-phys-liveness", cl::Hidden,
cl::desc("Eagerly compute live intervals for all physreg units."));
#else
static bool EnablePrecomputePhysRegs = false;
#endif // NDEBUG
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 = RegUnitRanges.size(); i != e; ++i)
delete RegUnitRanges[i];
RegUnitRanges.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>();
Indexes = &getAnalysis<SlotIndexes>();
DomTree = &getAnalysis<MachineDominatorTree>();
if (!LRCalc)
LRCalc = new LiveRangeCalc();
VirtRegIntervals.resize(MRI->getNumVirtRegs());
computeVirtRegs();
computeRegMasks();
computeLiveInRegUnits();
if (EnablePrecomputePhysRegs) {
for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
getRegUnit(i);
}
DEBUG(dump());
return true;
}
void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
OS << "********** INTERVALS **********\n";
for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
if (LiveRange *LR = RegUnitRanges[i])
OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
if (hasInterval(Reg))
OS << 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
LiveInterval* LiveIntervals::createInterval(unsigned reg) {
float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
llvm::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;
createAndComputeVirtRegInterval(Reg);
}
}
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::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
assert(LRCalc && "LRCalc not initialized.");
LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
for (MCSuperRegIterator Supers(*Roots, TRI, true);
Supers.isValid(); ++Supers) {
if (!MRI->reg_empty(*Supers))
LRCalc->createDeadDefs(LR, *Supers);
}
}
for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
for (MCSuperRegIterator Supers(*Roots, TRI, true);
Supers.isValid(); ++Supers) {
unsigned Reg = *Supers;
if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
LRCalc->extendToUses(LR, Reg);
}
}
}
void LiveIntervals::computeLiveInRegUnits() {
RegUnitRanges.resize(TRI->getNumRegUnits());
DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
SmallVector<unsigned, 8> NewRanges;
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;
LiveRange *LR = RegUnitRanges[Unit];
if (!LR) {
LR = RegUnitRanges[Unit] = new LiveRange();
NewRanges.push_back(Unit);
}
VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
(void)VNI;
DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
}
}
DEBUG(dbgs() << '\n');
}
DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
unsigned Unit = NewRanges[i];
computeRegUnitRange(*RegUnitRanges[Unit], Unit);
}
}
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();
LiveQueryResult LRQ = li->Query(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));
}
LiveRange NewLR;
for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
NewLR.addSegment(LiveRange::Segment(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 = NewLR.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');
NewLR.addSegment(LiveRange::Segment(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;
LiveRange::iterator LRI = NewLR.FindSegmentContaining(VNI->def);
assert(LRI != NewLR.end() && "Missing segment for PHI");
if (LRI->end != VNI->def.getDeadSlot())
continue;
if (VNI->isPHIDef()) {
VNI->markUnused();
NewLR.removeSegment(LRI->start, LRI->end);
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->segments.swap(NewLR.segments);
DEBUG(dbgs() << "Shrunk: " << *li << '\n');
return CanSeparate;
}
void LiveIntervals::extendToIndices(LiveRange &LR,
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(LR, Indices[i]);
}
void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
SmallVectorImpl<SlotIndex> *EndPoints) {
LiveQueryResult LRQ = LI->Query(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->removeSegment(Kill, LRQ.endPoint());
if (EndPoints) EndPoints->push_back(LRQ.endPoint());
return;
}
LI->removeSegment(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);
LiveQueryResult LRQ = LI->Query(MBBStart);
if (LRQ.valueIn() != VNI) {
I.skipChildren();
continue;
}
if (LRQ.endPoint() < MBBEnd) {
LI->removeSegment(MBBStart, LRQ.endPoint());
if (EndPoints) EndPoints->push_back(LRQ.endPoint());
I.skipChildren();
continue;
}
LI->removeSegment(MBBStart, MBBEnd);
if (EndPoints) EndPoints->push_back(MBBEnd);
++I;
}
}
}
void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
SmallVector<std::pair<LiveRange*, LiveRange::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) {
LiveRange &RURanges = getRegUnit(*Units);
if (RURanges.empty())
continue;
RU.push_back(std::make_pair(&RURanges, RURanges.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) {
LiveRange &RRanges = *RU[u].first;
LiveRange::iterator &I = RU[u].second;
if (I == RRanges.end())
continue;
I = RRanges.advanceTo(I, RI->end);
if (I == RRanges.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,
const MachineBlockFrequencyInfo *MBFI,
const MachineInstr *MI) {
BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
const float Scale = 1.0f / MBFI->getEntryFreq();
return (isDef + isUse) * (Freq.getFrequency() * Scale);
}
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::Segment
LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
LiveInterval& Interval = createEmptyInterval(reg);
VNInfo* VN = Interval.getNextValue(
SlotIndex(getInstructionIndex(startInst).getRegSlot()),
getVNInfoAllocator());
LiveRange::Segment S(
SlotIndex(getInstructionIndex(startInst).getRegSlot()),
getMBBEndIdx(startInst->getParent()), VN);
Interval.addSegment(S);
return S;
}
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<LiveRange*, 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) {}
LiveRange *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)) {
LiveInterval &LI = LIS.getInterval(Reg);
updateRange(LI, Reg);
continue;
}
for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
if (LiveRange *LR = getRegUnitLI(*Units))
updateRange(*LR, *Units);
}
if (hasRegMask)
updateRegMaskSlots();
}
private:
void updateRange(LiveRange &LR, unsigned Reg) {
if (!Updated.insert(&LR))
return;
DEBUG({
dbgs() << " ";
if (TargetRegisterInfo::isVirtualRegister(Reg))
dbgs() << PrintReg(Reg);
else
dbgs() << PrintRegUnit(Reg, &TRI);
dbgs() << ":\t" << LR << '\n';
});
if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
handleMoveDown(LR);
else
handleMoveUp(LR, Reg);
DEBUG(dbgs() << " -->\t" << LR << '\n');
LR.verify();
}
void handleMoveDown(LiveRange &LR) {
LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
LiveRange::iterator E = LR.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");
LiveRange::iterator NewI = LR.advanceTo(I, NewIdx.getRegSlot());
if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
assert(NewI->valno != DefVNI && "Multiple defs of value?");
LR.removeValNo(DefVNI);
return;
}
assert(NewI != I && "Inconsistent iterators");
std::copy(llvm::next(I), NewI, I);
*llvm::prior(NewI)
= LiveRange::Segment(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
}
void handleMoveUp(LiveRange &LR, unsigned Reg) {
LiveRange::iterator I = LR.find(OldIdx.getBaseIndex());
LiveRange::iterator E = LR.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(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());
LiveRange::iterator NewI = LR.find(NewIdx.getRegSlot());
if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
assert(NewI->valno != DefVNI && "Same value defined more than once?");
if (I->end.isDead()) {
LR.removeValNo(DefVNI);
return;
}
I->start = DefVNI->def;
LR.removeValNo(NewI->valno);
return;
}
if (!I->end.isDead()) {
I->start = DefVNI->def;
return;
}
std::copy_backward(NewI, I, llvm::next(I));
*NewI = LiveRange::Segment(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);
}
void
LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
MachineBasicBlock::iterator Begin,
MachineBasicBlock::iterator End,
ArrayRef<unsigned> OrigRegs) {
while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
--Begin;
while (End != MBB->end() && !Indexes->hasIndex(End))
++End;
SlotIndex endIdx;
if (End == MBB->end())
endIdx = getMBBEndIdx(MBB).getPrevSlot();
else
endIdx = getInstructionIndex(End);
Indexes->repairIndexesInRange(MBB, Begin, End);
for (MachineBasicBlock::iterator I = End; I != Begin;) {
--I;
MachineInstr *MI = I;
if (MI->isDebugValue())
continue;
for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
MOE = MI->operands_end(); MOI != MOE; ++MOI) {
if (MOI->isReg() &&
TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
!hasInterval(MOI->getReg())) {
createAndComputeVirtRegInterval(MOI->getReg());
}
}
}
for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
unsigned Reg = OrigRegs[i];
if (!TargetRegisterInfo::isVirtualRegister(Reg))
continue;
LiveInterval &LI = getInterval(Reg);
if (!LI.hasAtLeastOneValue())
continue;
LiveInterval::iterator LII = LI.find(endIdx);
SlotIndex lastUseIdx;
if (LII != LI.end() && LII->start < endIdx)
lastUseIdx = LII->end;
else
--LII;
for (MachineBasicBlock::iterator I = End; I != Begin;) {
--I;
MachineInstr *MI = I;
if (MI->isDebugValue())
continue;
SlotIndex instrIdx = getInstructionIndex(MI);
bool isStartValid = getInstructionFromIndex(LII->start);
bool isEndValid = getInstructionFromIndex(LII->end);
for (MachineInstr::mop_iterator OI = MI->operands_begin(),
OE = MI->operands_end(); OI != OE; ++OI) {
const MachineOperand &MO = *OI;
if (!MO.isReg() || MO.getReg() != Reg)
continue;
if (MO.isDef()) {
if (!isStartValid) {
if (LII->end.isDead()) {
SlotIndex prevStart;
if (LII != LI.begin())
prevStart = llvm::prior(LII)->start;
LI.removeSegment(*LII, true);
if (prevStart.isValid())
LII = LI.find(prevStart);
else
LII = LI.begin();
} else {
LII->start = instrIdx.getRegSlot();
LII->valno->def = instrIdx.getRegSlot();
if (MO.getSubReg() && !MO.isUndef())
lastUseIdx = instrIdx.getRegSlot();
else
lastUseIdx = SlotIndex();
continue;
}
}
if (!lastUseIdx.isValid()) {
VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
VNInfoAllocator);
LiveRange::Segment S(instrIdx.getRegSlot(),
instrIdx.getDeadSlot(), VNI);
LII = LI.addSegment(S);
} else if (LII->start != instrIdx.getRegSlot()) {
VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
VNInfoAllocator);
LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
LII = LI.addSegment(S);
}
if (MO.getSubReg() && !MO.isUndef())
lastUseIdx = instrIdx.getRegSlot();
else
lastUseIdx = SlotIndex();
} else if (MO.isUse()) {
if (!isEndValid && !LII->end.isBlock())
LII->end = instrIdx.getRegSlot();
if (!lastUseIdx.isValid())
lastUseIdx = instrIdx.getRegSlot();
}
}
}
}
}