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