25595be468614169d0fd7153167af70a1011d242
[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/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 static cl::opt<bool> VerifyFastRegalloc("verify-fast-regalloc", cl::Hidden,
39     cl::desc("Verify machine code before fast regalloc"));
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                atEndOfBlock(false) {}
54   private:
55     const TargetMachine *TM;
56     MachineFunction *MF;
57     MachineRegisterInfo *MRI;
58     const TargetRegisterInfo *TRI;
59     const TargetInstrInfo *TII;
60
61     // Basic block currently being allocated.
62     MachineBasicBlock *MBB;
63
64     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
65     // values are spilled.
66     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
67
68     // Everything we know about a live virtual register.
69     struct LiveReg {
70       MachineInstr *LastUse;    // Last instr to use reg.
71       unsigned PhysReg;         // Currently held here.
72       unsigned short LastOpNum; // OpNum on LastUse.
73       bool Dirty;               // Register needs spill.
74
75       LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
76                               Dirty(false) {}
77     };
78
79     typedef DenseMap<unsigned, LiveReg> LiveRegMap;
80     typedef LiveRegMap::value_type LiveRegEntry;
81
82     // LiveVirtRegs - This map contains entries for each virtual register
83     // that is currently available in a physical register.
84     LiveRegMap LiveVirtRegs;
85
86     // RegState - Track the state of a physical register.
87     enum RegState {
88       // A disabled register is not available for allocation, but an alias may
89       // be in use. A register can only be moved out of the disabled state if
90       // all aliases are disabled.
91       regDisabled,
92
93       // A free register is not currently in use and can be allocated
94       // immediately without checking aliases.
95       regFree,
96
97       // A reserved register has been assigned expolicitly (e.g., setting up a
98       // call parameter), and it remains reserved until it is used.
99       regReserved
100
101       // A register state may also be a virtual register number, indication that
102       // the physical register is currently allocated to a virtual register. In
103       // that case, LiveVirtRegs contains the inverse mapping.
104     };
105
106     // PhysRegState - One of the RegState enums, or a virtreg.
107     std::vector<unsigned> PhysRegState;
108
109     // UsedInInstr - BitVector of physregs that are used in the current
110     // instruction, and so cannot be allocated.
111     BitVector UsedInInstr;
112
113     // Allocatable - vector of allocatable physical registers.
114     BitVector Allocatable;
115
116     // atEndOfBlock - This flag is set after allocating all instructions in a
117     // block, before emitting final spills. When it is set, LiveRegMap is no
118     // longer updated properly sonce it will be cleared anyway.
119     bool atEndOfBlock;
120
121   public:
122     virtual const char *getPassName() const {
123       return "Fast Register Allocator";
124     }
125
126     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
127       AU.setPreservesCFG();
128       AU.addRequiredID(PHIEliminationID);
129       AU.addRequiredID(TwoAddressInstructionPassID);
130       MachineFunctionPass::getAnalysisUsage(AU);
131     }
132
133   private:
134     bool runOnMachineFunction(MachineFunction &Fn);
135     void AllocateBasicBlock();
136     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
137     bool isLastUseOfLocalReg(MachineOperand&);
138
139     void addKillFlag(const LiveReg&);
140     void killVirtReg(LiveRegMap::iterator i);
141     void killVirtReg(unsigned VirtReg);
142     void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator i,
143                       bool isKill);
144     void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg,
145                       bool isKill);
146
147     void usePhysReg(MachineOperand&);
148     void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
149     void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
150     void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
151     unsigned defineVirtReg(MachineInstr *MI, unsigned OpNum,
152                            unsigned VirtReg, unsigned Hint);
153     unsigned reloadVirtReg(MachineInstr *MI, unsigned OpNum,
154                            unsigned VirtReg, unsigned Hint);
155     void spillAll(MachineInstr *MI);
156     void setPhysReg(MachineOperand &MO, unsigned PhysReg);
157   };
158   char RAFast::ID = 0;
159 }
160
161 /// getStackSpaceFor - This allocates space for the specified virtual register
162 /// to be held on the stack.
163 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
164   // Find the location Reg would belong...
165   int SS = StackSlotForVirtReg[VirtReg];
166   if (SS != -1)
167     return SS;          // Already has space allocated?
168
169   // Allocate a new stack object for this spill location...
170   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
171                                                             RC->getAlignment());
172
173   // Assign the slot.
174   StackSlotForVirtReg[VirtReg] = FrameIdx;
175   return FrameIdx;
176 }
177
178 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
179 /// its virtual register, and it is guaranteed to be a block-local register.
180 ///
181 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
182   // Check for non-debug uses or defs following MO.
183   // This is the most likely way to fail - fast path it.
184   MachineOperand *i = &MO;
185   while ((i = i->getNextOperandForReg()))
186     if (!i->isDebug())
187       return false;
188
189   // If the register has ever been spilled or reloaded, we conservatively assume
190   // it is a global register used in multiple blocks.
191   if (StackSlotForVirtReg[MO.getReg()] != -1)
192     return false;
193
194   // Check that the use/def chain has exactly one operand - MO.
195   return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
196 }
197
198 /// addKillFlag - Set kill flags on last use of a virtual register.
199 void RAFast::addKillFlag(const LiveReg &LR) {
200   if (!LR.LastUse) return;
201   MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
202   if (MO.isDef())
203     MO.setIsDead();
204   else if (!LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum))
205     MO.setIsKill();
206 }
207
208 /// killVirtReg - Mark virtreg as no longer available.
209 void RAFast::killVirtReg(LiveRegMap::iterator lri) {
210   addKillFlag(lri->second);
211   const LiveReg &LR = lri->second;
212   assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
213   PhysRegState[LR.PhysReg] = regFree;
214   // Erase from LiveVirtRegs unless we're at the end of the block when
215   // everything will be bulk erased.
216   if (!atEndOfBlock)
217     LiveVirtRegs.erase(lri);
218 }
219
220 /// killVirtReg - Mark virtreg as no longer available.
221 void RAFast::killVirtReg(unsigned VirtReg) {
222   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
223          "killVirtReg needs a virtual register");
224   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
225   if (lri != LiveVirtRegs.end())
226     killVirtReg(lri);
227 }
228
229 /// spillVirtReg - This method spills the value specified by VirtReg into the
230 /// corresponding stack slot if needed. If isKill is set, the register is also
231 /// killed.
232 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
233                           unsigned VirtReg, bool isKill) {
234   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
235          "Spilling a physical register is illegal!");
236   LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
237   assert(lri != LiveVirtRegs.end() && "Spilling unmapped virtual register");
238   spillVirtReg(MI, lri, isKill);
239 }
240
241 /// spillVirtReg - Do the actual work of spilling.
242 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
243                           LiveRegMap::iterator lri, bool isKill) {
244   LiveReg &LR = lri->second;
245   assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
246
247   // If this physreg is used by the instruction, we want to kill it on the
248   // instruction, not on the spill.
249   bool spillKill = isKill && LR.LastUse != MI;
250
251   if (LR.Dirty) {
252     LR.Dirty = false;
253     DEBUG(dbgs() << "Spilling %reg" << lri->first
254                  << " in " << TRI->getName(LR.PhysReg));
255     const TargetRegisterClass *RC = MRI->getRegClass(lri->first);
256     int FI = getStackSpaceFor(lri->first, RC);
257     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
258     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, spillKill, FI, RC, TRI);
259     ++NumStores;   // Update statistics
260
261     if (spillKill)
262       LR.LastUse = 0; // Don't kill register again
263     else if (!isKill) {
264       MachineInstr *Spill = llvm::prior(MI);
265       LR.LastUse = Spill;
266       LR.LastOpNum = Spill->findRegisterUseOperandIdx(LR.PhysReg);
267     }
268   }
269
270   if (isKill)
271     killVirtReg(lri);
272 }
273
274 /// spillAll - Spill all dirty virtregs without killing them.
275 void RAFast::spillAll(MachineInstr *MI) {
276   SmallVector<unsigned, 16> Dirty;
277   for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
278        e = LiveVirtRegs.end(); i != e; ++i)
279     if (i->second.Dirty)
280       Dirty.push_back(i->first);
281   for (unsigned i = 0, e = Dirty.size(); i != e; ++i)
282     spillVirtReg(MI, Dirty[i], false);
283 }
284
285 /// usePhysReg - Handle the direct use of a physical register.
286 /// Check that the register is not used by a virtreg.
287 /// Kill the physreg, marking it free.
288 /// This may add implicit kills to MO->getParent() and invalidate MO.
289 void RAFast::usePhysReg(MachineOperand &MO) {
290   unsigned PhysReg = MO.getReg();
291   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
292          "Bad usePhysReg operand");
293
294   switch (PhysRegState[PhysReg]) {
295   case regDisabled:
296     break;
297   case regReserved:
298     PhysRegState[PhysReg] = regFree;
299     // Fall through
300   case regFree:
301     UsedInInstr.set(PhysReg);
302     MO.setIsKill();
303     return;
304   default:
305     // The physreg was allocated to a virtual register. That means to value we
306     // wanted has been clobbered.
307     llvm_unreachable("Instruction uses an allocated register");
308   }
309
310   // Maybe a superregister is reserved?
311   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
312        unsigned Alias = *AS; ++AS) {
313     switch (PhysRegState[Alias]) {
314     case regDisabled:
315       break;
316     case regReserved:
317       assert(TRI->isSuperRegister(PhysReg, Alias) &&
318              "Instruction is not using a subregister of a reserved register");
319       // Leave the superregister in the working set.
320       PhysRegState[Alias] = regFree;
321       UsedInInstr.set(Alias);
322       MO.getParent()->addRegisterKilled(Alias, TRI, true);
323       return;
324     case regFree:
325       if (TRI->isSuperRegister(PhysReg, Alias)) {
326         // Leave the superregister in the working set.
327         UsedInInstr.set(Alias);
328         MO.getParent()->addRegisterKilled(Alias, TRI, true);
329         return;
330       }
331       // Some other alias was in the working set - clear it.
332       PhysRegState[Alias] = regDisabled;
333       break;
334     default:
335       llvm_unreachable("Instruction uses an alias of an allocated register");
336     }
337   }
338
339   // All aliases are disabled, bring register into working set.
340   PhysRegState[PhysReg] = regFree;
341   UsedInInstr.set(PhysReg);
342   MO.setIsKill();
343 }
344
345 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
346 /// virtregs. This is very similar to defineVirtReg except the physreg is
347 /// reserved instead of allocated.
348 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
349                            RegState NewState) {
350   UsedInInstr.set(PhysReg);
351   switch (unsigned VirtReg = PhysRegState[PhysReg]) {
352   case regDisabled:
353     break;
354   default:
355     spillVirtReg(MI, VirtReg, true);
356     // Fall through.
357   case regFree:
358   case regReserved:
359     PhysRegState[PhysReg] = NewState;
360     return;
361   }
362
363   // This is a disabled register, disable all aliases.
364   PhysRegState[PhysReg] = NewState;
365   for (const unsigned *AS = TRI->getAliasSet(PhysReg);
366        unsigned Alias = *AS; ++AS) {
367     UsedInInstr.set(Alias);
368     switch (unsigned VirtReg = PhysRegState[Alias]) {
369     case regDisabled:
370       break;
371     default:
372       spillVirtReg(MI, VirtReg, true);
373       // Fall through.
374     case regFree:
375     case regReserved:
376       PhysRegState[Alias] = regDisabled;
377       if (TRI->isSuperRegister(PhysReg, Alias))
378         return;
379       break;
380     }
381   }
382 }
383
384
385 /// assignVirtToPhysReg - This method updates local state so that we know
386 /// that PhysReg is the proper container for VirtReg now.  The physical
387 /// register must not be used for anything else when this is called.
388 ///
389 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
390   DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
391                << TRI->getName(PhysReg) << "\n");
392   PhysRegState[PhysReg] = LRE.first;
393   assert(!LRE.second.PhysReg && "Already assigned a physreg");
394   LRE.second.PhysReg = PhysReg;
395 }
396
397 /// allocVirtReg - Allocate a physical register for VirtReg.
398 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
399   const unsigned spillCost = 100;
400   const unsigned VirtReg = LRE.first;
401
402   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
403          "Can only allocate virtual registers");
404
405   const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
406   TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
407   TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
408
409   // Ignore invalid hints.
410   if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
411                !RC->contains(Hint) || UsedInInstr.test(Hint) ||
412                !Allocatable.test(Hint)))
413     Hint = 0;
414
415   // If there is no hint, peek at the first use of this register.
416   if (!Hint && !MRI->use_nodbg_empty(VirtReg)) {
417     MachineInstr &MI = *MRI->use_nodbg_begin(VirtReg);
418     unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
419     // Copy to physreg -> use physreg as hint.
420     if (TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
421         SrcReg == VirtReg && TargetRegisterInfo::isPhysicalRegister(DstReg) &&
422         RC->contains(DstReg) && !UsedInInstr.test(DstReg) &&
423         Allocatable.test(DstReg)) {
424       Hint = DstReg;
425       DEBUG(dbgs() << "%reg" << VirtReg << " gets hint from " << MI);
426     }
427   }
428
429   // Take hint when possible.
430   if (Hint) {
431     assert(RC->contains(Hint) && !UsedInInstr.test(Hint) &&
432            Allocatable.test(Hint) && "Invalid hint should have been cleared");
433     switch(PhysRegState[Hint]) {
434     case regDisabled:
435     case regReserved:
436       break;
437     default:
438       spillVirtReg(MI, PhysRegState[Hint], true);
439       // Fall through.
440     case regFree:
441       return assignVirtToPhysReg(LRE, Hint);
442     }
443   }
444
445   // First try to find a completely free register.
446   unsigned BestCost = 0, BestReg = 0;
447   bool hasDisabled = false;
448   for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
449     unsigned PhysReg = *I;
450     switch(PhysRegState[PhysReg]) {
451     case regDisabled:
452       hasDisabled = true;
453     case regReserved:
454       continue;
455     case regFree:
456       if (!UsedInInstr.test(PhysReg))
457         return assignVirtToPhysReg(LRE, PhysReg);
458       continue;
459     default:
460       // Grab the first spillable register we meet.
461       if (!BestReg && !UsedInInstr.test(PhysReg))
462         BestReg = PhysReg, BestCost = spillCost;
463       continue;
464     }
465   }
466
467   DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
468                << " candidate=" << TRI->getName(BestReg) << "\n");
469
470   // Try to extend the working set for RC if there were any disabled registers.
471   if (hasDisabled && (!BestReg || BestCost >= spillCost)) {
472     for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
473       unsigned PhysReg = *I;
474       if (PhysRegState[PhysReg] != regDisabled || UsedInInstr.test(PhysReg))
475         continue;
476
477       // Calculate the cost of bringing PhysReg into the working set.
478       unsigned Cost=0;
479       bool Impossible = false;
480       for (const unsigned *AS = TRI->getAliasSet(PhysReg);
481       unsigned Alias = *AS; ++AS) {
482         if (UsedInInstr.test(Alias)) {
483           Impossible = true;
484           break;
485         }
486         switch (PhysRegState[Alias]) {
487         case regDisabled:
488           break;
489         case regReserved:
490           Impossible = true;
491           break;
492         case regFree:
493           Cost++;
494           break;
495         default:
496           Cost += spillCost;
497           break;
498         }
499       }
500       if (Impossible) continue;
501       DEBUG(dbgs() << "- candidate " << TRI->getName(PhysReg)
502         << " cost=" << Cost << "\n");
503       if (!BestReg || Cost < BestCost) {
504         BestReg = PhysReg;
505         BestCost = Cost;
506         if (Cost < spillCost) break;
507       }
508     }
509   }
510
511   if (BestReg) {
512     // BestCost is 0 when all aliases are already disabled.
513     if (BestCost) {
514       if (PhysRegState[BestReg] != regDisabled)
515         spillVirtReg(MI, PhysRegState[BestReg], true);
516       else {
517         // Make sure all aliases are disabled.
518         for (const unsigned *AS = TRI->getAliasSet(BestReg);
519              unsigned Alias = *AS; ++AS) {
520           switch (PhysRegState[Alias]) {
521           case regDisabled:
522             continue;
523           case regFree:
524             PhysRegState[Alias] = regDisabled;
525             break;
526           default:
527             spillVirtReg(MI, PhysRegState[Alias], true);
528             PhysRegState[Alias] = regDisabled;
529             break;
530           }
531         }
532       }
533     }
534     return assignVirtToPhysReg(LRE, BestReg);
535   }
536
537   // Nothing we can do.
538   std::string msg;
539   raw_string_ostream Msg(msg);
540   Msg << "Ran out of registers during register allocation!";
541   if (MI->isInlineAsm()) {
542     Msg << "\nPlease check your inline asm statement for "
543         << "invalid constraints:\n";
544     MI->print(Msg, TM);
545   }
546   report_fatal_error(Msg.str());
547 }
548
549 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
550 unsigned RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
551                                unsigned VirtReg, unsigned Hint) {
552   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
553          "Not a virtual register");
554   LiveRegMap::iterator lri;
555   bool New;
556   tie(lri, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
557   LiveReg &LR = lri->second;
558   if (New)
559     allocVirtReg(MI, *lri, Hint);
560   else
561     addKillFlag(LR); // Kill before redefine.
562   assert(LR.PhysReg && "Register not assigned");
563   LR.LastUse = MI;
564   LR.LastOpNum = OpNum;
565   LR.Dirty = true;
566   UsedInInstr.set(LR.PhysReg);
567   return LR.PhysReg;
568 }
569
570 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
571 unsigned RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
572                                unsigned VirtReg, unsigned Hint) {
573   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
574          "Not a virtual register");
575   LiveRegMap::iterator lri;
576   bool New;
577   tie(lri, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
578   LiveReg &LR = lri->second;
579   if (New) {
580     allocVirtReg(MI, *lri, Hint);
581     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
582     int FrameIndex = getStackSpaceFor(VirtReg, RC);
583     DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
584                  << TRI->getName(LR.PhysReg) << "\n");
585     TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
586     ++NumLoads;
587   } else if (LR.Dirty) {
588     MachineOperand &MO = MI->getOperand(OpNum);
589     if (isLastUseOfLocalReg(MO)) {
590       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
591       MO.setIsKill();
592     } else if (MO.isKill()) {
593       DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
594       MO.setIsKill(false);
595     }
596   }
597   assert(LR.PhysReg && "Register not assigned");
598   LR.LastUse = MI;
599   LR.LastOpNum = OpNum;
600   UsedInInstr.set(LR.PhysReg);
601   return LR.PhysReg;
602 }
603
604 // setPhysReg - Change MO the refer the PhysReg, considering subregs.
605 void RAFast::setPhysReg(MachineOperand &MO, unsigned PhysReg) {
606   if (unsigned Idx = MO.getSubReg()) {
607     MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, Idx) : 0);
608     MO.setSubReg(0);
609   } else
610     MO.setReg(PhysReg);
611 }
612
613 void RAFast::AllocateBasicBlock() {
614   DEBUG(dbgs() << "\nAllocating " << *MBB);
615
616   atEndOfBlock = false;
617   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
618   assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
619
620   MachineBasicBlock::iterator MII = MBB->begin();
621
622   // Add live-in registers as live.
623   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
624          E = MBB->livein_end(); I != E; ++I)
625     definePhysReg(MII, *I, regReserved);
626
627   SmallVector<unsigned, 8> VirtKills, PhysDefs;
628   SmallVector<MachineInstr*, 32> Coalesced;
629
630   // Otherwise, sequentially allocate each instruction in the MBB.
631   while (MII != MBB->end()) {
632     MachineInstr *MI = MII++;
633     const TargetInstrDesc &TID = MI->getDesc();
634     DEBUG({
635         dbgs() << "\n>> " << *MI << "Regs:";
636         for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
637           if (PhysRegState[Reg] == regDisabled) continue;
638           dbgs() << " " << TRI->getName(Reg);
639           switch(PhysRegState[Reg]) {
640           case regFree:
641             break;
642           case regReserved:
643             dbgs() << "*";
644             break;
645           default:
646             dbgs() << "=%reg" << PhysRegState[Reg];
647             if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
648               dbgs() << "*";
649             assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
650                    "Bad inverse map");
651             break;
652           }
653         }
654         dbgs() << '\n';
655         // Check that LiveVirtRegs is the inverse.
656         for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
657              e = LiveVirtRegs.end(); i != e; ++i) {
658            assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
659                   "Bad map key");
660            assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
661                   "Bad map value");
662            assert(PhysRegState[i->second.PhysReg] == i->first &&
663                   "Bad inverse map");
664         }
665       });
666
667     // Debug values are not allowed to change codegen in any way.
668     if (MI->isDebugValue()) {
669       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
670         MachineOperand &MO = MI->getOperand(i);
671         if (!MO.isReg()) continue;
672         unsigned Reg = MO.getReg();
673         if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
674         LiveRegMap::iterator lri = LiveVirtRegs.find(Reg);
675         if (lri != LiveVirtRegs.end())
676           setPhysReg(MO, lri->second.PhysReg);
677         else
678           MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
679       }
680       // Next instruction.
681       continue;
682     }
683
684     // If this is a copy, we may be able to coalesce.
685     unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
686     if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
687       CopySrc = CopyDst = 0;
688
689     // Track registers used by instruction.
690     UsedInInstr.reset();
691     PhysDefs.clear();
692
693     // First scan.
694     // Mark physreg uses and early clobbers as used.
695     // Find the end of the virtreg operands
696     unsigned VirtOpEnd = 0;
697     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
698       MachineOperand &MO = MI->getOperand(i);
699       if (!MO.isReg()) continue;
700       unsigned Reg = MO.getReg();
701       if (!Reg) continue;
702       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
703         VirtOpEnd = i+1;
704         continue;
705       }
706       if (!Allocatable.test(Reg)) continue;
707       if (MO.isUse()) {
708         usePhysReg(MO);
709       } else if (MO.isEarlyClobber()) {
710         definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
711         PhysDefs.push_back(Reg);
712       }
713     }
714
715     // Second scan.
716     // Allocate virtreg uses and early clobbers.
717     // Collect VirtKills
718     for (unsigned i = 0; i != VirtOpEnd; ++i) {
719       MachineOperand &MO = MI->getOperand(i);
720       if (!MO.isReg()) continue;
721       unsigned Reg = MO.getReg();
722       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
723       if (MO.isUse()) {
724         unsigned PhysReg = reloadVirtReg(MI, i, Reg, CopyDst);
725         CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
726         setPhysReg(MO, PhysReg);
727         if (MO.isKill())
728           VirtKills.push_back(Reg);
729       } else if (MO.isEarlyClobber()) {
730         unsigned PhysReg = defineVirtReg(MI, i, Reg, 0);
731         setPhysReg(MO, PhysReg);
732         PhysDefs.push_back(PhysReg);
733       }
734     }
735
736     // Process virtreg kills
737     for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
738       killVirtReg(VirtKills[i]);
739     VirtKills.clear();
740
741     MRI->addPhysRegsUsed(UsedInInstr);
742
743     // Track registers defined by instruction - early clobbers at this point.
744     UsedInInstr.reset();
745     for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
746       unsigned PhysReg = PhysDefs[i];
747       UsedInInstr.set(PhysReg);
748       for (const unsigned *AS = TRI->getAliasSet(PhysReg);
749             unsigned Alias = *AS; ++AS)
750         UsedInInstr.set(Alias);
751     }
752
753     // Third scan.
754     // Allocate defs and collect dead defs.
755     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
756       MachineOperand &MO = MI->getOperand(i);
757       if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue;
758       unsigned Reg = MO.getReg();
759
760       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
761         if (!Allocatable.test(Reg)) continue;
762         definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
763                                regFree : regReserved);
764         continue;
765       }
766       unsigned PhysReg = defineVirtReg(MI, i, Reg, CopySrc);
767       if (MO.isDead()) {
768         VirtKills.push_back(Reg);
769         CopyDst = 0; // cancel coalescing;
770       } else
771         CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
772       setPhysReg(MO, PhysReg);
773     }
774
775     // Spill all dirty virtregs before a call, in case of an exception.
776     if (TID.isCall()) {
777       DEBUG(dbgs() << "  Spilling remaining registers before call.\n");
778       spillAll(MI);
779     }
780
781     // Process virtreg deads.
782     for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
783       killVirtReg(VirtKills[i]);
784     VirtKills.clear();
785
786     MRI->addPhysRegsUsed(UsedInInstr);
787
788     if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
789       DEBUG(dbgs() << "-- coalescing: " << *MI);
790       Coalesced.push_back(MI);
791     } else {
792       DEBUG(dbgs() << "<< " << *MI);
793     }
794   }
795
796   // Spill all physical registers holding virtual registers now.
797   atEndOfBlock = true;
798   MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
799   if (MI != MBB->end() && MI->getDesc().isReturn()) {
800     // This is a return block, kill all virtual registers.
801     DEBUG(dbgs() << "Killing live registers at end of return block.\n");
802     for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
803          i != e; ++i)
804       killVirtReg(i);
805   } else {
806     // This is a normal block, spill any dirty virtregs.
807     DEBUG(dbgs() << "Spilling live registers at end of block.\n");
808     for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
809         i != e; ++i)
810       spillVirtReg(MI, i, true);
811   }
812   LiveVirtRegs.clear();
813
814   // Erase all the coalesced copies. We are delaying it until now because
815   // LiveVirtsRegs might refer to the instrs.
816   for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
817     MBB->erase(Coalesced[i]);
818   NumCopies += Coalesced.size();
819
820   DEBUG(MBB->dump());
821 }
822
823 /// runOnMachineFunction - Register allocate the whole function
824 ///
825 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
826   DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
827                << "********** Function: "
828                << ((Value*)Fn.getFunction())->getName() << '\n');
829   if (VerifyFastRegalloc)
830     Fn.verify(this, true);
831   MF = &Fn;
832   MRI = &MF->getRegInfo();
833   TM = &Fn.getTarget();
834   TRI = TM->getRegisterInfo();
835   TII = TM->getInstrInfo();
836
837   UsedInInstr.resize(TRI->getNumRegs());
838   Allocatable = TRI->getAllocatableSet(*MF);
839
840   // initialize the virtual->physical register map to have a 'null'
841   // mapping for all virtual registers
842   unsigned LastVirtReg = MRI->getLastVirtReg();
843   StackSlotForVirtReg.grow(LastVirtReg);
844
845   // Loop over all of the basic blocks, eliminating virtual register references
846   for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
847        MBBi != MBBe; ++MBBi) {
848     MBB = &*MBBi;
849     AllocateBasicBlock();
850   }
851
852   // Make sure the set of used physregs is closed under subreg operations.
853   MRI->closePhysRegsUsed(*TRI);
854
855   StackSlotForVirtReg.clear();
856   return true;
857 }
858
859 FunctionPass *llvm::createFastRegisterAllocator() {
860   return new RAFast();
861 }