1235633Sdim//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===// 2218885Sdim// 3218885Sdim// The LLVM Compiler Infrastructure 4218885Sdim// 5218885Sdim// This file is distributed under the University of Illinois Open Source 6218885Sdim// License. See LICENSE.TXT for details. 7218885Sdim// 8218885Sdim//===----------------------------------------------------------------------===// 9218885Sdim// 10218885Sdim// This file defines the RABasic function pass, which provides a minimal 11218885Sdim// implementation of the basic register allocator. 12218885Sdim// 13218885Sdim//===----------------------------------------------------------------------===// 14218885Sdim 15218885Sdim#define DEBUG_TYPE "regalloc" 16252723Sdim#include "llvm/CodeGen/Passes.h" 17245431Sdim#include "AllocationOrder.h" 18252723Sdim#include "LiveDebugVariables.h" 19223017Sdim#include "RegAllocBase.h" 20218885Sdim#include "Spiller.h" 21218885Sdim#include "llvm/Analysis/AliasAnalysis.h" 22218885Sdim#include "llvm/CodeGen/CalcSpillWeights.h" 23218885Sdim#include "llvm/CodeGen/LiveIntervalAnalysis.h" 24235633Sdim#include "llvm/CodeGen/LiveRangeEdit.h" 25252723Sdim#include "llvm/CodeGen/LiveRegMatrix.h" 26218885Sdim#include "llvm/CodeGen/LiveStackAnalysis.h" 27263509Sdim#include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 28218885Sdim#include "llvm/CodeGen/MachineFunctionPass.h" 29218885Sdim#include "llvm/CodeGen/MachineInstr.h" 30218885Sdim#include "llvm/CodeGen/MachineLoopInfo.h" 31218885Sdim#include "llvm/CodeGen/MachineRegisterInfo.h" 32218885Sdim#include "llvm/CodeGen/RegAllocRegistry.h" 33252723Sdim#include "llvm/CodeGen/VirtRegMap.h" 34252723Sdim#include "llvm/PassAnalysisSupport.h" 35252723Sdim#include "llvm/Support/Debug.h" 36252723Sdim#include "llvm/Support/raw_ostream.h" 37218885Sdim#include "llvm/Target/TargetMachine.h" 38218885Sdim#include "llvm/Target/TargetRegisterInfo.h" 39218885Sdim#include <cstdlib> 40219077Sdim#include <queue> 41218885Sdim 42218885Sdimusing namespace llvm; 43218885Sdim 44218885Sdimstatic RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", 45218885Sdim createBasicRegisterAllocator); 46218885Sdim 47218885Sdimnamespace { 48219077Sdim struct CompSpillWeight { 49219077Sdim bool operator()(LiveInterval *A, LiveInterval *B) const { 50219077Sdim return A->weight < B->weight; 51219077Sdim } 52219077Sdim }; 53219077Sdim} 54219077Sdim 55219077Sdimnamespace { 56218885Sdim/// RABasic provides a minimal implementation of the basic register allocation 57218885Sdim/// algorithm. It prioritizes live virtual registers by spill weight and spills 58218885Sdim/// whenever a register is unavailable. This is not practical in production but 59218885Sdim/// provides a useful baseline both for measuring other allocators and comparing 60218885Sdim/// the speed of the basic algorithm against other styles of allocators. 61218885Sdimclass RABasic : public MachineFunctionPass, public RegAllocBase 62218885Sdim{ 63218885Sdim // context 64218885Sdim MachineFunction *MF; 65218885Sdim 66218885Sdim // state 67252723Sdim OwningPtr<Spiller> SpillerInstance; 68219077Sdim std::priority_queue<LiveInterval*, std::vector<LiveInterval*>, 69219077Sdim CompSpillWeight> Queue; 70235633Sdim 71235633Sdim // Scratch space. Allocated here to avoid repeated malloc calls in 72235633Sdim // selectOrSplit(). 73235633Sdim BitVector UsableRegs; 74235633Sdim 75218885Sdimpublic: 76218885Sdim RABasic(); 77218885Sdim 78218885Sdim /// Return the pass name. 79218885Sdim virtual const char* getPassName() const { 80218885Sdim return "Basic Register Allocator"; 81218885Sdim } 82218885Sdim 83218885Sdim /// RABasic analysis usage. 84218885Sdim virtual void getAnalysisUsage(AnalysisUsage &AU) const; 85218885Sdim 86218885Sdim virtual void releaseMemory(); 87218885Sdim 88218885Sdim virtual Spiller &spiller() { return *SpillerInstance; } 89218885Sdim 90218885Sdim virtual float getPriority(LiveInterval *LI) { return LI->weight; } 91218885Sdim 92219077Sdim virtual void enqueue(LiveInterval *LI) { 93219077Sdim Queue.push(LI); 94219077Sdim } 95219077Sdim 96219077Sdim virtual LiveInterval *dequeue() { 97219077Sdim if (Queue.empty()) 98219077Sdim return 0; 99219077Sdim LiveInterval *LI = Queue.top(); 100219077Sdim Queue.pop(); 101219077Sdim return LI; 102219077Sdim } 103219077Sdim 104218885Sdim virtual unsigned selectOrSplit(LiveInterval &VirtReg, 105263509Sdim SmallVectorImpl<unsigned> &SplitVRegs); 106218885Sdim 107218885Sdim /// Perform register allocation. 108218885Sdim virtual bool runOnMachineFunction(MachineFunction &mf); 109218885Sdim 110235633Sdim // Helper for spilling all live virtual registers currently unified under preg 111235633Sdim // that interfere with the most recently queried lvr. Return true if spilling 112235633Sdim // was successful, and append any new spilled/split intervals to splitLVRs. 113235633Sdim bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, 114263509Sdim SmallVectorImpl<unsigned> &SplitVRegs); 115235633Sdim 116218885Sdim static char ID; 117218885Sdim}; 118218885Sdim 119218885Sdimchar RABasic::ID = 0; 120218885Sdim 121218885Sdim} // end anonymous namespace 122218885Sdim 123218885SdimRABasic::RABasic(): MachineFunctionPass(ID) { 124221345Sdim initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 125218885Sdim initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); 126218885Sdim initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); 127224145Sdim initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); 128235633Sdim initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); 129218885Sdim initializeLiveStacksPass(*PassRegistry::getPassRegistry()); 130218885Sdim initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry()); 131218885Sdim initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry()); 132218885Sdim initializeVirtRegMapPass(*PassRegistry::getPassRegistry()); 133245431Sdim initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry()); 134218885Sdim} 135218885Sdim 136218885Sdimvoid RABasic::getAnalysisUsage(AnalysisUsage &AU) const { 137218885Sdim AU.setPreservesCFG(); 138218885Sdim AU.addRequired<AliasAnalysis>(); 139218885Sdim AU.addPreserved<AliasAnalysis>(); 140218885Sdim AU.addRequired<LiveIntervals>(); 141245431Sdim AU.addPreserved<LiveIntervals>(); 142218885Sdim AU.addPreserved<SlotIndexes>(); 143221345Sdim AU.addRequired<LiveDebugVariables>(); 144221345Sdim AU.addPreserved<LiveDebugVariables>(); 145218885Sdim AU.addRequired<LiveStacks>(); 146218885Sdim AU.addPreserved<LiveStacks>(); 147263509Sdim AU.addRequired<MachineBlockFrequencyInfo>(); 148263509Sdim AU.addPreserved<MachineBlockFrequencyInfo>(); 149218885Sdim AU.addRequiredID(MachineDominatorsID); 150218885Sdim AU.addPreservedID(MachineDominatorsID); 151218885Sdim AU.addRequired<MachineLoopInfo>(); 152218885Sdim AU.addPreserved<MachineLoopInfo>(); 153218885Sdim AU.addRequired<VirtRegMap>(); 154218885Sdim AU.addPreserved<VirtRegMap>(); 155245431Sdim AU.addRequired<LiveRegMatrix>(); 156245431Sdim AU.addPreserved<LiveRegMatrix>(); 157218885Sdim MachineFunctionPass::getAnalysisUsage(AU); 158218885Sdim} 159218885Sdim 160218885Sdimvoid RABasic::releaseMemory() { 161218885Sdim SpillerInstance.reset(0); 162218885Sdim} 163218885Sdim 164218885Sdim 165218885Sdim// Spill or split all live virtual registers currently unified under PhysReg 166218885Sdim// that interfere with VirtReg. The newly spilled or split live intervals are 167218885Sdim// returned by appending them to SplitVRegs. 168235633Sdimbool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, 169263509Sdim SmallVectorImpl<unsigned> &SplitVRegs) { 170218885Sdim // Record each interference and determine if all are spillable before mutating 171218885Sdim // either the union or live intervals. 172245431Sdim SmallVector<LiveInterval*, 8> Intfs; 173245431Sdim 174218885Sdim // Collect interferences assigned to any alias of the physical register. 175245431Sdim for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) { 176245431Sdim LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units); 177245431Sdim Q.collectInterferingVRegs(); 178245431Sdim if (Q.seenUnspillableVReg()) 179218885Sdim return false; 180245431Sdim for (unsigned i = Q.interferingVRegs().size(); i; --i) { 181245431Sdim LiveInterval *Intf = Q.interferingVRegs()[i - 1]; 182245431Sdim if (!Intf->isSpillable() || Intf->weight > VirtReg.weight) 183245431Sdim return false; 184245431Sdim Intfs.push_back(Intf); 185218885Sdim } 186218885Sdim } 187218885Sdim DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) << 188218885Sdim " interferences with " << VirtReg << "\n"); 189245431Sdim assert(!Intfs.empty() && "expected interference"); 190218885Sdim 191218885Sdim // Spill each interfering vreg allocated to PhysReg or an alias. 192245431Sdim for (unsigned i = 0, e = Intfs.size(); i != e; ++i) { 193245431Sdim LiveInterval &Spill = *Intfs[i]; 194245431Sdim 195245431Sdim // Skip duplicates. 196245431Sdim if (!VRM->hasPhys(Spill.reg)) 197245431Sdim continue; 198245431Sdim 199245431Sdim // Deallocate the interfering vreg by removing it from the union. 200245431Sdim // A LiveInterval instance may not be in a union during modification! 201245431Sdim Matrix->unassign(Spill); 202245431Sdim 203245431Sdim // Spill the extracted interval. 204245431Sdim LiveRangeEdit LRE(&Spill, SplitVRegs, *MF, *LIS, VRM); 205245431Sdim spiller().spill(LRE); 206245431Sdim } 207218885Sdim return true; 208218885Sdim} 209218885Sdim 210218885Sdim// Driver for the register assignment and splitting heuristics. 211218885Sdim// Manages iteration over the LiveIntervalUnions. 212218885Sdim// 213218885Sdim// This is a minimal implementation of register assignment and splitting that 214218885Sdim// spills whenever we run out of registers. 215218885Sdim// 216218885Sdim// selectOrSplit can only be called once per live virtual register. We then do a 217218885Sdim// single interference test for each register the correct class until we find an 218218885Sdim// available register. So, the number of interference tests in the worst case is 219218885Sdim// |vregs| * |machineregs|. And since the number of interference tests is 220218885Sdim// minimal, there is no value in caching them outside the scope of 221218885Sdim// selectOrSplit(). 222218885Sdimunsigned RABasic::selectOrSplit(LiveInterval &VirtReg, 223263509Sdim SmallVectorImpl<unsigned> &SplitVRegs) { 224218885Sdim // Populate a list of physical register spill candidates. 225218885Sdim SmallVector<unsigned, 8> PhysRegSpillCands; 226218885Sdim 227218885Sdim // Check for an available register in this class. 228245431Sdim AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo); 229245431Sdim while (unsigned PhysReg = Order.next()) { 230245431Sdim // Check for interference in PhysReg 231245431Sdim switch (Matrix->checkInterference(VirtReg, PhysReg)) { 232245431Sdim case LiveRegMatrix::IK_Free: 233245431Sdim // PhysReg is available, allocate it. 234245431Sdim return PhysReg; 235218885Sdim 236245431Sdim case LiveRegMatrix::IK_VirtReg: 237245431Sdim // Only virtual registers in the way, we may be able to spill them. 238245431Sdim PhysRegSpillCands.push_back(PhysReg); 239235633Sdim continue; 240235633Sdim 241245431Sdim default: 242245431Sdim // RegMask or RegUnit interference. 243245431Sdim continue; 244218885Sdim } 245245431Sdim } 246218885Sdim 247218885Sdim // Try to spill another interfering reg with less spill weight. 248218885Sdim for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(), 249245431Sdim PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) { 250245431Sdim if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) 251245431Sdim continue; 252218885Sdim 253245431Sdim assert(!Matrix->checkInterference(VirtReg, *PhysRegI) && 254218885Sdim "Interference after spill."); 255218885Sdim // Tell the caller to allocate to this newly freed physical register. 256218885Sdim return *PhysRegI; 257218885Sdim } 258223017Sdim 259218885Sdim // No other spill candidates were found, so spill the current VirtReg. 260218885Sdim DEBUG(dbgs() << "spilling: " << VirtReg << '\n'); 261223017Sdim if (!VirtReg.isSpillable()) 262223017Sdim return ~0u; 263245431Sdim LiveRangeEdit LRE(&VirtReg, SplitVRegs, *MF, *LIS, VRM); 264221345Sdim spiller().spill(LRE); 265218885Sdim 266218885Sdim // The live virtual register requesting allocation was spilled, so tell 267218885Sdim // the caller not to allocate anything during this round. 268218885Sdim return 0; 269218885Sdim} 270218885Sdim 271218885Sdimbool RABasic::runOnMachineFunction(MachineFunction &mf) { 272218885Sdim DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n" 273218885Sdim << "********** Function: " 274245431Sdim << mf.getName() << '\n'); 275218885Sdim 276218885Sdim MF = &mf; 277245431Sdim RegAllocBase::init(getAnalysis<VirtRegMap>(), 278245431Sdim getAnalysis<LiveIntervals>(), 279245431Sdim getAnalysis<LiveRegMatrix>()); 280263509Sdim 281263509Sdim calculateSpillWeightsAndHints(*LIS, *MF, 282263509Sdim getAnalysis<MachineLoopInfo>(), 283263509Sdim getAnalysis<MachineBlockFrequencyInfo>()); 284263509Sdim 285221345Sdim SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM)); 286218885Sdim 287218885Sdim allocatePhysRegs(); 288218885Sdim 289218885Sdim // Diagnostic output before rewriting 290218885Sdim DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n"); 291218885Sdim 292218885Sdim releaseMemory(); 293218885Sdim return true; 294218885Sdim} 295218885Sdim 296218885SdimFunctionPass* llvm::createBasicRegisterAllocator() 297218885Sdim{ 298218885Sdim return new RABasic(); 299218885Sdim} 300