1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
38 static cl::opt<bool> VerifyFastRegalloc("verify-fast-regalloc", cl::Hidden,
39 cl::desc("Verify machine code before fast regalloc"));
41 STATISTIC(NumStores, "Number of stores added");
42 STATISTIC(NumLoads , "Number of loads added");
43 STATISTIC(NumCopies, "Number of copies coalesced");
45 static RegisterRegAlloc
46 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
49 class RAFast : public MachineFunctionPass {
52 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
53 atEndOfBlock(false) {}
55 const TargetMachine *TM;
57 MachineRegisterInfo *MRI;
58 const TargetRegisterInfo *TRI;
59 const TargetInstrInfo *TII;
61 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
62 // values are spilled.
63 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
65 // Everything we know about a live virtual register.
67 MachineInstr *LastUse; // Last instr to use reg.
68 unsigned PhysReg; // Currently held here.
69 unsigned short LastOpNum; // OpNum on LastUse.
70 bool Dirty; // Register needs spill.
72 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
74 assert(p && "Don't create LiveRegs without a PhysReg");
78 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
80 // LiveVirtRegs - This map contains entries for each virtual register
81 // that is currently available in a physical register.
82 LiveRegMap LiveVirtRegs;
84 // RegState - Track the state of a physical register.
86 // A disabled register is not available for allocation, but an alias may
87 // be in use. A register can only be moved out of the disabled state if
88 // all aliases are disabled.
91 // A free register is not currently in use and can be allocated
92 // immediately without checking aliases.
95 // A reserved register has been assigned expolicitly (e.g., setting up a
96 // call parameter), and it remains reserved until it is used.
99 // A register state may also be a virtual register number, indication that
100 // the physical register is currently allocated to a virtual register. In
101 // that case, LiveVirtRegs contains the inverse mapping.
104 // PhysRegState - One of the RegState enums, or a virtreg.
105 std::vector<unsigned> PhysRegState;
107 // UsedInInstr - BitVector of physregs that are used in the current
108 // instruction, and so cannot be allocated.
109 BitVector UsedInInstr;
111 // ReservedRegs - vector of reserved physical registers.
112 BitVector ReservedRegs;
114 // atEndOfBlock - This flag is set after allocating all instructions in a
115 // block, before emitting final spills. When it is set, LiveRegMap is no
116 // longer updated properly sonce it will be cleared anyway.
120 virtual const char *getPassName() const {
121 return "Fast Register Allocator";
124 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesCFG();
126 AU.addRequiredID(PHIEliminationID);
127 AU.addRequiredID(TwoAddressInstructionPassID);
128 MachineFunctionPass::getAnalysisUsage(AU);
132 bool runOnMachineFunction(MachineFunction &Fn);
133 void AllocateBasicBlock(MachineBasicBlock &MBB);
134 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
135 void addKillFlag(LiveRegMap::iterator i);
136 void killVirtReg(LiveRegMap::iterator i);
137 void killVirtReg(unsigned VirtReg);
138 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
139 LiveRegMap::iterator i, bool isKill);
140 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
141 unsigned VirtReg, bool isKill);
143 void usePhysReg(MachineOperand&);
144 void definePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
145 unsigned PhysReg, RegState NewState);
146 LiveRegMap::iterator assignVirtToPhysReg(unsigned VirtReg,
148 LiveRegMap::iterator allocVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
149 unsigned VirtReg, unsigned Hint);
150 unsigned defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
151 unsigned OpNum, unsigned VirtReg, unsigned Hint);
152 unsigned reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
153 unsigned OpNum, unsigned VirtReg, unsigned Hint);
154 void spillAll(MachineBasicBlock &MBB, MachineInstr *MI);
155 void setPhysReg(MachineOperand &MO, unsigned PhysReg);
160 /// getStackSpaceFor - This allocates space for the specified virtual register
161 /// to be held on the stack.
162 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
163 // Find the location Reg would belong...
164 int SS = StackSlotForVirtReg[VirtReg];
166 return SS; // Already has space allocated?
168 // Allocate a new stack object for this spill location...
169 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
173 StackSlotForVirtReg[VirtReg] = FrameIdx;
177 /// addKillFlag - Set kill flags on last use of a virtual register.
178 void RAFast::addKillFlag(LiveRegMap::iterator lri) {
179 assert(lri != LiveVirtRegs.end() && "Killing unmapped virtual register");
180 const LiveReg &LR = lri->second;
182 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
185 else if (!LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum))
190 /// killVirtReg - Mark virtreg as no longer available.
191 void RAFast::killVirtReg(LiveRegMap::iterator lri) {
193 const LiveReg &LR = lri->second;
194 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
195 PhysRegState[LR.PhysReg] = regFree;
196 // Erase from LiveVirtRegs unless we're at the end of the block when
197 // everything will be bulk erased.
199 LiveVirtRegs.erase(lri);
202 /// killVirtReg - Mark virtreg as no longer available.
203 void RAFast::killVirtReg(unsigned VirtReg) {
204 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
205 "killVirtReg needs a virtual register");
206 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
207 if (lri != LiveVirtRegs.end())
211 /// spillVirtReg - This method spills the value specified by VirtReg into the
212 /// corresponding stack slot if needed. If isKill is set, the register is also
214 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
215 MachineBasicBlock::iterator MI,
216 unsigned VirtReg, bool isKill) {
217 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
218 "Spilling a physical register is illegal!");
219 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
220 assert(lri != LiveVirtRegs.end() && "Spilling unmapped virtual register");
221 spillVirtReg(MBB, MI, lri, isKill);
224 /// spillVirtReg - Do the actual work of spilling.
225 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
226 MachineBasicBlock::iterator MI,
227 LiveRegMap::iterator lri, bool isKill) {
228 LiveReg &LR = lri->second;
229 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
231 // If this physreg is used by the instruction, we want to kill it on the
232 // instruction, not on the spill.
233 bool spillKill = isKill && LR.LastUse != MI;
237 DEBUG(dbgs() << "Spilling %reg" << lri->first
238 << " in " << TRI->getName(LR.PhysReg));
239 const TargetRegisterClass *RC = MRI->getRegClass(lri->first);
240 int FrameIndex = getStackSpaceFor(lri->first, RC);
241 DEBUG(dbgs() << " to stack slot #" << FrameIndex << "\n");
242 TII->storeRegToStackSlot(MBB, MI, LR.PhysReg, spillKill,
243 FrameIndex, RC, TRI);
244 ++NumStores; // Update statistics
247 LR.LastUse = 0; // Don't kill register again
249 MachineInstr *Spill = llvm::prior(MI);
251 LR.LastOpNum = Spill->findRegisterUseOperandIdx(LR.PhysReg);
259 /// spillAll - Spill all dirty virtregs without killing them.
260 void RAFast::spillAll(MachineBasicBlock &MBB, MachineInstr *MI) {
261 SmallVector<unsigned, 16> Dirty;
262 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
263 e = LiveVirtRegs.end(); i != e; ++i)
265 Dirty.push_back(i->first);
266 for (unsigned i = 0, e = Dirty.size(); i != e; ++i)
267 spillVirtReg(MBB, MI, Dirty[i], false);
270 /// usePhysReg - Handle the direct use of a physical register.
271 /// Check that the register is not used by a virtreg.
272 /// Kill the physreg, marking it free.
273 /// This may add implicit kills to MO->getParent() and invalidate MO.
274 void RAFast::usePhysReg(MachineOperand &MO) {
275 unsigned PhysReg = MO.getReg();
276 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
277 "Bad usePhysReg operand");
279 switch (PhysRegState[PhysReg]) {
283 PhysRegState[PhysReg] = regFree;
286 UsedInInstr.set(PhysReg);
290 // The physreg was allocated to a virtual register. That means to value we
291 // wanted has been clobbered.
292 llvm_unreachable("Instruction uses an allocated register");
295 // Maybe a superregister is reserved?
296 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
297 unsigned Alias = *AS; ++AS) {
298 switch (PhysRegState[Alias]) {
302 assert(TRI->isSuperRegister(PhysReg, Alias) &&
303 "Instruction is not using a subregister of a reserved register");
304 // Leave the superregister in the working set.
305 PhysRegState[Alias] = regFree;
306 UsedInInstr.set(Alias);
307 MO.getParent()->addRegisterKilled(Alias, TRI, true);
310 if (TRI->isSuperRegister(PhysReg, Alias)) {
311 // Leave the superregister in the working set.
312 UsedInInstr.set(Alias);
313 MO.getParent()->addRegisterKilled(Alias, TRI, true);
316 // Some other alias was in the working set - clear it.
317 PhysRegState[Alias] = regDisabled;
320 llvm_unreachable("Instruction uses an alias of an allocated register");
324 // All aliases are disabled, bring register into working set.
325 PhysRegState[PhysReg] = regFree;
326 UsedInInstr.set(PhysReg);
330 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
331 /// virtregs. This is very similar to defineVirtReg except the physreg is
332 /// reserved instead of allocated.
333 void RAFast::definePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
334 unsigned PhysReg, RegState NewState) {
335 UsedInInstr.set(PhysReg);
336 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
340 spillVirtReg(MBB, MI, VirtReg, true);
344 PhysRegState[PhysReg] = NewState;
348 // This is a disabled register, disable all aliases.
349 PhysRegState[PhysReg] = NewState;
350 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
351 unsigned Alias = *AS; ++AS) {
352 UsedInInstr.set(Alias);
353 switch (unsigned VirtReg = PhysRegState[Alias]) {
357 spillVirtReg(MBB, MI, VirtReg, true);
361 PhysRegState[Alias] = regDisabled;
362 if (TRI->isSuperRegister(PhysReg, Alias))
370 /// assignVirtToPhysReg - This method updates local state so that we know
371 /// that PhysReg is the proper container for VirtReg now. The physical
372 /// register must not be used for anything else when this is called.
374 RAFast::LiveRegMap::iterator
375 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
376 DEBUG(dbgs() << "Assigning %reg" << VirtReg << " to "
377 << TRI->getName(PhysReg) << "\n");
378 PhysRegState[PhysReg] = VirtReg;
379 return LiveVirtRegs.insert(std::make_pair(VirtReg, PhysReg)).first;
382 /// allocVirtReg - Allocate a physical register for VirtReg.
383 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineBasicBlock &MBB,
387 const unsigned spillCost = 100;
388 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
389 "Can only allocate virtual registers");
391 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
392 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
393 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
395 // Ignore invalid hints.
396 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
397 !RC->contains(Hint) || UsedInInstr.test(Hint)))
400 // If there is no hint, peek at the first use of this register.
401 if (!Hint && !MRI->use_nodbg_empty(VirtReg)) {
402 MachineInstr &MI = *MRI->use_nodbg_begin(VirtReg);
403 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
404 // Copy to physreg -> use physreg as hint.
405 if (TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
406 SrcReg == VirtReg && TargetRegisterInfo::isPhysicalRegister(DstReg) &&
407 RC->contains(DstReg) && !UsedInInstr.test(DstReg)) {
409 DEBUG(dbgs() << "%reg" << VirtReg << " gets hint from " << MI);
413 // Take hint when possible.
415 assert(RC->contains(Hint) && !UsedInInstr.test(Hint) &&
416 "Invalid hint should have been cleared");
417 switch(PhysRegState[Hint]) {
422 spillVirtReg(MBB, MI, PhysRegState[Hint], true);
425 return assignVirtToPhysReg(VirtReg, Hint);
429 // First try to find a completely free register.
430 unsigned BestCost = 0, BestReg = 0;
431 bool hasDisabled = false;
432 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
433 unsigned PhysReg = *I;
434 switch(PhysRegState[PhysReg]) {
440 if (!UsedInInstr.test(PhysReg))
441 return assignVirtToPhysReg(VirtReg, PhysReg);
444 // Grab the first spillable register we meet.
445 if (!BestReg && !UsedInInstr.test(PhysReg))
446 BestReg = PhysReg, BestCost = spillCost;
451 DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
452 << " candidate=" << TRI->getName(BestReg) << "\n");
454 // Try to extend the working set for RC if there were any disabled registers.
455 if (hasDisabled && (!BestReg || BestCost >= spillCost)) {
456 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
457 unsigned PhysReg = *I;
458 if (PhysRegState[PhysReg] != regDisabled || UsedInInstr.test(PhysReg))
461 // Calculate the cost of bringing PhysReg into the working set.
463 bool Impossible = false;
464 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
465 unsigned Alias = *AS; ++AS) {
466 if (UsedInInstr.test(Alias)) {
470 switch (PhysRegState[Alias]) {
484 if (Impossible) continue;
485 DEBUG(dbgs() << "- candidate " << TRI->getName(PhysReg)
486 << " cost=" << Cost << "\n");
487 if (!BestReg || Cost < BestCost) {
490 if (Cost < spillCost) break;
496 // BestCost is 0 when all aliases are already disabled.
498 if (PhysRegState[BestReg] != regDisabled)
499 spillVirtReg(MBB, MI, PhysRegState[BestReg], true);
501 // Make sure all aliases are disabled.
502 for (const unsigned *AS = TRI->getAliasSet(BestReg);
503 unsigned Alias = *AS; ++AS) {
504 switch (PhysRegState[Alias]) {
508 PhysRegState[Alias] = regDisabled;
511 spillVirtReg(MBB, MI, PhysRegState[Alias], true);
512 PhysRegState[Alias] = regDisabled;
518 return assignVirtToPhysReg(VirtReg, BestReg);
521 // Nothing we can do.
523 raw_string_ostream Msg(msg);
524 Msg << "Ran out of registers during register allocation!";
525 if (MI->isInlineAsm()) {
526 Msg << "\nPlease check your inline asm statement for "
527 << "invalid constraints:\n";
530 report_fatal_error(Msg.str());
531 return LiveVirtRegs.end();
534 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
535 unsigned RAFast::defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
536 unsigned OpNum, unsigned VirtReg, unsigned Hint) {
537 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
538 "Not a virtual register");
539 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
540 if (lri == LiveVirtRegs.end())
541 lri = allocVirtReg(MBB, MI, VirtReg, Hint);
543 addKillFlag(lri); // Kill before redefine.
544 LiveReg &LR = lri->second;
546 LR.LastOpNum = OpNum;
548 UsedInInstr.set(LR.PhysReg);
552 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
553 unsigned RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
554 unsigned OpNum, unsigned VirtReg, unsigned Hint) {
555 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
556 "Not a virtual register");
557 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
558 if (lri == LiveVirtRegs.end()) {
559 lri = allocVirtReg(MBB, MI, VirtReg, Hint);
560 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
561 int FrameIndex = getStackSpaceFor(VirtReg, RC);
562 DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
563 << TRI->getName(lri->second.PhysReg) << "\n");
564 TII->loadRegFromStackSlot(MBB, MI, lri->second.PhysReg, FrameIndex, RC,
568 LiveReg &LR = lri->second;
570 LR.LastOpNum = OpNum;
571 UsedInInstr.set(LR.PhysReg);
575 // setPhysReg - Change MO the refer the PhysReg, considering subregs.
576 void RAFast::setPhysReg(MachineOperand &MO, unsigned PhysReg) {
577 if (unsigned Idx = MO.getSubReg()) {
578 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, Idx) : 0);
584 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
585 DEBUG(dbgs() << "\nAllocating " << MBB);
587 atEndOfBlock = false;
588 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
589 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
591 MachineBasicBlock::iterator MII = MBB.begin();
593 // Add live-in registers as live.
594 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
595 E = MBB.livein_end(); I != E; ++I)
596 definePhysReg(MBB, MII, *I, regReserved);
598 SmallVector<unsigned, 8> VirtKills, PhysDefs;
599 SmallVector<MachineInstr*, 32> Coalesced;
601 // Otherwise, sequentially allocate each instruction in the MBB.
602 while (MII != MBB.end()) {
603 MachineInstr *MI = MII++;
604 const TargetInstrDesc &TID = MI->getDesc();
606 dbgs() << "\n>> " << *MI << "Regs:";
607 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
608 if (PhysRegState[Reg] == regDisabled) continue;
609 dbgs() << " " << TRI->getName(Reg);
610 switch(PhysRegState[Reg]) {
617 dbgs() << "=%reg" << PhysRegState[Reg];
618 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
620 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
626 // Check that LiveVirtRegs is the inverse.
627 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
628 e = LiveVirtRegs.end(); i != e; ++i) {
629 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
631 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
633 assert(PhysRegState[i->second.PhysReg] == i->first &&
638 // Debug values are not allowed to change codegen in any way.
639 if (MI->isDebugValue()) {
640 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
641 MachineOperand &MO = MI->getOperand(i);
642 if (!MO.isReg()) continue;
643 unsigned Reg = MO.getReg();
644 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
645 LiveRegMap::iterator lri = LiveVirtRegs.find(Reg);
646 if (lri != LiveVirtRegs.end())
647 setPhysReg(MO, lri->second.PhysReg);
649 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
655 // If this is a copy, we may be able to coalesce.
656 unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
657 if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
658 CopySrc = CopyDst = 0;
660 // Track registers used by instruction.
665 // Mark physreg uses and early clobbers as used.
666 // Find the end of the virtreg operands
667 unsigned VirtOpEnd = 0;
668 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
669 MachineOperand &MO = MI->getOperand(i);
670 if (!MO.isReg()) continue;
671 unsigned Reg = MO.getReg();
673 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
677 if (ReservedRegs.test(Reg)) continue;
680 } else if (MO.isEarlyClobber()) {
681 definePhysReg(MBB, MI, Reg, MO.isDead() ? regFree : regReserved);
682 PhysDefs.push_back(Reg);
687 // Allocate virtreg uses and early clobbers.
689 for (unsigned i = 0; i != VirtOpEnd; ++i) {
690 MachineOperand &MO = MI->getOperand(i);
691 if (!MO.isReg()) continue;
692 unsigned Reg = MO.getReg();
693 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
695 unsigned PhysReg = reloadVirtReg(MBB, MI, i, Reg, CopyDst);
696 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
697 setPhysReg(MO, PhysReg);
699 VirtKills.push_back(Reg);
700 } else if (MO.isEarlyClobber()) {
701 unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, 0);
702 setPhysReg(MO, PhysReg);
703 PhysDefs.push_back(PhysReg);
707 // Process virtreg kills
708 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
709 killVirtReg(VirtKills[i]);
712 MRI->addPhysRegsUsed(UsedInInstr);
714 // Track registers defined by instruction - early clobbers at this point.
716 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
717 unsigned PhysReg = PhysDefs[i];
718 UsedInInstr.set(PhysReg);
719 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
720 unsigned Alias = *AS; ++AS)
721 UsedInInstr.set(Alias);
725 // Allocate defs and collect dead defs.
726 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
727 MachineOperand &MO = MI->getOperand(i);
728 if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue;
729 unsigned Reg = MO.getReg();
731 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
732 if (ReservedRegs.test(Reg)) continue;
733 definePhysReg(MBB, MI, Reg, (MO.isImplicit() || MO.isDead()) ?
734 regFree : regReserved);
737 unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, CopySrc);
739 VirtKills.push_back(Reg);
740 CopyDst = 0; // cancel coalescing;
742 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
743 setPhysReg(MO, PhysReg);
746 // Spill all dirty virtregs before a call, in case of an exception.
748 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
752 // Process virtreg deads.
753 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
754 killVirtReg(VirtKills[i]);
757 MRI->addPhysRegsUsed(UsedInInstr);
759 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
760 DEBUG(dbgs() << "-- coalescing: " << *MI);
761 Coalesced.push_back(MI);
763 DEBUG(dbgs() << "<< " << *MI);
767 // Spill all physical registers holding virtual registers now.
769 DEBUG(dbgs() << "Killing live registers at end of block.\n");
770 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
771 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
773 spillVirtReg(MBB, MI, i, true);
774 LiveVirtRegs.clear();
776 // Erase all the coalesced copies. We are delaying it until now because
777 // LiveVirtsRegs might refer to the instrs.
778 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
779 MBB.erase(Coalesced[i]);
780 NumCopies += Coalesced.size();
785 /// runOnMachineFunction - Register allocate the whole function
787 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
788 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
789 << "********** Function: "
790 << ((Value*)Fn.getFunction())->getName() << '\n');
791 if (VerifyFastRegalloc)
792 Fn.verify(this, true);
794 MRI = &MF->getRegInfo();
795 TM = &Fn.getTarget();
796 TRI = TM->getRegisterInfo();
797 TII = TM->getInstrInfo();
799 UsedInInstr.resize(TRI->getNumRegs());
800 ReservedRegs = TRI->getReservedRegs(*MF);
802 // initialize the virtual->physical register map to have a 'null'
803 // mapping for all virtual registers
804 unsigned LastVirtReg = MRI->getLastVirtReg();
805 StackSlotForVirtReg.grow(LastVirtReg);
807 // Loop over all of the basic blocks, eliminating virtual register references
808 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
810 AllocateBasicBlock(*MBB);
812 // Make sure the set of used physregs is closed under subreg operations.
813 MRI->closePhysRegsUsed(*TRI);
815 StackSlotForVirtReg.clear();
819 FunctionPass *llvm::createFastRegisterAllocator() {