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