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 STATISTIC(NumStores, "Number of stores added");
39 STATISTIC(NumLoads , "Number of loads added");
40 STATISTIC(NumCopies, "Number of copies coalesced");
42 static RegisterRegAlloc
43 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
46 class RAFast : public MachineFunctionPass {
49 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
50 isBulkSpilling(false) {}
52 const TargetMachine *TM;
54 MachineRegisterInfo *MRI;
55 const TargetRegisterInfo *TRI;
56 const TargetInstrInfo *TII;
58 // Basic block currently being allocated.
59 MachineBasicBlock *MBB;
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),
76 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
77 typedef LiveRegMap::value_type LiveRegEntry;
79 // LiveVirtRegs - This map contains entries for each virtual register
80 // that is currently available in a physical register.
81 LiveRegMap LiveVirtRegs;
83 // RegState - Track the state of a physical register.
85 // A disabled register is not available for allocation, but an alias may
86 // be in use. A register can only be moved out of the disabled state if
87 // all aliases are disabled.
90 // A free register is not currently in use and can be allocated
91 // immediately without checking aliases.
94 // A reserved register has been assigned expolicitly (e.g., setting up a
95 // call parameter), and it remains reserved until it is used.
98 // A register state may also be a virtual register number, indication that
99 // the physical register is currently allocated to a virtual register. In
100 // that case, LiveVirtRegs contains the inverse mapping.
103 // PhysRegState - One of the RegState enums, or a virtreg.
104 std::vector<unsigned> PhysRegState;
106 // UsedInInstr - BitVector of physregs that are used in the current
107 // instruction, and so cannot be allocated.
108 BitVector UsedInInstr;
110 // Allocatable - vector of allocatable physical registers.
111 BitVector Allocatable;
113 // SkippedInstrs - Descriptors of instructions whose clobber list was ignored
114 // because all registers were spilled. It is still necessary to mark all the
115 // clobbered registers as used by the function.
116 SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
118 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
119 // completely after spilling all live registers. LiveRegMap entries should
126 spillImpossible = ~0u
129 virtual const char *getPassName() const {
130 return "Fast Register Allocator";
133 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.setPreservesCFG();
135 AU.addRequiredID(PHIEliminationID);
136 AU.addRequiredID(TwoAddressInstructionPassID);
137 MachineFunctionPass::getAnalysisUsage(AU);
141 bool runOnMachineFunction(MachineFunction &Fn);
142 void AllocateBasicBlock();
143 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
144 bool isLastUseOfLocalReg(MachineOperand&);
146 void addKillFlag(const LiveReg&);
147 void killVirtReg(LiveRegMap::iterator);
148 void killVirtReg(unsigned VirtReg);
149 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
150 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
152 void usePhysReg(MachineOperand&);
153 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
154 unsigned calcSpillCost(unsigned PhysReg) const;
155 void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
156 void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
157 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
158 unsigned VirtReg, unsigned Hint);
159 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
160 unsigned VirtReg, unsigned Hint);
161 void spillAll(MachineInstr *MI);
162 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
167 /// getStackSpaceFor - This allocates space for the specified virtual register
168 /// to be held on the stack.
169 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
170 // Find the location Reg would belong...
171 int SS = StackSlotForVirtReg[VirtReg];
173 return SS; // Already has space allocated?
175 // Allocate a new stack object for this spill location...
176 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
180 StackSlotForVirtReg[VirtReg] = FrameIdx;
184 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
185 /// its virtual register, and it is guaranteed to be a block-local register.
187 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
188 // Check for non-debug uses or defs following MO.
189 // This is the most likely way to fail - fast path it.
190 MachineOperand *Next = &MO;
191 while ((Next = Next->getNextOperandForReg()))
192 if (!Next->isDebug())
195 // If the register has ever been spilled or reloaded, we conservatively assume
196 // it is a global register used in multiple blocks.
197 if (StackSlotForVirtReg[MO.getReg()] != -1)
200 // Check that the use/def chain has exactly one operand - MO.
201 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
204 /// addKillFlag - Set kill flags on last use of a virtual register.
205 void RAFast::addKillFlag(const LiveReg &LR) {
206 if (!LR.LastUse) return;
207 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
208 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
209 if (MO.getReg() == LR.PhysReg)
212 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
216 /// killVirtReg - Mark virtreg as no longer available.
217 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
218 addKillFlag(LRI->second);
219 const LiveReg &LR = LRI->second;
220 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
221 PhysRegState[LR.PhysReg] = regFree;
222 // Erase from LiveVirtRegs unless we're spilling in bulk.
224 LiveVirtRegs.erase(LRI);
227 /// killVirtReg - Mark virtreg as no longer available.
228 void RAFast::killVirtReg(unsigned VirtReg) {
229 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
230 "killVirtReg needs a virtual register");
231 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
232 if (LRI != LiveVirtRegs.end())
236 /// spillVirtReg - This method spills the value specified by VirtReg into the
237 /// corresponding stack slot if needed. If isKill is set, the register is also
239 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
240 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
241 "Spilling a physical register is illegal!");
242 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
243 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
244 spillVirtReg(MI, LRI);
247 /// spillVirtReg - Do the actual work of spilling.
248 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
249 LiveRegMap::iterator LRI) {
250 LiveReg &LR = LRI->second;
251 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
254 // If this physreg is used by the instruction, we want to kill it on the
255 // instruction, not on the spill.
256 bool SpillKill = LR.LastUse != MI;
258 DEBUG(dbgs() << "Spilling %reg" << LRI->first
259 << " in " << TRI->getName(LR.PhysReg));
260 const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
261 int FI = getStackSpaceFor(LRI->first, RC);
262 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
263 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
264 ++NumStores; // Update statistics
267 LR.LastUse = 0; // Don't kill register again
272 /// spillAll - Spill all dirty virtregs without killing them.
273 void RAFast::spillAll(MachineInstr *MI) {
274 if (LiveVirtRegs.empty()) return;
275 isBulkSpilling = true;
276 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
277 // of spilling here is deterministic, if arbitrary.
278 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
281 LiveVirtRegs.clear();
282 isBulkSpilling = 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);
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);
376 PhysRegState[Alias] = regDisabled;
377 if (TRI->isSuperRegister(PhysReg, Alias))
385 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
386 // aliases so it is free for allocation.
387 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
388 // can be allocated directly.
389 // Returns spillImpossible when PhysReg or an alias can't be spilled.
390 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
391 if (UsedInInstr.test(PhysReg))
392 return spillImpossible;
393 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
399 return spillImpossible;
401 return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
404 // This is a disabled register, add up const of aliases.
406 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
407 unsigned Alias = *AS; ++AS) {
408 if (UsedInInstr.test(Alias))
409 return spillImpossible;
410 switch (unsigned VirtReg = PhysRegState[Alias]) {
417 return spillImpossible;
419 Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
427 /// assignVirtToPhysReg - This method updates local state so that we know
428 /// that PhysReg is the proper container for VirtReg now. The physical
429 /// register must not be used for anything else when this is called.
431 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
432 DEBUG(dbgs() << "Assigning %reg" << LRE.first << " to "
433 << TRI->getName(PhysReg) << "\n");
434 PhysRegState[PhysReg] = LRE.first;
435 assert(!LRE.second.PhysReg && "Already assigned a physreg");
436 LRE.second.PhysReg = PhysReg;
439 /// allocVirtReg - Allocate a physical register for VirtReg.
440 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
441 const unsigned VirtReg = LRE.first;
443 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
444 "Can only allocate virtual registers");
446 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
448 // Ignore invalid hints.
449 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
450 !RC->contains(Hint) || !Allocatable.test(Hint)))
453 // Take hint when possible.
455 switch(calcSpillCost(Hint)) {
457 definePhysReg(MI, Hint, regFree);
460 return assignVirtToPhysReg(LRE, Hint);
461 case spillImpossible:
466 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
467 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
469 // First try to find a completely free register.
470 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
471 unsigned PhysReg = *I;
472 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
473 return assignVirtToPhysReg(LRE, PhysReg);
476 DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
479 unsigned BestReg = 0, BestCost = spillImpossible;
480 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
481 unsigned Cost = calcSpillCost(*I);
482 // Cost is 0 when all aliases are already disabled.
484 return assignVirtToPhysReg(LRE, *I);
486 BestReg = *I, BestCost = Cost;
490 definePhysReg(MI, BestReg, regFree);
491 return assignVirtToPhysReg(LRE, BestReg);
494 // Nothing we can do.
496 raw_string_ostream Msg(msg);
497 Msg << "Ran out of registers during register allocation!";
498 if (MI->isInlineAsm()) {
499 Msg << "\nPlease check your inline asm statement for "
500 << "invalid constraints:\n";
503 report_fatal_error(Msg.str());
506 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
507 RAFast::LiveRegMap::iterator
508 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
509 unsigned VirtReg, unsigned Hint) {
510 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
511 "Not a virtual register");
512 LiveRegMap::iterator LRI;
514 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
515 LiveReg &LR = LRI->second;
516 bool PartialRedef = MI->getOperand(OpNum).getSubReg();
518 // If there is no hint, peek at the only use of this register.
519 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
520 MRI->hasOneNonDBGUse(VirtReg)) {
521 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
522 // It's a copy, use the destination register as a hint.
523 if (TII->isMoveInstr(*MRI->use_nodbg_begin(VirtReg),
524 SrcReg, DstReg, SrcSubReg, DstSubReg))
527 allocVirtReg(MI, *LRI, Hint);
528 // If this is only a partial redefinition, we must reload the other parts.
529 if (PartialRedef && MI->readsVirtualRegister(VirtReg)) {
530 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
531 int FI = getStackSpaceFor(VirtReg, RC);
532 DEBUG(dbgs() << "Reloading for partial redef: %reg" << VirtReg << "\n");
533 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FI, RC, TRI);
536 } else if (LR.LastUse && !PartialRedef) {
537 // Redefining a live register - kill at the last use, unless it is this
538 // instruction defining VirtReg multiple times.
539 if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
542 assert(LR.PhysReg && "Register not assigned");
544 LR.LastOpNum = OpNum;
546 UsedInInstr.set(LR.PhysReg);
550 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
551 RAFast::LiveRegMap::iterator
552 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
553 unsigned VirtReg, unsigned Hint) {
554 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
555 "Not a virtual register");
556 LiveRegMap::iterator LRI;
558 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
559 LiveReg &LR = LRI->second;
560 MachineOperand &MO = MI->getOperand(OpNum);
562 allocVirtReg(MI, *LRI, Hint);
563 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
564 int FrameIndex = getStackSpaceFor(VirtReg, RC);
565 DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
566 << TRI->getName(LR.PhysReg) << "\n");
567 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
569 } else if (LR.Dirty) {
570 if (isLastUseOfLocalReg(MO)) {
571 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
573 } else if (MO.isKill()) {
574 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
577 } else if (MO.isKill()) {
578 // We must remove kill flags from uses of reloaded registers because the
579 // register would be killed immediately, and there might be a second use:
580 // %foo = OR %x<kill>, %x
581 // This would cause a second reload of %x into a different register.
582 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
585 assert(LR.PhysReg && "Register not assigned");
587 LR.LastOpNum = OpNum;
588 UsedInInstr.set(LR.PhysReg);
592 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
593 // subregs. This may invalidate any operand pointers.
594 // Return true if the operand kills its register.
595 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
596 MachineOperand &MO = MI->getOperand(OpNum);
597 if (!MO.getSubReg()) {
599 return MO.isKill() || MO.isDead();
602 // Handle subregister index.
603 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
606 // A kill flag implies killing the full register. Add corresponding super
609 MI->addRegisterKilled(PhysReg, TRI, true);
615 void RAFast::AllocateBasicBlock() {
616 DEBUG(dbgs() << "\nAllocating " << *MBB);
618 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
619 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
621 MachineBasicBlock::iterator MII = MBB->begin();
623 // Add live-in registers as live.
624 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
625 E = MBB->livein_end(); I != E; ++I)
626 definePhysReg(MII, *I, regReserved);
628 SmallVector<unsigned, 8> PhysECs, VirtDead;
629 SmallVector<MachineInstr*, 32> Coalesced;
631 // Otherwise, sequentially allocate each instruction in the MBB.
632 while (MII != MBB->end()) {
633 MachineInstr *MI = MII++;
634 const TargetInstrDesc &TID = MI->getDesc();
636 dbgs() << "\n>> " << *MI << "Regs:";
637 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
638 if (PhysRegState[Reg] == regDisabled) continue;
639 dbgs() << " " << TRI->getName(Reg);
640 switch(PhysRegState[Reg]) {
647 dbgs() << "=%reg" << PhysRegState[Reg];
648 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
650 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
656 // Check that LiveVirtRegs is the inverse.
657 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
658 e = LiveVirtRegs.end(); i != e; ++i) {
659 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
661 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
663 assert(PhysRegState[i->second.PhysReg] == i->first &&
668 // Debug values are not allowed to change codegen in any way.
669 if (MI->isDebugValue()) {
670 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
671 MachineOperand &MO = MI->getOperand(i);
672 if (!MO.isReg()) continue;
673 unsigned Reg = MO.getReg();
674 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
675 LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
676 if (LRI != LiveVirtRegs.end())
677 setPhysReg(MI, i, LRI->second.PhysReg);
679 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
685 // If this is a copy, we may be able to coalesce.
686 unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
687 if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
688 CopySrc = CopyDst = 0;
690 // Track registers used by instruction.
695 // Mark physreg uses and early clobbers as used.
696 // Find the end of the virtreg operands
697 unsigned VirtOpEnd = 0;
698 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
699 MachineOperand &MO = MI->getOperand(i);
700 if (!MO.isReg()) continue;
701 unsigned Reg = MO.getReg();
703 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
707 if (!Allocatable.test(Reg)) continue;
710 } else if (MO.isEarlyClobber()) {
711 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
712 regFree : regReserved);
713 PhysECs.push_back(Reg);
718 // Allocate virtreg uses and early clobbers.
720 for (unsigned i = 0; i != VirtOpEnd; ++i) {
721 MachineOperand &MO = MI->getOperand(i);
722 if (!MO.isReg()) continue;
723 unsigned Reg = MO.getReg();
724 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
726 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
727 unsigned PhysReg = LRI->second.PhysReg;
728 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
729 if (setPhysReg(MI, i, PhysReg))
731 } else if (MO.isEarlyClobber()) {
732 // Note: defineVirtReg may invalidate MO.
733 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
734 unsigned PhysReg = LRI->second.PhysReg;
735 if (setPhysReg(MI, i, PhysReg))
736 VirtDead.push_back(Reg);
737 PhysECs.push_back(PhysReg);
738 // Don't attempt coalescing when earlyclobbers are present.
743 MRI->addPhysRegsUsed(UsedInInstr);
745 // Track registers defined by instruction - early clobbers at this point.
747 for (unsigned i = 0, e = PhysECs.size(); i != e; ++i) {
748 unsigned PhysReg = PhysECs[i];
749 UsedInInstr.set(PhysReg);
750 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
751 unsigned Alias = *AS; ++AS)
752 UsedInInstr.set(Alias);
755 unsigned DefOpEnd = MI->getNumOperands();
757 // Spill all virtregs before a call. This serves two purposes: 1. If an
758 // exception is thrown, the landing pad is going to expect to find registers
759 // in their spill slots, and 2. we don't have to wade through all the
760 // <imp-def> operands on the call instruction.
761 DefOpEnd = VirtOpEnd;
762 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
765 // The imp-defs are skipped below, but we still need to mark those
766 // registers as used by the function.
767 SkippedInstrs.insert(&TID);
771 // Allocate defs and collect dead defs.
772 for (unsigned i = 0; i != DefOpEnd; ++i) {
773 MachineOperand &MO = MI->getOperand(i);
774 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
776 unsigned Reg = MO.getReg();
778 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
779 if (!Allocatable.test(Reg)) continue;
780 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
781 regFree : regReserved);
784 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
785 unsigned PhysReg = LRI->second.PhysReg;
786 if (setPhysReg(MI, i, PhysReg)) {
787 VirtDead.push_back(Reg);
788 CopyDst = 0; // cancel coalescing;
790 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
793 // Kill dead defs after the scan to ensure that multiple defs of the same
794 // register are allocated identically. We didn't need to do this for uses
795 // because we are crerating our own kill flags, and they are always at the
797 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
798 killVirtReg(VirtDead[i]);
801 MRI->addPhysRegsUsed(UsedInInstr);
803 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
804 DEBUG(dbgs() << "-- coalescing: " << *MI);
805 Coalesced.push_back(MI);
807 DEBUG(dbgs() << "<< " << *MI);
811 // Spill all physical registers holding virtual registers now.
812 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
813 spillAll(MBB->getFirstTerminator());
815 // Erase all the coalesced copies. We are delaying it until now because
816 // LiveVirtRegs might refer to the instrs.
817 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
818 MBB->erase(Coalesced[i]);
819 NumCopies += Coalesced.size();
824 /// runOnMachineFunction - Register allocate the whole function
826 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
827 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
828 << "********** Function: "
829 << ((Value*)Fn.getFunction())->getName() << '\n');
831 MRI = &MF->getRegInfo();
832 TM = &Fn.getTarget();
833 TRI = TM->getRegisterInfo();
834 TII = TM->getInstrInfo();
836 UsedInInstr.resize(TRI->getNumRegs());
837 Allocatable = TRI->getAllocatableSet(*MF);
839 // initialize the virtual->physical register map to have a 'null'
840 // mapping for all virtual registers
841 unsigned LastVirtReg = MRI->getLastVirtReg();
842 StackSlotForVirtReg.grow(LastVirtReg);
844 // Loop over all of the basic blocks, eliminating virtual register references
845 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
846 MBBi != MBBe; ++MBBi) {
848 AllocateBasicBlock();
851 // Make sure the set of used physregs is closed under subreg operations.
852 MRI->closePhysRegsUsed(*TRI);
854 // Add the clobber lists for all the instructions we skipped earlier.
855 for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
856 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
857 if (const unsigned *Defs = (*I)->getImplicitDefs())
859 MRI->setPhysRegUsed(*Defs++);
861 SkippedInstrs.clear();
862 StackSlotForVirtReg.clear();
866 FunctionPass *llvm::createFastRegisterAllocator() {