LLVM API Documentation

RegAllocFast.cpp
Go to the documentation of this file.
00001 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This register allocator allocates registers to a basic block at a time,
00011 // attempting to keep values in registers and reusing registers as appropriate.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/IndexedMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/SparseSet.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/MachineFrameInfo.h"
00024 #include "llvm/CodeGen/MachineFunctionPass.h"
00025 #include "llvm/CodeGen/MachineInstr.h"
00026 #include "llvm/CodeGen/MachineInstrBuilder.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/CodeGen/RegAllocRegistry.h"
00029 #include "llvm/CodeGen/RegisterClassInfo.h"
00030 #include "llvm/IR/BasicBlock.h"
00031 #include "llvm/Support/CommandLine.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Target/TargetInstrInfo.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include "llvm/Target/TargetSubtargetInfo.h"
00038 #include <algorithm>
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "regalloc"
00042 
00043 STATISTIC(NumStores, "Number of stores added");
00044 STATISTIC(NumLoads , "Number of loads added");
00045 STATISTIC(NumCopies, "Number of copies coalesced");
00046 
00047 static RegisterRegAlloc
00048   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
00049 
00050 namespace {
00051   class RAFast : public MachineFunctionPass {
00052   public:
00053     static char ID;
00054     RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
00055                isBulkSpilling(false) {}
00056   private:
00057     const TargetMachine *TM;
00058     MachineFunction *MF;
00059     MachineRegisterInfo *MRI;
00060     const TargetRegisterInfo *TRI;
00061     const TargetInstrInfo *TII;
00062     RegisterClassInfo RegClassInfo;
00063 
00064     // Basic block currently being allocated.
00065     MachineBasicBlock *MBB;
00066 
00067     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
00068     // values are spilled.
00069     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
00070 
00071     // Everything we know about a live virtual register.
00072     struct LiveReg {
00073       MachineInstr *LastUse;    // Last instr to use reg.
00074       unsigned VirtReg;         // Virtual register number.
00075       unsigned PhysReg;         // Currently held here.
00076       unsigned short LastOpNum; // OpNum on LastUse.
00077       bool Dirty;               // Register needs spill.
00078 
00079       explicit LiveReg(unsigned v)
00080         : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
00081 
00082       unsigned getSparseSetIndex() const {
00083         return TargetRegisterInfo::virtReg2Index(VirtReg);
00084       }
00085     };
00086 
00087     typedef SparseSet<LiveReg> LiveRegMap;
00088 
00089     // LiveVirtRegs - This map contains entries for each virtual register
00090     // that is currently available in a physical register.
00091     LiveRegMap LiveVirtRegs;
00092 
00093     DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
00094 
00095     // RegState - Track the state of a physical register.
00096     enum RegState {
00097       // A disabled register is not available for allocation, but an alias may
00098       // be in use. A register can only be moved out of the disabled state if
00099       // all aliases are disabled.
00100       regDisabled,
00101 
00102       // A free register is not currently in use and can be allocated
00103       // immediately without checking aliases.
00104       regFree,
00105 
00106       // A reserved register has been assigned explicitly (e.g., setting up a
00107       // call parameter), and it remains reserved until it is used.
00108       regReserved
00109 
00110       // A register state may also be a virtual register number, indication that
00111       // the physical register is currently allocated to a virtual register. In
00112       // that case, LiveVirtRegs contains the inverse mapping.
00113     };
00114 
00115     // PhysRegState - One of the RegState enums, or a virtreg.
00116     std::vector<unsigned> PhysRegState;
00117 
00118     // Set of register units.
00119     typedef SparseSet<unsigned> UsedInInstrSet;
00120 
00121     // Set of register units that are used in the current instruction, and so
00122     // cannot be allocated.
00123     UsedInInstrSet UsedInInstr;
00124 
00125     // Mark a physreg as used in this instruction.
00126     void markRegUsedInInstr(unsigned PhysReg) {
00127       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
00128         UsedInInstr.insert(*Units);
00129     }
00130 
00131     // Check if a physreg or any of its aliases are used in this instruction.
00132     bool isRegUsedInInstr(unsigned PhysReg) const {
00133       for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
00134         if (UsedInInstr.count(*Units))
00135           return true;
00136       return false;
00137     }
00138 
00139     // SkippedInstrs - Descriptors of instructions whose clobber list was
00140     // ignored because all registers were spilled. It is still necessary to
00141     // mark all the clobbered registers as used by the function.
00142     SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
00143 
00144     // isBulkSpilling - This flag is set when LiveRegMap will be cleared
00145     // completely after spilling all live registers. LiveRegMap entries should
00146     // not be erased.
00147     bool isBulkSpilling;
00148 
00149     enum : unsigned {
00150       spillClean = 1,
00151       spillDirty = 100,
00152       spillImpossible = ~0u
00153     };
00154   public:
00155     const char *getPassName() const override {
00156       return "Fast Register Allocator";
00157     }
00158 
00159     void getAnalysisUsage(AnalysisUsage &AU) const override {
00160       AU.setPreservesCFG();
00161       MachineFunctionPass::getAnalysisUsage(AU);
00162     }
00163 
00164   private:
00165     bool runOnMachineFunction(MachineFunction &Fn) override;
00166     void AllocateBasicBlock();
00167     void handleThroughOperands(MachineInstr *MI,
00168                                SmallVectorImpl<unsigned> &VirtDead);
00169     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
00170     bool isLastUseOfLocalReg(MachineOperand&);
00171 
00172     void addKillFlag(const LiveReg&);
00173     void killVirtReg(LiveRegMap::iterator);
00174     void killVirtReg(unsigned VirtReg);
00175     void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
00176     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
00177 
00178     void usePhysReg(MachineOperand&);
00179     void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
00180     unsigned calcSpillCost(unsigned PhysReg) const;
00181     void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
00182     LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
00183       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
00184     }
00185     LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
00186       return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
00187     }
00188     LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
00189     LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
00190                                       unsigned Hint);
00191     LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
00192                                        unsigned VirtReg, unsigned Hint);
00193     LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
00194                                        unsigned VirtReg, unsigned Hint);
00195     void spillAll(MachineBasicBlock::iterator MI);
00196     bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
00197   };
00198   char RAFast::ID = 0;
00199 }
00200 
00201 /// getStackSpaceFor - This allocates space for the specified virtual register
00202 /// to be held on the stack.
00203 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
00204   // Find the location Reg would belong...
00205   int SS = StackSlotForVirtReg[VirtReg];
00206   if (SS != -1)
00207     return SS;          // Already has space allocated?
00208 
00209   // Allocate a new stack object for this spill location...
00210   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
00211                                                             RC->getAlignment());
00212 
00213   // Assign the slot.
00214   StackSlotForVirtReg[VirtReg] = FrameIdx;
00215   return FrameIdx;
00216 }
00217 
00218 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
00219 /// its virtual register, and it is guaranteed to be a block-local register.
00220 ///
00221 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
00222   // If the register has ever been spilled or reloaded, we conservatively assume
00223   // it is a global register used in multiple blocks.
00224   if (StackSlotForVirtReg[MO.getReg()] != -1)
00225     return false;
00226 
00227   // Check that the use/def chain has exactly one operand - MO.
00228   MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
00229   if (&*I != &MO)
00230     return false;
00231   return ++I == MRI->reg_nodbg_end();
00232 }
00233 
00234 /// addKillFlag - Set kill flags on last use of a virtual register.
00235 void RAFast::addKillFlag(const LiveReg &LR) {
00236   if (!LR.LastUse) return;
00237   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
00238   if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
00239     if (MO.getReg() == LR.PhysReg)
00240       MO.setIsKill();
00241     else
00242       LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
00243   }
00244 }
00245 
00246 /// killVirtReg - Mark virtreg as no longer available.
00247 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
00248   addKillFlag(*LRI);
00249   assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
00250          "Broken RegState mapping");
00251   PhysRegState[LRI->PhysReg] = regFree;
00252   // Erase from LiveVirtRegs unless we're spilling in bulk.
00253   if (!isBulkSpilling)
00254     LiveVirtRegs.erase(LRI);
00255 }
00256 
00257 /// killVirtReg - Mark virtreg as no longer available.
00258 void RAFast::killVirtReg(unsigned VirtReg) {
00259   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
00260          "killVirtReg needs a virtual register");
00261   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
00262   if (LRI != LiveVirtRegs.end())
00263     killVirtReg(LRI);
00264 }
00265 
00266 /// spillVirtReg - This method spills the value specified by VirtReg into the
00267 /// corresponding stack slot if needed.
00268 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
00269   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
00270          "Spilling a physical register is illegal!");
00271   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
00272   assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
00273   spillVirtReg(MI, LRI);
00274 }
00275 
00276 /// spillVirtReg - Do the actual work of spilling.
00277 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
00278                           LiveRegMap::iterator LRI) {
00279   LiveReg &LR = *LRI;
00280   assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
00281 
00282   if (LR.Dirty) {
00283     // If this physreg is used by the instruction, we want to kill it on the
00284     // instruction, not on the spill.
00285     bool SpillKill = LR.LastUse != MI;
00286     LR.Dirty = false;
00287     DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
00288                  << " in " << PrintReg(LR.PhysReg, TRI));
00289     const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
00290     int FI = getStackSpaceFor(LRI->VirtReg, RC);
00291     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
00292     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
00293     ++NumStores;   // Update statistics
00294 
00295     // If this register is used by DBG_VALUE then insert new DBG_VALUE to
00296     // identify spilled location as the place to find corresponding variable's
00297     // value.
00298     SmallVectorImpl<MachineInstr *> &LRIDbgValues =
00299       LiveDbgValueMap[LRI->VirtReg];
00300     for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
00301       MachineInstr *DBG = LRIDbgValues[li];
00302       const MDNode *MDPtr = DBG->getOperand(2).getMetadata();
00303       bool IsIndirect = DBG->isIndirectDebugValue();
00304       uint64_t Offset = IsIndirect ? DBG->getOperand(1).getImm() : 0;
00305       DebugLoc DL;
00306       if (MI == MBB->end()) {
00307         // If MI is at basic block end then use last instruction's location.
00308         MachineBasicBlock::iterator EI = MI;
00309         DL = (--EI)->getDebugLoc();
00310       } else
00311         DL = MI->getDebugLoc();
00312       MachineInstr *NewDV =
00313           BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
00314               .addFrameIndex(FI).addImm(Offset).addMetadata(MDPtr);
00315       assert(NewDV->getParent() == MBB && "dangling parent pointer");
00316       (void)NewDV;
00317       DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
00318     }
00319     // Now this register is spilled there is should not be any DBG_VALUE
00320     // pointing to this register because they are all pointing to spilled value
00321     // now.
00322     LRIDbgValues.clear();
00323     if (SpillKill)
00324       LR.LastUse = nullptr; // Don't kill register again
00325   }
00326   killVirtReg(LRI);
00327 }
00328 
00329 /// spillAll - Spill all dirty virtregs without killing them.
00330 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
00331   if (LiveVirtRegs.empty()) return;
00332   isBulkSpilling = true;
00333   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
00334   // of spilling here is deterministic, if arbitrary.
00335   for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
00336        i != e; ++i)
00337     spillVirtReg(MI, i);
00338   LiveVirtRegs.clear();
00339   isBulkSpilling = false;
00340 }
00341 
00342 /// usePhysReg - Handle the direct use of a physical register.
00343 /// Check that the register is not used by a virtreg.
00344 /// Kill the physreg, marking it free.
00345 /// This may add implicit kills to MO->getParent() and invalidate MO.
00346 void RAFast::usePhysReg(MachineOperand &MO) {
00347   unsigned PhysReg = MO.getReg();
00348   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
00349          "Bad usePhysReg operand");
00350   markRegUsedInInstr(PhysReg);
00351   switch (PhysRegState[PhysReg]) {
00352   case regDisabled:
00353     break;
00354   case regReserved:
00355     PhysRegState[PhysReg] = regFree;
00356     // Fall through
00357   case regFree:
00358     MO.setIsKill();
00359     return;
00360   default:
00361     // The physreg was allocated to a virtual register. That means the value we
00362     // wanted has been clobbered.
00363     llvm_unreachable("Instruction uses an allocated register");
00364   }
00365 
00366   // Maybe a superregister is reserved?
00367   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
00368     unsigned Alias = *AI;
00369     switch (PhysRegState[Alias]) {
00370     case regDisabled:
00371       break;
00372     case regReserved:
00373       assert(TRI->isSuperRegister(PhysReg, Alias) &&
00374              "Instruction is not using a subregister of a reserved register");
00375       // Leave the superregister in the working set.
00376       PhysRegState[Alias] = regFree;
00377       MO.getParent()->addRegisterKilled(Alias, TRI, true);
00378       return;
00379     case regFree:
00380       if (TRI->isSuperRegister(PhysReg, Alias)) {
00381         // Leave the superregister in the working set.
00382         MO.getParent()->addRegisterKilled(Alias, TRI, true);
00383         return;
00384       }
00385       // Some other alias was in the working set - clear it.
00386       PhysRegState[Alias] = regDisabled;
00387       break;
00388     default:
00389       llvm_unreachable("Instruction uses an alias of an allocated register");
00390     }
00391   }
00392 
00393   // All aliases are disabled, bring register into working set.
00394   PhysRegState[PhysReg] = regFree;
00395   MO.setIsKill();
00396 }
00397 
00398 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
00399 /// virtregs. This is very similar to defineVirtReg except the physreg is
00400 /// reserved instead of allocated.
00401 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
00402                            RegState NewState) {
00403   markRegUsedInInstr(PhysReg);
00404   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
00405   case regDisabled:
00406     break;
00407   default:
00408     spillVirtReg(MI, VirtReg);
00409     // Fall through.
00410   case regFree:
00411   case regReserved:
00412     PhysRegState[PhysReg] = NewState;
00413     return;
00414   }
00415 
00416   // This is a disabled register, disable all aliases.
00417   PhysRegState[PhysReg] = NewState;
00418   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
00419     unsigned Alias = *AI;
00420     switch (unsigned VirtReg = PhysRegState[Alias]) {
00421     case regDisabled:
00422       break;
00423     default:
00424       spillVirtReg(MI, VirtReg);
00425       // Fall through.
00426     case regFree:
00427     case regReserved:
00428       PhysRegState[Alias] = regDisabled;
00429       if (TRI->isSuperRegister(PhysReg, Alias))
00430         return;
00431       break;
00432     }
00433   }
00434 }
00435 
00436 
00437 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
00438 // aliases so it is free for allocation.
00439 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
00440 // can be allocated directly.
00441 // Returns spillImpossible when PhysReg or an alias can't be spilled.
00442 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
00443   if (isRegUsedInInstr(PhysReg)) {
00444     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
00445     return spillImpossible;
00446   }
00447   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
00448   case regDisabled:
00449     break;
00450   case regFree:
00451     return 0;
00452   case regReserved:
00453     DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
00454                  << PrintReg(PhysReg, TRI) << " is reserved already.\n");
00455     return spillImpossible;
00456   default: {
00457     LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
00458     assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
00459     return I->Dirty ? spillDirty : spillClean;
00460   }
00461   }
00462 
00463   // This is a disabled register, add up cost of aliases.
00464   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
00465   unsigned Cost = 0;
00466   for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
00467     unsigned Alias = *AI;
00468     switch (unsigned VirtReg = PhysRegState[Alias]) {
00469     case regDisabled:
00470       break;
00471     case regFree:
00472       ++Cost;
00473       break;
00474     case regReserved:
00475       return spillImpossible;
00476     default: {
00477       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
00478       assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
00479       Cost += I->Dirty ? spillDirty : spillClean;
00480       break;
00481     }
00482     }
00483   }
00484   return Cost;
00485 }
00486 
00487 
00488 /// assignVirtToPhysReg - This method updates local state so that we know
00489 /// that PhysReg is the proper container for VirtReg now.  The physical
00490 /// register must not be used for anything else when this is called.
00491 ///
00492 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
00493   DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
00494                << PrintReg(PhysReg, TRI) << "\n");
00495   PhysRegState[PhysReg] = LR.VirtReg;
00496   assert(!LR.PhysReg && "Already assigned a physreg");
00497   LR.PhysReg = PhysReg;
00498 }
00499 
00500 RAFast::LiveRegMap::iterator
00501 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
00502   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
00503   assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
00504   assignVirtToPhysReg(*LRI, PhysReg);
00505   return LRI;
00506 }
00507 
00508 /// allocVirtReg - Allocate a physical register for VirtReg.
00509 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
00510                                                   LiveRegMap::iterator LRI,
00511                                                   unsigned Hint) {
00512   const unsigned VirtReg = LRI->VirtReg;
00513 
00514   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
00515          "Can only allocate virtual registers");
00516 
00517   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
00518 
00519   // Ignore invalid hints.
00520   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
00521                !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
00522     Hint = 0;
00523 
00524   // Take hint when possible.
00525   if (Hint) {
00526     // Ignore the hint if we would have to spill a dirty register.
00527     unsigned Cost = calcSpillCost(Hint);
00528     if (Cost < spillDirty) {
00529       if (Cost)
00530         definePhysReg(MI, Hint, regFree);
00531       // definePhysReg may kill virtual registers and modify LiveVirtRegs.
00532       // That invalidates LRI, so run a new lookup for VirtReg.
00533       return assignVirtToPhysReg(VirtReg, Hint);
00534     }
00535   }
00536 
00537   ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
00538 
00539   // First try to find a completely free register.
00540   for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
00541     unsigned PhysReg = *I;
00542     if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
00543       assignVirtToPhysReg(*LRI, PhysReg);
00544       return LRI;
00545     }
00546   }
00547 
00548   DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
00549                << RC->getName() << "\n");
00550 
00551   unsigned BestReg = 0, BestCost = spillImpossible;
00552   for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
00553     unsigned Cost = calcSpillCost(*I);
00554     DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
00555     DEBUG(dbgs() << "\tCost: " << Cost << "\n");
00556     DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
00557     // Cost is 0 when all aliases are already disabled.
00558     if (Cost == 0) {
00559       assignVirtToPhysReg(*LRI, *I);
00560       return LRI;
00561     }
00562     if (Cost < BestCost)
00563       BestReg = *I, BestCost = Cost;
00564   }
00565 
00566   if (BestReg) {
00567     definePhysReg(MI, BestReg, regFree);
00568     // definePhysReg may kill virtual registers and modify LiveVirtRegs.
00569     // That invalidates LRI, so run a new lookup for VirtReg.
00570     return assignVirtToPhysReg(VirtReg, BestReg);
00571   }
00572 
00573   // Nothing we can do. Report an error and keep going with a bad allocation.
00574   if (MI->isInlineAsm())
00575     MI->emitError("inline assembly requires more registers than available");
00576   else
00577     MI->emitError("ran out of registers during register allocation");
00578   definePhysReg(MI, *AO.begin(), regFree);
00579   return assignVirtToPhysReg(VirtReg, *AO.begin());
00580 }
00581 
00582 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
00583 RAFast::LiveRegMap::iterator
00584 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
00585                       unsigned VirtReg, unsigned Hint) {
00586   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
00587          "Not a virtual register");
00588   LiveRegMap::iterator LRI;
00589   bool New;
00590   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
00591   if (New) {
00592     // If there is no hint, peek at the only use of this register.
00593     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
00594         MRI->hasOneNonDBGUse(VirtReg)) {
00595       const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
00596       // It's a copy, use the destination register as a hint.
00597       if (UseMI.isCopyLike())
00598         Hint = UseMI.getOperand(0).getReg();
00599     }
00600     LRI = allocVirtReg(MI, LRI, Hint);
00601   } else if (LRI->LastUse) {
00602     // Redefining a live register - kill at the last use, unless it is this
00603     // instruction defining VirtReg multiple times.
00604     if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
00605       addKillFlag(*LRI);
00606   }
00607   assert(LRI->PhysReg && "Register not assigned");
00608   LRI->LastUse = MI;
00609   LRI->LastOpNum = OpNum;
00610   LRI->Dirty = true;
00611   markRegUsedInInstr(LRI->PhysReg);
00612   return LRI;
00613 }
00614 
00615 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
00616 RAFast::LiveRegMap::iterator
00617 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
00618                       unsigned VirtReg, unsigned Hint) {
00619   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
00620          "Not a virtual register");
00621   LiveRegMap::iterator LRI;
00622   bool New;
00623   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
00624   MachineOperand &MO = MI->getOperand(OpNum);
00625   if (New) {
00626     LRI = allocVirtReg(MI, LRI, Hint);
00627     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
00628     int FrameIndex = getStackSpaceFor(VirtReg, RC);
00629     DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
00630                  << PrintReg(LRI->PhysReg, TRI) << "\n");
00631     TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
00632     ++NumLoads;
00633   } else if (LRI->Dirty) {
00634     if (isLastUseOfLocalReg(MO)) {
00635       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
00636       if (MO.isUse())
00637         MO.setIsKill();
00638       else
00639         MO.setIsDead();
00640     } else if (MO.isKill()) {
00641       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
00642       MO.setIsKill(false);
00643     } else if (MO.isDead()) {
00644       DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
00645       MO.setIsDead(false);
00646     }
00647   } else if (MO.isKill()) {
00648     // We must remove kill flags from uses of reloaded registers because the
00649     // register would be killed immediately, and there might be a second use:
00650     //   %foo = OR %x<kill>, %x
00651     // This would cause a second reload of %x into a different register.
00652     DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
00653     MO.setIsKill(false);
00654   } else if (MO.isDead()) {
00655     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
00656     MO.setIsDead(false);
00657   }
00658   assert(LRI->PhysReg && "Register not assigned");
00659   LRI->LastUse = MI;
00660   LRI->LastOpNum = OpNum;
00661   markRegUsedInInstr(LRI->PhysReg);
00662   return LRI;
00663 }
00664 
00665 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
00666 // subregs. This may invalidate any operand pointers.
00667 // Return true if the operand kills its register.
00668 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
00669   MachineOperand &MO = MI->getOperand(OpNum);
00670   bool Dead = MO.isDead();
00671   if (!MO.getSubReg()) {
00672     MO.setReg(PhysReg);
00673     return MO.isKill() || Dead;
00674   }
00675 
00676   // Handle subregister index.
00677   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
00678   MO.setSubReg(0);
00679 
00680   // A kill flag implies killing the full register. Add corresponding super
00681   // register kill.
00682   if (MO.isKill()) {
00683     MI->addRegisterKilled(PhysReg, TRI, true);
00684     return true;
00685   }
00686 
00687   // A <def,read-undef> of a sub-register requires an implicit def of the full
00688   // register.
00689   if (MO.isDef() && MO.isUndef())
00690     MI->addRegisterDefined(PhysReg, TRI);
00691 
00692   return Dead;
00693 }
00694 
00695 // Handle special instruction operand like early clobbers and tied ops when
00696 // there are additional physreg defines.
00697 void RAFast::handleThroughOperands(MachineInstr *MI,
00698                                    SmallVectorImpl<unsigned> &VirtDead) {
00699   DEBUG(dbgs() << "Scanning for through registers:");
00700   SmallSet<unsigned, 8> ThroughRegs;
00701   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00702     MachineOperand &MO = MI->getOperand(i);
00703     if (!MO.isReg()) continue;
00704     unsigned Reg = MO.getReg();
00705     if (!TargetRegisterInfo::isVirtualRegister(Reg))
00706       continue;
00707     if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
00708         (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
00709       if (ThroughRegs.insert(Reg))
00710         DEBUG(dbgs() << ' ' << PrintReg(Reg));
00711     }
00712   }
00713 
00714   // If any physreg defines collide with preallocated through registers,
00715   // we must spill and reallocate.
00716   DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
00717   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00718     MachineOperand &MO = MI->getOperand(i);
00719     if (!MO.isReg() || !MO.isDef()) continue;
00720     unsigned Reg = MO.getReg();
00721     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
00722     markRegUsedInInstr(Reg);
00723     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
00724       if (ThroughRegs.count(PhysRegState[*AI]))
00725         definePhysReg(MI, *AI, regFree);
00726     }
00727   }
00728 
00729   SmallVector<unsigned, 8> PartialDefs;
00730   DEBUG(dbgs() << "Allocating tied uses.\n");
00731   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00732     MachineOperand &MO = MI->getOperand(i);
00733     if (!MO.isReg()) continue;
00734     unsigned Reg = MO.getReg();
00735     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
00736     if (MO.isUse()) {
00737       unsigned DefIdx = 0;
00738       if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
00739       DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
00740         << DefIdx << ".\n");
00741       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
00742       unsigned PhysReg = LRI->PhysReg;
00743       setPhysReg(MI, i, PhysReg);
00744       // Note: we don't update the def operand yet. That would cause the normal
00745       // def-scan to attempt spilling.
00746     } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
00747       DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
00748       // Reload the register, but don't assign to the operand just yet.
00749       // That would confuse the later phys-def processing pass.
00750       LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
00751       PartialDefs.push_back(LRI->PhysReg);
00752     }
00753   }
00754 
00755   DEBUG(dbgs() << "Allocating early clobbers.\n");
00756   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00757     MachineOperand &MO = MI->getOperand(i);
00758     if (!MO.isReg()) continue;
00759     unsigned Reg = MO.getReg();
00760     if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
00761     if (!MO.isEarlyClobber())
00762       continue;
00763     // Note: defineVirtReg may invalidate MO.
00764     LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
00765     unsigned PhysReg = LRI->PhysReg;
00766     if (setPhysReg(MI, i, PhysReg))
00767       VirtDead.push_back(Reg);
00768   }
00769 
00770   // Restore UsedInInstr to a state usable for allocating normal virtual uses.
00771   UsedInInstr.clear();
00772   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00773     MachineOperand &MO = MI->getOperand(i);
00774     if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
00775     unsigned Reg = MO.getReg();
00776     if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
00777     DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
00778                  << " as used in instr\n");
00779     markRegUsedInInstr(Reg);
00780   }
00781 
00782   // Also mark PartialDefs as used to avoid reallocation.
00783   for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
00784     markRegUsedInInstr(PartialDefs[i]);
00785 }
00786 
00787 void RAFast::AllocateBasicBlock() {
00788   DEBUG(dbgs() << "\nAllocating " << *MBB);
00789 
00790   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
00791   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
00792 
00793   MachineBasicBlock::iterator MII = MBB->begin();
00794 
00795   // Add live-in registers as live.
00796   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
00797          E = MBB->livein_end(); I != E; ++I)
00798     if (MRI->isAllocatable(*I))
00799       definePhysReg(MII, *I, regReserved);
00800 
00801   SmallVector<unsigned, 8> VirtDead;
00802   SmallVector<MachineInstr*, 32> Coalesced;
00803 
00804   // Otherwise, sequentially allocate each instruction in the MBB.
00805   while (MII != MBB->end()) {
00806     MachineInstr *MI = MII++;
00807     const MCInstrDesc &MCID = MI->getDesc();
00808     DEBUG({
00809         dbgs() << "\n>> " << *MI << "Regs:";
00810         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
00811           if (PhysRegState[Reg] == regDisabled) continue;
00812           dbgs() << " " << TRI->getName(Reg);
00813           switch(PhysRegState[Reg]) {
00814           case regFree:
00815             break;
00816           case regReserved:
00817             dbgs() << "*";
00818             break;
00819           default: {
00820             dbgs() << '=' << PrintReg(PhysRegState[Reg]);
00821             LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
00822             assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
00823             if (I->Dirty)
00824               dbgs() << "*";
00825             assert(I->PhysReg == Reg && "Bad inverse map");
00826             break;
00827           }
00828           }
00829         }
00830         dbgs() << '\n';
00831         // Check that LiveVirtRegs is the inverse.
00832         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
00833              e = LiveVirtRegs.end(); i != e; ++i) {
00834            assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
00835                   "Bad map key");
00836            assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
00837                   "Bad map value");
00838            assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
00839         }
00840       });
00841 
00842     // Debug values are not allowed to change codegen in any way.
00843     if (MI->isDebugValue()) {
00844       bool ScanDbgValue = true;
00845       while (ScanDbgValue) {
00846         ScanDbgValue = false;
00847         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00848           MachineOperand &MO = MI->getOperand(i);
00849           if (!MO.isReg()) continue;
00850           unsigned Reg = MO.getReg();
00851           if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
00852           LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
00853           if (LRI != LiveVirtRegs.end())
00854             setPhysReg(MI, i, LRI->PhysReg);
00855           else {
00856             int SS = StackSlotForVirtReg[Reg];
00857             if (SS == -1) {
00858               // We can't allocate a physreg for a DebugValue, sorry!
00859               DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
00860               MO.setReg(0);
00861             }
00862             else {
00863               // Modify DBG_VALUE now that the value is in a spill slot.
00864               bool IsIndirect = MI->isIndirectDebugValue();
00865               uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
00866               const MDNode *MDPtr =
00867                 MI->getOperand(MI->getNumOperands()-1).getMetadata();
00868               DebugLoc DL = MI->getDebugLoc();
00869               MachineBasicBlock *MBB = MI->getParent();
00870               MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
00871                                             TII->get(TargetOpcode::DBG_VALUE))
00872                   .addFrameIndex(SS).addImm(Offset).addMetadata(MDPtr);
00873               DEBUG(dbgs() << "Modifying debug info due to spill:"
00874                            << "\t" << *NewDV);
00875               // Scan NewDV operands from the beginning.
00876               MI = NewDV;
00877               ScanDbgValue = true;
00878               break;
00879             }
00880           }
00881           LiveDbgValueMap[Reg].push_back(MI);
00882         }
00883       }
00884       // Next instruction.
00885       continue;
00886     }
00887 
00888     // If this is a copy, we may be able to coalesce.
00889     unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
00890     if (MI->isCopy()) {
00891       CopyDst = MI->getOperand(0).getReg();
00892       CopySrc = MI->getOperand(1).getReg();
00893       CopyDstSub = MI->getOperand(0).getSubReg();
00894       CopySrcSub = MI->getOperand(1).getSubReg();
00895     }
00896 
00897     // Track registers used by instruction.
00898     UsedInInstr.clear();
00899 
00900     // First scan.
00901     // Mark physreg uses and early clobbers as used.
00902     // Find the end of the virtreg operands
00903     unsigned VirtOpEnd = 0;
00904     bool hasTiedOps = false;
00905     bool hasEarlyClobbers = false;
00906     bool hasPartialRedefs = false;
00907     bool hasPhysDefs = false;
00908     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00909       MachineOperand &MO = MI->getOperand(i);
00910       // Make sure MRI knows about registers clobbered by regmasks.
00911       if (MO.isRegMask()) {
00912         MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
00913         continue;
00914       }
00915       if (!MO.isReg()) continue;
00916       unsigned Reg = MO.getReg();
00917       if (!Reg) continue;
00918       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00919         VirtOpEnd = i+1;
00920         if (MO.isUse()) {
00921           hasTiedOps = hasTiedOps ||
00922                               MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
00923         } else {
00924           if (MO.isEarlyClobber())
00925             hasEarlyClobbers = true;
00926           if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
00927             hasPartialRedefs = true;
00928         }
00929         continue;
00930       }
00931       if (!MRI->isAllocatable(Reg)) continue;
00932       if (MO.isUse()) {
00933         usePhysReg(MO);
00934       } else if (MO.isEarlyClobber()) {
00935         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
00936                                regFree : regReserved);
00937         hasEarlyClobbers = true;
00938       } else
00939         hasPhysDefs = true;
00940     }
00941 
00942     // The instruction may have virtual register operands that must be allocated
00943     // the same register at use-time and def-time: early clobbers and tied
00944     // operands. If there are also physical defs, these registers must avoid
00945     // both physical defs and uses, making them more constrained than normal
00946     // operands.
00947     // Similarly, if there are multiple defs and tied operands, we must make
00948     // sure the same register is allocated to uses and defs.
00949     // We didn't detect inline asm tied operands above, so just make this extra
00950     // pass for all inline asm.
00951     if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
00952         (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
00953       handleThroughOperands(MI, VirtDead);
00954       // Don't attempt coalescing when we have funny stuff going on.
00955       CopyDst = 0;
00956       // Pretend we have early clobbers so the use operands get marked below.
00957       // This is not necessary for the common case of a single tied use.
00958       hasEarlyClobbers = true;
00959     }
00960 
00961     // Second scan.
00962     // Allocate virtreg uses.
00963     for (unsigned i = 0; i != VirtOpEnd; ++i) {
00964       MachineOperand &MO = MI->getOperand(i);
00965       if (!MO.isReg()) continue;
00966       unsigned Reg = MO.getReg();
00967       if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
00968       if (MO.isUse()) {
00969         LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
00970         unsigned PhysReg = LRI->PhysReg;
00971         CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
00972         if (setPhysReg(MI, i, PhysReg))
00973           killVirtReg(LRI);
00974       }
00975     }
00976 
00977     for (UsedInInstrSet::iterator
00978          I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
00979       MRI->setRegUnitUsed(*I);
00980 
00981     // Track registers defined by instruction - early clobbers and tied uses at
00982     // this point.
00983     UsedInInstr.clear();
00984     if (hasEarlyClobbers) {
00985       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00986         MachineOperand &MO = MI->getOperand(i);
00987         if (!MO.isReg()) continue;
00988         unsigned Reg = MO.getReg();
00989         if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
00990         // Look for physreg defs and tied uses.
00991         if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
00992         markRegUsedInInstr(Reg);
00993       }
00994     }
00995 
00996     unsigned DefOpEnd = MI->getNumOperands();
00997     if (MI->isCall()) {
00998       // Spill all virtregs before a call. This serves two purposes: 1. If an
00999       // exception is thrown, the landing pad is going to expect to find
01000       // registers in their spill slots, and 2. we don't have to wade through
01001       // all the <imp-def> operands on the call instruction.
01002       DefOpEnd = VirtOpEnd;
01003       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
01004       spillAll(MI);
01005 
01006       // The imp-defs are skipped below, but we still need to mark those
01007       // registers as used by the function.
01008       SkippedInstrs.insert(&MCID);
01009     }
01010 
01011     // Third scan.
01012     // Allocate defs and collect dead defs.
01013     for (unsigned i = 0; i != DefOpEnd; ++i) {
01014       MachineOperand &MO = MI->getOperand(i);
01015       if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
01016         continue;
01017       unsigned Reg = MO.getReg();
01018 
01019       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
01020         if (!MRI->isAllocatable(Reg)) continue;
01021         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
01022                                regFree : regReserved);
01023         continue;
01024       }
01025       LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
01026       unsigned PhysReg = LRI->PhysReg;
01027       if (setPhysReg(MI, i, PhysReg)) {
01028         VirtDead.push_back(Reg);
01029         CopyDst = 0; // cancel coalescing;
01030       } else
01031         CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
01032     }
01033 
01034     // Kill dead defs after the scan to ensure that multiple defs of the same
01035     // register are allocated identically. We didn't need to do this for uses
01036     // because we are crerating our own kill flags, and they are always at the
01037     // last use.
01038     for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
01039       killVirtReg(VirtDead[i]);
01040     VirtDead.clear();
01041 
01042     for (UsedInInstrSet::iterator
01043          I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
01044       MRI->setRegUnitUsed(*I);
01045 
01046     if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
01047       DEBUG(dbgs() << "-- coalescing: " << *MI);
01048       Coalesced.push_back(MI);
01049     } else {
01050       DEBUG(dbgs() << "<< " << *MI);
01051     }
01052   }
01053 
01054   // Spill all physical registers holding virtual registers now.
01055   DEBUG(dbgs() << "Spilling live registers at end of block.\n");
01056   spillAll(MBB->getFirstTerminator());
01057 
01058   // Erase all the coalesced copies. We are delaying it until now because
01059   // LiveVirtRegs might refer to the instrs.
01060   for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
01061     MBB->erase(Coalesced[i]);
01062   NumCopies += Coalesced.size();
01063 
01064   DEBUG(MBB->dump());
01065 }
01066 
01067 /// runOnMachineFunction - Register allocate the whole function
01068 ///
01069 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
01070   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
01071                << "********** Function: " << Fn.getName() << '\n');
01072   MF = &Fn;
01073   MRI = &MF->getRegInfo();
01074   TM = &Fn.getTarget();
01075   TRI = TM->getSubtargetImpl()->getRegisterInfo();
01076   TII = TM->getSubtargetImpl()->getInstrInfo();
01077   MRI->freezeReservedRegs(Fn);
01078   RegClassInfo.runOnMachineFunction(Fn);
01079   UsedInInstr.clear();
01080   UsedInInstr.setUniverse(TRI->getNumRegUnits());
01081 
01082   assert(!MRI->isSSA() && "regalloc requires leaving SSA");
01083 
01084   // initialize the virtual->physical register map to have a 'null'
01085   // mapping for all virtual registers
01086   StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
01087   LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
01088 
01089   // Loop over all of the basic blocks, eliminating virtual register references
01090   for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
01091        MBBi != MBBe; ++MBBi) {
01092     MBB = &*MBBi;
01093     AllocateBasicBlock();
01094   }
01095 
01096   // Add the clobber lists for all the instructions we skipped earlier.
01097   for (const MCInstrDesc *Desc : SkippedInstrs)
01098     if (const uint16_t *Defs = Desc->getImplicitDefs())
01099       while (*Defs)
01100         MRI->setPhysRegUsed(*Defs++);
01101 
01102   // All machine operands and other references to virtual registers have been
01103   // replaced. Remove the virtual registers.
01104   MRI->clearVirtRegs();
01105 
01106   SkippedInstrs.clear();
01107   StackSlotForVirtReg.clear();
01108   LiveDbgValueMap.clear();
01109   return true;
01110 }
01111 
01112 FunctionPass *llvm::createFastRegisterAllocator() {
01113   return new RAFast();
01114 }