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