Home | History | Annotate | Download | only in CodeGen
      1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This register allocator allocates registers to a basic block at a time,
     11 // attempting to keep values in registers and reusing registers as appropriate.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "regalloc"
     16 #include "llvm/CodeGen/Passes.h"
     17 #include "llvm/ADT/DenseMap.h"
     18 #include "llvm/ADT/IndexedMap.h"
     19 #include "llvm/ADT/STLExtras.h"
     20 #include "llvm/ADT/SmallSet.h"
     21 #include "llvm/ADT/SmallVector.h"
     22 #include "llvm/ADT/SparseSet.h"
     23 #include "llvm/ADT/Statistic.h"
     24 #include "llvm/CodeGen/MachineFrameInfo.h"
     25 #include "llvm/CodeGen/MachineFunctionPass.h"
     26 #include "llvm/CodeGen/MachineInstr.h"
     27 #include "llvm/CodeGen/MachineInstrBuilder.h"
     28 #include "llvm/CodeGen/MachineRegisterInfo.h"
     29 #include "llvm/CodeGen/RegAllocRegistry.h"
     30 #include "llvm/CodeGen/RegisterClassInfo.h"
     31 #include "llvm/IR/BasicBlock.h"
     32 #include "llvm/Support/CommandLine.h"
     33 #include "llvm/Support/Debug.h"
     34 #include "llvm/Support/ErrorHandling.h"
     35 #include "llvm/Support/raw_ostream.h"
     36 #include "llvm/Target/TargetInstrInfo.h"
     37 #include "llvm/Target/TargetMachine.h"
     38 #include <algorithm>
     39 using namespace llvm;
     40 
     41 STATISTIC(NumStores, "Number of stores added");
     42 STATISTIC(NumLoads , "Number of loads added");
     43 STATISTIC(NumCopies, "Number of copies coalesced");
     44 
     45 static RegisterRegAlloc
     46   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
     47 
     48 namespace {
     49   class RAFast : public MachineFunctionPass {
     50   public:
     51     static char ID;
     52     RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
     53                isBulkSpilling(false) {}
     54   private:
     55     const TargetMachine *TM;
     56     MachineFunction *MF;
     57     MachineRegisterInfo *MRI;
     58     const TargetRegisterInfo *TRI;
     59     const TargetInstrInfo *TII;
     60     RegisterClassInfo RegClassInfo;
     61 
     62     // Basic block currently being allocated.
     63     MachineBasicBlock *MBB;
     64 
     65     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
     66     // values are spilled.
     67     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
     68 
     69     // Everything we know about a live virtual register.
     70     struct LiveReg {
     71       MachineInstr *LastUse;    // Last instr to use reg.
     72       unsigned VirtReg;         // Virtual register number.
     73       unsigned PhysReg;         // Currently held here.
     74       unsigned short LastOpNum; // OpNum on LastUse.
     75       bool Dirty;               // Register needs spill.
     76 
     77       explicit LiveReg(unsigned v)
     78         : LastUse(0), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false) {}
     79 
     80       unsigned getSparseSetIndex() const {
     81         return TargetRegisterInfo::virtReg2Index(VirtReg);
     82       }
     83     };
     84 
     85     typedef SparseSet<LiveReg> LiveRegMap;
     86 
     87     // LiveVirtRegs - This map contains entries for each virtual register
     88     // that is currently available in a physical register.
     89     LiveRegMap LiveVirtRegs;
     90 
     91     DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
     92 
     93     // RegState - Track the state of a physical register.
     94     enum RegState {
     95       // A disabled register is not available for allocation, but an alias may
     96       // be in use. A register can only be moved out of the disabled state if
     97       // all aliases are disabled.
     98       regDisabled,
     99 
    100       // A free register is not currently in use and can be allocated
    101       // immediately without checking aliases.
    102       regFree,
    103 
    104       // A reserved register has been assigned explicitly (e.g., setting up a
    105       // call parameter), and it remains reserved until it is used.
    106       regReserved
    107 
    108       // A register state may also be a virtual register number, indication that
    109       // the physical register is currently allocated to a virtual register. In
    110       // that case, LiveVirtRegs contains the inverse mapping.
    111     };
    112 
    113     // PhysRegState - One of the RegState enums, or a virtreg.
    114     std::vector<unsigned> PhysRegState;
    115 
    116     // Set of register units.
    117     typedef SparseSet<unsigned> UsedInInstrSet;
    118 
    119     // Set of register units that are used in the current instruction, and so
    120     // cannot be allocated.
    121     UsedInInstrSet UsedInInstr;
    122 
    123     // Mark a physreg as used in this instruction.
    124     void markRegUsedInInstr(unsigned PhysReg) {
    125       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
    126         UsedInInstr.insert(*Units);
    127     }
    128 
    129     // Check if a physreg or any of its aliases are used in this instruction.
    130     bool isRegUsedInInstr(unsigned PhysReg) const {
    131       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
    132         if (UsedInInstr.count(*Units))
    133           return true;
    134       return false;
    135     }
    136 
    137     // SkippedInstrs - Descriptors of instructions whose clobber list was
    138     // ignored because all registers were spilled. It is still necessary to
    139     // mark all the clobbered registers as used by the function.
    140     SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
    141 
    142     // isBulkSpilling - This flag is set when LiveRegMap will be cleared
    143     // completely after spilling all live registers. LiveRegMap entries should
    144     // not be erased.
    145     bool isBulkSpilling;
    146 
    147     enum {
    148       spillClean = 1,
    149       spillDirty = 100,
    150       spillImpossible = ~0u
    151     };
    152   public:
    153     virtual const char *getPassName() const {
    154       return "Fast Register Allocator";
    155     }
    156 
    157     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    158       AU.setPreservesCFG();
    159       MachineFunctionPass::getAnalysisUsage(AU);
    160     }
    161 
    162   private:
    163     bool runOnMachineFunction(MachineFunction &Fn);
    164     void AllocateBasicBlock();
    165     void handleThroughOperands(MachineInstr *MI,
    166                                SmallVectorImpl<unsigned> &VirtDead);
    167     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
    168     bool isLastUseOfLocalReg(MachineOperand&);
    169 
    170     void addKillFlag(const LiveReg&);
    171     void killVirtReg(LiveRegMap::iterator);
    172     void killVirtReg(unsigned VirtReg);
    173     void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
    174     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
    175 
    176     void usePhysReg(MachineOperand&);
    177     void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
    178     unsigned calcSpillCost(unsigned PhysReg) const;
    179     void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
    180     LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
    181       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
    182     }
    183     LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
    184       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
    185     }
    186     LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
    187     LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
    188                                       unsigned Hint);
    189     LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
    190                                        unsigned VirtReg, unsigned Hint);
    191     LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
    192                                        unsigned VirtReg, unsigned Hint);
    193     void spillAll(MachineBasicBlock::iterator MI);
    194     bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
    195   };
    196   char RAFast::ID = 0;
    197 }
    198 
    199 /// getStackSpaceFor - This allocates space for the specified virtual register
    200 /// to be held on the stack.
    201 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
    202   // Find the location Reg would belong...
    203   int SS = StackSlotForVirtReg[VirtReg];
    204   if (SS != -1)
    205     return SS;          // Already has space allocated?
    206 
    207   // Allocate a new stack object for this spill location...
    208   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
    209                                                             RC->getAlignment());
    210 
    211   // Assign the slot.
    212   StackSlotForVirtReg[VirtReg] = FrameIdx;
    213   return FrameIdx;
    214 }
    215 
    216 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
    217 /// its virtual register, and it is guaranteed to be a block-local register.
    218 ///
    219 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
    220   // If the register has ever been spilled or reloaded, we conservatively assume
    221   // it is a global register used in multiple blocks.
    222   if (StackSlotForVirtReg[MO.getReg()] != -1)
    223     return false;
    224 
    225   // Check that the use/def chain has exactly one operand - MO.
    226   MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
    227   if (&I.getOperand() != &MO)
    228     return false;
    229   return ++I == MRI->reg_nodbg_end();
    230 }
    231 
    232 /// addKillFlag - Set kill flags on last use of a virtual register.
    233 void RAFast::addKillFlag(const LiveReg &LR) {
    234   if (!LR.LastUse) return;
    235   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
    236   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
    237     if (MO.getReg() == LR.PhysReg)
    238       MO.setIsKill();
    239     else
    240       LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
    241   }
    242 }
    243 
    244 /// killVirtReg - Mark virtreg as no longer available.
    245 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
    246   addKillFlag(*LRI);
    247   assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
    248          "Broken RegState mapping");
    249   PhysRegState[LRI->PhysReg] = regFree;
    250   // Erase from LiveVirtRegs unless we're spilling in bulk.
    251   if (!isBulkSpilling)
    252     LiveVirtRegs.erase(LRI);
    253 }
    254 
    255 /// killVirtReg - Mark virtreg as no longer available.
    256 void RAFast::killVirtReg(unsigned VirtReg) {
    257   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
    258          "killVirtReg needs a virtual register");
    259   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
    260   if (LRI != LiveVirtRegs.end())
    261     killVirtReg(LRI);
    262 }
    263 
    264 /// spillVirtReg - This method spills the value specified by VirtReg into the
    265 /// corresponding stack slot if needed.
    266 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
    267   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
    268          "Spilling a physical register is illegal!");
    269   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
    270   assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
    271   spillVirtReg(MI, LRI);
    272 }
    273 
    274 /// spillVirtReg - Do the actual work of spilling.
    275 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
    276                           LiveRegMap::iterator LRI) {
    277   LiveReg &LR = *LRI;
    278   assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
    279 
    280   if (LR.Dirty) {
    281     // If this physreg is used by the instruction, we want to kill it on the
    282     // instruction, not on the spill.
    283     bool SpillKill = LR.LastUse != MI;
    284     LR.Dirty = false;
    285     DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
    286                  << " in " << PrintReg(LR.PhysReg, TRI));
    287     const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
    288     int FI = getStackSpaceFor(LRI->VirtReg, RC);
    289     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
    290     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
    291     ++NumStores;   // Update statistics
    292 
    293     // If this register is used by DBG_VALUE then insert new DBG_VALUE to
    294     // identify spilled location as the place to find corresponding variable's
    295     // value.
    296     SmallVector<MachineInstr *, 4> &LRIDbgValues =
    297       LiveDbgValueMap[LRI->VirtReg];
    298     for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
    299       MachineInstr *DBG = LRIDbgValues[li];
    300       const MDNode *MDPtr =
    301         DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
    302       int64_t Offset = 0;
    303       if (DBG->getOperand(1).isImm())
    304         Offset = DBG->getOperand(1).getImm();
    305       DebugLoc DL;
    306       if (MI == MBB->end()) {
    307         // If MI is at basic block end then use last instruction's location.
    308         MachineBasicBlock::iterator EI = MI;
    309         DL = (--EI)->getDebugLoc();
    310       }
    311       else
    312         DL = MI->getDebugLoc();
    313       if (MachineInstr *NewDV =
    314           TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
    315         MachineBasicBlock *MBB = DBG->getParent();
    316         MBB->insert(MI, NewDV);
    317         DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
    318       }
    319     }
    320     // Now this register is spilled there is should not be any DBG_VALUE
    321     // pointing to this register because they are all pointing to spilled value
    322     // now.
    323     LRIDbgValues.clear();
    324     if (SpillKill)
    325       LR.LastUse = 0; // Don't kill register again
    326   }
    327   killVirtReg(LRI);
    328 }
    329 
    330 /// spillAll - Spill all dirty virtregs without killing them.
    331 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
    332   if (LiveVirtRegs.empty()) return;
    333   isBulkSpilling = true;
    334   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
    335   // of spilling here is deterministic, if arbitrary.
    336   for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
    337        i != e; ++i)
    338     spillVirtReg(MI, i);
    339   LiveVirtRegs.clear();
    340   isBulkSpilling = false;
    341 }
    342 
    343 /// usePhysReg - Handle the direct use of a physical register.
    344 /// Check that the register is not used by a virtreg.
    345 /// Kill the physreg, marking it free.
    346 /// This may add implicit kills to MO->getParent() and invalidate MO.
    347 void RAFast::usePhysReg(MachineOperand &MO) {
    348   unsigned PhysReg = MO.getReg();
    349   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
    350          "Bad usePhysReg operand");
    351   markRegUsedInInstr(PhysReg);
    352   switch (PhysRegState[PhysReg]) {
    353   case regDisabled:
    354     break;
    355   case regReserved:
    356     PhysRegState[PhysReg] = regFree;
    357     // Fall through
    358   case regFree:
    359     MO.setIsKill();
    360     return;
    361   default:
    362     // The physreg was allocated to a virtual register. That means the value we
    363     // wanted has been clobbered.
    364     llvm_unreachable("Instruction uses an allocated register");
    365   }
    366 
    367   // Maybe a superregister is reserved?
    368   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
    369     unsigned Alias = *AI;
    370     switch (PhysRegState[Alias]) {
    371     case regDisabled:
    372       break;
    373     case regReserved:
    374       assert(TRI->isSuperRegister(PhysReg, Alias) &&
    375              "Instruction is not using a subregister of a reserved register");
    376       // Leave the superregister in the working set.
    377       PhysRegState[Alias] = regFree;
    378       MO.getParent()->addRegisterKilled(Alias, TRI, true);
    379       return;
    380     case regFree:
    381       if (TRI->isSuperRegister(PhysReg, Alias)) {
    382         // Leave the superregister in the working set.
    383         MO.getParent()->addRegisterKilled(Alias, TRI, true);
    384         return;
    385       }
    386       // Some other alias was in the working set - clear it.
    387       PhysRegState[Alias] = regDisabled;
    388       break;
    389     default:
    390       llvm_unreachable("Instruction uses an alias of an allocated register");
    391     }
    392   }
    393 
    394   // All aliases are disabled, bring register into working set.
    395   PhysRegState[PhysReg] = regFree;
    396   MO.setIsKill();
    397 }
    398 
    399 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
    400 /// virtregs. This is very similar to defineVirtReg except the physreg is
    401 /// reserved instead of allocated.
    402 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
    403                            RegState NewState) {
    404   markRegUsedInInstr(PhysReg);
    405   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
    406   case regDisabled:
    407     break;
    408   default:
    409     spillVirtReg(MI, VirtReg);
    410     // Fall through.
    411   case regFree:
    412   case regReserved:
    413     PhysRegState[PhysReg] = NewState;
    414     return;
    415   }
    416 
    417   // This is a disabled register, disable all aliases.
    418   PhysRegState[PhysReg] = NewState;
    419   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
    420     unsigned Alias = *AI;
    421     switch (unsigned VirtReg = PhysRegState[Alias]) {
    422     case regDisabled:
    423       break;
    424     default:
    425       spillVirtReg(MI, VirtReg);
    426       // Fall through.
    427     case regFree:
    428     case regReserved:
    429       PhysRegState[Alias] = regDisabled;
    430       if (TRI->isSuperRegister(PhysReg, Alias))
    431         return;
    432       break;
    433     }
    434   }
    435 }
    436 
    437 
    438 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
    439 // aliases so it is free for allocation.
    440 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
    441 // can be allocated directly.
    442 // Returns spillImpossible when PhysReg or an alias can't be spilled.
    443 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
    444   if (isRegUsedInInstr(PhysReg)) {
    445     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
    446     return spillImpossible;
    447   }
    448   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
    449   case regDisabled:
    450     break;
    451   case regFree:
    452     return 0;
    453   case regReserved:
    454     DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
    455                  << PrintReg(PhysReg, TRI) << " is reserved already.\n");
    456     return spillImpossible;
    457   default: {
    458     LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
    459     assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
    460     return I->Dirty ? spillDirty : spillClean;
    461   }
    462   }
    463 
    464   // This is a disabled register, add up cost of aliases.
    465   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
    466   unsigned Cost = 0;
    467   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
    468     unsigned Alias = *AI;
    469     switch (unsigned VirtReg = PhysRegState[Alias]) {
    470     case regDisabled:
    471       break;
    472     case regFree:
    473       ++Cost;
    474       break;
    475     case regReserved:
    476       return spillImpossible;
    477     default: {
    478       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
    479       assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
    480       Cost += I->Dirty ? spillDirty : spillClean;
    481       break;
    482     }
    483     }
    484   }
    485   return Cost;
    486 }
    487 
    488 
    489 /// assignVirtToPhysReg - This method updates local state so that we know
    490 /// that PhysReg is the proper container for VirtReg now.  The physical
    491 /// register must not be used for anything else when this is called.
    492 ///
    493 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
    494   DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
    495                << PrintReg(PhysReg, TRI) << "\n");
    496   PhysRegState[PhysReg] = LR.VirtReg;
    497   assert(!LR.PhysReg && "Already assigned a physreg");
    498   LR.PhysReg = PhysReg;
    499 }
    500 
    501 RAFast::LiveRegMap::iterator
    502 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
    503   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
    504   assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
    505   assignVirtToPhysReg(*LRI, PhysReg);
    506   return LRI;
    507 }
    508 
    509 /// allocVirtReg - Allocate a physical register for VirtReg.
    510 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
    511                                                   LiveRegMap::iterator LRI,
    512                                                   unsigned Hint) {
    513   const unsigned VirtReg = LRI->VirtReg;
    514 
    515   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
    516          "Can only allocate virtual registers");
    517 
    518   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
    519 
    520   // Ignore invalid hints.
    521   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
    522                !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
    523     Hint = 0;
    524 
    525   // Take hint when possible.
    526   if (Hint) {
    527     // Ignore the hint if we would have to spill a dirty register.
    528     unsigned Cost = calcSpillCost(Hint);
    529     if (Cost < spillDirty) {
    530       if (Cost)
    531         definePhysReg(MI, Hint, regFree);
    532       // definePhysReg may kill virtual registers and modify LiveVirtRegs.
    533       // That invalidates LRI, so run a new lookup for VirtReg.
    534       return assignVirtToPhysReg(VirtReg, Hint);
    535     }
    536   }
    537 
    538   ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
    539 
    540   // First try to find a completely free register.
    541   for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
    542     unsigned PhysReg = *I;
    543     if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
    544       assignVirtToPhysReg(*LRI, PhysReg);
    545       return LRI;
    546     }
    547   }
    548 
    549   DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
    550                << RC->getName() << "\n");
    551 
    552   unsigned BestReg = 0, BestCost = spillImpossible;
    553   for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
    554     unsigned Cost = calcSpillCost(*I);
    555     DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
    556     DEBUG(dbgs() << "\tCost: " << Cost << "\n");
    557     DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
    558     // Cost is 0 when all aliases are already disabled.
    559     if (Cost == 0) {
    560       assignVirtToPhysReg(*LRI, *I);
    561       return LRI;
    562     }
    563     if (Cost < BestCost)
    564       BestReg = *I, BestCost = Cost;
    565   }
    566 
    567   if (BestReg) {
    568     definePhysReg(MI, BestReg, regFree);
    569     // definePhysReg may kill virtual registers and modify LiveVirtRegs.
    570     // That invalidates LRI, so run a new lookup for VirtReg.
    571     return assignVirtToPhysReg(VirtReg, BestReg);
    572   }
    573 
    574   // Nothing we can do. Report an error and keep going with a bad allocation.
    575   MI->emitError("ran out of registers during register allocation");
    576   definePhysReg(MI, *AO.begin(), regFree);
    577   return assignVirtToPhysReg(VirtReg, *AO.begin());
    578 }
    579 
    580 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
    581 RAFast::LiveRegMap::iterator
    582 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
    583                       unsigned VirtReg, unsigned Hint) {
    584   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
    585          "Not a virtual register");
    586   LiveRegMap::iterator LRI;
    587   bool New;
    588   tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
    589   if (New) {
    590     // If there is no hint, peek at the only use of this register.
    591     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
    592         MRI->hasOneNonDBGUse(VirtReg)) {
    593       const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
    594       // It's a copy, use the destination register as a hint.
    595       if (UseMI.isCopyLike())
    596         Hint = UseMI.getOperand(0).getReg();
    597     }
    598     LRI = allocVirtReg(MI, LRI, Hint);
    599   } else if (LRI->LastUse) {
    600     // Redefining a live register - kill at the last use, unless it is this
    601     // instruction defining VirtReg multiple times.
    602     if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
    603       addKillFlag(*LRI);
    604   }
    605   assert(LRI->PhysReg && "Register not assigned");
    606   LRI->LastUse = MI;
    607   LRI->LastOpNum = OpNum;
    608   LRI->Dirty = true;
    609   markRegUsedInInstr(LRI->PhysReg);
    610   return LRI;
    611 }
    612 
    613 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
    614 RAFast::LiveRegMap::iterator
    615 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
    616                       unsigned VirtReg, unsigned Hint) {
    617   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
    618          "Not a virtual register");
    619   LiveRegMap::iterator LRI;
    620   bool New;
    621   tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
    622   MachineOperand &MO = MI->getOperand(OpNum);
    623   if (New) {
    624     LRI = allocVirtReg(MI, LRI, Hint);
    625     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
    626     int FrameIndex = getStackSpaceFor(VirtReg, RC);
    627     DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
    628                  << PrintReg(LRI->PhysReg, TRI) << "\n");
    629     TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
    630     ++NumLoads;
    631   } else if (LRI->Dirty) {
    632     if (isLastUseOfLocalReg(MO)) {
    633       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
    634       if (MO.isUse())
    635         MO.setIsKill();
    636       else
    637         MO.setIsDead();
    638     } else if (MO.isKill()) {
    639       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
    640       MO.setIsKill(false);
    641     } else if (MO.isDead()) {
    642       DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
    643       MO.setIsDead(false);
    644     }
    645   } else if (MO.isKill()) {
    646     // We must remove kill flags from uses of reloaded registers because the
    647     // register would be killed immediately, and there might be a second use:
    648     //   %foo = OR %x<kill>, %x
    649     // This would cause a second reload of %x into a different register.
    650     DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
    651     MO.setIsKill(false);
    652   } else if (MO.isDead()) {
    653     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
    654     MO.setIsDead(false);
    655   }
    656   assert(LRI->PhysReg && "Register not assigned");
    657   LRI->LastUse = MI;
    658   LRI->LastOpNum = OpNum;
    659   markRegUsedInInstr(LRI->PhysReg);
    660   return LRI;
    661 }
    662 
    663 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
    664 // subregs. This may invalidate any operand pointers.
    665 // Return true if the operand kills its register.
    666 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
    667   MachineOperand &MO = MI->getOperand(OpNum);
    668   bool Dead = MO.isDead();
    669   if (!MO.getSubReg()) {
    670     MO.setReg(PhysReg);
    671     return MO.isKill() || Dead;
    672   }
    673 
    674   // Handle subregister index.
    675   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
    676   MO.setSubReg(0);
    677 
    678   // A kill flag implies killing the full register. Add corresponding super
    679   // register kill.
    680   if (MO.isKill()) {
    681     MI->addRegisterKilled(PhysReg, TRI, true);
    682     return true;
    683   }
    684 
    685   // A <def,read-undef> of a sub-register requires an implicit def of the full
    686   // register.
    687   if (MO.isDef() && MO.isUndef())
    688     MI->addRegisterDefined(PhysReg, TRI);
    689 
    690   return Dead;
    691 }
    692 
    693 // Handle special instruction operand like early clobbers and tied ops when
    694 // there are additional physreg defines.
    695 void RAFast::handleThroughOperands(MachineInstr *MI,
    696                                    SmallVectorImpl<unsigned> &VirtDead) {
    697   DEBUG(dbgs() << "Scanning for through registers:");
    698   SmallSet<unsigned, 8> ThroughRegs;
    699   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    700     MachineOperand &MO = MI->getOperand(i);
    701     if (!MO.isReg()) continue;
    702     unsigned Reg = MO.getReg();
    703     if (!TargetRegisterInfo::isVirtualRegister(Reg))
    704       continue;
    705     if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
    706         (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
    707       if (ThroughRegs.insert(Reg))
    708         DEBUG(dbgs() << ' ' << PrintReg(Reg));
    709     }
    710   }
    711 
    712   // If any physreg defines collide with preallocated through registers,
    713   // we must spill and reallocate.
    714   DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
    715   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    716     MachineOperand &MO = MI->getOperand(i);
    717     if (!MO.isReg() || !MO.isDef()) continue;
    718     unsigned Reg = MO.getReg();
    719     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
    720     markRegUsedInInstr(Reg);
    721     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
    722       if (ThroughRegs.count(PhysRegState[*AI]))
    723         definePhysReg(MI, *AI, regFree);
    724     }
    725   }
    726 
    727   SmallVector<unsigned, 8> PartialDefs;
    728   DEBUG(dbgs() << "Allocating tied uses.\n");
    729   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    730     MachineOperand &MO = MI->getOperand(i);
    731     if (!MO.isReg()) continue;
    732     unsigned Reg = MO.getReg();
    733     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
    734     if (MO.isUse()) {
    735       unsigned DefIdx = 0;
    736       if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
    737       DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
    738         << DefIdx << ".\n");
    739       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
    740       unsigned PhysReg = LRI->PhysReg;
    741       setPhysReg(MI, i, PhysReg);
    742       // Note: we don't update the def operand yet. That would cause the normal
    743       // def-scan to attempt spilling.
    744     } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
    745       DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
    746       // Reload the register, but don't assign to the operand just yet.
    747       // That would confuse the later phys-def processing pass.
    748       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
    749       PartialDefs.push_back(LRI->PhysReg);
    750     }
    751   }
    752 
    753   DEBUG(dbgs() << "Allocating early clobbers.\n");
    754   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    755     MachineOperand &MO = MI->getOperand(i);
    756     if (!MO.isReg()) continue;
    757     unsigned Reg = MO.getReg();
    758     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
    759     if (!MO.isEarlyClobber())
    760       continue;
    761     // Note: defineVirtReg may invalidate MO.
    762     LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
    763     unsigned PhysReg = LRI->PhysReg;
    764     if (setPhysReg(MI, i, PhysReg))
    765       VirtDead.push_back(Reg);
    766   }
    767 
    768   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
    769   UsedInInstr.clear();
    770   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    771     MachineOperand &MO = MI->getOperand(i);
    772     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
    773     unsigned Reg = MO.getReg();
    774     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
    775     DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
    776                  << " as used in instr\n");
    777     markRegUsedInInstr(Reg);
    778   }
    779 
    780   // Also mark PartialDefs as used to avoid reallocation.
    781   for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
    782     markRegUsedInInstr(PartialDefs[i]);
    783 }
    784 
    785 void RAFast::AllocateBasicBlock() {
    786   DEBUG(dbgs() << "\nAllocating " << *MBB);
    787 
    788   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
    789   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
    790 
    791   MachineBasicBlock::iterator MII = MBB->begin();
    792 
    793   // Add live-in registers as live.
    794   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
    795          E = MBB->livein_end(); I != E; ++I)
    796     if (MRI->isAllocatable(*I))
    797       definePhysReg(MII, *I, regReserved);
    798 
    799   SmallVector<unsigned, 8> VirtDead;
    800   SmallVector<MachineInstr*, 32> Coalesced;
    801 
    802   // Otherwise, sequentially allocate each instruction in the MBB.
    803   while (MII != MBB->end()) {
    804     MachineInstr *MI = MII++;
    805     const MCInstrDesc &MCID = MI->getDesc();
    806     DEBUG({
    807         dbgs() << "\n>> " << *MI << "Regs:";
    808         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
    809           if (PhysRegState[Reg] == regDisabled) continue;
    810           dbgs() << " " << TRI->getName(Reg);
    811           switch(PhysRegState[Reg]) {
    812           case regFree:
    813             break;
    814           case regReserved:
    815             dbgs() << "*";
    816             break;
    817           default: {
    818             dbgs() << '=' << PrintReg(PhysRegState[Reg]);
    819             LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
    820             assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
    821             if (I->Dirty)
    822               dbgs() << "*";
    823             assert(I->PhysReg == Reg && "Bad inverse map");
    824             break;
    825           }
    826           }
    827         }
    828         dbgs() << '\n';
    829         // Check that LiveVirtRegs is the inverse.
    830         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
    831              e = LiveVirtRegs.end(); i != e; ++i) {
    832            assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
    833                   "Bad map key");
    834            assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
    835                   "Bad map value");
    836            assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
    837         }
    838       });
    839 
    840     // Debug values are not allowed to change codegen in any way.
    841     if (MI->isDebugValue()) {
    842       bool ScanDbgValue = true;
    843       while (ScanDbgValue) {
    844         ScanDbgValue = false;
    845         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    846           MachineOperand &MO = MI->getOperand(i);
    847           if (!MO.isReg()) continue;
    848           unsigned Reg = MO.getReg();
    849           if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
    850           LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
    851           if (LRI != LiveVirtRegs.end())
    852             setPhysReg(MI, i, LRI->PhysReg);
    853           else {
    854             int SS = StackSlotForVirtReg[Reg];
    855             if (SS == -1) {
    856               // We can't allocate a physreg for a DebugValue, sorry!
    857               DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
    858               MO.setReg(0);
    859             }
    860             else {
    861               // Modify DBG_VALUE now that the value is in a spill slot.
    862               int64_t Offset = MI->getOperand(1).getImm();
    863               const MDNode *MDPtr =
    864                 MI->getOperand(MI->getNumOperands()-1).getMetadata();
    865               DebugLoc DL = MI->getDebugLoc();
    866               if (MachineInstr *NewDV =
    867                   TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
    868                 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
    869                       "\t" << *MI);
    870                 MachineBasicBlock *MBB = MI->getParent();
    871                 MBB->insert(MBB->erase(MI), NewDV);
    872                 // Scan NewDV operands from the beginning.
    873                 MI = NewDV;
    874                 ScanDbgValue = true;
    875                 break;
    876               } else {
    877                 // We can't allocate a physreg for a DebugValue; sorry!
    878                 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
    879                 MO.setReg(0);
    880               }
    881             }
    882           }
    883           LiveDbgValueMap[Reg].push_back(MI);
    884         }
    885       }
    886       // Next instruction.
    887       continue;
    888     }
    889 
    890     // If this is a copy, we may be able to coalesce.
    891     unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
    892     if (MI->isCopy()) {
    893       CopyDst = MI->getOperand(0).getReg();
    894       CopySrc = MI->getOperand(1).getReg();
    895       CopyDstSub = MI->getOperand(0).getSubReg();
    896       CopySrcSub = MI->getOperand(1).getSubReg();
    897     }
    898 
    899     // Track registers used by instruction.
    900     UsedInInstr.clear();
    901 
    902     // First scan.
    903     // Mark physreg uses and early clobbers as used.
    904     // Find the end of the virtreg operands
    905     unsigned VirtOpEnd = 0;
    906     bool hasTiedOps = false;
    907     bool hasEarlyClobbers = false;
    908     bool hasPartialRedefs = false;
    909     bool hasPhysDefs = false;
    910     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    911       MachineOperand &MO = MI->getOperand(i);
    912       // Make sure MRI knows about registers clobbered by regmasks.
    913       if (MO.isRegMask()) {
    914         MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
    915         continue;
    916       }
    917       if (!MO.isReg()) continue;
    918       unsigned Reg = MO.getReg();
    919       if (!Reg) continue;
    920       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
    921         VirtOpEnd = i+1;
    922         if (MO.isUse()) {
    923           hasTiedOps = hasTiedOps ||
    924                               MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
    925         } else {
    926           if (MO.isEarlyClobber())
    927             hasEarlyClobbers = true;
    928           if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
    929             hasPartialRedefs = true;
    930         }
    931         continue;
    932       }
    933       if (!MRI->isAllocatable(Reg)) continue;
    934       if (MO.isUse()) {
    935         usePhysReg(MO);
    936       } else if (MO.isEarlyClobber()) {
    937         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
    938                                regFree : regReserved);
    939         hasEarlyClobbers = true;
    940       } else
    941         hasPhysDefs = true;
    942     }
    943 
    944     // The instruction may have virtual register operands that must be allocated
    945     // the same register at use-time and def-time: early clobbers and tied
    946     // operands. If there are also physical defs, these registers must avoid
    947     // both physical defs and uses, making them more constrained than normal
    948     // operands.
    949     // Similarly, if there are multiple defs and tied operands, we must make
    950     // sure the same register is allocated to uses and defs.
    951     // We didn't detect inline asm tied operands above, so just make this extra
    952     // pass for all inline asm.
    953     if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
    954         (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
    955       handleThroughOperands(MI, VirtDead);
    956       // Don't attempt coalescing when we have funny stuff going on.
    957       CopyDst = 0;
    958       // Pretend we have early clobbers so the use operands get marked below.
    959       // This is not necessary for the common case of a single tied use.
    960       hasEarlyClobbers = true;
    961     }
    962 
    963     // Second scan.
    964     // Allocate virtreg uses.
    965     for (unsigned i = 0; i != VirtOpEnd; ++i) {
    966       MachineOperand &MO = MI->getOperand(i);
    967       if (!MO.isReg()) continue;
    968       unsigned Reg = MO.getReg();
    969       if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
    970       if (MO.isUse()) {
    971         LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
    972         unsigned PhysReg = LRI->PhysReg;
    973         CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
    974         if (setPhysReg(MI, i, PhysReg))
    975           killVirtReg(LRI);
    976       }
    977     }
    978 
    979     for (UsedInInstrSet::iterator
    980          I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
    981       MRI->setRegUnitUsed(*I);
    982 
    983     // Track registers defined by instruction - early clobbers and tied uses at
    984     // this point.
    985     UsedInInstr.clear();
    986     if (hasEarlyClobbers) {
    987       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    988         MachineOperand &MO = MI->getOperand(i);
    989         if (!MO.isReg()) continue;
    990         unsigned Reg = MO.getReg();
    991         if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
    992         // Look for physreg defs and tied uses.
    993         if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
    994         markRegUsedInInstr(Reg);
    995       }
    996     }
    997 
    998     unsigned DefOpEnd = MI->getNumOperands();
    999     if (MI->isCall()) {
   1000       // Spill all virtregs before a call. This serves two purposes: 1. If an
   1001       // exception is thrown, the landing pad is going to expect to find
   1002       // registers in their spill slots, and 2. we don't have to wade through
   1003       // all the <imp-def> operands on the call instruction.
   1004       DefOpEnd = VirtOpEnd;
   1005       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
   1006       spillAll(MI);
   1007 
   1008       // The imp-defs are skipped below, but we still need to mark those
   1009       // registers as used by the function.
   1010       SkippedInstrs.insert(&MCID);
   1011     }
   1012 
   1013     // Third scan.
   1014     // Allocate defs and collect dead defs.
   1015     for (unsigned i = 0; i != DefOpEnd; ++i) {
   1016       MachineOperand &MO = MI->getOperand(i);
   1017       if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
   1018         continue;
   1019       unsigned Reg = MO.getReg();
   1020 
   1021       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
   1022         if (!MRI->isAllocatable(Reg)) continue;
   1023         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
   1024                                regFree : regReserved);
   1025         continue;
   1026       }
   1027       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
   1028       unsigned PhysReg = LRI->PhysReg;
   1029       if (setPhysReg(MI, i, PhysReg)) {
   1030         VirtDead.push_back(Reg);
   1031         CopyDst = 0; // cancel coalescing;
   1032       } else
   1033         CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
   1034     }
   1035 
   1036     // Kill dead defs after the scan to ensure that multiple defs of the same
   1037     // register are allocated identically. We didn't need to do this for uses
   1038     // because we are crerating our own kill flags, and they are always at the
   1039     // last use.
   1040     for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
   1041       killVirtReg(VirtDead[i]);
   1042     VirtDead.clear();
   1043 
   1044     for (UsedInInstrSet::iterator
   1045          I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
   1046       MRI->setRegUnitUsed(*I);
   1047 
   1048     if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
   1049       DEBUG(dbgs() << "-- coalescing: " << *MI);
   1050       Coalesced.push_back(MI);
   1051     } else {
   1052       DEBUG(dbgs() << "<< " << *MI);
   1053     }
   1054   }
   1055 
   1056   // Spill all physical registers holding virtual registers now.
   1057   DEBUG(dbgs() << "Spilling live registers at end of block.\n");
   1058   spillAll(MBB->getFirstTerminator());
   1059 
   1060   // Erase all the coalesced copies. We are delaying it until now because
   1061   // LiveVirtRegs might refer to the instrs.
   1062   for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
   1063     MBB->erase(Coalesced[i]);
   1064   NumCopies += Coalesced.size();
   1065 
   1066   DEBUG(MBB->dump());
   1067 }
   1068 
   1069 /// runOnMachineFunction - Register allocate the whole function
   1070 ///
   1071 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
   1072   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
   1073                << "********** Function: " << Fn.getName() << '\n');
   1074   MF = &Fn;
   1075   MRI = &MF->getRegInfo();
   1076   TM = &Fn.getTarget();
   1077   TRI = TM->getRegisterInfo();
   1078   TII = TM->getInstrInfo();
   1079   MRI->freezeReservedRegs(Fn);
   1080   RegClassInfo.runOnMachineFunction(Fn);
   1081   UsedInInstr.clear();
   1082   UsedInInstr.setUniverse(TRI->getNumRegUnits());
   1083 
   1084   assert(!MRI->isSSA() && "regalloc requires leaving SSA");
   1085 
   1086   // initialize the virtual->physical register map to have a 'null'
   1087   // mapping for all virtual registers
   1088   StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
   1089   LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
   1090 
   1091   // Loop over all of the basic blocks, eliminating virtual register references
   1092   for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
   1093        MBBi != MBBe; ++MBBi) {
   1094     MBB = &*MBBi;
   1095     AllocateBasicBlock();
   1096   }
   1097 
   1098   // Add the clobber lists for all the instructions we skipped earlier.
   1099   for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
   1100        I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
   1101     if (const uint16_t *Defs = (*I)->getImplicitDefs())
   1102       while (*Defs)
   1103         MRI->setPhysRegUsed(*Defs++);
   1104 
   1105   // All machine operands and other references to virtual registers have been
   1106   // replaced. Remove the virtual registers.
   1107   MRI->clearVirtRegs();
   1108 
   1109   SkippedInstrs.clear();
   1110   StackSlotForVirtReg.clear();
   1111   LiveDbgValueMap.clear();
   1112   return true;
   1113 }
   1114 
   1115 FunctionPass *llvm::createFastRegisterAllocator() {
   1116   return new RAFast();
   1117 }
   1118