#define DEBUG_TYPE "regalloc"
#include "PBQP/HeuristicSolver.h"
#include "PBQP/Graph.h"
#include "PBQP/Heuristics/Briggs.h"
#include "VirtRegMap.h"
#include "VirtRegRewriter.h"
#include "llvm/CodeGen/CalcSpillWeights.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/LiveStackAnalysis.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/RegisterCoalescer.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <vector>
using namespace llvm;
static RegisterRegAlloc
registerPBQPRepAlloc("pbqp", "PBQP register allocator",
llvm::createPBQPRegisterAllocator);
static cl::opt<bool>
pbqpCoalescing("pbqp-coalescing",
cl::desc("Attempt coalescing during PBQP register allocation."),
cl::init(false), cl::Hidden);
namespace {
class PBQPRegAlloc : public MachineFunctionPass {
public:
static char ID;
PBQPRegAlloc() : MachineFunctionPass(&ID) {}
virtual const char* getPassName() const {
return "PBQP Register Allocator";
}
virtual void getAnalysisUsage(AnalysisUsage &au) const {
au.addRequired<SlotIndexes>();
au.addPreserved<SlotIndexes>();
au.addRequired<LiveIntervals>();
au.addRequired<RegisterCoalescer>();
au.addRequired<CalculateSpillWeights>();
au.addRequired<LiveStacks>();
au.addPreserved<LiveStacks>();
au.addRequired<MachineLoopInfo>();
au.addPreserved<MachineLoopInfo>();
au.addRequired<VirtRegMap>();
MachineFunctionPass::getAnalysisUsage(au);
}
virtual bool runOnMachineFunction(MachineFunction &MF);
private:
typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
typedef std::vector<const LiveInterval*> Node2LIMap;
typedef std::vector<unsigned> AllowedSet;
typedef std::vector<AllowedSet> AllowedSetMap;
typedef std::set<unsigned> RegSet;
typedef std::pair<unsigned, unsigned> RegPair;
typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;
typedef std::set<LiveInterval*> LiveIntervalSet;
typedef std::vector<PBQP::Graph::NodeItr> NodeVector;
MachineFunction *mf;
const TargetMachine *tm;
const TargetRegisterInfo *tri;
const TargetInstrInfo *tii;
const MachineLoopInfo *loopInfo;
MachineRegisterInfo *mri;
LiveIntervals *lis;
LiveStacks *lss;
VirtRegMap *vrm;
LI2NodeMap li2Node;
Node2LIMap node2LI;
AllowedSetMap allowedSets;
LiveIntervalSet vregIntervalsToAlloc,
emptyVRegIntervals;
NodeVector problemNodes;
template <typename RegContainer>
PBQP::Vector buildCostVector(unsigned vReg,
const RegContainer &allowed,
const CoalesceMap &cealesces,
PBQP::PBQPNum spillCost) const;
template <typename RegContainer>
PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
const RegContainer &allowed2) const;
template <typename RegContainer>
PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
const RegContainer &allowed2,
PBQP::PBQPNum cBenefit) const;
CoalesceMap findCoalesces();
void findVRegIntervalsToAlloc();
PBQP::Graph constructPBQPProblem();
void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);
bool mapPBQPToRegAlloc(const PBQP::Solution &solution);
void finalizeAlloc() const;
};
char PBQPRegAlloc::ID = 0;
}
template <typename RegContainer>
PBQP::Vector PBQPRegAlloc::buildCostVector(unsigned vReg,
const RegContainer &allowed,
const CoalesceMap &coalesces,
PBQP::PBQPNum spillCost) const {
typedef typename RegContainer::const_iterator AllowedItr;
PBQP::Vector v(allowed.size() + 1, 0);
v[0] = spillCost;
unsigned ai = 0;
for (AllowedItr itr = allowed.begin(), end = allowed.end();
itr != end; ++itr, ++ai) {
unsigned pReg = *itr;
CoalesceMap::const_iterator cmItr =
coalesces.find(RegPair(vReg, pReg));
if (cmItr == coalesces.end())
continue;
v[ai + 1] = -cmItr->second;
}
return v;
}
template <typename RegContainer>
PBQP::Matrix* PBQPRegAlloc::buildInterferenceMatrix(
const RegContainer &allowed1, const RegContainer &allowed2) const {
typedef typename RegContainer::const_iterator RegContainerIterator;
PBQP::Matrix *m =
new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
bool isZeroMatrix = true;
unsigned ri = 1;
for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
a1Itr != a1End; ++a1Itr) {
unsigned ci = 1;
unsigned reg1 = *a1Itr;
for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
a2Itr != a2End; ++a2Itr) {
unsigned reg2 = *a2Itr;
if (tri->regsOverlap(reg1, reg2)) {
(*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
isZeroMatrix = false;
}
++ci;
}
++ri;
}
if (isZeroMatrix) {
delete m;
return 0;
}
return m;
}
template <typename RegContainer>
PBQP::Matrix* PBQPRegAlloc::buildCoalescingMatrix(
const RegContainer &allowed1, const RegContainer &allowed2,
PBQP::PBQPNum cBenefit) const {
typedef typename RegContainer::const_iterator RegContainerIterator;
PBQP::Matrix *m =
new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);
m->reset(0);
bool isZeroMatrix = true;
unsigned ri = 1;
for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
a1Itr != a1End; ++a1Itr) {
unsigned ci = 1;
unsigned reg1 = *a1Itr;
for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
a2Itr != a2End; ++a2Itr) {
if (reg1 == *a2Itr) {
(*m)[ri][ci] = -cBenefit;
isZeroMatrix = false;
}
++ci;
}
++ri;
}
if (isZeroMatrix) {
delete m;
return 0;
}
return m;
}
PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {
typedef MachineFunction::const_iterator MFIterator;
typedef MachineBasicBlock::const_iterator MBBIterator;
typedef LiveInterval::const_vni_iterator VNIIterator;
CoalesceMap coalescesFound;
for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
bbItr != bbEnd; ++bbItr) {
const MachineBasicBlock *mbb = &*bbItr;
for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
iItr != iEnd; ++iItr) {
const MachineInstr *instr = &*iItr;
unsigned srcReg, dstReg, srcSubReg, dstSubReg;
if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
continue;
if (dstReg == srcReg)
continue;
bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);
if (srcRegIsPhysical && dstRegIsPhysical)
continue;
const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);
const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);
if (srcRegClass != dstRegClass)
continue;
if (srcRegIsPhysical) {
if (std::find(dstRegClass->allocation_order_begin(*mf),
dstRegClass->allocation_order_end(*mf), srcReg) ==
dstRegClass->allocation_order_end(*mf))
continue;
}
if (dstRegIsPhysical) {
if (std::find(srcRegClass->allocation_order_begin(*mf),
srcRegClass->allocation_order_end(*mf), dstReg) ==
srcRegClass->allocation_order_end(*mf))
continue;
}
const LiveInterval *srcLI = &lis->getInterval(srcReg),
*dstLI = &lis->getInterval(dstReg);
if (srcLI->overlaps(*dstLI)) {
bool badDef = false;
for (VNIIterator
vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
vniItr != vniEnd; ++vniItr) {
if (!(*vniItr)->def.isValid()) {
badDef = true;
break;
}
if (dstLI->liveAt((*vniItr)->def)) {
badDef = true;
break;
}
}
if (badDef)
continue;
for (VNIIterator
vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
vniItr != vniEnd; ++vniItr) {
if ((*vniItr)->getCopy() == instr)
continue;
if (!(*vniItr)->def.isValid()) {
badDef = true;
break;
}
if (srcLI->liveAt((*vniItr)->def)) {
badDef = true;
break;
}
}
if (badDef)
continue;
}
float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;
coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
}
}
return coalescesFound;
}
void PBQPRegAlloc::findVRegIntervalsToAlloc() {
for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
itr != end; ++itr) {
if (TargetRegisterInfo::isPhysicalRegister(itr->first))
continue;
LiveInterval *li = itr->second;
if (!li->empty()) {
vregIntervalsToAlloc.insert(li);
}
else {
emptyVRegIntervals.insert(li);
}
}
}
PBQP::Graph PBQPRegAlloc::constructPBQPProblem() {
typedef std::vector<const LiveInterval*> LIVector;
typedef std::vector<unsigned> RegVector;
LIVector physIntervals;
li2Node.clear();
node2LI.clear();
allowedSets.clear();
for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
itr != end; ++itr) {
if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
physIntervals.push_back(itr->second);
mri->setPhysRegUsed(itr->second->reg);
}
}
for (LiveIntervalSet::const_iterator
itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
itr != end; ++itr) {
const LiveInterval *li = *itr;
li2Node[li] = node2LI.size();
node2LI.push_back(li);
}
CoalesceMap coalesces;
if (pbqpCoalescing) {
coalesces = findCoalesces();
}
PBQP::Graph problem;
problemNodes.resize(vregIntervalsToAlloc.size());
allowedSets.resize(vregIntervalsToAlloc.size());
for (unsigned node = 0; node < node2LI.size(); ++node) {
const LiveInterval *li = node2LI[node];
const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
RegVector liAllowed(liRC->allocation_order_begin(*mf),
liRC->allocation_order_end(*mf));
for (LIVector::iterator pItr = physIntervals.begin(),
pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {
if (!li->overlaps(**pItr))
continue;
unsigned pReg = (*pItr)->reg;
if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
continue;
RegVector::iterator eraseItr =
std::find(liAllowed.begin(), liAllowed.end(), pReg);
if (eraseItr != liAllowed.end())
liAllowed.erase(eraseItr);
const unsigned *aliasItr = tri->getAliasSet(pReg);
if (aliasItr != 0) {
for (; *aliasItr != 0; ++aliasItr) {
RegVector::iterator eraseItr =
std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);
if (eraseItr != liAllowed.end()) {
liAllowed.erase(eraseItr);
}
}
}
}
allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());
PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
li->weight : std::numeric_limits<PBQP::PBQPNum>::min();
problemNodes[node] =
problem.addNode(
buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));
}
for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
const LiveInterval *li = node2LI[node1];
for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
const LiveInterval *li2 = node2LI[node2];
CoalesceMap::const_iterator cmItr =
coalesces.find(RegPair(li->reg, li2->reg));
PBQP::Matrix *m = 0;
if (cmItr != coalesces.end()) {
m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
cmItr->second);
}
else if (li->overlaps(*li2)) {
m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
}
if (m != 0) {
problem.addEdge(problemNodes[node1],
problemNodes[node2],
*m);
delete m;
}
}
}
assert(problem.getNumNodes() == allowedSets.size());
return problem;
}
void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled,
MachineRegisterInfo* mri) {
int stackSlot = vrm->getStackSlot(spilled->reg);
if (stackSlot == VirtRegMap::NO_STACK_SLOT)
return;
const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);
VNInfo *vni;
if (stackInterval.getNumValNums() != 0)
vni = stackInterval.getValNumInfo(0);
else
vni = stackInterval.getNextValue(
SlotIndex(), 0, false, lss->getVNInfoAllocator());
LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
stackInterval.MergeRangesInAsValue(rhsInterval, vni);
}
bool PBQPRegAlloc::mapPBQPToRegAlloc(const PBQP::Solution &solution) {
bool anotherRoundNeeded = false;
vrm->clearAllVirt();
for (unsigned node = 0; node < node2LI.size(); ++node) {
unsigned virtReg = node2LI[node]->reg,
allocSelection = solution.getSelection(problemNodes[node]);
if (allocSelection != 0) {
unsigned physReg = allowedSets[node][allocSelection - 1];
DEBUG(dbgs() << "VREG " << virtReg << " -> "
<< tri->getName(physReg) << "\n");
assert(physReg != 0);
vrm->assignVirt2Phys(virtReg, physReg);
}
else {
vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));
const LiveInterval *spillInterval = node2LI[node];
double oldSpillWeight = spillInterval->weight;
SmallVector<LiveInterval*, 8> spillIs;
std::vector<LiveInterval*> newSpills =
lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
addStackInterval(spillInterval, mri);
(void) oldSpillWeight;
DEBUG(dbgs() << "VREG " << virtReg << " -> SPILLED (Cost: "
<< oldSpillWeight << ", New vregs: ");
for (std::vector<LiveInterval*>::const_iterator
itr = newSpills.begin(), end = newSpills.end();
itr != end; ++itr) {
assert(!(*itr)->empty() && "Empty spill range.");
DEBUG(dbgs() << (*itr)->reg << " ");
vregIntervalsToAlloc.insert(*itr);
}
DEBUG(dbgs() << ")\n");
anotherRoundNeeded |= !newSpills.empty();
}
}
return !anotherRoundNeeded;
}
void PBQPRegAlloc::finalizeAlloc() const {
typedef LiveIntervals::iterator LIIterator;
typedef LiveInterval::Ranges::const_iterator LRIterator;
for (LiveIntervalSet::const_iterator
itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
itr != end; ++itr) {
LiveInterval *li = *itr;
unsigned physReg = vrm->getRegAllocPref(li->reg);
if (physReg == 0) {
const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
physReg = *liRC->allocation_order_begin(*mf);
}
vrm->assignVirt2Phys(li->reg, physReg);
}
SmallVector<MachineBasicBlock*, 8> liveInMBBs;
MachineBasicBlock *entryMBB = &*mf->begin();
for (LIIterator liItr = lis->begin(), liEnd = lis->end();
liItr != liEnd; ++liItr) {
const LiveInterval *li = liItr->second;
unsigned reg = 0;
if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
reg = li->reg;
}
else if (vrm->isAssignedReg(li->reg)) {
reg = vrm->getPhys(li->reg);
}
else {
continue;
}
if (reg == 0) {
continue;
}
for (LRIterator lrItr = li->begin(), lrEnd = li->end();
lrItr != lrEnd; ++lrItr) {
if (lis->findLiveInMBBs(lrItr->start, lrItr->end, liveInMBBs)) {
for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
if (liveInMBBs[i] != entryMBB) {
if (!liveInMBBs[i]->isLiveIn(reg)) {
liveInMBBs[i]->addLiveIn(reg);
}
}
}
liveInMBBs.clear();
}
}
}
}
bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {
mf = &MF;
tm = &mf->getTarget();
tri = tm->getRegisterInfo();
tii = tm->getInstrInfo();
mri = &mf->getRegInfo();
lis = &getAnalysis<LiveIntervals>();
lss = &getAnalysis<LiveStacks>();
loopInfo = &getAnalysis<MachineLoopInfo>();
vrm = &getAnalysis<VirtRegMap>();
DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");
findVRegIntervalsToAlloc();
if (!vregIntervalsToAlloc.empty()) {
bool pbqpAllocComplete = false;
unsigned round = 0;
while (!pbqpAllocComplete) {
DEBUG(dbgs() << " PBQP Regalloc round " << round << ":\n");
PBQP::Graph problem = constructPBQPProblem();
PBQP::Solution solution =
PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(problem);
pbqpAllocComplete = mapPBQPToRegAlloc(solution);
++round;
}
}
finalizeAlloc();
vregIntervalsToAlloc.clear();
emptyVRegIntervals.clear();
li2Node.clear();
node2LI.clear();
allowedSets.clear();
problemNodes.clear();
DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
rewriter->runOnMachineFunction(*mf, *vrm, lis);
return true;
}
FunctionPass* llvm::createPBQPRegisterAllocator() {
return new PBQPRegAlloc();
}
#undef DEBUG_TYPE