DwarfWriter reading basic type information from llvm-gcc4 code.
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
index 0878e466d23473a7faf882212bc5d734dd9379ec..252fcfc2e83131bab476c506e8195b8635e4fe9a 100644 (file)
@@ -12,6 +12,9 @@
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "regalloc"
+#include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "PhysRegTracker.h"
+#include "VirtRegMap.h"
 #include "llvm/Function.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/SSARegMap.h"
 #include "llvm/Target/MRegisterInfo.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/Support/Debug.h"
+#include "llvm/ADT/EquivalenceClasses.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
-#include "LiveIntervalAnalysis.h"
-#include "PhysRegTracker.h"
-#include "VirtRegMap.h"
+#include "llvm/Support/Debug.h"
 #include <algorithm>
 #include <cmath>
+#include <iostream>
 #include <set>
 #include <queue>
+#include <memory>
 using namespace llvm;
 
 namespace {
@@ -44,10 +47,17 @@ namespace {
     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
     typedef std::vector<IntervalPtr> IntervalPtrs;
   private:
+    /// RelatedRegClasses - This structure is built the first time a function is
+    /// compiled, and keeps track of which register classes have registers that
+    /// belong to multiple classes or have aliases that are in other classes.
+    EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
+    std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
+
     MachineFunction* mf_;
     const TargetMachine* tm_;
     const MRegisterInfo* mri_;
     LiveIntervals* li_;
+    bool *PhysRegsUsed;
 
     /// handled_ - Intervals are added to the handled_ set in the order of their
     /// start value.  This is uses for backtracking.
@@ -118,6 +128,8 @@ namespace {
     /// stack slot. returns the stack slot
     int assignVirt2StackSlot(unsigned virtReg);
 
+    void ComputeRelatedRegClasses();
+
     template <typename ItTy>
     void printIntervals(const char* const str, ItTy i, ItTy e) const {
       if (str) std::cerr << str << " intervals:\n";
@@ -133,12 +145,55 @@ namespace {
   };
 }
 
+void RA::ComputeRelatedRegClasses() {
+  const MRegisterInfo &MRI = *mri_;
+  
+  // First pass, add all reg classes to the union, and determine at least one
+  // reg class that each register is in.
+  bool HasAliases = false;
+  for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
+       E = MRI.regclass_end(); RCI != E; ++RCI) {
+    RelatedRegClasses.insert(*RCI);
+    for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
+         I != E; ++I) {
+      HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
+      
+      const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
+      if (PRC) {
+        // Already processed this register.  Just make sure we know that
+        // multiple register classes share a register.
+        RelatedRegClasses.unionSets(PRC, *RCI);
+      } else {
+        PRC = *RCI;
+      }
+    }
+  }
+  
+  // Second pass, now that we know conservatively what register classes each reg
+  // belongs to, add info about aliases.  We don't need to do this for targets
+  // without register aliases.
+  if (HasAliases)
+    for (std::map<unsigned, const TargetRegisterClass*>::iterator
+         I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
+         I != E; ++I)
+      for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
+        RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
+}
+
 bool RA::runOnMachineFunction(MachineFunction &fn) {
   mf_ = &fn;
   tm_ = &fn.getTarget();
   mri_ = tm_->getRegisterInfo();
   li_ = &getAnalysis<LiveIntervals>();
 
+  // If this is the first function compiled, compute the related reg classes.
+  if (RelatedRegClasses.empty())
+    ComputeRelatedRegClasses();
+  
+  PhysRegsUsed = new bool[mri_->getNumRegs()];
+  std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
+  fn.setUsedPhysRegs(PhysRegsUsed);
+
   if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
   vrm_.reset(new VirtRegMap(*mf_));
   if (!spiller_.get()) spiller_.reset(createSpiller());
@@ -147,6 +202,7 @@ bool RA::runOnMachineFunction(MachineFunction &fn) {
 
   linearScan();
 
+  // Rewrite spill code and update the PhysRegsUsed set.
   spiller_->runOnMachineFunction(*mf_, *vrm_);
 
   vrm_.reset();  // Free the VirtRegMap
@@ -170,9 +226,10 @@ void RA::initIntervalSets()
          "interval sets should be empty on initialization");
 
   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
-    if (MRegisterInfo::isPhysicalRegister(i->second.reg))
+    if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
+      PhysRegsUsed[i->second.reg] = true;
       fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
-    else
+    else
       unhandled_.push(&i->second);
   }
 }
@@ -201,7 +258,7 @@ void RA::linearScan()
 
     assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
            "Can only allocate virtual registers!");
-    
+
     // Allocating a virtual register. try to find a free
     // physical register or spill an interval (possibly this one) in order to
     // assign it one.
@@ -259,7 +316,7 @@ void RA::processActiveIntervals(unsigned CurPoint)
       active_[i] = active_.back();
       active_.pop_back();
       --i; --e;
-      
+
     } else if (IntervalPos->start > CurPoint) {
       // Move inactive intervals to inactive list.
       DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
@@ -293,7 +350,7 @@ void RA::processInactiveIntervals(unsigned CurPoint)
     unsigned reg = Interval->reg;
 
     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
-    
+
     if (IntervalPos == Interval->end()) {       // remove expired intervals.
       DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
 
@@ -324,7 +381,7 @@ void RA::processInactiveIntervals(unsigned CurPoint)
 
 /// updateSpillWeights - updates the spill weights of the specifed physical
 /// register and its weight.
-static void updateSpillWeights(std::vector<float> &Weights, 
+static void updateSpillWeights(std::vector<float> &Weights,
                                unsigned reg, float weight,
                                const MRegisterInfo *MRI) {
   Weights[reg] += weight;
@@ -358,56 +415,99 @@ void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
 
   PhysRegTracker backupPrt = *prt_;
 
-  std::vector<float> SpillWeights;
-  SpillWeights.assign(mri_->getNumRegs(), 0.0);
-
+  std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
   unsigned StartPosition = cur->beginNumber();
-
-  // for each interval in active, update spill weights.
-  for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
-       i != e; ++i) {
-    unsigned reg = i->first->reg;
-    assert(MRegisterInfo::isVirtualRegister(reg) &&
-           "Can only allocate virtual registers!");
-    reg = vrm_->getPhys(reg);
-    updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
-  }
-
+  const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
+  const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
+      
   // for every interval in inactive we overlap with, mark the
-  // register as not free and update spill weights
+  // register as not free and update spill weights.
   for (IntervalPtrs::const_iterator i = inactive_.begin(),
          e = inactive_.end(); i != e; ++i) {
-    if (cur->overlapsFrom(*i->first, i->second-1)) {
-      unsigned reg = i->first->reg;
-      assert(MRegisterInfo::isVirtualRegister(reg) &&
-             "Can only allocate virtual registers!");
-      reg = vrm_->getPhys(reg);
-      prt_->addRegUse(reg);
-      updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
+    unsigned Reg = i->first->reg;
+    assert(MRegisterInfo::isVirtualRegister(Reg) &&
+           "Can only allocate virtual registers!");
+    const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
+    // If this is not in a related reg class to the register we're allocating, 
+    // don't check it.
+    if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
+        cur->overlapsFrom(*i->first, i->second-1)) {
+      Reg = vrm_->getPhys(Reg);
+      prt_->addRegUse(Reg);
+      SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
     }
   }
-
-  // For every interval in fixed we overlap with, mark the register as not free
-  // and update spill weights.
-  for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
-    IntervalPtr &IP = fixed_[i];
-    LiveInterval *I = IP.first;
-    if (I->endNumber() > StartPosition) {
-      LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
-      IP.second = II;
-      if (II != I->begin() && II->start > StartPosition)
-        --II;
-      if (cur->overlapsFrom(*I, II)) {
-        unsigned reg = I->reg;
-        prt_->addRegUse(reg);
-        updateSpillWeights(SpillWeights, reg, I->weight, mri_);
+  
+  // Speculatively check to see if we can get a register right now.  If not,
+  // we know we won't be able to by adding more constraints.  If so, we can
+  // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
+  // is very bad (it contains all callee clobbered registers for any functions
+  // with a call), so we want to avoid doing that if possible.
+  unsigned physReg = getFreePhysReg(cur);
+  if (physReg) {
+    // We got a register.  However, if it's in the fixed_ list, we might
+    // conflict with it.  Check to see if we conflict with it or any of its
+    // aliases.
+    std::set<unsigned> RegAliases;
+    for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
+      RegAliases.insert(*AS);
+    
+    bool ConflictsWithFixed = false;
+    for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
+      if (physReg == fixed_[i].first->reg ||
+          RegAliases.count(fixed_[i].first->reg)) {
+        // Okay, this reg is on the fixed list.  Check to see if we actually
+        // conflict.
+        IntervalPtr &IP = fixed_[i];
+        LiveInterval *I = IP.first;
+        if (I->endNumber() > StartPosition) {
+          LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
+          IP.second = II;
+          if (II != I->begin() && II->start > StartPosition)
+            --II;
+          if (cur->overlapsFrom(*I, II)) {
+            ConflictsWithFixed = true;
+            break;
+          }
+        }
       }
     }
-  }
+    
+    // Okay, the register picked by our speculative getFreePhysReg call turned
+    // out to be in use.  Actually add all of the conflicting fixed registers to
+    // prt so we can do an accurate query.
+    if (ConflictsWithFixed) {
+      // For every interval in fixed we overlap with, mark the register as not
+      // free and update spill weights.
+      for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
+        IntervalPtr &IP = fixed_[i];
+        LiveInterval *I = IP.first;
+
+        const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
+        if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
+            I->endNumber() > StartPosition) {
+          LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
+          IP.second = II;
+          if (II != I->begin() && II->start > StartPosition)
+            --II;
+          if (cur->overlapsFrom(*I, II)) {
+            unsigned reg = I->reg;
+            prt_->addRegUse(reg);
+            SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
+          }
+        }
+      }
 
-  unsigned physReg = getFreePhysReg(cur);
-  // restore the physical register tracker
+      // Using the newly updated prt_ object, which includes conflicts in the
+      // future, see if there are any registers available.
+      physReg = getFreePhysReg(cur);
+    }
+  }
+    
+  // Restore the physical register tracker, removing information about the
+  // future.
   *prt_ = backupPrt;
+  
   // if we find a free register, we are done: assign this virtual to
   // the free physical register and add this interval to the active
   // list.
@@ -421,19 +521,35 @@ void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
   }
   DEBUG(std::cerr << "no free registers\n");
 
+  // Compile the spill weights into an array that is better for scanning.
+  std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
+  for (std::vector<std::pair<unsigned, float> >::iterator
+       I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
+    updateSpillWeights(SpillWeights, I->first, I->second, mri_);
+  
+  // for each interval in active, update spill weights.
+  for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
+       i != e; ++i) {
+    unsigned reg = i->first->reg;
+    assert(MRegisterInfo::isVirtualRegister(reg) &&
+           "Can only allocate virtual registers!");
+    reg = vrm_->getPhys(reg);
+    updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
+  }
   DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
 
   float minWeight = float(HUGE_VAL);
   unsigned minReg = 0;
-  const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
-  for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_),
-       e = rc->allocation_order_end(*mf_); i != e; ++i) {
+  for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
+       e = RC->allocation_order_end(*mf_); i != e; ++i) {
     unsigned reg = *i;
     if (minWeight > SpillWeights[reg]) {
       minWeight = SpillWeights[reg];
       minReg = reg;
     }
   }
+// FIXME:  assert(minReg && "Didn't find any reg!");
   DEBUG(std::cerr << "\t\tregister with min weight: "
         << mri_->getName(minReg) << " (" << minWeight << ")\n");
 
@@ -535,26 +651,17 @@ void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
     IntervalPtrs::iterator it;
     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
       active_.erase(it);
-      if (MRegisterInfo::isPhysicalRegister(i->reg)) {
-        assert(0 && "daksjlfd");
-        prt_->delRegUse(i->reg);
+      assert(!MRegisterInfo::isPhysicalRegister(i->reg));
+      if (!spilled.count(i->reg))
         unhandled_.push(i);
-      } else {
-        if (!spilled.count(i->reg))
-          unhandled_.push(i);
-        prt_->delRegUse(vrm_->getPhys(i->reg));
-        vrm_->clearVirt(i->reg);
-      }
+      prt_->delRegUse(vrm_->getPhys(i->reg));
+      vrm_->clearVirt(i->reg);
     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
       inactive_.erase(it);
-      if (MRegisterInfo::isPhysicalRegister(i->reg)) {
-        assert(0 && "daksjlfd");
+      assert(!MRegisterInfo::isPhysicalRegister(i->reg));
+      if (!spilled.count(i->reg))
         unhandled_.push(i);
-      } else {
-        if (!spilled.count(i->reg))
-          unhandled_.push(i);
-        vrm_->clearVirt(i->reg);
-      }
+      vrm_->clearVirt(i->reg);
     } else {
       assert(MRegisterInfo::isVirtualRegister(i->reg) &&
              "Can only allocate virtual registers!");
@@ -578,11 +685,8 @@ void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
         HI->expiredAt(cur->beginNumber())) {
       DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
       active_.push_back(std::make_pair(HI, HI->begin()));
-      if (MRegisterInfo::isPhysicalRegister(HI->reg)) {
-        assert(0 &&"sdflkajsdf");
-        prt_->addRegUse(HI->reg);
-      } else
-        prt_->addRegUse(vrm_->getPhys(HI->reg));
+      assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
+      prt_->addRegUse(vrm_->getPhys(HI->reg));
     }
   }
 
@@ -593,29 +697,63 @@ void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
 
 /// getFreePhysReg - return a free physical register for this virtual register
 /// interval if we have one, otherwise return 0.
-unsigned RA::getFreePhysReg(LiveInterval* cur)
-{
+unsigned RA::getFreePhysReg(LiveInterval *cur) {
   std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
+  unsigned MaxInactiveCount = 0;
+  
+  const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
+  const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
        i != e; ++i) {
     unsigned reg = i->first->reg;
     assert(MRegisterInfo::isVirtualRegister(reg) &&
            "Can only allocate virtual registers!");
-    reg = vrm_->getPhys(reg);
-    ++inactiveCounts[reg];
+
+    // If this is not in a related reg class to the register we're allocating, 
+    // don't check it.
+    const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
+    if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
+      reg = vrm_->getPhys(reg);
+      ++inactiveCounts[reg];
+      MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
+    }
   }
 
   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
 
-  unsigned freeReg = 0;
-  for (TargetRegisterClass::iterator i = rc->allocation_order_begin(*mf_),
-       e = rc->allocation_order_end(*mf_); i != e; ++i) {
-    unsigned reg = *i;
-    if (prt_->isRegAvail(reg) &&
-        (!freeReg || inactiveCounts[freeReg] < inactiveCounts[reg]))
-        freeReg = reg;
+  unsigned FreeReg = 0;
+  unsigned FreeRegInactiveCount = 0;
+  
+  // Scan for the first available register.
+  TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
+  TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
+  for (; I != E; ++I)
+    if (prt_->isRegAvail(*I)) {
+      FreeReg = *I;
+      FreeRegInactiveCount = inactiveCounts[FreeReg];
+      break;
+    }
+  
+  // If there are no free regs, or if this reg has the max inactive count,
+  // return this register.
+  if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
+  
+  // Continue scanning the registers, looking for the one with the highest
+  // inactive count.  Alkis found that this reduced register pressure very
+  // slightly on X86 (in rev 1.94 of this file), though this should probably be
+  // reevaluated now.
+  for (; I != E; ++I) {
+    unsigned Reg = *I;
+    if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
+      FreeReg = Reg;
+      FreeRegInactiveCount = inactiveCounts[Reg];
+      if (FreeRegInactiveCount == MaxInactiveCount)
+        break;    // We found the one with the max inactive count.
+    }
   }
-  return freeReg;
+  
+  return FreeReg;
 }
 
 FunctionPass* llvm::createLinearScanRegisterAllocator() {