blob: 709fdafc3e114dc3da4a0fe951a9d317cdb36fb7 [file] [log] [blame]
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001//===-- 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
33using namespace llvm;
34
35namespace {
36 Statistic<> numSpilled ("ra-linearscan", "Number of registers spilled");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037
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
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000153 /// getStackSlot - returns the offset of the specified
154 /// register on the stack
155 int getStackSlot(unsigned virtReg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000156
157 /// spillVirtReg - spills the virtual register
158 void spillVirtReg(unsigned virtReg);
159
160 /// loadPhysReg - loads to the physical register the value of
161 /// the virtual register specifed. Virtual register must have
162 /// an assigned stack slot
163 void loadVirt2PhysReg(unsigned virtReg, unsigned physReg);
164
165 void printVirt2PhysMap() const {
166 std::cerr << "allocated registers:\n";
167 for (Virt2PhysMap::const_iterator
168 i = v2pMap_.begin(), e = v2pMap_.end(); i != e; ++i) {
169 std::cerr << '[' << i->first << ','
170 << mri_->getName(i->second) << "]\n";
171 }
172 std::cerr << '\n';
173 }
174 void printIntervals(const char* const str,
175 RA::IntervalPtrs::const_iterator i,
176 RA::IntervalPtrs::const_iterator e) const {
177 if (str) std::cerr << str << " intervals:\n";
178 for (; i != e; ++i) {
179 std::cerr << "\t\t" << **i << " -> ";
180 if ((*i)->reg < MRegisterInfo::FirstVirtualRegister) {
181 std::cerr << mri_->getName((*i)->reg);
182 }
183 else {
184 std::cerr << mri_->getName(v2pMap_.find((*i)->reg)->second);
185 }
186 std::cerr << '\n';
187 }
188 }
189 };
190}
191
192bool RA::runOnMachineFunction(MachineFunction &fn) {
193 mf_ = &fn;
194 tm_ = &fn.getTarget();
195 mri_ = tm_->getRegisterInfo();
196 li_ = &getAnalysis<LiveIntervals>().getIntervals();
197 active_.clear();
198 inactive_.clear();
199 mbbs_ = getAnalysis<LiveIntervals>().getOrderedMachineBasicBlockPtrs();
200 p2vMap_.resize(MRegisterInfo::FirstVirtualRegister-1);
201 p2vMap_.clear();
202 v2pMap_.clear();
203 v2ssMap_.clear();
204
Alkis Evlogimenos58587072003-11-30 23:40:39 +0000205 DEBUG(
206 for (MachineBasicBlockPtrs::iterator
207 mbbi = mbbs_.begin(), mbbe = mbbs_.end();
208 mbbi != mbbe; ++mbbi) {
209 MachineBasicBlock* mbb = *mbbi;
210 std::cerr << mbb->getBasicBlock()->getName() << '\n';
211 for (MachineBasicBlock::iterator
212 ii = mbb->begin(), ie = mbb->end();
213 ii != ie; ++ii) {
214 MachineInstr* instr = *ii;
215
216 std::cerr << "\t";
217 instr->print(std::cerr, *tm_);
218 }
219 }
220 );
221
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000222 // FIXME: this will work only for the X86 backend. I need to
223 // device an algorthm to select the minimal (considering register
224 // aliasing) number of temp registers to reserve so that we have 2
225 // registers for each register class available.
226
227 // reserve R32: EDI, EBX,
228 // R16: DI, BX,
229 // R8: DH, BH,
230 // RFP: FP5, FP6
231 reserved_.push_back(19); /* EDI */
232 reserved_.push_back(17); /* EBX */
233 reserved_.push_back(12); /* DI */
234 reserved_.push_back( 7); /* BX */
235 reserved_.push_back(11); /* DH */
236 reserved_.push_back( 4); /* BH */
237 reserved_.push_back(28); /* FP5 */
238 reserved_.push_back(29); /* FP6 */
239
240 // liner scan algorithm
241 for (Intervals::const_iterator
242 i = li_->begin(), e = li_->end(); i != e; ++i) {
243 DEBUG(std::cerr << "processing current interval: " << *i << '\n');
244
245 DEBUG(printIntervals("\tactive", active_.begin(), active_.end()));
246 DEBUG(printIntervals("\tinactive", inactive_.begin(), inactive_.end()));
247
248 processActiveIntervals(i);
249 // processInactiveIntervals(i);
250
251 // if this register is preallocated, look for an interval that
252 // overlaps with it and assign it to a memory location
253 if (i->reg < MRegisterInfo::FirstVirtualRegister) {
254 for (IntervalPtrs::iterator
255 ai = active_.begin(), ae = active_.end(); ai != ae; ++ai) {
256 unsigned virtReg = (*ai)->reg;
257 Virt2PhysMap::const_iterator it = v2pMap_.find(virtReg);
258 if (it != v2pMap_.end() && it->second == i->reg) {
259 active_.erase(ai);
260 clearVirtReg(virtReg);
261 break;
262 }
263 }
264 reservePhysReg(i->reg);
265 active_.push_back(&*i);
266 }
267 // otherwise we are allocating a virtual register. try to find
268 // a free physical register or spill an interval in order to
269 // assign it one (we could spill the current though).
270 else {
271 unsigned physReg = getFreePhysReg(i->reg);
272 if (!physReg) {
273 assignStackSlotAtInterval(i);
274 }
275 else {
276 assignVirt2PhysReg(i->reg, physReg);
277 active_.push_back(&*i);
278 }
279 }
280 }
281 DEBUG(std::cerr << "finished register allocation\n");
282 DEBUG(printVirt2PhysMap());
283
284 DEBUG(std::cerr << "Rewrite machine code:\n");
285 for (MachineBasicBlockPtrs::iterator
286 mbbi = mbbs_.begin(), mbbe = mbbs_.end(); mbbi != mbbe; ++mbbi) {
287 instrAdded_ = 0;
288 currentMbb_ = *mbbi;
289
290 for (currentInstr_ = currentMbb_->begin();
291 currentInstr_ != currentMbb_->end(); ++currentInstr_) {
292
293 DEBUG(std::cerr << "\tinstruction: ";
294 (*currentInstr_)->print(std::cerr, *tm_););
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000295
296 // use our current mapping and actually replace and
297 // virtual register with its allocated physical registers
298 DEBUG(std::cerr << "\t\treplacing virtual registers with mapped "
299 "physical registers:\n");
300 for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
301 i != e; ++i) {
302 MachineOperand& op = (*currentInstr_)->getOperand(i);
303 if (op.isVirtualRegister()) {
304 unsigned virtReg = op.getAllocatedRegNum();
305 unsigned physReg = v2pMap_[virtReg];
306 // if this virtual registers lives on the stack,
307 // load it to a temporary physical register
308 if (physReg) {
309 DEBUG(std::cerr << "\t\t\t%reg" << virtReg
310 << " -> " << mri_->getName(physReg) << '\n');
311 (*currentInstr_)->SetMachineOperandReg(i, physReg);
312 }
313 }
314 }
315
316 DEBUG(std::cerr << "\t\tloading temporarily used operands to "
317 "registers:\n");
318 for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
319 i != e; ++i) {
320 MachineOperand& op = (*currentInstr_)->getOperand(i);
321 if (op.isVirtualRegister() && op.opIsUse()) {
322 unsigned virtReg = op.getAllocatedRegNum();
323 unsigned physReg = v2pMap_[virtReg];
324 if (!physReg) {
325 physReg = getFreeTempPhysReg(virtReg);
326 }
327 loadVirt2PhysReg(virtReg, physReg);
328 tempUseOperands_.push_back(virtReg);
329 (*currentInstr_)->SetMachineOperandReg(i, physReg);
330 }
331 }
332
333 DEBUG(std::cerr << "\t\tclearing temporarily used operands:\n");
334 for (unsigned i = 0, e = tempUseOperands_.size(); i != e; ++i) {
335 clearVirtReg(tempUseOperands_[i]);
336 }
337 tempUseOperands_.clear();
338
339 DEBUG(std::cerr << "\t\tassigning temporarily defined operands to "
340 "registers:\n");
341 for (unsigned i = 0, e = (*currentInstr_)->getNumOperands();
342 i != e; ++i) {
343 MachineOperand& op = (*currentInstr_)->getOperand(i);
344 if (op.isVirtualRegister() && !op.opIsUse()) {
345 unsigned virtReg = op.getAllocatedRegNum();
346 unsigned physReg = v2pMap_[virtReg];
347 if (!physReg) {
348 physReg = getFreeTempPhysReg(virtReg);
349 }
350 if (op.opIsDefAndUse()) {
351 loadVirt2PhysReg(virtReg, physReg);
352 }
353 else {
354 assignVirt2PhysReg(virtReg, physReg);
355 }
356 tempDefOperands_.push_back(virtReg);
357 (*currentInstr_)->SetMachineOperandReg(i, physReg);
358 }
359 }
360
361
362 // if the instruction is a two address instruction and the
363 // source operands are not identical we need to insert
364 // extra instructions.
365
366 unsigned opcode = (*currentInstr_)->getOpcode();
367 if (tm_->getInstrInfo().isTwoAddrInstr(opcode) &&
368 (*currentInstr_)->getOperand(0).getAllocatedRegNum() !=
369 (*currentInstr_)->getOperand(1).getAllocatedRegNum()) {
370 assert((*currentInstr_)->getOperand(1).isRegister() &&
371 (*currentInstr_)->getOperand(1).getAllocatedRegNum() &&
372 (*currentInstr_)->getOperand(1).opIsUse() &&
373 "Two address instruction invalid");
374
375 unsigned regA =
376 (*currentInstr_)->getOperand(0).getAllocatedRegNum();
377 unsigned regB =
378 (*currentInstr_)->getOperand(1).getAllocatedRegNum();
379 unsigned regC =
380 ((*currentInstr_)->getNumOperands() > 2 &&
381 (*currentInstr_)->getOperand(2).isRegister()) ?
382 (*currentInstr_)->getOperand(2).getAllocatedRegNum() :
383 0;
384
385 const TargetRegisterClass* rc = mri_->getRegClass(regA);
386
387 // special case: "a = b op a". If b is a temporary
388 // reserved register rewrite as: "b = b op a; a = b"
389 // otherwise use a temporary reserved register t and
390 // rewrite as: "t = b; t = t op a; a = t"
391 if (regC && regA == regC) {
392 // b is a temp reserved register
393 if (find(reserved_.begin(), reserved_.end(),
394 regB) != reserved_.end()) {
395 (*currentInstr_)->SetMachineOperandReg(0, regB);
396 ++currentInstr_;
397 instrAdded_ += mri_->copyRegToReg(*currentMbb_,
398 currentInstr_,
399 regA,
400 regB,
401 rc);
402 --currentInstr_;
403 }
404 // b is just a normal register
405 else {
406 unsigned tempReg = getFreeTempPhysReg(rc);
407 assert (tempReg &&
408 "no free temp reserved physical register?");
409 instrAdded_ += mri_->copyRegToReg(*currentMbb_,
410 currentInstr_,
411 tempReg,
412 regB,
413 rc);
414 (*currentInstr_)->SetMachineOperandReg(0, tempReg);
415 (*currentInstr_)->SetMachineOperandReg(1, tempReg);
416 ++currentInstr_;
417 instrAdded_ += mri_->copyRegToReg(*currentMbb_,
418 currentInstr_,
419 regA,
420 tempReg,
421 rc);
422 --currentInstr_;
423 }
424 }
425 // "a = b op c" gets rewritten to "a = b; a = a op c"
426 else {
427 instrAdded_ += mri_->copyRegToReg(*currentMbb_,
428 currentInstr_,
429 regA,
430 regB,
431 rc);
432 (*currentInstr_)->SetMachineOperandReg(1, regA);
433 }
434 }
Alkis Evlogimenos58587072003-11-30 23:40:39 +0000435
436 DEBUG(std::cerr << "\t\tspilling temporarily defined operands "
437 "of this instruction:\n");
438 ++currentInstr_; // we want to insert after this instruction
439 for (unsigned i = 0, e = tempDefOperands_.size(); i != e; ++i) {
440 spillVirtReg(tempDefOperands_[i]);
441 }
442 --currentInstr_; // restore currentInstr_ iterator
443 tempDefOperands_.clear();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000444 }
445
446 for (unsigned i = 0, e = p2vMap_.size(); i != e; ++i) {
447 assert(p2vMap_[i] != i &&
448 "reserved physical registers at end of basic block?");
449 }
450 }
451
452 return true;
453}
454
455void RA::processActiveIntervals(Intervals::const_iterator cur)
456{
457 DEBUG(std::cerr << "\tprocessing active intervals:\n");
458 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end();) {
459 unsigned reg = (*i)->reg;
460 // remove expired intervals. we expire earlier because this if
461 // an interval expires this is going to be the last use. in
462 // this case we can reuse the register for a def in the same
463 // instruction
464 if ((*i)->expired(cur->start() + 1)) {
465 DEBUG(std::cerr << "\t\tinterval " << **i << " expired\n");
466 if (reg < MRegisterInfo::FirstVirtualRegister) {
467 clearReservedPhysReg(reg);
468 }
469 else {
470 p2vMap_[v2pMap_[reg]] = 0;
471 }
472 // remove interval from active
473 i = active_.erase(i);
474 }
475 // move not active intervals to inactive list
476// else if (!(*i)->overlaps(curIndex)) {
477// DEBUG(std::cerr << "\t\t\tinterval " << **i << " inactive\n");
478// unmarkReg(virtReg);
479// // add interval to inactive
480// inactive_.push_back(*i);
481// // remove interval from active
482// i = active_.erase(i);
483// }
484 else {
485 ++i;
486 }
487 }
488}
489
490void RA::processInactiveIntervals(Intervals::const_iterator cur)
491{
492// DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
493// for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end();) {
494// unsigned virtReg = (*i)->reg;
495// // remove expired intervals
496// if ((*i)->expired(curIndex)) {
497// DEBUG(std::cerr << "\t\t\tinterval " << **i << " expired\n");
498// freePhysReg(virtReg);
499// // remove from inactive
500// i = inactive_.erase(i);
501// }
502// // move re-activated intervals in active list
503// else if ((*i)->overlaps(curIndex)) {
504// DEBUG(std::cerr << "\t\t\tinterval " << **i << " active\n");
505// markReg(virtReg);
506// // add to active
507// active_.push_back(*i);
508// // remove from inactive
509// i = inactive_.erase(i);
510// }
511// else {
512// ++i;
513// }
514// }
515}
516
517void RA::assignStackSlotAtInterval(Intervals::const_iterator cur)
518{
519 DEBUG(std::cerr << "\t\tassigning stack slot at interval "
520 << *cur << ":\n");
521 assert(!active_.empty() &&
522 "active set cannot be empty when choosing a register to spill");
523 const TargetRegisterClass* rcCur =
524 mf_->getSSARegMap()->getRegClass(cur->reg);
525
526 // find the interval for a virtual register that ends last in
527 // active and belongs to the same register class as the current
528 // interval
529 IntervalPtrs::iterator lastEndActive = active_.begin();
530 for (IntervalPtrs::iterator e = active_.end();
531 lastEndActive != e; ++lastEndActive) {
532 if ((*lastEndActive)->reg >= MRegisterInfo::FirstVirtualRegister) {
533 const TargetRegisterClass* rc =
534 mri_->getRegClass(v2pMap_[(*lastEndActive)->reg]);
535 if (rcCur == rc) {
536 break;
537 }
538 }
539 }
540 for (IntervalPtrs::iterator i = lastEndActive, e = active_.end();
541 i != e; ++i) {
542 if ((*i)->reg >= MRegisterInfo::FirstVirtualRegister) {
543 const TargetRegisterClass* rc =
544 mri_->getRegClass(v2pMap_[(*i)->reg]);
545 if (rcCur == rc &&
546 (*lastEndActive)->end() < (*i)->end()) {
547 lastEndActive = i;
548 }
549 }
550 }
551
552 // find the interval for a virtual register that ends last in
553 // inactive and belongs to the same register class as the current
554 // interval
555 IntervalPtrs::iterator lastEndInactive = inactive_.begin();
556 for (IntervalPtrs::iterator e = inactive_.end();
557 lastEndInactive != e; ++lastEndInactive) {
558 if ((*lastEndInactive)->reg >= MRegisterInfo::FirstVirtualRegister) {
559 const TargetRegisterClass* rc =
560 mri_->getRegClass(v2pMap_[(*lastEndInactive)->reg]);
561 if (rcCur == rc) {
562 break;
563 }
564 }
565 }
566 for (IntervalPtrs::iterator i = lastEndInactive, e = inactive_.end();
567 i != e; ++i) {
568 if ((*i)->reg >= MRegisterInfo::FirstVirtualRegister) {
569 const TargetRegisterClass* rc =
570 mri_->getRegClass(v2pMap_[(*i)->reg]);
571 if (rcCur == rc &&
572 (*lastEndInactive)->end() < (*i)->end()) {
573 lastEndInactive = i;
574 }
575 }
576 }
577
578 unsigned lastEndActiveInactive = 0;
579 if (lastEndActive != active_.end() &&
580 lastEndActiveInactive < (*lastEndActive)->end()) {
581 lastEndActiveInactive = (*lastEndActive)->end();
582 }
583 if (lastEndInactive != inactive_.end() &&
584 lastEndActiveInactive < (*lastEndInactive)->end()) {
585 lastEndActiveInactive = (*lastEndInactive)->end();
586 }
587
588 if (lastEndActiveInactive > cur->end()) {
589 if (lastEndInactive == inactive_.end() ||
590 (*lastEndActive)->end() > (*lastEndInactive)->end()) {
591 assignVirt2StackSlot((*lastEndActive)->reg);
592 active_.erase(lastEndActive);
593 }
594 else {
595 assignVirt2StackSlot((*lastEndInactive)->reg);
596 inactive_.erase(lastEndInactive);
597 }
598 unsigned physReg = getFreePhysReg(cur->reg);
599 assert(physReg && "no free physical register after spill?");
600 assignVirt2PhysReg(cur->reg, physReg);
601 active_.push_back(&*cur);
602 }
603 else {
604 assignVirt2StackSlot(cur->reg);
605 }
606}
607
608void RA::reservePhysReg(unsigned physReg)
609{
610 DEBUG(std::cerr << "\t\t\treserving physical physical register: "
611 << mri_->getName(physReg) << '\n');
612 // if this register holds a value spill it
613 unsigned virtReg = p2vMap_[physReg];
614 if (virtReg != 0) {
615 assert(virtReg != physReg && "reserving an already reserved phus reg?");
616 // remove interval from active
617 for (IntervalPtrs::iterator i = active_.begin(), e = active_.end();
618 i != e; ++i) {
619 if ((*i)->reg == virtReg) {
620 active_.erase(i);
621 break;
622 }
623 }
624 spillVirtReg(virtReg);
625 }
626 p2vMap_[physReg] = physReg; // this denotes a reserved physical register
627}
628
629void RA::clearReservedPhysReg(unsigned physReg)
630{
631 DEBUG(std::cerr << "\t\t\tclearing reserved physical physical register: "
632 << mri_->getName(physReg) << '\n');
633 assert(p2vMap_[physReg] == physReg &&
634 "attempt to clear a non reserved physical register");
635 p2vMap_[physReg] = 0;
636}
637
638bool RA::physRegAvailable(unsigned physReg)
639{
640 if (p2vMap_[physReg]) {
641 return false;
642 }
643
644 // if it aliases other registers it is still not free
645 for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
646 if (p2vMap_[*as]) {
647 return false;
648 }
649 }
650
651 // if it is one of the reserved registers it is still not free
652 if (find(reserved_.begin(), reserved_.end(), physReg) != reserved_.end()) {
653 return false;
654 }
655
656 return true;
657}
658
659unsigned RA::getFreePhysReg(unsigned virtReg)
660{
661 DEBUG(std::cerr << "\t\tgetting free physical register: ");
662 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
663 TargetRegisterClass::iterator reg = rc->allocation_order_begin(*mf_);
664 TargetRegisterClass::iterator regEnd = rc->allocation_order_end(*mf_);
665
666 for (; reg != regEnd; ++reg) {
667 if (physRegAvailable(*reg)) {
668 assert(*reg != 0 && "Cannot use register!");
669 DEBUG(std::cerr << mri_->getName(*reg) << '\n');
670 return *reg; // Found an unused register!
671 }
672 }
673
674 DEBUG(std::cerr << "no free register\n");
675 return 0;
676}
677
678bool RA::tempPhysRegAvailable(unsigned physReg)
679{
680 assert(find(reserved_.begin(), reserved_.end(), physReg) != reserved_.end()
681 && "cannot call this method with a non reserved temp register");
682
683 if (p2vMap_[physReg]) {
684 return false;
685 }
686
687 // if it aliases other registers it is still not free
688 for (const unsigned* as = mri_->getAliasSet(physReg); *as; ++as) {
689 if (p2vMap_[*as]) {
690 return false;
691 }
692 }
693
694 return true;
695}
696
697unsigned RA::getFreeTempPhysReg(const TargetRegisterClass* rc)
698{
699 DEBUG(std::cerr << "\t\tgetting free temporary physical register: ");
700
701 for (Regs::const_iterator
702 reg = reserved_.begin(), regEnd = reserved_.end();
703 reg != regEnd; ++reg) {
704 if (rc == mri_->getRegClass(*reg) && tempPhysRegAvailable(*reg)) {
705 assert(*reg != 0 && "Cannot use register!");
706 DEBUG(std::cerr << mri_->getName(*reg) << '\n');
707 return *reg; // Found an unused register!
708 }
709 }
710 assert(0 && "no free temporary physical register?");
711 return 0;
712}
713
714void RA::assignVirt2PhysReg(unsigned virtReg, unsigned physReg)
715{
716 assert((physRegAvailable(physReg) ||
717 find(reserved_.begin(),
718 reserved_.end(),
719 physReg) != reserved_.end()) &&
720 "attempt to allocate to a not available physical register");
721 v2pMap_[virtReg] = physReg;
722 p2vMap_[physReg] = virtReg;
723}
724
725void RA::clearVirtReg(unsigned virtReg)
726{
727 Virt2PhysMap::iterator it = v2pMap_.find(virtReg);
728 assert(it != v2pMap_.end() &&
729 "attempting to clear a not allocated virtual register");
730 unsigned physReg = it->second;
731 p2vMap_[physReg] = 0;
732 v2pMap_[virtReg] = 0; // this marks that this virtual register
733 // lives on the stack
734 DEBUG(std::cerr << "\t\t\tcleared register " << mri_->getName(physReg)
735 << "\n");
736}
737
738void RA::assignVirt2StackSlot(unsigned virtReg)
739{
740 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
741 int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc);
742
743 bool inserted = v2ssMap_.insert(std::make_pair(virtReg, frameIndex)).second;
744 assert(inserted &&
745 "attempt to assign stack slot to already assigned register?");
746 // if the virtual register was previously assigned clear the mapping
747 // and free the virtual register
748 if (v2pMap_.find(virtReg) != v2pMap_.end()) {
749 clearVirtReg(virtReg);
750 }
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000751 else {
752 v2pMap_[virtReg] = 0; // this marks that this virtual register
753 // lives on the stack
754 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000755}
756
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000757int RA::getStackSlot(unsigned virtReg)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000758{
759 // use lower_bound so that we can do a possibly O(1) insert later
760 // if necessary
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000761 Virt2StackSlotMap::iterator it = v2ssMap_.find(virtReg);
762 assert(it != v2ssMap_.end() &&
763 "attempt to get stack slot on register that does not live on the stack");
764 return it->second;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000765}
766
767void RA::spillVirtReg(unsigned virtReg)
768{
769 DEBUG(std::cerr << "\t\t\tspilling register: " << virtReg);
770 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000771 int frameIndex = getStackSlot(virtReg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000772 DEBUG(std::cerr << " to stack slot #" << frameIndex << '\n');
773 ++numSpilled;
774 instrAdded_ += mri_->storeRegToStackSlot(*currentMbb_, currentInstr_,
775 v2pMap_[virtReg], frameIndex, rc);
776 clearVirtReg(virtReg);
777}
778
779void RA::loadVirt2PhysReg(unsigned virtReg, unsigned physReg)
780{
781 DEBUG(std::cerr << "\t\t\tloading register: " << virtReg);
782 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg);
Alkis Evlogimenos69546d52003-12-04 03:57:28 +0000783 int frameIndex = getStackSlot(virtReg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000784 DEBUG(std::cerr << " from stack slot #" << frameIndex << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000785 instrAdded_ += mri_->loadRegFromStackSlot(*currentMbb_, currentInstr_,
786 physReg, frameIndex, rc);
787 assignVirt2PhysReg(virtReg, physReg);
788}
789
790FunctionPass* llvm::createLinearScanRegisterAllocator() {
791 return new RA();
792}