6a8dd6572e5bc9f6e6ed9dbfcd96881484eea482
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a linear scan register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "regalloc"
14 #include "llvm/Function.h"
15 #include "llvm/CodeGen/LiveIntervals.h"
16 #include "llvm/CodeGen/LiveVariables.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegInfo.h"
26 #include "llvm/Support/CFG.h"
27 #include "Support/Debug.h"
28 #include "Support/DepthFirstIterator.h"
29 #include "Support/Statistic.h"
30 #include "Support/STLExtras.h"
31 #include <iostream>
32
33 using namespace llvm;
34
35 namespace {
36     Statistic<> numSpilled ("ra-linearscan", "Number of registers spilled");
37
38     class RA : public MachineFunctionPass {
39     public:
40         typedef std::vector<const LiveIntervals::Interval*> IntervalPtrs;
41
42     private:
43         MachineFunction* mf_;
44         const TargetMachine* tm_;
45         const MRegisterInfo* mri_;
46         MachineBasicBlock* currentMbb_;
47         MachineBasicBlock::iterator currentInstr_;
48         typedef LiveIntervals::Intervals Intervals;
49         const Intervals* li_;
50         IntervalPtrs active_, inactive_;
51
52         typedef std::vector<unsigned> Regs;
53         Regs tempUseOperands_;
54         Regs tempDefOperands_;
55
56         Regs reserved_;
57
58         typedef LiveIntervals::MachineBasicBlockPtrs MachineBasicBlockPtrs;
59         MachineBasicBlockPtrs mbbs_;
60
61         typedef std::vector<unsigned> Phys2VirtMap;
62         Phys2VirtMap p2vMap_;
63
64         typedef std::map<unsigned, unsigned> Virt2PhysMap;
65         Virt2PhysMap v2pMap_;
66
67         typedef std::map<unsigned, int> Virt2StackSlotMap;
68         Virt2StackSlotMap v2ssMap_;
69
70         int instrAdded_;
71
72     public:
73         virtual const char* getPassName() const {
74             return "Linear Scan Register Allocator";
75         }
76
77         virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78             AU.addRequired<LiveVariables>();
79             AU.addRequired<LiveIntervals>();
80             MachineFunctionPass::getAnalysisUsage(AU);
81         }
82
83     private:
84         /// runOnMachineFunction - register allocate the whole function
85         bool runOnMachineFunction(MachineFunction&);
86
87         /// processActiveIntervals - expire old intervals and move
88         /// non-overlapping ones to the incative list
89         void processActiveIntervals(Intervals::const_iterator cur);
90
91         /// processInactiveIntervals - expire old intervals and move
92         /// overlapping ones to the active list
93         void processInactiveIntervals(Intervals::const_iterator cur);
94
95         /// assignStackSlotAtInterval - choose and spill
96         /// interval. Currently we spill the interval with the last
97         /// end point in the active and inactive lists and the current
98         /// interval
99         void assignStackSlotAtInterval(Intervals::const_iterator cur);
100
101         ///
102         /// register handling helpers
103         ///
104
105         /// reservePhysReg - reserves a physical register and spills
106         /// any value assigned to it if any
107         void reservePhysReg(unsigned reg);
108
109         /// clearReservedPhysReg - marks pysical register as free for
110         /// use
111         void clearReservedPhysReg(unsigned reg);
112
113         /// physRegAvailable - returns true if the specifed physical
114         /// register is available
115         bool physRegAvailable(unsigned physReg);
116
117         /// getFreePhysReg - return a free physical register for this
118         /// virtual register if we have one, otherwise return 0
119         unsigned getFreePhysReg(unsigned virtReg);
120
121
122         /// tempPhysRegAvailable - returns true if the specifed
123         /// temporary physical register is available
124         bool tempPhysRegAvailable(unsigned physReg);
125
126         /// getFreeTempPhysReg - return a free temprorary physical
127         /// register for this register class if we have one (should
128         /// never return 0)
129         unsigned getFreeTempPhysReg(const TargetRegisterClass* rc);
130
131         /// getFreeTempPhysReg - return a free temprorary physical
132         /// register for this virtual register if we have one (should
133         /// never return 0)
134         unsigned getFreeTempPhysReg(unsigned virtReg) {
135             const TargetRegisterClass* rc =
136                 mf_->getSSARegMap()->getRegClass(virtReg);
137             return getFreeTempPhysReg(rc);
138         }
139
140         /// assignVirt2PhysReg - assigns the free physical register to
141         /// the virtual register passed as arguments
142         void assignVirt2PhysReg(unsigned virtReg, unsigned physReg);
143
144         /// clearVirtReg - free the physical register associated with this
145         /// virtual register and disassociate virtual->physical and
146         /// physical->virtual mappings
147         void clearVirtReg(unsigned virtReg);
148
149         /// assignVirt2StackSlot - assigns this virtual register to a
150         /// stack slot
151         void assignVirt2StackSlot(unsigned virtReg);
152
153         /// findOrCreateStackSlot - returns the offset of the
154         /// specified register on the stack allocating space if
155         /// necessary
156         int findOrCreateStackSlot(unsigned virtReg);
157
158         /// spillVirtReg - spills the virtual register
159         void spillVirtReg(unsigned virtReg);
160
161         /// loadPhysReg - loads to the physical register the value of
162         /// the virtual register specifed. Virtual register must have
163         /// an assigned stack slot
164         void loadVirt2PhysReg(unsigned virtReg, unsigned physReg);
165
166         void printVirt2PhysMap() const {
167             std::cerr << "allocated registers:\n";
168             for (Virt2PhysMap::const_iterator
169                      i = v2pMap_.begin(), e = v2pMap_.end(); i != e; ++i) {
170                 std::cerr << '[' << i->first << ','
171                           << mri_->getName(i->second) << "]\n";
172             }
173             std::cerr << '\n';
174         }
175         void printIntervals(const char* const str,
176                             RA::IntervalPtrs::const_iterator i,
177                             RA::IntervalPtrs::const_iterator e) const {
178             if (str) std::cerr << str << " intervals:\n";
179             for (; i != e; ++i) {
180                 std::cerr << "\t\t" << **i << " -> ";
181                 if ((*i)->reg < MRegisterInfo::FirstVirtualRegister) {
182                     std::cerr << mri_->getName((*i)->reg);
183                 }
184                 else {
185                     std::cerr << mri_->getName(v2pMap_.find((*i)->reg)->second);
186                 }
187                 std::cerr << '\n';
188             }
189         }
190     };
191 }
192
193 bool RA::runOnMachineFunction(MachineFunction &fn) {
194     mf_ = &fn;
195     tm_ = &fn.getTarget();
196     mri_ = tm_->getRegisterInfo();
197     li_ = &getAnalysis<LiveIntervals>().getIntervals();
198     active_.clear();
199     inactive_.clear();
200     mbbs_ = getAnalysis<LiveIntervals>().getOrderedMachineBasicBlockPtrs();
201     p2vMap_.resize(MRegisterInfo::FirstVirtualRegister-1);
202     p2vMap_.clear();
203     v2pMap_.clear();
204     v2ssMap_.clear();
205
206     DEBUG(
207         for (MachineBasicBlockPtrs::iterator
208                  mbbi = mbbs_.begin(), mbbe = mbbs_.end();
209              mbbi != mbbe; ++mbbi) {
210             MachineBasicBlock* mbb = *mbbi;
211             std::cerr << mbb->getBasicBlock()->getName() << '\n';
212             for (MachineBasicBlock::iterator
213                      ii = mbb->begin(), ie = mbb->end();
214                  ii != ie; ++ii) {
215                 MachineInstr* instr = *ii;
216                      
217                 std::cerr << "\t";
218                 instr->print(std::cerr, *tm_);
219             }
220         }
221         );
222
223     // FIXME: this will work only for the X86 backend. I need to
224     // device an algorthm to select the minimal (considering register
225     // aliasing) number of temp registers to reserve so that we have 2
226     // registers for each register class available.
227
228     // reserve R32: EDI, EBX,
229     //         R16:  DI,  BX,
230     //         R8:   DH,  BH,
231     //         RFP: FP5, FP6
232     reserved_.push_back(19); /* EDI */
233     reserved_.push_back(17); /* EBX */
234     reserved_.push_back(12); /*  DI */
235     reserved_.push_back( 7); /*  BX */
236     reserved_.push_back(11); /*  DH */
237     reserved_.push_back( 4); /*  BH */
238     reserved_.push_back(28); /* FP5 */
239     reserved_.push_back(29); /* FP6 */
240
241     // liner scan algorithm
242     for (Intervals::const_iterator
243              i = li_->begin(), e = li_->end(); i != e; ++i) {
244         DEBUG(std::cerr << "processing current interval: " << *i << '\n');
245
246         DEBUG(printIntervals("\tactive", active_.begin(), active_.end()));
247         DEBUG(printIntervals("\tinactive", inactive_.begin(), inactive_.end()));
248
249         processActiveIntervals(i);
250         // processInactiveIntervals(i);
251
252         // if this register is preallocated, look for an interval that
253         // overlaps with it and assign it to a memory location
254         if (i->reg < MRegisterInfo::FirstVirtualRegister) {
255             for (IntervalPtrs::iterator
256                      ai = active_.begin(), ae = active_.end(); ai != ae; ++ai) {
257                 unsigned virtReg = (*ai)->reg;
258                 Virt2PhysMap::const_iterator it = v2pMap_.find(virtReg);
259                 if (it != v2pMap_.end() && it->second == i->reg) {
260                     active_.erase(ai);
261                     clearVirtReg(virtReg);
262                     break;
263                 }
264             }
265             reservePhysReg(i->reg);
266             active_.push_back(&*i);
267         }
268         // otherwise we are allocating a virtual register. try to find
269         // a free physical register or spill an interval in order to
270         // assign it one (we could spill the current though).
271         else {
272             unsigned physReg = getFreePhysReg(i->reg);
273             if (!physReg) {
274                 assignStackSlotAtInterval(i);
275             }
276             else {
277                 assignVirt2PhysReg(i->reg, physReg);
278                 active_.push_back(&*i);
279             }
280         }
281     }
282     DEBUG(std::cerr << "finished register allocation\n");
283     DEBUG(printVirt2PhysMap());
284
285     DEBUG(std::cerr << "Rewrite machine code:\n");
286     for (MachineBasicBlockPtrs::iterator
287              mbbi = mbbs_.begin(), mbbe = mbbs_.end(); mbbi != mbbe; ++mbbi) {
288         instrAdded_ = 0;
289         currentMbb_ = *mbbi;
290
291         for (currentInstr_ = currentMbb_->begin();
292              currentInstr_ != currentMbb_->end(); ++currentInstr_) {
293
294             DEBUG(std::cerr << "\tinstruction: ";
295                   (*currentInstr_)->print(std::cerr, *tm_););
296
297             // use our current mapping and actually replace and
298             // virtual register with its allocated physical registers
299             DEBUG(std::cerr << "\t\treplacing virtual registers with mapped "
300                   "physical registers:\n");
301             for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
302                  i != e; ++i) {
303                 MachineOperand& op = (*currentInstr_)->getOperand(i);
304                 if (op.isVirtualRegister()) {
305                     unsigned virtReg = op.getAllocatedRegNum();
306                     unsigned physReg = v2pMap_[virtReg];
307                     // if this virtual registers lives on the stack,
308                     // load it to a temporary physical register
309                     if (physReg) {
310                         DEBUG(std::cerr << "\t\t\t%reg" << virtReg
311                               << " -> " << mri_->getName(physReg) << '\n');
312                         (*currentInstr_)->SetMachineOperandReg(i, physReg);
313                     }
314                 }
315             }
316
317             DEBUG(std::cerr << "\t\tloading temporarily used operands to "
318                   "registers:\n");
319             for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
320                  i != e; ++i) {
321                 MachineOperand& op = (*currentInstr_)->getOperand(i);
322                 if (op.isVirtualRegister() && op.opIsUse()) {
323                     unsigned virtReg = op.getAllocatedRegNum();
324                     unsigned physReg = v2pMap_[virtReg];
325                     if (!physReg) {
326                         physReg = getFreeTempPhysReg(virtReg);
327                     }
328                     loadVirt2PhysReg(virtReg, physReg);
329                     tempUseOperands_.push_back(virtReg);
330                     (*currentInstr_)->SetMachineOperandReg(i, physReg);
331                 }
332             }
333
334             DEBUG(std::cerr << "\t\tclearing temporarily used operands:\n");
335             for (unsigned i = 0, e = tempUseOperands_.size(); i != e; ++i) {
336                 clearVirtReg(tempUseOperands_[i]);
337             }
338             tempUseOperands_.clear();
339
340             DEBUG(std::cerr << "\t\tassigning temporarily defined operands to "
341                   "registers:\n");
342             for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
343                  i != e; ++i) {
344                 MachineOperand& op = (*currentInstr_)->getOperand(i);
345                 if (op.isVirtualRegister() && !op.opIsUse()) {
346                     unsigned virtReg = op.getAllocatedRegNum();
347                     unsigned physReg = v2pMap_[virtReg];
348                     if (!physReg) {
349                         physReg = getFreeTempPhysReg(virtReg);
350                     }
351                     if (op.opIsDefAndUse()) {
352                         loadVirt2PhysReg(virtReg, physReg);
353                     }
354                     else {
355                         assignVirt2PhysReg(virtReg, physReg);
356                     }
357                     tempDefOperands_.push_back(virtReg);
358                     (*currentInstr_)->SetMachineOperandReg(i, physReg);
359                 }
360             }
361
362
363             // if the instruction is a two address instruction and the
364             // source operands are not identical we need to insert
365             // extra instructions.
366
367             unsigned opcode = (*currentInstr_)->getOpcode();
368             if (tm_->getInstrInfo().isTwoAddrInstr(opcode) &&
369                 (*currentInstr_)->getOperand(0).getAllocatedRegNum() !=
370                 (*currentInstr_)->getOperand(1).getAllocatedRegNum()) {
371                 assert((*currentInstr_)->getOperand(1).isRegister() &&
372                        (*currentInstr_)->getOperand(1).getAllocatedRegNum() &&
373                        (*currentInstr_)->getOperand(1).opIsUse() &&
374                        "Two address instruction invalid");
375
376                 unsigned regA =
377                     (*currentInstr_)->getOperand(0).getAllocatedRegNum();
378                 unsigned regB =
379                     (*currentInstr_)->getOperand(1).getAllocatedRegNum();
380                 unsigned regC =
381                     ((*currentInstr_)->getNumOperands() > 2 &&
382                      (*currentInstr_)->getOperand(2).isRegister()) ?
383                     (*currentInstr_)->getOperand(2).getAllocatedRegNum() :
384                     0;
385
386                 const TargetRegisterClass* rc = mri_->getRegClass(regA);
387
388                 // special case: "a = b op a". If b is a temporary
389                 // reserved register rewrite as: "b = b op a; a = b"
390                 // otherwise use a temporary reserved register t and
391                 // rewrite as: "t = b; t = t op a; a = t"
392                 if (regC && regA == regC) {
393                     // b is a temp reserved register
394                     if (find(reserved_.begin(), reserved_.end(),
395                              regB) != reserved_.end()) {
396                         (*currentInstr_)->SetMachineOperandReg(0, regB);
397                         ++currentInstr_;
398                         instrAdded_ += mri_->copyRegToReg(*currentMbb_,
399                                                           currentInstr_,
400                                                           regA,
401                                                           regB,
402                                                           rc);
403                         --currentInstr_;
404                     }
405                     // b is just a normal register
406                     else {
407                         unsigned tempReg = getFreeTempPhysReg(rc);
408                         assert (tempReg &&
409                                 "no free temp reserved physical register?");
410                         instrAdded_ += mri_->copyRegToReg(*currentMbb_,
411                                                           currentInstr_,
412                                                           tempReg,
413                                                           regB,
414                                                           rc);
415                         (*currentInstr_)->SetMachineOperandReg(0, tempReg);
416                         (*currentInstr_)->SetMachineOperandReg(1, tempReg);
417                         ++currentInstr_;
418                         instrAdded_ += mri_->copyRegToReg(*currentMbb_,
419                                                           currentInstr_,
420                                                           regA,
421                                                           tempReg,
422                                                           rc);
423                         --currentInstr_;
424                     }
425                 }
426                 // "a = b op c" gets rewritten to "a = b; a = a op c"
427                 else {
428                     instrAdded_ += mri_->copyRegToReg(*currentMbb_,
429                                                       currentInstr_,
430                                                       regA,
431                                                       regB,
432                                                       rc);
433                     (*currentInstr_)->SetMachineOperandReg(1, regA);
434                 }
435             }
436
437             DEBUG(std::cerr << "\t\tspilling temporarily defined operands "
438                   "of this instruction:\n");
439             ++currentInstr_; // we want to insert after this instruction
440             for (unsigned i = 0, e = tempDefOperands_.size(); i != e; ++i) {
441                 spillVirtReg(tempDefOperands_[i]);
442             }
443             --currentInstr_; // restore currentInstr_ iterator
444             tempDefOperands_.clear();
445         }
446
447         for (unsigned i = 0, e = p2vMap_.size(); i != e; ++i) {
448             assert(p2vMap_[i] != i &&
449                    "reserved physical registers at end of basic block?");
450         }
451     }
452
453     return true;
454 }
455
456 void RA::processActiveIntervals(Intervals::const_iterator cur)
457 {
458     DEBUG(std::cerr << "\tprocessing active intervals:\n");
459     for (IntervalPtrs::iterator i = active_.begin(); i != active_.end();) {
460         unsigned reg = (*i)->reg;
461         // remove expired intervals. we expire earlier because this if
462         // an interval expires this is going to be the last use. in
463         // this case we can reuse the register for a def in the same
464         // instruction
465         if ((*i)->expired(cur->start() + 1)) {
466             DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
467             if (reg < MRegisterInfo::FirstVirtualRegister) {
468                 clearReservedPhysReg(reg);
469             }
470             else {
471                 p2vMap_[v2pMap_[reg]] = 0;
472             }
473             // remove interval from active
474             i = active_.erase(i);
475         }
476         // move not active intervals to inactive list
477 //         else if (!(*i)->overlaps(curIndex)) {
478 //             DEBUG(std::cerr << "\t\t\tinterval " << **i << " inactive\n");
479 //             unmarkReg(virtReg);
480 //             // add interval to inactive
481 //             inactive_.push_back(*i);
482 //             // remove interval from active
483 //             i = active_.erase(i);
484 //         }
485         else {
486             ++i;
487         }
488     }
489 }
490
491 void RA::processInactiveIntervals(Intervals::const_iterator cur)
492 {
493 //     DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
494 //     for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end();) {
495 //         unsigned virtReg = (*i)->reg;
496 //         // remove expired intervals
497 //         if ((*i)->expired(curIndex)) {
498 //             DEBUG(std::cerr << "\t\t\tinterval " << **i << " expired\n");
499 //             freePhysReg(virtReg);
500 //             // remove from inactive
501 //             i = inactive_.erase(i);
502 //         }
503 //         // move re-activated intervals in active list
504 //         else if ((*i)->overlaps(curIndex)) {
505 //             DEBUG(std::cerr << "\t\t\tinterval " << **i << " active\n");
506 //             markReg(virtReg);
507 //             // add to active
508 //             active_.push_back(*i);
509 //             // remove from inactive
510 //             i = inactive_.erase(i);
511 //         }
512 //         else {
513 //             ++i;
514 //         }
515 //     }
516 }
517
518 void RA::assignStackSlotAtInterval(Intervals::const_iterator cur)
519 {
520     DEBUG(std::cerr << "\t\tassigning stack slot at interval "
521           << *cur << ":\n");
522     assert(!active_.empty() &&
523            "active set cannot be empty when choosing a register to spill");
524     const TargetRegisterClass* rcCur =
525         mf_->getSSARegMap()->getRegClass(cur->reg);
526
527     // find the interval for a virtual register that ends last in
528     // active and belongs to the same register class as the current
529     // interval
530     IntervalPtrs::iterator lastEndActive = active_.begin();
531     for (IntervalPtrs::iterator e = active_.end();
532          lastEndActive != e; ++lastEndActive) {
533         if ((*lastEndActive)->reg >= MRegisterInfo::FirstVirtualRegister) {
534             const TargetRegisterClass* rc =
535                 mri_->getRegClass(v2pMap_[(*lastEndActive)->reg]);
536             if (rcCur == rc) {
537                 break;
538             }
539         }
540     }
541     for (IntervalPtrs::iterator i = lastEndActive, e = active_.end();
542          i != e; ++i) {
543         if ((*i)->reg >= MRegisterInfo::FirstVirtualRegister) {
544             const TargetRegisterClass* rc =
545                 mri_->getRegClass(v2pMap_[(*i)->reg]);
546             if (rcCur == rc &&
547                 (*lastEndActive)->end() < (*i)->end()) {
548                 lastEndActive = i;
549             }
550         }
551     }
552
553     // find the interval for a virtual register that ends last in
554     // inactive and belongs to the same register class as the current
555     // interval
556     IntervalPtrs::iterator lastEndInactive = inactive_.begin();
557     for (IntervalPtrs::iterator e = inactive_.end();
558          lastEndInactive != e; ++lastEndInactive) {
559         if ((*lastEndInactive)->reg >= MRegisterInfo::FirstVirtualRegister) {
560             const TargetRegisterClass* rc =
561                 mri_->getRegClass(v2pMap_[(*lastEndInactive)->reg]);
562             if (rcCur == rc) {
563                 break;
564             }
565         }
566     }
567     for (IntervalPtrs::iterator i = lastEndInactive, e = inactive_.end();
568          i != e; ++i) {
569         if ((*i)->reg >= MRegisterInfo::FirstVirtualRegister) {
570             const TargetRegisterClass* rc =
571                 mri_->getRegClass(v2pMap_[(*i)->reg]);
572             if (rcCur == rc &&
573                 (*lastEndInactive)->end() < (*i)->end()) {
574                 lastEndInactive = i;
575             }
576         }
577     }
578
579     unsigned lastEndActiveInactive = 0;
580     if (lastEndActive != active_.end() &&
581         lastEndActiveInactive < (*lastEndActive)->end()) {
582         lastEndActiveInactive = (*lastEndActive)->end();
583     }
584     if (lastEndInactive != inactive_.end() &&
585         lastEndActiveInactive < (*lastEndInactive)->end()) {
586         lastEndActiveInactive = (*lastEndInactive)->end();
587     }
588
589     if (lastEndActiveInactive > cur->end()) {
590         if (lastEndInactive == inactive_.end() ||
591             (*lastEndActive)->end() > (*lastEndInactive)->end()) {
592             assignVirt2StackSlot((*lastEndActive)->reg);
593             active_.erase(lastEndActive);
594         }
595         else {
596             assignVirt2StackSlot((*lastEndInactive)->reg);
597             inactive_.erase(lastEndInactive);
598         }
599         unsigned physReg = getFreePhysReg(cur->reg);
600         assert(physReg && "no free physical register after spill?");
601         assignVirt2PhysReg(cur->reg, physReg);
602         active_.push_back(&*cur);
603     }
604     else {
605         assignVirt2StackSlot(cur->reg);
606     }
607 }
608
609 void RA::reservePhysReg(unsigned physReg)
610 {
611     DEBUG(std::cerr << "\t\t\treserving physical physical register: "
612           << mri_->getName(physReg) << '\n');
613     // if this register holds a value spill it
614     unsigned virtReg = p2vMap_[physReg];
615     if (virtReg != 0) {
616         assert(virtReg != physReg && "reserving an already reserved phus reg?");
617         // remove interval from active
618         for (IntervalPtrs::iterator i = active_.begin(), e = active_.end();
619              i != e; ++i) {
620             if ((*i)->reg == virtReg) {
621                 active_.erase(i);
622                 break;
623             }
624         }
625         spillVirtReg(virtReg);
626     }
627     p2vMap_[physReg] = physReg; // this denotes a reserved physical register
628 }
629
630 void RA::clearReservedPhysReg(unsigned physReg)
631 {
632     DEBUG(std::cerr << "\t\t\tclearing reserved physical physical register: "
633           << mri_->getName(physReg) << '\n');
634     assert(p2vMap_[physReg] == physReg &&
635            "attempt to clear a non reserved physical register");
636     p2vMap_[physReg] = 0;
637 }
638
639 bool RA::physRegAvailable(unsigned physReg)
640 {
641     if (p2vMap_[physReg]) {
642         return false;
643     }
644
645     // if it aliases other registers it is still not free
646     for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
647         if (p2vMap_[*as]) {
648             return false;
649         }
650     }
651
652     // if it is one of the reserved registers it is still not free
653     if (find(reserved_.begin(), reserved_.end(), physReg) != reserved_.end()) {
654         return false;
655     }
656
657     return true;
658 }
659
660 unsigned RA::getFreePhysReg(unsigned virtReg)
661 {
662     DEBUG(std::cerr << "\t\tgetting free physical register: ");
663     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
664     TargetRegisterClass::iterator reg = rc->allocation_order_begin(*mf_);
665     TargetRegisterClass::iterator regEnd = rc->allocation_order_end(*mf_);
666
667     for (; reg != regEnd; ++reg) {
668         if (physRegAvailable(*reg)) {
669             assert(*reg != 0 && "Cannot use register!");
670             DEBUG(std::cerr << mri_->getName(*reg) << '\n');
671             return *reg; // Found an unused register!
672         }
673     }
674
675     DEBUG(std::cerr << "no free register\n");
676     return 0;
677 }
678
679 bool RA::tempPhysRegAvailable(unsigned physReg)
680 {
681     assert(find(reserved_.begin(), reserved_.end(), physReg) != reserved_.end()
682            && "cannot call this method with a non reserved temp register");
683
684     if (p2vMap_[physReg]) {
685         return false;
686     }
687
688     // if it aliases other registers it is still not free
689     for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
690         if (p2vMap_[*as]) {
691             return false;
692         }
693     }
694
695     return true;
696 }
697
698 unsigned RA::getFreeTempPhysReg(const TargetRegisterClass* rc)
699 {
700     DEBUG(std::cerr << "\t\tgetting free temporary physical register: ");
701
702     for (Regs::const_iterator
703              reg = reserved_.begin(), regEnd = reserved_.end();
704          reg != regEnd; ++reg) {
705         if (rc == mri_->getRegClass(*reg) && tempPhysRegAvailable(*reg)) {
706             assert(*reg != 0 && "Cannot use register!");
707             DEBUG(std::cerr << mri_->getName(*reg) << '\n');
708             return *reg; // Found an unused register!
709         }
710     }
711     assert(0 && "no free temporary physical register?");
712     return 0;
713 }
714
715 void RA::assignVirt2PhysReg(unsigned virtReg, unsigned physReg)
716 {
717     assert((physRegAvailable(physReg) ||
718             find(reserved_.begin(),
719                  reserved_.end(),
720                  physReg) != reserved_.end()) &&
721            "attempt to allocate to a not available physical register");
722     v2pMap_[virtReg] = physReg;
723     p2vMap_[physReg] = virtReg;
724 }
725
726 void RA::clearVirtReg(unsigned virtReg)
727 {
728     Virt2PhysMap::iterator it = v2pMap_.find(virtReg);
729     assert(it != v2pMap_.end() &&
730            "attempting to clear a not allocated virtual register");
731     unsigned physReg = it->second;
732     p2vMap_[physReg] = 0;
733     v2pMap_[virtReg] = 0; // this marks that this virtual register
734                           // lives on the stack
735     DEBUG(std::cerr << "\t\t\tcleared register " << mri_->getName(physReg)
736           << "\n");
737 }
738
739 void RA::assignVirt2StackSlot(unsigned virtReg)
740 {
741     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
742     int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc);
743
744     bool inserted = v2ssMap_.insert(std::make_pair(virtReg, frameIndex)).second;
745     assert(inserted &&
746            "attempt to assign stack slot to already assigned register?");
747     // if the virtual register was previously assigned clear the mapping
748     // and free the virtual register
749     if (v2pMap_.find(virtReg) != v2pMap_.end()) {
750         clearVirtReg(virtReg);
751     }
752 }
753
754 int RA::findOrCreateStackSlot(unsigned virtReg)
755 {
756     // use lower_bound so that we can do a possibly O(1) insert later
757     // if necessary
758     Virt2StackSlotMap::iterator it = v2ssMap_.lower_bound(virtReg);
759     if (it != v2ssMap_.end() && it->first == virtReg) {
760         return it->second;
761     }
762     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
763     int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc);
764
765     v2ssMap_.insert(it, std::make_pair(virtReg, frameIndex));
766
767     return frameIndex;
768 }
769
770 void RA::spillVirtReg(unsigned virtReg)
771 {
772     DEBUG(std::cerr << "\t\t\tspilling register: " << virtReg);
773     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
774     int frameIndex = findOrCreateStackSlot(virtReg);
775     DEBUG(std::cerr << " to stack slot #" << frameIndex << '\n');
776     ++numSpilled;
777     instrAdded_ += mri_->storeRegToStackSlot(*currentMbb_, currentInstr_,
778                                              v2pMap_[virtReg], frameIndex, rc);
779     clearVirtReg(virtReg);
780 }
781
782 void RA::loadVirt2PhysReg(unsigned virtReg, unsigned physReg)
783 {
784     DEBUG(std::cerr << "\t\t\tloading register: " << virtReg);
785     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
786     int frameIndex = findOrCreateStackSlot(virtReg);
787     DEBUG(std::cerr << " from stack slot #" << frameIndex << '\n');
788     instrAdded_ += mri_->loadRegFromStackSlot(*currentMbb_, currentInstr_,
789                                               physReg, frameIndex, rc);
790     assignVirt2PhysReg(virtReg, physReg);
791 }
792
793 FunctionPass* llvm::createLinearScanRegisterAllocator() {
794     return new RA();
795 }