LLVM API Documentation

RegAllocBigBlock.cpp

Go to the documentation of this file.
00001 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the RABigBlock class
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 // This register allocator is derived from RegAllocLocal.cpp. Like it, this
00015 // allocator works on one basic block at a time, oblivious to others.
00016 // However, the algorithm used here is suited for long blocks of
00017 // instructions - registers are spilled by greedily choosing those holding
00018 // values that will not be needed for the longest amount of time. This works
00019 // particularly well for blocks with 10 or more times as many instructions
00020 // as machine registers, but can be used for general code.
00021 //
00022 //===----------------------------------------------------------------------===//
00023 //
00024 // TODO: - automagically invoke linearscan for (groups of) small BBs?
00025 //       - break ties when picking regs? (probably not worth it in a
00026 //         JIT context)
00027 //
00028 //===----------------------------------------------------------------------===//
00029 
00030 #define DEBUG_TYPE "regalloc"
00031 #include "llvm/BasicBlock.h"
00032 #include "llvm/CodeGen/Passes.h"
00033 #include "llvm/CodeGen/MachineFunctionPass.h"
00034 #include "llvm/CodeGen/MachineInstr.h"
00035 #include "llvm/CodeGen/MachineFrameInfo.h"
00036 #include "llvm/CodeGen/MachineRegisterInfo.h"
00037 #include "llvm/CodeGen/LiveVariables.h"
00038 #include "llvm/CodeGen/RegAllocRegistry.h"
00039 #include "llvm/Target/TargetInstrInfo.h"
00040 #include "llvm/Target/TargetMachine.h"
00041 #include "llvm/Support/CommandLine.h"
00042 #include "llvm/Support/Debug.h"
00043 #include "llvm/Support/Compiler.h"
00044 #include "llvm/ADT/IndexedMap.h"
00045 #include "llvm/ADT/DenseMap.h"
00046 #include "llvm/ADT/SmallVector.h"
00047 #include "llvm/ADT/Statistic.h"
00048 #include <algorithm>
00049 using namespace llvm;
00050 
00051 STATISTIC(NumStores, "Number of stores added");
00052 STATISTIC(NumLoads , "Number of loads added");
00053 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
00054 
00055 static RegisterRegAlloc
00056   bigBlockRegAlloc("bigblock", "Big-block register allocator",
00057                 createBigBlockRegisterAllocator);
00058 
00059 namespace {
00060 /// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
00061 /// keys.
00062   struct VRegKeyInfo {
00063     static inline unsigned getEmptyKey() { return -1U; }
00064     static inline unsigned getTombstoneKey() { return -2U; }
00065     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
00066     static unsigned getHashValue(const unsigned &Key) { return Key; }
00067   };
00068 
00069 
00070 /// This register allocator is derived from RegAllocLocal.cpp. Like it, this
00071 /// allocator works on one basic block at a time, oblivious to others.
00072 /// However, the algorithm used here is suited for long blocks of
00073 /// instructions - registers are spilled by greedily choosing those holding
00074 /// values that will not be needed for the longest amount of time. This works
00075 /// particularly well for blocks with 10 or more times as many instructions
00076 /// as machine registers, but can be used for general code.
00077 ///
00078 /// TODO: - automagically invoke linearscan for (groups of) small BBs?
00079 ///       - break ties when picking regs? (probably not worth it in a
00080 ///         JIT context)
00081 ///
00082   class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
00083   public:
00084     static char ID;
00085     RABigBlock() : MachineFunctionPass(&ID) {}
00086   private:
00087     /// TM - For getting at TargetMachine info 
00088     ///
00089     const TargetMachine *TM;
00090     
00091     /// MF - Our generic MachineFunction pointer
00092     ///
00093     MachineFunction *MF;
00094     
00095     /// RegInfo - For dealing with machine register info (aliases, folds
00096     /// etc)
00097     const TargetRegisterInfo *RegInfo;
00098 
00099     typedef SmallVector<unsigned, 2> VRegTimes;
00100 
00101     /// VRegReadTable - maps VRegs in a BB to the set of times they are read
00102     ///
00103     DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
00104 
00105     /// VRegReadIdx - keeps track of the "current time" in terms of
00106     /// positions in VRegReadTable
00107     DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
00108 
00109     /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
00110     /// values are spilled.
00111     IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
00112 
00113     /// Virt2PhysRegMap - This map contains entries for each virtual register
00114     /// that is currently available in a physical register.
00115     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
00116 
00117     /// PhysRegsUsed - This array is effectively a map, containing entries for
00118     /// each physical register that currently has a value (ie, it is in
00119     /// Virt2PhysRegMap).  The value mapped to is the virtual register
00120     /// corresponding to the physical register (the inverse of the
00121     /// Virt2PhysRegMap), or 0.  The value is set to 0 if this register is pinned
00122     /// because it is used by a future instruction, and to -2 if it is not
00123     /// allocatable.  If the entry for a physical register is -1, then the
00124     /// physical register is "not in the map".
00125     ///
00126     std::vector<int> PhysRegsUsed;
00127 
00128     /// VirtRegModified - This bitset contains information about which virtual
00129     /// registers need to be spilled back to memory when their registers are
00130     /// scavenged.  If a virtual register has simply been rematerialized, there
00131     /// is no reason to spill it to memory when we need the register back.
00132     ///
00133     std::vector<int> VirtRegModified;
00134 
00135     /// MBBLastInsnTime - the number of the the last instruction in MBB
00136     ///
00137     int MBBLastInsnTime;
00138 
00139     /// MBBCurTime - the number of the the instruction being currently processed
00140     ///
00141     int MBBCurTime;
00142 
00143     unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
00144       return Virt2PhysRegMap[VirtReg];
00145     }
00146 
00147     unsigned &getVirt2StackSlot(unsigned VirtReg) {
00148       return StackSlotForVirtReg[VirtReg];
00149     }
00150 
00151     /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
00152     ///
00153     void markVirtRegModified(unsigned Reg, bool Val = true) {
00154       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
00155       Reg -= TargetRegisterInfo::FirstVirtualRegister;
00156       if (VirtRegModified.size() <= Reg)
00157         VirtRegModified.resize(Reg+1);
00158       VirtRegModified[Reg] = Val;
00159     }
00160     
00161     /// isVirtRegModified - Lets us query the VirtRegModified bitset
00162     ///
00163     bool isVirtRegModified(unsigned Reg) const {
00164       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
00165       assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
00166              && "Illegal virtual register!");
00167       return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
00168     }
00169 
00170   public:
00171     /// getPassName - returns the BigBlock allocator's name
00172     ///
00173     virtual const char *getPassName() const {
00174       return "BigBlock Register Allocator";
00175     }
00176 
00177     /// getAnalaysisUsage - declares the required analyses
00178     ///
00179     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00180       AU.addRequiredID(PHIEliminationID);
00181       AU.addRequiredID(TwoAddressInstructionPassID);
00182       MachineFunctionPass::getAnalysisUsage(AU);
00183     }
00184 
00185   private:
00186     /// runOnMachineFunction - Register allocate the whole function
00187     ///
00188     bool runOnMachineFunction(MachineFunction &Fn);
00189 
00190     /// AllocateBasicBlock - Register allocate the specified basic block.
00191     ///
00192     void AllocateBasicBlock(MachineBasicBlock &MBB);
00193 
00194     /// FillVRegReadTable - Fill out the table of vreg read times given a BB
00195     ///
00196     void FillVRegReadTable(MachineBasicBlock &MBB);
00197     
00198     /// areRegsEqual - This method returns true if the specified registers are
00199     /// related to each other.  To do this, it checks to see if they are equal
00200     /// or if the first register is in the alias set of the second register.
00201     ///
00202     bool areRegsEqual(unsigned R1, unsigned R2) const {
00203       if (R1 == R2) return true;
00204       for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
00205            *AliasSet; ++AliasSet) {
00206         if (*AliasSet == R1) return true;
00207       }
00208       return false;
00209     }
00210 
00211     /// getStackSpaceFor - This returns the frame index of the specified virtual
00212     /// register on the stack, allocating space if necessary.
00213     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
00214 
00215     /// removePhysReg - This method marks the specified physical register as no
00216     /// longer being in use.
00217     ///
00218     void removePhysReg(unsigned PhysReg);
00219 
00220     /// spillVirtReg - This method spills the value specified by PhysReg into
00221     /// the virtual register slot specified by VirtReg.  It then updates the RA
00222     /// data structures to indicate the fact that PhysReg is now available.
00223     ///
00224     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
00225                       unsigned VirtReg, unsigned PhysReg);
00226 
00227     /// spillPhysReg - This method spills the specified physical register into
00228     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
00229     /// true, then the request is ignored if the physical register does not
00230     /// contain a virtual register.
00231     ///
00232     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
00233                       unsigned PhysReg, bool OnlyVirtRegs = false);
00234 
00235     /// assignVirtToPhysReg - This method updates local state so that we know
00236     /// that PhysReg is the proper container for VirtReg now.  The physical
00237     /// register must not be used for anything else when this is called.
00238     ///
00239     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
00240 
00241     /// isPhysRegAvailable - Return true if the specified physical register is
00242     /// free and available for use.  This also includes checking to see if
00243     /// aliased registers are all free...
00244     ///
00245     bool isPhysRegAvailable(unsigned PhysReg) const;
00246 
00247     /// getFreeReg - Look to see if there is a free register available in the
00248     /// specified register class.  If not, return 0.
00249     ///
00250     unsigned getFreeReg(const TargetRegisterClass *RC);
00251 
00252     /// chooseReg - Pick a physical register to hold the specified
00253     /// virtual register by choosing the one which will be read furthest
00254     /// in the future.
00255     ///
00256     unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
00257                     unsigned VirtReg);
00258 
00259     /// reloadVirtReg - This method transforms the specified specified virtual
00260     /// register use to refer to a physical register.  This method may do this
00261     /// in one of several ways: if the register is available in a physical
00262     /// register already, it uses that physical register.  If the value is not
00263     /// in a physical register, and if there are physical registers available,
00264     /// it loads it into a register.  If register pressure is high, and it is
00265     /// possible, it tries to fold the load of the virtual register into the
00266     /// instruction itself.  It avoids doing this if register pressure is low to
00267     /// improve the chance that subsequent instructions can use the reloaded
00268     /// value.  This method returns the modified instruction.
00269     ///
00270     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
00271                                 unsigned OpNum);
00272 
00273   };
00274   char RABigBlock::ID = 0;
00275 }
00276 
00277 /// getStackSpaceFor - This allocates space for the specified virtual register
00278 /// to be held on the stack.
00279 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
00280   // Find the location Reg would belong...
00281   int FrameIdx = getVirt2StackSlot(VirtReg);
00282 
00283   if (FrameIdx)
00284     return FrameIdx - 1;          // Already has space allocated?
00285 
00286   // Allocate a new stack object for this spill location...
00287   FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
00288                                                        RC->getAlignment());
00289 
00290   // Assign the slot...
00291   getVirt2StackSlot(VirtReg) = FrameIdx + 1;
00292   return FrameIdx;
00293 }
00294 
00295 
00296 /// removePhysReg - This method marks the specified physical register as no
00297 /// longer being in use.
00298 ///
00299 void RABigBlock::removePhysReg(unsigned PhysReg) {
00300   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
00301 }
00302 
00303 
00304 /// spillVirtReg - This method spills the value specified by PhysReg into the
00305 /// virtual register slot specified by VirtReg.  It then updates the RA data
00306 /// structures to indicate the fact that PhysReg is now available.
00307 ///
00308 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
00309                            MachineBasicBlock::iterator I,
00310                            unsigned VirtReg, unsigned PhysReg) {
00311   assert(VirtReg && "Spilling a physical register is illegal!"
00312          " Must not have appropriate kill for the register or use exists beyond"
00313          " the intended one.");
00314   DOUT << "  Spilling register " << RegInfo->getName(PhysReg)
00315        << " containing %reg" << VirtReg;
00316   
00317   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
00318   
00319   if (!isVirtRegModified(VirtReg))
00320     DOUT << " which has not been modified, so no store necessary!";
00321 
00322   // Otherwise, there is a virtual register corresponding to this physical
00323   // register.  We only need to spill it into its stack slot if it has been
00324   // modified.
00325   if (isVirtRegModified(VirtReg)) {
00326     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
00327     int FrameIndex = getStackSpaceFor(VirtReg, RC);
00328     DOUT << " to stack slot #" << FrameIndex;
00329     TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
00330     ++NumStores;   // Update statistics
00331   }
00332 
00333   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
00334 
00335   DOUT << "\n";
00336   removePhysReg(PhysReg);
00337 }
00338 
00339 
00340 /// spillPhysReg - This method spills the specified physical register into the
00341 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
00342 /// then the request is ignored if the physical register does not contain a
00343 /// virtual register.
00344 ///
00345 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
00346                            unsigned PhysReg, bool OnlyVirtRegs) {
00347   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
00348     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
00349     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
00350       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
00351   } else {
00352     // If the selected register aliases any other registers, we must make
00353     // sure that one of the aliases isn't alive.
00354     for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
00355          *AliasSet; ++AliasSet)
00356       if (PhysRegsUsed[*AliasSet] != -1 &&     // Spill aliased register.
00357           PhysRegsUsed[*AliasSet] != -2)       // If allocatable.
00358         if (PhysRegsUsed[*AliasSet])
00359           spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
00360   }
00361 }
00362 
00363 
00364 /// assignVirtToPhysReg - This method updates local state so that we know
00365 /// that PhysReg is the proper container for VirtReg now.  The physical
00366 /// register must not be used for anything else when this is called.
00367 ///
00368 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
00369   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
00370   // Update information to note the fact that this register was just used, and
00371   // it holds VirtReg.
00372   PhysRegsUsed[PhysReg] = VirtReg;
00373   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
00374 }
00375 
00376 
00377 /// isPhysRegAvailable - Return true if the specified physical register is free
00378 /// and available for use.  This also includes checking to see if aliased
00379 /// registers are all free...
00380 ///
00381 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
00382   if (PhysRegsUsed[PhysReg] != -1) return false;
00383 
00384   // If the selected register aliases any other allocated registers, it is
00385   // not free!
00386   for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
00387        *AliasSet; ++AliasSet)
00388     if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
00389       return false;                    // Can't use this reg then.
00390   return true;
00391 }
00392 
00393   
00394 /// getFreeReg - Look to see if there is a free register available in the
00395 /// specified register class.  If not, return 0.
00396 ///
00397 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
00398   // Get iterators defining the range of registers that are valid to allocate in
00399   // this class, which also specifies the preferred allocation order.
00400   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
00401   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
00402 
00403   for (; RI != RE; ++RI)
00404     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
00405       assert(*RI != 0 && "Cannot use register!");
00406       return *RI; // Found an unused register!
00407     }
00408   return 0;
00409 }
00410 
00411 
00412 /// chooseReg - Pick a physical register to hold the specified
00413 /// virtual register by choosing the one whose value will be read
00414 /// furthest in the future.
00415 ///
00416 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
00417                          unsigned VirtReg) {
00418   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
00419   // First check to see if we have a free register of the requested type...
00420   unsigned PhysReg = getFreeReg(RC);
00421 
00422   // If we didn't find an unused register, find the one which will be
00423   // read at the most distant point in time.
00424   if (PhysReg == 0) {
00425     unsigned delay=0, longest_delay=0;
00426     VRegTimes* ReadTimes;
00427 
00428     unsigned curTime = MBBCurTime;
00429 
00430     // for all physical regs in the RC,
00431     for(TargetRegisterClass::iterator pReg = RC->begin(); 
00432                                       pReg != RC->end();  ++pReg) {
00433       // how long until they're read?
00434       if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
00435         ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
00436         if(ReadTimes && !ReadTimes->empty()) {
00437             unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
00438             while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
00439                 ++pt;
00440             }
00441 
00442             if(pt < ReadTimes->size())
00443                 delay = (*ReadTimes)[pt] - curTime;
00444             else
00445                 delay = MBBLastInsnTime + 1 - curTime;
00446         } else {
00447             // This register is only defined, but never
00448             // read in this MBB. Therefore the next read
00449             // happens after the end of this MBB
00450             delay = MBBLastInsnTime + 1 - curTime;
00451         }
00452 
00453         
00454         if(delay > longest_delay) {
00455           longest_delay = delay;
00456           PhysReg = *pReg;
00457         }
00458       }
00459     }
00460 
00461     if(PhysReg == 0) { // ok, now we're desperate. We couldn't choose
00462                        // a register to spill by looking through the
00463                        // read timetable, so now we just spill the
00464                        // first allocatable register we find.
00465                        
00466       // for all physical regs in the RC,
00467       for(TargetRegisterClass::iterator pReg = RC->begin(); 
00468                                         pReg != RC->end();  ++pReg) {
00469         // if we find a register we can spill
00470         if(PhysRegsUsed[*pReg]>=-1)
00471           PhysReg = *pReg; // choose it to be spilled
00472       }
00473     }
00474     
00475     assert(PhysReg && "couldn't choose a register to spill :( ");
00476     // TODO: assert that RC->contains(PhysReg) / handle aliased registers?
00477 
00478     // since we needed to look in the table we need to spill this register.
00479     spillPhysReg(MBB, I, PhysReg);
00480   }
00481 
00482   // assign the vreg to our chosen physical register
00483   assignVirtToPhysReg(VirtReg, PhysReg);
00484   return PhysReg; // and return it
00485 }
00486 
00487 
00488 /// reloadVirtReg - This method transforms an instruction with a virtual
00489 /// register use to one that references a physical register. It does this as
00490 /// follows:
00491 ///
00492 ///   1) If the register is already in a physical register, it uses it.
00493 ///   2) Otherwise, if there is a free physical register, it uses that.
00494 ///   3) Otherwise, it calls chooseReg() to get the physical register
00495 ///      holding the most distantly needed value, generating a spill in
00496 ///      the process.
00497 ///
00498 /// This method returns the modified instruction.
00499 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
00500                                      unsigned OpNum) {
00501   unsigned VirtReg = MI->getOperand(OpNum).getReg();
00502   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
00503 
00504   // If the virtual register is already available in a physical register,
00505   // just update the instruction and return.
00506   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
00507     MI->getOperand(OpNum).setReg(PR);
00508     return MI;
00509   }
00510 
00511   // Otherwise, if we have free physical registers available to hold the
00512   // value, use them.
00513   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
00514   unsigned PhysReg = getFreeReg(RC);
00515   int FrameIndex = getStackSpaceFor(VirtReg, RC);
00516 
00517   if (PhysReg) {   // we have a free register, so use it.
00518     assignVirtToPhysReg(VirtReg, PhysReg);
00519   } else {  // no free registers available.
00520     // try to fold the spill into the instruction
00521     SmallVector<unsigned, 2> Ops;
00522     Ops.push_back(OpNum);
00523     if(MachineInstr* FMI = TII->foldMemoryOperand(*MF, MI, Ops, FrameIndex)) {
00524       ++NumFolded;
00525       FMI->copyKillDeadInfo(MI);
00526       return MBB.insert(MBB.erase(MI), FMI);
00527     }
00528     
00529     // determine which of the physical registers we'll kill off, since we
00530     // couldn't fold.
00531     PhysReg = chooseReg(MBB, MI, VirtReg);
00532   }
00533 
00534   // this virtual register is now unmodified (since we just reloaded it)
00535   markVirtRegModified(VirtReg, false);
00536 
00537   DOUT << "  Reloading %reg" << VirtReg << " into "
00538        << RegInfo->getName(PhysReg) << "\n";
00539 
00540   // Add move instruction(s)
00541   TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
00542   ++NumLoads;    // Update statistics
00543 
00544   MF->getRegInfo().setPhysRegUsed(PhysReg);
00545   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
00546   return MI;
00547 }
00548 
00549 /// Fill out the vreg read timetable. Since ReadTime increases
00550 /// monotonically, the individual readtime sets will be sorted
00551 /// in ascending order.
00552 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
00553   // loop over each instruction
00554   MachineBasicBlock::iterator MII;
00555   unsigned ReadTime;
00556   
00557   for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
00558     MachineInstr *MI = MII;
00559     
00560     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
00561       MachineOperand& MO = MI->getOperand(i);
00562       // look for vreg reads..
00563       if (MO.isReg() && !MO.isDef() && MO.getReg() &&
00564           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
00565           // ..and add them to the read table.
00566           VRegTimes* &Times = VRegReadTable[MO.getReg()];
00567           if(!VRegReadTable[MO.getReg()]) {
00568               Times = new VRegTimes;
00569               VRegReadIdx[MO.getReg()] = 0;
00570           }
00571         Times->push_back(ReadTime);
00572       }
00573     }
00574 
00575   }  
00576 
00577   MBBLastInsnTime = ReadTime;
00578 
00579   for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
00580       Reads != VRegReadTable.end(); ++Reads) {
00581       if(Reads->second) {
00582           DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
00583       }
00584   }
00585 }
00586 
00587 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
00588 /// read/mod/write register, i.e. update partial register.
00589 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
00590   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00591     MachineOperand& MO = MI->getOperand(i);
00592     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
00593         MO.isDef() && !MO.isDead())
00594       return true;
00595   }
00596   return false;
00597 }
00598 
00599 /// isReadModWriteImplicitDef - True if this is an implicit def for a
00600 /// read/mod/write register, i.e. update partial register.
00601 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
00602   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00603     MachineOperand& MO = MI->getOperand(i);
00604     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
00605         !MO.isDef() && MO.isKill())
00606       return true;
00607   }
00608   return false;
00609 }
00610 
00611 
00612 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
00613   // loop over each instruction
00614   MachineBasicBlock::iterator MII = MBB.begin();
00615   const TargetInstrInfo &TII = *TM->getInstrInfo();
00616   
00617   DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
00618         if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
00619 
00620   // If this is the first basic block in the machine function, add live-in
00621   // registers as active.
00622   if (&MBB == &*MF->begin()) {
00623     for (MachineRegisterInfo::livein_iterator
00624          I = MF->getRegInfo().livein_begin(),
00625          E = MF->getRegInfo().livein_end(); I != E; ++I) {
00626       unsigned Reg = I->first;
00627       MF->getRegInfo().setPhysRegUsed(Reg);
00628       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
00629       for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
00630            *AliasSet; ++AliasSet) {
00631         if (PhysRegsUsed[*AliasSet] != -2) {
00632           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
00633           MF->getRegInfo().setPhysRegUsed(*AliasSet);
00634         }
00635       }
00636     }    
00637   }
00638   
00639   // Otherwise, sequentially allocate each instruction in the MBB.
00640   MBBCurTime = -1;
00641   while (MII != MBB.end()) {
00642     MachineInstr *MI = MII++;
00643     MBBCurTime++;
00644     const TargetInstrDesc &TID = MI->getDesc();
00645     DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
00646           DOUT << "  Regs have values: ";
00647           for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
00648             if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
00649                DOUT << "[" << RegInfo->getName(i)
00650                     << ",%reg" << PhysRegsUsed[i] << "] ";
00651           DOUT << "\n");
00652 
00653     SmallVector<unsigned, 8> Kills;
00654     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00655       MachineOperand& MO = MI->getOperand(i);
00656       if (MO.isReg() && MO.isKill()) {
00657         if (!MO.isImplicit())
00658           Kills.push_back(MO.getReg());
00659         else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
00660           // These are extra physical register kills when a sub-register
00661           // is defined (def of a sub-register is a read/mod/write of the
00662           // larger registers). Ignore.
00663           Kills.push_back(MO.getReg());
00664       }
00665     }
00666 
00667     // Get the used operands into registers.  This has the potential to spill
00668     // incoming values if we are out of registers.  Note that we completely
00669     // ignore physical register uses here.  We assume that if an explicit
00670     // physical register is referenced by the instruction, that it is guaranteed
00671     // to be live-in, or the input is badly hosed.
00672     //
00673     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
00674       MachineOperand& MO = MI->getOperand(i);
00675       // here we are looking for only used operands (never def&use)
00676       if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
00677           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
00678         MI = reloadVirtReg(MBB, MI, i);
00679     }
00680 
00681     // If this instruction is the last user of this register, kill the
00682     // value, freeing the register being used, so it doesn't need to be
00683     // spilled to memory.
00684     //
00685     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
00686       unsigned VirtReg = Kills[i];
00687       unsigned PhysReg = VirtReg;
00688       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
00689         // If the virtual register was never materialized into a register, it
00690         // might not be in the map, but it won't hurt to zero it out anyway.
00691         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
00692         PhysReg = PhysRegSlot;
00693         PhysRegSlot = 0;
00694       } else if (PhysRegsUsed[PhysReg] == -2) {
00695         // Unallocatable register dead, ignore.
00696         continue;
00697       } else {
00698         assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
00699                "Silently clearing a virtual register?");
00700       }
00701 
00702       if (PhysReg) {
00703         DOUT << "  Last use of " << RegInfo->getName(PhysReg)
00704              << "[%reg" << VirtReg <<"], removing it from live set\n";
00705         removePhysReg(PhysReg);
00706         for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
00707              *AliasSet; ++AliasSet) {
00708           if (PhysRegsUsed[*AliasSet] != -2) {
00709             DOUT  << "  Last use of "
00710                   << RegInfo->getName(*AliasSet)
00711                   << "[%reg" << VirtReg <<"], removing it from live set\n";
00712             removePhysReg(*AliasSet);
00713           }
00714         }
00715       }
00716     }
00717 
00718     // Loop over all of the operands of the instruction, spilling registers that
00719     // are defined, and marking explicit destinations in the PhysRegsUsed map.
00720     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00721       MachineOperand& MO = MI->getOperand(i);
00722       if (MO.isReg() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
00723           TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
00724         unsigned Reg = MO.getReg();
00725         if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
00726         // These are extra physical register defs when a sub-register
00727         // is defined (def of a sub-register is a read/mod/write of the
00728         // larger registers). Ignore.
00729         if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
00730 
00731         MF->getRegInfo().setPhysRegUsed(Reg);
00732         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
00733         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
00734         for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
00735              *AliasSet; ++AliasSet) {
00736           if (PhysRegsUsed[*AliasSet] != -2) {
00737             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
00738             MF->getRegInfo().setPhysRegUsed(*AliasSet);
00739           }
00740         }
00741       }
00742     }
00743 
00744     // Loop over the implicit defs, spilling them as well.
00745     if (TID.getImplicitDefs()) {
00746       for (const unsigned *ImplicitDefs = TID.getImplicitDefs();
00747            *ImplicitDefs; ++ImplicitDefs) {
00748         unsigned Reg = *ImplicitDefs;
00749         if (PhysRegsUsed[Reg] != -2) {
00750           spillPhysReg(MBB, MI, Reg, true);
00751           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
00752         }
00753         MF->getRegInfo().setPhysRegUsed(Reg);
00754         for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
00755              *AliasSet; ++AliasSet) {
00756           if (PhysRegsUsed[*AliasSet] != -2) {
00757             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
00758             MF->getRegInfo().setPhysRegUsed(*AliasSet);
00759           }
00760         }
00761       }
00762     }
00763 
00764     SmallVector<unsigned, 8> DeadDefs;
00765     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00766       MachineOperand& MO = MI->getOperand(i);
00767       if (MO.isReg() && MO.isDead())
00768         DeadDefs.push_back(MO.getReg());
00769     }
00770 
00771     // Okay, we have allocated all of the source operands and spilled any values
00772     // that would be destroyed by defs of this instruction.  Loop over the
00773     // explicit defs and assign them to a register, spilling incoming values if
00774     // we need to scavenge a register.
00775     //
00776     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00777       MachineOperand& MO = MI->getOperand(i);
00778       if (MO.isReg() && MO.isDef() && MO.getReg() &&
00779           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
00780         unsigned DestVirtReg = MO.getReg();
00781         unsigned DestPhysReg;
00782 
00783         // If DestVirtReg already has a value, use it.
00784         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
00785           DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
00786         MF->getRegInfo().setPhysRegUsed(DestPhysReg);
00787         markVirtRegModified(DestVirtReg);
00788         MI->getOperand(i).setReg(DestPhysReg);  // Assign the output register
00789       }
00790     }
00791 
00792     // If this instruction defines any registers that are immediately dead,
00793     // kill them now.
00794     //
00795     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
00796       unsigned VirtReg = DeadDefs[i];
00797       unsigned PhysReg = VirtReg;
00798       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
00799         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
00800         PhysReg = PhysRegSlot;
00801         assert(PhysReg != 0);
00802         PhysRegSlot = 0;
00803       } else if (PhysRegsUsed[PhysReg] == -2) {
00804         // Unallocatable register dead, ignore.
00805         continue;
00806       }
00807 
00808       if (PhysReg) {
00809         DOUT  << "  Register " << RegInfo->getName(PhysReg)
00810               << " [%reg" << VirtReg
00811               << "] is never used, removing it from live set\n";
00812         removePhysReg(PhysReg);
00813         for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
00814              *AliasSet; ++AliasSet) {
00815           if (PhysRegsUsed[*AliasSet] != -2) {
00816             DOUT  << "  Register " << RegInfo->getName(*AliasSet)
00817                   << " [%reg" << *AliasSet
00818                   << "] is never used, removing it from live set\n";
00819             removePhysReg(*AliasSet);
00820           }
00821         }
00822       }
00823     }
00824     
00825     // Finally, if this is a noop copy instruction, zap it.
00826     unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
00827     if (TII.isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
00828         SrcReg == DstReg)
00829       MBB.erase(MI);
00830   }
00831 
00832   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
00833 
00834   // Spill all physical registers holding virtual registers now.
00835   for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
00836     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
00837       if (unsigned VirtReg = PhysRegsUsed[i])
00838         spillVirtReg(MBB, MI, VirtReg, i);
00839       else
00840         removePhysReg(i);
00841     }
00842 }
00843 
00844 /// runOnMachineFunction - Register allocate the whole function
00845 ///
00846 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
00847   DOUT << "Machine Function " << "\n";
00848   MF = &Fn;
00849   TM = &Fn.getTarget();
00850   RegInfo = TM->getRegisterInfo();
00851 
00852   PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
00853   
00854   // At various places we want to efficiently check to see whether a register
00855   // is allocatable.  To handle this, we mark all unallocatable registers as
00856   // being pinned down, permanently.
00857   {
00858     BitVector Allocable = RegInfo->getAllocatableSet(Fn);
00859     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
00860       if (!Allocable[i])
00861         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
00862   }
00863 
00864   // initialize the virtual->physical register map to have a 'null'
00865   // mapping for all virtual registers
00866   Virt2PhysRegMap.grow(MF->getRegInfo().getLastVirtReg());
00867   StackSlotForVirtReg.grow(MF->getRegInfo().getLastVirtReg());
00868   VirtRegModified.resize(MF->getRegInfo().getLastVirtReg() - 
00869                          TargetRegisterInfo::FirstVirtualRegister + 1, 0);
00870 
00871   // Loop over all of the basic blocks, eliminating virtual register references
00872   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
00873        MBB != MBBe; ++MBB) {
00874     // fill out the read timetable 
00875     FillVRegReadTable(*MBB);
00876     // use it to allocate the BB
00877     AllocateBasicBlock(*MBB);
00878     // clear it
00879     VRegReadTable.clear();
00880   }
00881   
00882   StackSlotForVirtReg.clear();
00883   PhysRegsUsed.clear();
00884   VirtRegModified.clear();
00885   Virt2PhysRegMap.clear();
00886   return true;
00887 }
00888 
00889 FunctionPass *llvm::createBigBlockRegisterAllocator() {
00890   return new RABigBlock();
00891 }
00892