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 // Basic block currently being allocated.
62 MachineBasicBlock *MBB;
64 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
65 // values are spilled.
66 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
68 // Everything we know about a live virtual register.
70 MachineInstr *LastUse; // Last instr to use reg.
71 unsigned PhysReg; // Currently held here.
72 unsigned short LastOpNum; // OpNum on LastUse.
73 bool Dirty; // Register needs spill.
75 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
79 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
80 typedef LiveRegMap::value_type LiveRegEntry;
82 // LiveVirtRegs - This map contains entries for each virtual register
83 // that is currently available in a physical register.
84 LiveRegMap LiveVirtRegs;
86 // RegState - Track the state of a physical register.
88 // A disabled register is not available for allocation, but an alias may
89 // be in use. A register can only be moved out of the disabled state if
90 // all aliases are disabled.
93 // A free register is not currently in use and can be allocated
94 // immediately without checking aliases.
97 // A reserved register has been assigned expolicitly (e.g., setting up a
98 // call parameter), and it remains reserved until it is used.
101 // A register state may also be a virtual register number, indication that
102 // the physical register is currently allocated to a virtual register. In
103 // that case, LiveVirtRegs contains the inverse mapping.
106 // PhysRegState - One of the RegState enums, or a virtreg.
107 std::vector<unsigned> PhysRegState;
109 // UsedInInstr - BitVector of physregs that are used in the current
110 // instruction, and so cannot be allocated.
111 BitVector UsedInInstr;
113 // Allocatable - vector of allocatable physical registers.
114 BitVector Allocatable;
116 // atEndOfBlock - This flag is set after allocating all instructions in a
117 // block, before emitting final spills. When it is set, LiveRegMap is no
118 // longer updated properly sonce it will be cleared anyway.
122 virtual const char *getPassName() const {
123 return "Fast Register Allocator";
126 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
127 AU.setPreservesCFG();
128 AU.addRequiredID(PHIEliminationID);
129 AU.addRequiredID(TwoAddressInstructionPassID);
130 MachineFunctionPass::getAnalysisUsage(AU);
134 bool runOnMachineFunction(MachineFunction &Fn);
135 void AllocateBasicBlock();
136 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
137 bool isLastUseOfLocalReg(MachineOperand&);
139 void addKillFlag(const LiveReg&);
140 void killVirtReg(LiveRegMap::iterator i);
141 void killVirtReg(unsigned VirtReg);
142 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator i,
144 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg,
147 void usePhysReg(MachineOperand&);
148 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
149 void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
150 void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
151 unsigned defineVirtReg(MachineInstr *MI, unsigned OpNum,
152 unsigned VirtReg, unsigned Hint);
153 unsigned reloadVirtReg(MachineInstr *MI, unsigned OpNum,
154 unsigned VirtReg, unsigned Hint);
155 void spillAll(MachineInstr *MI);
156 void setPhysReg(MachineOperand &MO, unsigned PhysReg);
161 /// getStackSpaceFor - This allocates space for the specified virtual register
162 /// to be held on the stack.
163 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
164 // Find the location Reg would belong...
165 int SS = StackSlotForVirtReg[VirtReg];
167 return SS; // Already has space allocated?
169 // Allocate a new stack object for this spill location...
170 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
174 StackSlotForVirtReg[VirtReg] = FrameIdx;
178 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
179 /// its virtual register, and it is guaranteed to be a block-local register.
181 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
182 // Check for non-debug uses or defs following MO.
183 // This is the most likely way to fail - fast path it.
184 MachineOperand *i = &MO;
185 while ((i = i->getNextOperandForReg()))
189 // If the register has ever been spilled or reloaded, we conservatively assume
190 // it is a global register used in multiple blocks.
191 if (StackSlotForVirtReg[MO.getReg()] != -1)
194 // Check that the use/def chain has exactly one operand - MO.
195 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
198 /// addKillFlag - Set kill flags on last use of a virtual register.
199 void RAFast::addKillFlag(const LiveReg &LR) {
200 if (!LR.LastUse) return;
201 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
204 else if (!LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum))
208 /// killVirtReg - Mark virtreg as no longer available.
209 void RAFast::killVirtReg(LiveRegMap::iterator lri) {
210 addKillFlag(lri->second);
211 const LiveReg &LR = lri->second;
212 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
213 PhysRegState[LR.PhysReg] = regFree;
214 // Erase from LiveVirtRegs unless we're at the end of the block when
215 // everything will be bulk erased.
217 LiveVirtRegs.erase(lri);
220 /// killVirtReg - Mark virtreg as no longer available.
221 void RAFast::killVirtReg(unsigned VirtReg) {
222 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
223 "killVirtReg needs a virtual register");
224 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
225 if (lri != LiveVirtRegs.end())
229 /// spillVirtReg - This method spills the value specified by VirtReg into the
230 /// corresponding stack slot if needed. If isKill is set, the register is also
232 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
233 unsigned VirtReg, bool isKill) {
234 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
235 "Spilling a physical register is illegal!");
236 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
237 assert(lri != LiveVirtRegs.end() && "Spilling unmapped virtual register");
238 spillVirtReg(MI, lri, isKill);
241 /// spillVirtReg - Do the actual work of spilling.
242 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
243 LiveRegMap::iterator lri, bool isKill) {
244 LiveReg &LR = lri->second;
245 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
247 // If this physreg is used by the instruction, we want to kill it on the
248 // instruction, not on the spill.
249 bool spillKill = isKill && LR.LastUse != MI;
253 DEBUG(dbgs() << "Spilling %reg" << lri->first
254 << " in " << TRI->getName(LR.PhysReg));
255 const TargetRegisterClass *RC = MRI->getRegClass(lri->first);
256 int FI = getStackSpaceFor(lri->first, RC);
257 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
258 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, spillKill, FI, RC, TRI);
259 ++NumStores; // Update statistics
262 LR.LastUse = 0; // Don't kill register again
264 MachineInstr *Spill = llvm::prior(MI);
266 LR.LastOpNum = Spill->findRegisterUseOperandIdx(LR.PhysReg);
274 /// spillAll - Spill all dirty virtregs without killing them.
275 void RAFast::spillAll(MachineInstr *MI) {
276 SmallVector<unsigned, 16> Dirty;
277 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
278 e = LiveVirtRegs.end(); i != e; ++i)
280 Dirty.push_back(i->first);
281 for (unsigned i = 0, e = Dirty.size(); i != e; ++i)
282 spillVirtReg(MI, Dirty[i], false);
285 /// usePhysReg - Handle the direct use of a physical register.
286 /// Check that the register is not used by a virtreg.
287 /// Kill the physreg, marking it free.
288 /// This may add implicit kills to MO->getParent() and invalidate MO.
289 void RAFast::usePhysReg(MachineOperand &MO) {
290 unsigned PhysReg = MO.getReg();
291 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
292 "Bad usePhysReg operand");
294 switch (PhysRegState[PhysReg]) {
298 PhysRegState[PhysReg] = regFree;
301 UsedInInstr.set(PhysReg);
305 // The physreg was allocated to a virtual register. That means to value we
306 // wanted has been clobbered.
307 llvm_unreachable("Instruction uses an allocated register");
310 // Maybe a superregister is reserved?
311 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
312 unsigned Alias = *AS; ++AS) {
313 switch (PhysRegState[Alias]) {
317 assert(TRI->isSuperRegister(PhysReg, Alias) &&
318 "Instruction is not using a subregister of a reserved register");
319 // Leave the superregister in the working set.
320 PhysRegState[Alias] = regFree;
321 UsedInInstr.set(Alias);
322 MO.getParent()->addRegisterKilled(Alias, TRI, true);
325 if (TRI->isSuperRegister(PhysReg, Alias)) {
326 // Leave the superregister in the working set.
327 UsedInInstr.set(Alias);
328 MO.getParent()->addRegisterKilled(Alias, TRI, true);
331 // Some other alias was in the working set - clear it.
332 PhysRegState[Alias] = regDisabled;
335 llvm_unreachable("Instruction uses an alias of an allocated register");
339 // All aliases are disabled, bring register into working set.
340 PhysRegState[PhysReg] = regFree;
341 UsedInInstr.set(PhysReg);
345 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
346 /// virtregs. This is very similar to defineVirtReg except the physreg is
347 /// reserved instead of allocated.
348 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
350 UsedInInstr.set(PhysReg);
351 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
355 spillVirtReg(MI, VirtReg, true);
359 PhysRegState[PhysReg] = NewState;
363 // This is a disabled register, disable all aliases.
364 PhysRegState[PhysReg] = NewState;
365 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
366 unsigned Alias = *AS; ++AS) {
367 UsedInInstr.set(Alias);
368 switch (unsigned VirtReg = PhysRegState[Alias]) {
372 spillVirtReg(MI, VirtReg, true);
376 PhysRegState[Alias] = regDisabled;
377 if (TRI->isSuperRegister(PhysReg, Alias))
385 /// assignVirtToPhysReg - This method updates local state so that we know
386 /// that PhysReg is the proper container for VirtReg now. The physical
387 /// register must not be used for anything else when this is called.
389 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
390 DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
391 << TRI->getName(PhysReg) << "\n");
392 PhysRegState[PhysReg] = LRE.first;
393 assert(!LRE.second.PhysReg && "Already assigned a physreg");
394 LRE.second.PhysReg = PhysReg;
397 /// allocVirtReg - Allocate a physical register for VirtReg.
398 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
399 const unsigned spillCost = 100;
400 const unsigned VirtReg = LRE.first;
402 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
403 "Can only allocate virtual registers");
405 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
406 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
407 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
409 // Ignore invalid hints.
410 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
411 !RC->contains(Hint) || UsedInInstr.test(Hint) ||
412 !Allocatable.test(Hint)))
415 // If there is no hint, peek at the first use of this register.
416 if (!Hint && !MRI->use_nodbg_empty(VirtReg)) {
417 MachineInstr &MI = *MRI->use_nodbg_begin(VirtReg);
418 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
419 // Copy to physreg -> use physreg as hint.
420 if (TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
421 SrcReg == VirtReg && TargetRegisterInfo::isPhysicalRegister(DstReg) &&
422 RC->contains(DstReg) && !UsedInInstr.test(DstReg) &&
423 Allocatable.test(DstReg)) {
425 DEBUG(dbgs() << "%reg" << VirtReg << " gets hint from " << MI);
429 // Take hint when possible.
431 assert(RC->contains(Hint) && !UsedInInstr.test(Hint) &&
432 Allocatable.test(Hint) && "Invalid hint should have been cleared");
433 switch(PhysRegState[Hint]) {
438 spillVirtReg(MI, PhysRegState[Hint], true);
441 return assignVirtToPhysReg(LRE, Hint);
445 // First try to find a completely free register.
446 unsigned BestCost = 0, BestReg = 0;
447 bool hasDisabled = false;
448 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
449 unsigned PhysReg = *I;
450 switch(PhysRegState[PhysReg]) {
456 if (!UsedInInstr.test(PhysReg))
457 return assignVirtToPhysReg(LRE, PhysReg);
460 // Grab the first spillable register we meet.
461 if (!BestReg && !UsedInInstr.test(PhysReg))
462 BestReg = PhysReg, BestCost = spillCost;
467 DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
468 << " candidate=" << TRI->getName(BestReg) << "\n");
470 // Try to extend the working set for RC if there were any disabled registers.
471 if (hasDisabled && (!BestReg || BestCost >= spillCost)) {
472 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
473 unsigned PhysReg = *I;
474 if (PhysRegState[PhysReg] != regDisabled || UsedInInstr.test(PhysReg))
477 // Calculate the cost of bringing PhysReg into the working set.
479 bool Impossible = false;
480 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
481 unsigned Alias = *AS; ++AS) {
482 if (UsedInInstr.test(Alias)) {
486 switch (PhysRegState[Alias]) {
500 if (Impossible) continue;
501 DEBUG(dbgs() << "- candidate " << TRI->getName(PhysReg)
502 << " cost=" << Cost << "\n");
503 if (!BestReg || Cost < BestCost) {
506 if (Cost < spillCost) break;
512 // BestCost is 0 when all aliases are already disabled.
514 if (PhysRegState[BestReg] != regDisabled)
515 spillVirtReg(MI, PhysRegState[BestReg], true);
517 // Make sure all aliases are disabled.
518 for (const unsigned *AS = TRI->getAliasSet(BestReg);
519 unsigned Alias = *AS; ++AS) {
520 switch (PhysRegState[Alias]) {
524 PhysRegState[Alias] = regDisabled;
527 spillVirtReg(MI, PhysRegState[Alias], true);
528 PhysRegState[Alias] = regDisabled;
534 return assignVirtToPhysReg(LRE, BestReg);
537 // Nothing we can do.
539 raw_string_ostream Msg(msg);
540 Msg << "Ran out of registers during register allocation!";
541 if (MI->isInlineAsm()) {
542 Msg << "\nPlease check your inline asm statement for "
543 << "invalid constraints:\n";
546 report_fatal_error(Msg.str());
549 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
550 unsigned RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
551 unsigned VirtReg, unsigned Hint) {
552 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
553 "Not a virtual register");
554 LiveRegMap::iterator lri;
556 tie(lri, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
557 LiveReg &LR = lri->second;
559 allocVirtReg(MI, *lri, Hint);
561 addKillFlag(LR); // Kill before redefine.
562 assert(LR.PhysReg && "Register not assigned");
564 LR.LastOpNum = OpNum;
566 UsedInInstr.set(LR.PhysReg);
570 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
571 unsigned RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
572 unsigned VirtReg, unsigned Hint) {
573 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
574 "Not a virtual register");
575 LiveRegMap::iterator lri;
577 tie(lri, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
578 LiveReg &LR = lri->second;
580 allocVirtReg(MI, *lri, Hint);
581 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
582 int FrameIndex = getStackSpaceFor(VirtReg, RC);
583 DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
584 << TRI->getName(LR.PhysReg) << "\n");
585 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
587 } else if (LR.Dirty) {
588 MachineOperand &MO = MI->getOperand(OpNum);
589 if (isLastUseOfLocalReg(MO)) {
590 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
592 } else if (MO.isKill()) {
593 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
597 assert(LR.PhysReg && "Register not assigned");
599 LR.LastOpNum = OpNum;
600 UsedInInstr.set(LR.PhysReg);
604 // setPhysReg - Change MO the refer the PhysReg, considering subregs.
605 void RAFast::setPhysReg(MachineOperand &MO, unsigned PhysReg) {
606 if (unsigned Idx = MO.getSubReg()) {
607 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, Idx) : 0);
613 void RAFast::AllocateBasicBlock() {
614 DEBUG(dbgs() << "\nAllocating " << *MBB);
616 atEndOfBlock = false;
617 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
618 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
620 MachineBasicBlock::iterator MII = MBB->begin();
622 // Add live-in registers as live.
623 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
624 E = MBB->livein_end(); I != E; ++I)
625 definePhysReg(MII, *I, regReserved);
627 SmallVector<unsigned, 8> VirtKills, PhysDefs;
628 SmallVector<MachineInstr*, 32> Coalesced;
630 // Otherwise, sequentially allocate each instruction in the MBB.
631 while (MII != MBB->end()) {
632 MachineInstr *MI = MII++;
633 const TargetInstrDesc &TID = MI->getDesc();
635 dbgs() << "\n>> " << *MI << "Regs:";
636 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
637 if (PhysRegState[Reg] == regDisabled) continue;
638 dbgs() << " " << TRI->getName(Reg);
639 switch(PhysRegState[Reg]) {
646 dbgs() << "=%reg" << PhysRegState[Reg];
647 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
649 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
655 // Check that LiveVirtRegs is the inverse.
656 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
657 e = LiveVirtRegs.end(); i != e; ++i) {
658 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
660 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
662 assert(PhysRegState[i->second.PhysReg] == i->first &&
667 // Debug values are not allowed to change codegen in any way.
668 if (MI->isDebugValue()) {
669 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
670 MachineOperand &MO = MI->getOperand(i);
671 if (!MO.isReg()) continue;
672 unsigned Reg = MO.getReg();
673 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
674 LiveRegMap::iterator lri = LiveVirtRegs.find(Reg);
675 if (lri != LiveVirtRegs.end())
676 setPhysReg(MO, lri->second.PhysReg);
678 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
684 // If this is a copy, we may be able to coalesce.
685 unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
686 if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
687 CopySrc = CopyDst = 0;
689 // Track registers used by instruction.
694 // Mark physreg uses and early clobbers as used.
695 // Find the end of the virtreg operands
696 unsigned VirtOpEnd = 0;
697 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
698 MachineOperand &MO = MI->getOperand(i);
699 if (!MO.isReg()) continue;
700 unsigned Reg = MO.getReg();
702 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
706 if (!Allocatable.test(Reg)) continue;
709 } else if (MO.isEarlyClobber()) {
710 definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
711 PhysDefs.push_back(Reg);
716 // Allocate virtreg uses and early clobbers.
718 for (unsigned i = 0; i != VirtOpEnd; ++i) {
719 MachineOperand &MO = MI->getOperand(i);
720 if (!MO.isReg()) continue;
721 unsigned Reg = MO.getReg();
722 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
724 unsigned PhysReg = reloadVirtReg(MI, i, Reg, CopyDst);
725 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
726 setPhysReg(MO, PhysReg);
728 VirtKills.push_back(Reg);
729 } else if (MO.isEarlyClobber()) {
730 unsigned PhysReg = defineVirtReg(MI, i, Reg, 0);
731 setPhysReg(MO, PhysReg);
732 PhysDefs.push_back(PhysReg);
736 // Process virtreg kills
737 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
738 killVirtReg(VirtKills[i]);
741 MRI->addPhysRegsUsed(UsedInInstr);
743 // Track registers defined by instruction - early clobbers at this point.
745 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
746 unsigned PhysReg = PhysDefs[i];
747 UsedInInstr.set(PhysReg);
748 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
749 unsigned Alias = *AS; ++AS)
750 UsedInInstr.set(Alias);
754 // Allocate defs and collect dead defs.
755 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
756 MachineOperand &MO = MI->getOperand(i);
757 if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue;
758 unsigned Reg = MO.getReg();
760 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
761 if (!Allocatable.test(Reg)) continue;
762 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
763 regFree : regReserved);
766 unsigned PhysReg = defineVirtReg(MI, i, Reg, CopySrc);
768 VirtKills.push_back(Reg);
769 CopyDst = 0; // cancel coalescing;
771 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
772 setPhysReg(MO, PhysReg);
775 // Spill all dirty virtregs before a call, in case of an exception.
777 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
781 // Process virtreg deads.
782 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
783 killVirtReg(VirtKills[i]);
786 MRI->addPhysRegsUsed(UsedInInstr);
788 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
789 DEBUG(dbgs() << "-- coalescing: " << *MI);
790 Coalesced.push_back(MI);
792 DEBUG(dbgs() << "<< " << *MI);
796 // Spill all physical registers holding virtual registers now.
798 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
799 if (MI != MBB->end() && MI->getDesc().isReturn()) {
800 // This is a return block, kill all virtual registers.
801 DEBUG(dbgs() << "Killing live registers at end of return block.\n");
802 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
806 // This is a normal block, spill any dirty virtregs.
807 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
808 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
810 spillVirtReg(MI, i, true);
812 LiveVirtRegs.clear();
814 // Erase all the coalesced copies. We are delaying it until now because
815 // LiveVirtsRegs might refer to the instrs.
816 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
817 MBB->erase(Coalesced[i]);
818 NumCopies += Coalesced.size();
823 /// runOnMachineFunction - Register allocate the whole function
825 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
826 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
827 << "********** Function: "
828 << ((Value*)Fn.getFunction())->getName() << '\n');
829 if (VerifyFastRegalloc)
830 Fn.verify(this, true);
832 MRI = &MF->getRegInfo();
833 TM = &Fn.getTarget();
834 TRI = TM->getRegisterInfo();
835 TII = TM->getInstrInfo();
837 UsedInInstr.resize(TRI->getNumRegs());
838 Allocatable = TRI->getAllocatableSet(*MF);
840 // initialize the virtual->physical register map to have a 'null'
841 // mapping for all virtual registers
842 unsigned LastVirtReg = MRI->getLastVirtReg();
843 StackSlotForVirtReg.grow(LastVirtReg);
845 // Loop over all of the basic blocks, eliminating virtual register references
846 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
847 MBBi != MBBe; ++MBBi) {
849 AllocateBasicBlock();
852 // Make sure the set of used physregs is closed under subreg operations.
853 MRI->closePhysRegsUsed(*TRI);
855 StackSlotForVirtReg.clear();
859 FunctionPass *llvm::createFastRegisterAllocator() {