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