Fix a coalescer bug wrt how dead copy interval is shortened.
[oota-llvm.git] / lib / CodeGen / RegAllocBigBlock.cpp
1 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
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 file implements the RABigBlock class
11 //
12 //===----------------------------------------------------------------------===//
13
14 // This register allocator is derived from RegAllocLocal.cpp. Like it, this
15 // allocator works on one basic block at a time, oblivious to others.
16 // However, the algorithm used here is suited for long blocks of
17 // instructions - registers are spilled by greedily choosing those holding
18 // values that will not be needed for the longest amount of time. This works
19 // particularly well for blocks with 10 or more times as many instructions
20 // as machine registers, but can be used for general code.
21 //
22 //===----------------------------------------------------------------------===//
23 //
24 // TODO: - automagically invoke linearscan for (groups of) small BBs?
25 //       - break ties when picking regs? (probably not worth it in a
26 //         JIT context)
27 //
28 //===----------------------------------------------------------------------===//
29
30 #define DEBUG_TYPE "regalloc"
31 #include "llvm/BasicBlock.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/LiveVariables.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/ADT/IndexedMap.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
48 #include <algorithm>
49 using namespace llvm;
50
51 STATISTIC(NumStores, "Number of stores added");
52 STATISTIC(NumLoads , "Number of loads added");
53 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
54
55 namespace {
56   static RegisterRegAlloc
57     bigBlockRegAlloc("bigblock", "  Big-block register allocator",
58                   createBigBlockRegisterAllocator);
59
60 /// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
61 /// keys.
62   struct VRegKeyInfo {
63     static inline unsigned getEmptyKey() { return -1U; }
64     static inline unsigned getTombstoneKey() { return -2U; }
65     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
66     static unsigned getHashValue(const unsigned &Key) { return Key; }
67   };
68
69
70 /// This register allocator is derived from RegAllocLocal.cpp. Like it, this
71 /// allocator works on one basic block at a time, oblivious to others.
72 /// However, the algorithm used here is suited for long blocks of
73 /// instructions - registers are spilled by greedily choosing those holding
74 /// values that will not be needed for the longest amount of time. This works
75 /// particularly well for blocks with 10 or more times as many instructions
76 /// as machine registers, but can be used for general code.
77 ///
78 /// TODO: - automagically invoke linearscan for (groups of) small BBs?
79 ///       - break ties when picking regs? (probably not worth it in a
80 ///         JIT context)
81 ///
82   class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
83   public:
84     static char ID;
85     RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
86   private:
87     /// TM - For getting at TargetMachine info 
88     ///
89     const TargetMachine *TM;
90     
91     /// MF - Our generic MachineFunction pointer
92     ///
93     MachineFunction *MF;
94     
95     /// RegInfo - For dealing with machine register info (aliases, folds
96     /// etc)
97     const TargetRegisterInfo *RegInfo;
98
99     typedef SmallVector<unsigned, 2> VRegTimes;
100
101     /// VRegReadTable - maps VRegs in a BB to the set of times they are read
102     ///
103     DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
104
105     /// VRegReadIdx - keeps track of the "current time" in terms of
106     /// positions in VRegReadTable
107     DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
108
109     /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
110     /// values are spilled.
111     IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
112
113     /// Virt2PhysRegMap - This map contains entries for each virtual register
114     /// that is currently available in a physical register.
115     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
116
117     /// PhysRegsUsed - This array is effectively a map, containing entries for
118     /// each physical register that currently has a value (ie, it is in
119     /// Virt2PhysRegMap).  The value mapped to is the virtual register
120     /// corresponding to the physical register (the inverse of the
121     /// Virt2PhysRegMap), or 0.  The value is set to 0 if this register is pinned
122     /// because it is used by a future instruction, and to -2 if it is not
123     /// allocatable.  If the entry for a physical register is -1, then the
124     /// physical register is "not in the map".
125     ///
126     std::vector<int> PhysRegsUsed;
127
128     /// VirtRegModified - This bitset contains information about which virtual
129     /// registers need to be spilled back to memory when their registers are
130     /// scavenged.  If a virtual register has simply been rematerialized, there
131     /// is no reason to spill it to memory when we need the register back.
132     ///
133     std::vector<int> VirtRegModified;
134
135     /// MBBLastInsnTime - the number of the the last instruction in MBB
136     ///
137     int MBBLastInsnTime;
138
139     /// MBBCurTime - the number of the the instruction being currently processed
140     ///
141     int MBBCurTime;
142
143     unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
144       return Virt2PhysRegMap[VirtReg];
145     }
146
147     unsigned &getVirt2StackSlot(unsigned VirtReg) {
148       return StackSlotForVirtReg[VirtReg];
149     }
150
151     /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
152     ///
153     void markVirtRegModified(unsigned Reg, bool Val = true) {
154       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
155       Reg -= TargetRegisterInfo::FirstVirtualRegister;
156       if (VirtRegModified.size() <= Reg)
157         VirtRegModified.resize(Reg+1);
158       VirtRegModified[Reg] = Val;
159     }
160     
161     /// isVirtRegModified - Lets us query the VirtRegModified bitset
162     ///
163     bool isVirtRegModified(unsigned Reg) const {
164       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
165       assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
166              && "Illegal virtual register!");
167       return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
168     }
169
170   public:
171     /// getPassName - returns the BigBlock allocator's name
172     ///
173     virtual const char *getPassName() const {
174       return "BigBlock Register Allocator";
175     }
176
177     /// getAnalaysisUsage - declares the required analyses
178     ///
179     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
180       AU.addRequiredID(PHIEliminationID);
181       AU.addRequiredID(TwoAddressInstructionPassID);
182       MachineFunctionPass::getAnalysisUsage(AU);
183     }
184
185   private:
186     /// runOnMachineFunction - Register allocate the whole function
187     ///
188     bool runOnMachineFunction(MachineFunction &Fn);
189
190     /// AllocateBasicBlock - Register allocate the specified basic block.
191     ///
192     void AllocateBasicBlock(MachineBasicBlock &MBB);
193
194     /// FillVRegReadTable - Fill out the table of vreg read times given a BB
195     ///
196     void FillVRegReadTable(MachineBasicBlock &MBB);
197     
198     /// areRegsEqual - This method returns true if the specified registers are
199     /// related to each other.  To do this, it checks to see if they are equal
200     /// or if the first register is in the alias set of the second register.
201     ///
202     bool areRegsEqual(unsigned R1, unsigned R2) const {
203       if (R1 == R2) return true;
204       for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
205            *AliasSet; ++AliasSet) {
206         if (*AliasSet == R1) return true;
207       }
208       return false;
209     }
210
211     /// getStackSpaceFor - This returns the frame index of the specified virtual
212     /// register on the stack, allocating space if necessary.
213     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
214
215     /// removePhysReg - This method marks the specified physical register as no
216     /// longer being in use.
217     ///
218     void removePhysReg(unsigned PhysReg);
219
220     /// spillVirtReg - This method spills the value specified by PhysReg into
221     /// the virtual register slot specified by VirtReg.  It then updates the RA
222     /// data structures to indicate the fact that PhysReg is now available.
223     ///
224     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
225                       unsigned VirtReg, unsigned PhysReg);
226
227     /// spillPhysReg - This method spills the specified physical register into
228     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
229     /// true, then the request is ignored if the physical register does not
230     /// contain a virtual register.
231     ///
232     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
233                       unsigned PhysReg, bool OnlyVirtRegs = false);
234
235     /// assignVirtToPhysReg - This method updates local state so that we know
236     /// that PhysReg is the proper container for VirtReg now.  The physical
237     /// register must not be used for anything else when this is called.
238     ///
239     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
240
241     /// isPhysRegAvailable - Return true if the specified physical register is
242     /// free and available for use.  This also includes checking to see if
243     /// aliased registers are all free...
244     ///
245     bool isPhysRegAvailable(unsigned PhysReg) const;
246
247     /// getFreeReg - Look to see if there is a free register available in the
248     /// specified register class.  If not, return 0.
249     ///
250     unsigned getFreeReg(const TargetRegisterClass *RC);
251
252     /// chooseReg - Pick a physical register to hold the specified
253     /// virtual register by choosing the one which will be read furthest
254     /// in the future.
255     ///
256     unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
257                     unsigned VirtReg);
258
259     /// reloadVirtReg - This method transforms the specified specified virtual
260     /// register use to refer to a physical register.  This method may do this
261     /// in one of several ways: if the register is available in a physical
262     /// register already, it uses that physical register.  If the value is not
263     /// in a physical register, and if there are physical registers available,
264     /// it loads it into a register.  If register pressure is high, and it is
265     /// possible, it tries to fold the load of the virtual register into the
266     /// instruction itself.  It avoids doing this if register pressure is low to
267     /// improve the chance that subsequent instructions can use the reloaded
268     /// value.  This method returns the modified instruction.
269     ///
270     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
271                                 unsigned OpNum);
272
273   };
274   char RABigBlock::ID = 0;
275 }
276
277 /// getStackSpaceFor - This allocates space for the specified virtual register
278 /// to be held on the stack.
279 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
280   // Find the location Reg would belong...
281   int FrameIdx = getVirt2StackSlot(VirtReg);
282
283   if (FrameIdx)
284     return FrameIdx - 1;          // Already has space allocated?
285
286   // Allocate a new stack object for this spill location...
287   FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
288                                                        RC->getAlignment());
289
290   // Assign the slot...
291   getVirt2StackSlot(VirtReg) = FrameIdx + 1;
292   return FrameIdx;
293 }
294
295
296 /// removePhysReg - This method marks the specified physical register as no
297 /// longer being in use.
298 ///
299 void RABigBlock::removePhysReg(unsigned PhysReg) {
300   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
301 }
302
303
304 /// spillVirtReg - This method spills the value specified by PhysReg into the
305 /// virtual register slot specified by VirtReg.  It then updates the RA data
306 /// structures to indicate the fact that PhysReg is now available.
307 ///
308 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
309                            MachineBasicBlock::iterator I,
310                            unsigned VirtReg, unsigned PhysReg) {
311   assert(VirtReg && "Spilling a physical register is illegal!"
312          " Must not have appropriate kill for the register or use exists beyond"
313          " the intended one.");
314   DOUT << "  Spilling register " << RegInfo->getName(PhysReg)
315        << " containing %reg" << VirtReg;
316   
317   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
318   
319   if (!isVirtRegModified(VirtReg))
320     DOUT << " which has not been modified, so no store necessary!";
321
322   // Otherwise, there is a virtual register corresponding to this physical
323   // register.  We only need to spill it into its stack slot if it has been
324   // modified.
325   if (isVirtRegModified(VirtReg)) {
326     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
327     int FrameIndex = getStackSpaceFor(VirtReg, RC);
328     DOUT << " to stack slot #" << FrameIndex;
329     TII->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
330     ++NumStores;   // Update statistics
331   }
332
333   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
334
335   DOUT << "\n";
336   removePhysReg(PhysReg);
337 }
338
339
340 /// spillPhysReg - This method spills the specified physical register into the
341 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
342 /// then the request is ignored if the physical register does not contain a
343 /// virtual register.
344 ///
345 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
346                            unsigned PhysReg, bool OnlyVirtRegs) {
347   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
348     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
349     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
350       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
351   } else {
352     // If the selected register aliases any other registers, we must make
353     // sure that one of the aliases isn't alive.
354     for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
355          *AliasSet; ++AliasSet)
356       if (PhysRegsUsed[*AliasSet] != -1 &&     // Spill aliased register.
357           PhysRegsUsed[*AliasSet] != -2)       // If allocatable.
358         if (PhysRegsUsed[*AliasSet])
359           spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
360   }
361 }
362
363
364 /// assignVirtToPhysReg - This method updates local state so that we know
365 /// that PhysReg is the proper container for VirtReg now.  The physical
366 /// register must not be used for anything else when this is called.
367 ///
368 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
369   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
370   // Update information to note the fact that this register was just used, and
371   // it holds VirtReg.
372   PhysRegsUsed[PhysReg] = VirtReg;
373   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
374 }
375
376
377 /// isPhysRegAvailable - Return true if the specified physical register is free
378 /// and available for use.  This also includes checking to see if aliased
379 /// registers are all free...
380 ///
381 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
382   if (PhysRegsUsed[PhysReg] != -1) return false;
383
384   // If the selected register aliases any other allocated registers, it is
385   // not free!
386   for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
387        *AliasSet; ++AliasSet)
388     if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
389       return false;                    // Can't use this reg then.
390   return true;
391 }
392
393   
394 /// getFreeReg - Look to see if there is a free register available in the
395 /// specified register class.  If not, return 0.
396 ///
397 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
398   // Get iterators defining the range of registers that are valid to allocate in
399   // this class, which also specifies the preferred allocation order.
400   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
401   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
402
403   for (; RI != RE; ++RI)
404     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
405       assert(*RI != 0 && "Cannot use register!");
406       return *RI; // Found an unused register!
407     }
408   return 0;
409 }
410
411
412 /// chooseReg - Pick a physical register to hold the specified
413 /// virtual register by choosing the one whose value will be read
414 /// furthest in the future.
415 ///
416 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
417                          unsigned VirtReg) {
418   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
419   // First check to see if we have a free register of the requested type...
420   unsigned PhysReg = getFreeReg(RC);
421
422   // If we didn't find an unused register, find the one which will be
423   // read at the most distant point in time.
424   if (PhysReg == 0) {
425     unsigned delay=0, longest_delay=0;
426     VRegTimes* ReadTimes;
427
428     unsigned curTime = MBBCurTime;
429
430     // for all physical regs in the RC,
431     for(TargetRegisterClass::iterator pReg = RC->begin(); 
432                                       pReg != RC->end();  ++pReg) {
433       // how long until they're read?
434       if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
435         ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
436         if(ReadTimes && !ReadTimes->empty()) {
437             unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
438             while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
439                 ++pt;
440             }
441
442             if(pt < ReadTimes->size())
443                 delay = (*ReadTimes)[pt] - curTime;
444             else
445                 delay = MBBLastInsnTime + 1 - curTime;
446         } else {
447             // This register is only defined, but never
448             // read in this MBB. Therefore the next read
449             // happens after the end of this MBB
450             delay = MBBLastInsnTime + 1 - curTime;
451         }
452
453         
454         if(delay > longest_delay) {
455           longest_delay = delay;
456           PhysReg = *pReg;
457         }
458       }
459     }
460
461     if(PhysReg == 0) { // ok, now we're desperate. We couldn't choose
462                        // a register to spill by looking through the
463                        // read timetable, so now we just spill the
464                        // first allocatable register we find.
465                        
466       // for all physical regs in the RC,
467       for(TargetRegisterClass::iterator pReg = RC->begin(); 
468                                         pReg != RC->end();  ++pReg) {
469         // if we find a register we can spill
470         if(PhysRegsUsed[*pReg]>=-1)
471           PhysReg = *pReg; // choose it to be spilled
472       }
473     }
474     
475     assert(PhysReg && "couldn't choose a register to spill :( ");
476     // TODO: assert that RC->contains(PhysReg) / handle aliased registers?
477
478     // since we needed to look in the table we need to spill this register.
479     spillPhysReg(MBB, I, PhysReg);
480   }
481
482   // assign the vreg to our chosen physical register
483   assignVirtToPhysReg(VirtReg, PhysReg);
484   return PhysReg; // and return it
485 }
486
487
488 /// reloadVirtReg - This method transforms an instruction with a virtual
489 /// register use to one that references a physical register. It does this as
490 /// follows:
491 ///
492 ///   1) If the register is already in a physical register, it uses it.
493 ///   2) Otherwise, if there is a free physical register, it uses that.
494 ///   3) Otherwise, it calls chooseReg() to get the physical register
495 ///      holding the most distantly needed value, generating a spill in
496 ///      the process.
497 ///
498 /// This method returns the modified instruction.
499 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
500                                      unsigned OpNum) {
501   unsigned VirtReg = MI->getOperand(OpNum).getReg();
502   const TargetInstrInfo* TII = MBB.getParent()->getTarget().getInstrInfo();
503
504   // If the virtual register is already available in a physical register,
505   // just update the instruction and return.
506   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
507     MI->getOperand(OpNum).setReg(PR);
508     return MI;
509   }
510
511   // Otherwise, if we have free physical registers available to hold the
512   // value, use them.
513   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
514   unsigned PhysReg = getFreeReg(RC);
515   int FrameIndex = getStackSpaceFor(VirtReg, RC);
516
517   if (PhysReg) {   // we have a free register, so use it.
518     assignVirtToPhysReg(VirtReg, PhysReg);
519   } else {  // no free registers available.
520     // try to fold the spill into the instruction
521     SmallVector<unsigned, 2> Ops;
522     Ops.push_back(OpNum);
523     if(MachineInstr* FMI = TII->foldMemoryOperand(*MF, MI, Ops, FrameIndex)) {
524       ++NumFolded;
525       FMI->copyKillDeadInfo(MI);
526       return MBB.insert(MBB.erase(MI), FMI);
527     }
528     
529     // determine which of the physical registers we'll kill off, since we
530     // couldn't fold.
531     PhysReg = chooseReg(MBB, MI, VirtReg);
532   }
533
534   // this virtual register is now unmodified (since we just reloaded it)
535   markVirtRegModified(VirtReg, false);
536
537   DOUT << "  Reloading %reg" << VirtReg << " into "
538        << RegInfo->getName(PhysReg) << "\n";
539
540   // Add move instruction(s)
541   TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
542   ++NumLoads;    // Update statistics
543
544   MF->getRegInfo().setPhysRegUsed(PhysReg);
545   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
546   return MI;
547 }
548
549 /// Fill out the vreg read timetable. Since ReadTime increases
550 /// monotonically, the individual readtime sets will be sorted
551 /// in ascending order.
552 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
553   // loop over each instruction
554   MachineBasicBlock::iterator MII;
555   unsigned ReadTime;
556   
557   for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
558     MachineInstr *MI = MII;
559     
560     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
561       MachineOperand& MO = MI->getOperand(i);
562       // look for vreg reads..
563       if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
564           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
565           // ..and add them to the read table.
566           VRegTimes* &Times = VRegReadTable[MO.getReg()];
567           if(!VRegReadTable[MO.getReg()]) {
568               Times = new VRegTimes;
569               VRegReadIdx[MO.getReg()] = 0;
570           }
571         Times->push_back(ReadTime);
572       }
573     }
574
575   }  
576
577   MBBLastInsnTime = ReadTime;
578
579   for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
580       Reads != VRegReadTable.end(); ++Reads) {
581       if(Reads->second) {
582           DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
583       }
584   }
585 }
586
587 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
588 /// read/mod/write register, i.e. update partial register.
589 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
590   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
591     MachineOperand& MO = MI->getOperand(i);
592     if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
593         MO.isDef() && !MO.isDead())
594       return true;
595   }
596   return false;
597 }
598
599 /// isReadModWriteImplicitDef - True if this is an implicit def for a
600 /// read/mod/write register, i.e. update partial register.
601 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
602   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603     MachineOperand& MO = MI->getOperand(i);
604     if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
605         !MO.isDef() && MO.isKill())
606       return true;
607   }
608   return false;
609 }
610
611
612 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
613   // loop over each instruction
614   MachineBasicBlock::iterator MII = MBB.begin();
615   const TargetInstrInfo &TII = *TM->getInstrInfo();
616   
617   DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
618         if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
619
620   // If this is the first basic block in the machine function, add live-in
621   // registers as active.
622   if (&MBB == &*MF->begin()) {
623     for (MachineRegisterInfo::livein_iterator
624          I = MF->getRegInfo().livein_begin(),
625          E = MF->getRegInfo().livein_end(); I != E; ++I) {
626       unsigned Reg = I->first;
627       MF->getRegInfo().setPhysRegUsed(Reg);
628       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
629       for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
630            *AliasSet; ++AliasSet) {
631         if (PhysRegsUsed[*AliasSet] != -2) {
632           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
633           MF->getRegInfo().setPhysRegUsed(*AliasSet);
634         }
635       }
636     }    
637   }
638   
639   // Otherwise, sequentially allocate each instruction in the MBB.
640   MBBCurTime = -1;
641   while (MII != MBB.end()) {
642     MachineInstr *MI = MII++;
643     MBBCurTime++;
644     const TargetInstrDesc &TID = MI->getDesc();
645     DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
646           DOUT << "  Regs have values: ";
647           for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
648             if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
649                DOUT << "[" << RegInfo->getName(i)
650                     << ",%reg" << PhysRegsUsed[i] << "] ";
651           DOUT << "\n");
652
653     SmallVector<unsigned, 8> Kills;
654     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
655       MachineOperand& MO = MI->getOperand(i);
656       if (MO.isRegister() && MO.isKill()) {
657         if (!MO.isImplicit())
658           Kills.push_back(MO.getReg());
659         else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
660           // These are extra physical register kills when a sub-register
661           // is defined (def of a sub-register is a read/mod/write of the
662           // larger registers). Ignore.
663           Kills.push_back(MO.getReg());
664       }
665     }
666
667     // Get the used operands into registers.  This has the potential to spill
668     // incoming values if we are out of registers.  Note that we completely
669     // ignore physical register uses here.  We assume that if an explicit
670     // physical register is referenced by the instruction, that it is guaranteed
671     // to be live-in, or the input is badly hosed.
672     //
673     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
674       MachineOperand& MO = MI->getOperand(i);
675       // here we are looking for only used operands (never def&use)
676       if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
677           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
678         MI = reloadVirtReg(MBB, MI, i);
679     }
680
681     // If this instruction is the last user of this register, kill the
682     // value, freeing the register being used, so it doesn't need to be
683     // spilled to memory.
684     //
685     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
686       unsigned VirtReg = Kills[i];
687       unsigned PhysReg = VirtReg;
688       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
689         // If the virtual register was never materialized into a register, it
690         // might not be in the map, but it won't hurt to zero it out anyway.
691         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
692         PhysReg = PhysRegSlot;
693         PhysRegSlot = 0;
694       } else if (PhysRegsUsed[PhysReg] == -2) {
695         // Unallocatable register dead, ignore.
696         continue;
697       } else {
698         assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
699                "Silently clearing a virtual register?");
700       }
701
702       if (PhysReg) {
703         DOUT << "  Last use of " << RegInfo->getName(PhysReg)
704              << "[%reg" << VirtReg <<"], removing it from live set\n";
705         removePhysReg(PhysReg);
706         for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
707              *AliasSet; ++AliasSet) {
708           if (PhysRegsUsed[*AliasSet] != -2) {
709             DOUT  << "  Last use of "
710                   << RegInfo->getName(*AliasSet)
711                   << "[%reg" << VirtReg <<"], removing it from live set\n";
712             removePhysReg(*AliasSet);
713           }
714         }
715       }
716     }
717
718     // Loop over all of the operands of the instruction, spilling registers that
719     // are defined, and marking explicit destinations in the PhysRegsUsed map.
720     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
721       MachineOperand& MO = MI->getOperand(i);
722       if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
723           TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
724         unsigned Reg = MO.getReg();
725         if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
726         // These are extra physical register defs when a sub-register
727         // is defined (def of a sub-register is a read/mod/write of the
728         // larger registers). Ignore.
729         if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
730
731         MF->getRegInfo().setPhysRegUsed(Reg);
732         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
733         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
734         for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
735              *AliasSet; ++AliasSet) {
736           if (PhysRegsUsed[*AliasSet] != -2) {
737             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
738             MF->getRegInfo().setPhysRegUsed(*AliasSet);
739           }
740         }
741       }
742     }
743
744     // Loop over the implicit defs, spilling them as well.
745     if (TID.getImplicitDefs()) {
746       for (const unsigned *ImplicitDefs = TID.getImplicitDefs();
747            *ImplicitDefs; ++ImplicitDefs) {
748         unsigned Reg = *ImplicitDefs;
749         if (PhysRegsUsed[Reg] != -2) {
750           spillPhysReg(MBB, MI, Reg, true);
751           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
752         }
753         MF->getRegInfo().setPhysRegUsed(Reg);
754         for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
755              *AliasSet; ++AliasSet) {
756           if (PhysRegsUsed[*AliasSet] != -2) {
757             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
758             MF->getRegInfo().setPhysRegUsed(*AliasSet);
759           }
760         }
761       }
762     }
763
764     SmallVector<unsigned, 8> DeadDefs;
765     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
766       MachineOperand& MO = MI->getOperand(i);
767       if (MO.isRegister() && MO.isDead())
768         DeadDefs.push_back(MO.getReg());
769     }
770
771     // Okay, we have allocated all of the source operands and spilled any values
772     // that would be destroyed by defs of this instruction.  Loop over the
773     // explicit defs and assign them to a register, spilling incoming values if
774     // we need to scavenge a register.
775     //
776     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
777       MachineOperand& MO = MI->getOperand(i);
778       if (MO.isRegister() && MO.isDef() && MO.getReg() &&
779           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
780         unsigned DestVirtReg = MO.getReg();
781         unsigned DestPhysReg;
782
783         // If DestVirtReg already has a value, use it.
784         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
785           DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
786         MF->getRegInfo().setPhysRegUsed(DestPhysReg);
787         markVirtRegModified(DestVirtReg);
788         MI->getOperand(i).setReg(DestPhysReg);  // Assign the output register
789       }
790     }
791
792     // If this instruction defines any registers that are immediately dead,
793     // kill them now.
794     //
795     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
796       unsigned VirtReg = DeadDefs[i];
797       unsigned PhysReg = VirtReg;
798       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
799         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
800         PhysReg = PhysRegSlot;
801         assert(PhysReg != 0);
802         PhysRegSlot = 0;
803       } else if (PhysRegsUsed[PhysReg] == -2) {
804         // Unallocatable register dead, ignore.
805         continue;
806       }
807
808       if (PhysReg) {
809         DOUT  << "  Register " << RegInfo->getName(PhysReg)
810               << " [%reg" << VirtReg
811               << "] is never used, removing it frame live list\n";
812         removePhysReg(PhysReg);
813         for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
814              *AliasSet; ++AliasSet) {
815           if (PhysRegsUsed[*AliasSet] != -2) {
816             DOUT  << "  Register " << RegInfo->getName(*AliasSet)
817                   << " [%reg" << *AliasSet
818                   << "] is never used, removing it frame live list\n";
819             removePhysReg(*AliasSet);
820           }
821         }
822       }
823     }
824     
825     // Finally, if this is a noop copy instruction, zap it.
826     unsigned SrcReg, DstReg;
827     if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
828       MBB.erase(MI);
829   }
830
831   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
832
833   // Spill all physical registers holding virtual registers now.
834   for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
835     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
836       if (unsigned VirtReg = PhysRegsUsed[i])
837         spillVirtReg(MBB, MI, VirtReg, i);
838       else
839         removePhysReg(i);
840     }
841 }
842
843 /// runOnMachineFunction - Register allocate the whole function
844 ///
845 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
846   DOUT << "Machine Function " << "\n";
847   MF = &Fn;
848   TM = &Fn.getTarget();
849   RegInfo = TM->getRegisterInfo();
850
851   PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
852   
853   // At various places we want to efficiently check to see whether a register
854   // is allocatable.  To handle this, we mark all unallocatable registers as
855   // being pinned down, permanently.
856   {
857     BitVector Allocable = RegInfo->getAllocatableSet(Fn);
858     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
859       if (!Allocable[i])
860         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
861   }
862
863   // initialize the virtual->physical register map to have a 'null'
864   // mapping for all virtual registers
865   Virt2PhysRegMap.grow(MF->getRegInfo().getLastVirtReg());
866   StackSlotForVirtReg.grow(MF->getRegInfo().getLastVirtReg());
867   VirtRegModified.resize(MF->getRegInfo().getLastVirtReg() - 
868                          TargetRegisterInfo::FirstVirtualRegister + 1, 0);
869
870   // Loop over all of the basic blocks, eliminating virtual register references
871   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
872        MBB != MBBe; ++MBB) {
873     // fill out the read timetable 
874     FillVRegReadTable(*MBB);
875     // use it to allocate the BB
876     AllocateBasicBlock(*MBB);
877     // clear it
878     VRegReadTable.clear();
879   }
880   
881   StackSlotForVirtReg.clear();
882   PhysRegsUsed.clear();
883   VirtRegModified.clear();
884   Virt2PhysRegMap.clear();
885   return true;
886 }
887
888 FunctionPass *llvm::createBigBlockRegisterAllocator() {
889   return new RABigBlock();
890 }
891