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/LiveVariables.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IndexedMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
42 static RegisterRegAlloc
43 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
46 class RAFast : public MachineFunctionPass {
49 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
51 const TargetMachine *TM;
53 const TargetRegisterInfo *TRI;
54 const TargetInstrInfo *TII;
56 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57 // values are spilled.
58 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
60 // Virt2PhysRegMap - This map contains entries for each virtual register
61 // that is currently available in a physical register.
62 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
64 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
65 return Virt2PhysRegMap[VirtReg];
68 // PhysRegsUsed - This array is effectively a map, containing entries for
69 // each physical register that currently has a value (ie, it is in
70 // Virt2PhysRegMap). The value mapped to is the virtual register
71 // corresponding to the physical register (the inverse of the
72 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
73 // because it is used by a future instruction, and to -2 if it is not
74 // allocatable. If the entry for a physical register is -1, then the
75 // physical register is "not in the map".
77 std::vector<int> PhysRegsUsed;
79 // UsedInInstr - BitVector of physregs that are used in the current
80 // instruction, and so cannot be allocated.
81 BitVector UsedInInstr;
83 // Virt2LastUseMap - This maps each virtual register to its last use
84 // (MachineInstr*, operand index pair).
85 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
88 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
89 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
90 return Virt2LastUseMap[Reg];
93 // VirtRegModified - This bitset contains information about which virtual
94 // registers need to be spilled back to memory when their registers are
95 // scavenged. If a virtual register has simply been rematerialized, there
96 // is no reason to spill it to memory when we need the register back.
98 BitVector VirtRegModified;
100 // UsedInMultipleBlocks - Tracks whether a particular register is used in
101 // more than one block.
102 BitVector UsedInMultipleBlocks;
104 void markVirtRegModified(unsigned Reg, bool Val = true) {
105 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
106 Reg -= TargetRegisterInfo::FirstVirtualRegister;
108 VirtRegModified.set(Reg);
110 VirtRegModified.reset(Reg);
113 bool isVirtRegModified(unsigned Reg) const {
114 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
115 assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
116 VirtRegModified.size() && "Illegal virtual register!");
117 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
121 virtual const char *getPassName() const {
122 return "Fast Register Allocator";
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.setPreservesCFG();
127 AU.addRequired<LiveVariables>();
128 AU.addRequiredID(PHIEliminationID);
129 AU.addRequiredID(TwoAddressInstructionPassID);
130 MachineFunctionPass::getAnalysisUsage(AU);
134 /// runOnMachineFunction - Register allocate the whole function
135 bool runOnMachineFunction(MachineFunction &Fn);
137 /// AllocateBasicBlock - Register allocate the specified basic block.
138 void AllocateBasicBlock(MachineBasicBlock &MBB);
141 /// areRegsEqual - This method returns true if the specified registers are
142 /// related to each other. To do this, it checks to see if they are equal
143 /// or if the first register is in the alias set of the second register.
145 bool areRegsEqual(unsigned R1, unsigned R2) const {
146 if (R1 == R2) return true;
147 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
148 *AliasSet; ++AliasSet) {
149 if (*AliasSet == R1) return true;
154 /// getStackSpaceFor - This returns the frame index of the specified virtual
155 /// register on the stack, allocating space if necessary.
156 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
158 /// removePhysReg - This method marks the specified physical register as no
159 /// longer being in use.
161 void removePhysReg(unsigned PhysReg);
163 /// spillVirtReg - This method spills the value specified by PhysReg into
164 /// the virtual register slot specified by VirtReg. It then updates the RA
165 /// data structures to indicate the fact that PhysReg is now available.
167 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
168 unsigned VirtReg, unsigned PhysReg);
170 /// spillPhysReg - This method spills the specified physical register into
171 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
172 /// true, then the request is ignored if the physical register does not
173 /// contain a virtual register.
175 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
176 unsigned PhysReg, bool OnlyVirtRegs = false);
178 /// assignVirtToPhysReg - This method updates local state so that we know
179 /// that PhysReg is the proper container for VirtReg now. The physical
180 /// register must not be used for anything else when this is called.
182 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
184 /// isPhysRegAvailable - Return true if the specified physical register is
185 /// free and available for use. This also includes checking to see if
186 /// aliased registers are all free...
188 bool isPhysRegAvailable(unsigned PhysReg) const;
190 /// isPhysRegSpillable - Can PhysReg be freed by spilling?
191 bool isPhysRegSpillable(unsigned PhysReg) const;
193 /// getFreeReg - Look to see if there is a free register available in the
194 /// specified register class. If not, return 0.
196 unsigned getFreeReg(const TargetRegisterClass *RC);
198 /// getReg - Find a physical register to hold the specified virtual
199 /// register. If all compatible physical registers are used, this method
200 /// spills the last used virtual register to the stack, and uses that
201 /// register. If NoFree is true, that means the caller knows there isn't
202 /// a free register, do not call getFreeReg().
203 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
204 unsigned VirtReg, bool NoFree = false);
206 /// reloadVirtReg - This method transforms the specified virtual
207 /// register use to refer to a physical register. This method may do this
208 /// in one of several ways: if the register is available in a physical
209 /// register already, it uses that physical register. If the value is not
210 /// in a physical register, and if there are physical registers available,
211 /// it loads it into a register: PhysReg if that is an available physical
212 /// register, otherwise any physical register of the right class.
213 /// If register pressure is high, and it is possible, it tries to fold the
214 /// load of the virtual register into the instruction itself. It avoids
215 /// doing this if register pressure is low to improve the chance that
216 /// subsequent instructions can use the reloaded value. This method
217 /// returns the modified instruction.
219 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
220 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
223 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
229 /// getStackSpaceFor - This allocates space for the specified virtual register
230 /// to be held on the stack.
231 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
232 // Find the location Reg would belong...
233 int SS = StackSlotForVirtReg[VirtReg];
235 return SS; // Already has space allocated?
237 // Allocate a new stack object for this spill location...
238 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
242 StackSlotForVirtReg[VirtReg] = FrameIdx;
247 /// removePhysReg - This method marks the specified physical register as no
248 /// longer being in use.
250 void RAFast::removePhysReg(unsigned PhysReg) {
251 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
255 /// spillVirtReg - This method spills the value specified by PhysReg into the
256 /// virtual register slot specified by VirtReg. It then updates the RA data
257 /// structures to indicate the fact that PhysReg is now available.
259 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
260 MachineBasicBlock::iterator I,
261 unsigned VirtReg, unsigned PhysReg) {
262 assert(VirtReg && "Spilling a physical register is illegal!"
263 " Must not have appropriate kill for the register or use exists beyond"
264 " the intended one.");
265 DEBUG(dbgs() << " Spilling register " << TRI->getName(PhysReg)
266 << " containing %reg" << VirtReg);
268 if (!isVirtRegModified(VirtReg)) {
269 DEBUG(dbgs() << " which has not been modified, so no store necessary!");
270 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
272 LastUse.first->getOperand(LastUse.second).setIsKill();
274 // Otherwise, there is a virtual register corresponding to this physical
275 // register. We only need to spill it into its stack slot if it has been
277 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
278 int FrameIndex = getStackSpaceFor(VirtReg, RC);
279 DEBUG(dbgs() << " to stack slot #" << FrameIndex);
280 // If the instruction reads the register that's spilled, (e.g. this can
281 // happen if it is a move to a physical register), then the spill
282 // instruction is not a kill.
283 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
284 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC, TRI);
285 ++NumStores; // Update statistics
288 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
290 DEBUG(dbgs() << '\n');
291 removePhysReg(PhysReg);
295 /// spillPhysReg - This method spills the specified physical register into the
296 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
297 /// then the request is ignored if the physical register does not contain a
298 /// virtual register.
300 void RAFast::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
301 unsigned PhysReg, bool OnlyVirtRegs) {
302 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
303 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
304 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
305 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
309 // If the selected register aliases any other registers, we must make
310 // sure that one of the aliases isn't alive.
311 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
312 *AliasSet; ++AliasSet) {
313 if (PhysRegsUsed[*AliasSet] == -1 || // Spill aliased register.
314 PhysRegsUsed[*AliasSet] == -2) // If allocatable.
317 if (PhysRegsUsed[*AliasSet])
318 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
323 /// assignVirtToPhysReg - This method updates local state so that we know
324 /// that PhysReg is the proper container for VirtReg now. The physical
325 /// register must not be used for anything else when this is called.
327 void RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
328 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
329 // Update information to note the fact that this register was just used, and
331 PhysRegsUsed[PhysReg] = VirtReg;
332 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
333 UsedInInstr.set(PhysReg);
337 /// isPhysRegAvailable - Return true if the specified physical register is free
338 /// and available for use. This also includes checking to see if aliased
339 /// registers are all free...
341 bool RAFast::isPhysRegAvailable(unsigned PhysReg) const {
342 if (PhysRegsUsed[PhysReg] != -1) return false;
344 // If the selected register aliases any other allocated registers, it is
346 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
347 *AliasSet; ++AliasSet)
348 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
349 return false; // Can't use this reg then.
353 /// isPhysRegSpillable - Return true if the specified physical register can be
354 /// spilled for use in the current instruction.
356 bool RAFast::isPhysRegSpillable(unsigned PhysReg) const {
357 // Test that PhysReg and all aliases are either free or assigned to a VirtReg
358 // that is not used in the instruction.
359 if (PhysRegsUsed[PhysReg] != -1 &&
360 (PhysRegsUsed[PhysReg] <= 0 || UsedInInstr.test(PhysReg)))
363 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
364 *AliasSet; ++AliasSet)
365 if (PhysRegsUsed[*AliasSet] != -1 &&
366 (PhysRegsUsed[*AliasSet] <= 0 || UsedInInstr.test(*AliasSet)))
372 /// getFreeReg - Look to see if there is a free register available in the
373 /// specified register class. If not, return 0.
375 unsigned RAFast::getFreeReg(const TargetRegisterClass *RC) {
376 // Get iterators defining the range of registers that are valid to allocate in
377 // this class, which also specifies the preferred allocation order.
378 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
379 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
381 for (; RI != RE; ++RI)
382 if (isPhysRegAvailable(*RI)) { // Is reg unused?
383 assert(*RI != 0 && "Cannot use register!");
384 return *RI; // Found an unused register!
390 /// getReg - Find a physical register to hold the specified virtual
391 /// register. If all compatible physical registers are used, this method spills
392 /// the last used virtual register to the stack, and uses that register.
394 unsigned RAFast::getReg(MachineBasicBlock &MBB, MachineInstr *I,
395 unsigned VirtReg, bool NoFree) {
396 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
398 // First check to see if we have a free register of the requested type...
399 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
402 // Assign the register.
403 assignVirtToPhysReg(VirtReg, PhysReg);
407 // If we didn't find an unused register, scavenge one now! Don't be fancy,
408 // just grab the first possible register.
409 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
410 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
412 for (; RI != RE; ++RI)
413 if (isPhysRegSpillable(*RI)) {
418 assert(PhysReg && "Physical register not assigned!?!?");
419 spillPhysReg(MBB, I, PhysReg);
420 assignVirtToPhysReg(VirtReg, PhysReg);
425 /// reloadVirtReg - This method transforms the specified virtual
426 /// register use to refer to a physical register. This method may do this in
427 /// one of several ways: if the register is available in a physical register
428 /// already, it uses that physical register. If the value is not in a physical
429 /// register, and if there are physical registers available, it loads it into a
430 /// register: PhysReg if that is an available physical register, otherwise any
431 /// register. If register pressure is high, and it is possible, it tries to
432 /// fold the load of the virtual register into the instruction itself. It
433 /// avoids doing this if register pressure is low to improve the chance that
434 /// subsequent instructions can use the reloaded value. This method returns
435 /// the modified instruction.
437 MachineInstr *RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
439 SmallSet<unsigned, 4> &ReloadedRegs,
441 unsigned VirtReg = MI->getOperand(OpNum).getReg();
443 // If the virtual register is already available, just update the instruction
445 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
446 MI->getOperand(OpNum).setReg(PR); // Assign the input register
447 if (!MI->isDebugValue()) {
448 // Do not do these for DBG_VALUE as they can affect codegen.
450 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
455 // Otherwise, we need to fold it into the current instruction, or reload it.
456 // If we have registers available to hold the value, use them.
457 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
458 // If we already have a PhysReg (this happens when the instruction is a
459 // reg-to-reg copy with a PhysReg destination) use that.
460 if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
461 !isPhysRegAvailable(PhysReg))
462 PhysReg = getFreeReg(RC);
463 int FrameIndex = getStackSpaceFor(VirtReg, RC);
465 if (PhysReg) { // Register is available, allocate it!
466 assignVirtToPhysReg(VirtReg, PhysReg);
467 } else { // No registers available.
468 // Force some poor hapless value out of the register file to
469 // make room for the new register, and reload it.
470 PhysReg = getReg(MBB, MI, VirtReg, true);
473 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
475 DEBUG(dbgs() << " Reloading %reg" << VirtReg << " into "
476 << TRI->getName(PhysReg) << "\n");
478 // Add move instruction(s)
479 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC, TRI);
480 ++NumLoads; // Update statistics
482 MF->getRegInfo().setPhysRegUsed(PhysReg);
483 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
484 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
486 if (!ReloadedRegs.insert(PhysReg)) {
488 raw_string_ostream Msg(msg);
489 Msg << "Ran out of registers during register allocation!";
490 if (MI->isInlineAsm()) {
491 Msg << "\nPlease check your inline asm statement for invalid "
495 report_fatal_error(Msg.str());
497 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
498 *SubRegs; ++SubRegs) {
499 if (ReloadedRegs.insert(*SubRegs)) continue;
502 raw_string_ostream Msg(msg);
503 Msg << "Ran out of registers during register allocation!";
504 if (MI->isInlineAsm()) {
505 Msg << "\nPlease check your inline asm statement for invalid "
509 report_fatal_error(Msg.str());
515 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
516 /// read/mod/write register, i.e. update partial register.
517 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
518 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
519 MachineOperand &MO = MI->getOperand(i);
520 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
521 MO.isDef() && !MO.isDead())
527 /// isReadModWriteImplicitDef - True if this is an implicit def for a
528 /// read/mod/write register, i.e. update partial register.
529 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
530 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
531 MachineOperand &MO = MI->getOperand(i);
532 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
533 !MO.isDef() && MO.isKill())
539 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
540 // loop over each instruction
541 MachineBasicBlock::iterator MII = MBB.begin();
544 const BasicBlock *LBB = MBB.getBasicBlock();
546 dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
549 // Add live-in registers as active.
550 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
551 E = MBB.livein_end(); I != E; ++I) {
553 MF->getRegInfo().setPhysRegUsed(Reg);
554 PhysRegsUsed[Reg] = 0; // It is free and reserved now
555 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
556 *SubRegs; ++SubRegs) {
557 if (PhysRegsUsed[*SubRegs] == -2) continue;
558 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
559 MF->getRegInfo().setPhysRegUsed(*SubRegs);
563 // Otherwise, sequentially allocate each instruction in the MBB.
564 while (MII != MBB.end()) {
565 MachineInstr *MI = MII++;
566 const TargetInstrDesc &TID = MI->getDesc();
568 dbgs() << "\nStarting RegAlloc of: " << *MI;
569 dbgs() << " Regs have values: ";
570 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
571 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
572 dbgs() << "[" << TRI->getName(i)
573 << ",%reg" << PhysRegsUsed[i] << "] ";
577 // Track registers used by instruction.
580 // Determine whether this is a copy instruction. The cases where the
581 // source or destination are phys regs are handled specially.
582 unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
583 unsigned SrcCopyPhysReg = 0U;
584 bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
585 SrcCopySubReg, DstCopySubReg);
586 if (isCopy && SrcCopySubReg == 0 && DstCopySubReg == 0 &&
587 TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
588 SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
590 // Loop over the implicit uses, making sure they don't get reallocated.
591 if (TID.ImplicitUses) {
592 for (const unsigned *ImplicitUses = TID.ImplicitUses;
593 *ImplicitUses; ++ImplicitUses)
594 UsedInInstr.set(*ImplicitUses);
597 SmallVector<unsigned, 8> Kills;
598 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
599 MachineOperand &MO = MI->getOperand(i);
600 if (!MO.isReg() || !MO.isKill()) continue;
602 if (!MO.isImplicit())
603 Kills.push_back(MO.getReg());
604 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
605 // These are extra physical register kills when a sub-register
606 // is defined (def of a sub-register is a read/mod/write of the
607 // larger registers). Ignore.
608 Kills.push_back(MO.getReg());
611 // If any physical regs are earlyclobber, spill any value they might
612 // have in them, then mark them unallocatable.
613 // If any virtual regs are earlyclobber, allocate them now (before
614 // freeing inputs that are killed).
615 if (MI->isInlineAsm()) {
616 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
617 MachineOperand &MO = MI->getOperand(i);
618 if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
622 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
623 unsigned DestVirtReg = MO.getReg();
624 unsigned DestPhysReg;
626 // If DestVirtReg already has a value, use it.
627 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
628 DestPhysReg = getReg(MBB, MI, DestVirtReg);
629 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
630 markVirtRegModified(DestVirtReg);
631 getVirtRegLastUse(DestVirtReg) =
632 std::make_pair((MachineInstr*)0, 0);
633 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
634 << " to %reg" << DestVirtReg << "\n");
635 MO.setReg(DestPhysReg); // Assign the earlyclobber register
637 unsigned Reg = MO.getReg();
638 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
639 // These are extra physical register defs when a sub-register
640 // is defined (def of a sub-register is a read/mod/write of the
641 // larger registers). Ignore.
642 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
644 MF->getRegInfo().setPhysRegUsed(Reg);
645 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
646 PhysRegsUsed[Reg] = 0; // It is free and reserved now
648 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
649 *SubRegs; ++SubRegs) {
650 if (PhysRegsUsed[*SubRegs] == -2) continue;
651 MF->getRegInfo().setPhysRegUsed(*SubRegs);
652 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
658 // If a DBG_VALUE says something is located in a spilled register,
659 // change the DBG_VALUE to be undef, which prevents the register
660 // from being reloaded here. Doing that would change the generated
661 // code, unless another use immediately follows this instruction.
662 if (MI->isDebugValue() &&
663 MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
664 unsigned VirtReg = MI->getOperand(0).getReg();
665 if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
666 !getVirt2PhysRegMapSlot(VirtReg))
667 MI->getOperand(0).setReg(0U);
670 // Get the used operands into registers. This has the potential to spill
671 // incoming values if we are out of registers. Note that we completely
672 // ignore physical register uses here. We assume that if an explicit
673 // physical register is referenced by the instruction, that it is guaranteed
674 // to be live-in, or the input is badly hosed.
676 SmallSet<unsigned, 4> ReloadedRegs;
677 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
678 MachineOperand &MO = MI->getOperand(i);
679 // here we are looking for only used operands (never def&use)
680 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
681 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
682 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
683 isCopy ? DstCopyReg : 0);
686 // If this instruction is the last user of this register, kill the
687 // value, freeing the register being used, so it doesn't need to be
688 // spilled to memory.
690 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
691 unsigned VirtReg = Kills[i];
692 unsigned PhysReg = VirtReg;
693 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
694 // If the virtual register was never materialized into a register, it
695 // might not be in the map, but it won't hurt to zero it out anyway.
696 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
697 PhysReg = PhysRegSlot;
699 } else if (PhysRegsUsed[PhysReg] == -2) {
700 // Unallocatable register dead, ignore.
703 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
704 "Silently clearing a virtual register?");
707 if (!PhysReg) continue;
709 DEBUG(dbgs() << " Last use of " << TRI->getName(PhysReg)
710 << "[%reg" << VirtReg <<"], removing it from live set\n");
711 removePhysReg(PhysReg);
712 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
713 *SubRegs; ++SubRegs) {
714 if (PhysRegsUsed[*SubRegs] != -2) {
715 DEBUG(dbgs() << " Last use of "
716 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
717 <<"], removing it from live set\n");
718 removePhysReg(*SubRegs);
723 // Track registers defined by instruction.
726 // Loop over all of the operands of the instruction, spilling registers that
727 // are defined, and marking explicit destinations in the PhysRegsUsed map.
728 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
729 MachineOperand &MO = MI->getOperand(i);
730 if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
731 MO.isEarlyClobber() ||
732 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
735 unsigned Reg = MO.getReg();
736 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
737 // These are extra physical register defs when a sub-register
738 // is defined (def of a sub-register is a read/mod/write of the
739 // larger registers). Ignore.
740 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
742 MF->getRegInfo().setPhysRegUsed(Reg);
743 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
744 PhysRegsUsed[Reg] = 0; // It is free and reserved now
746 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
747 *SubRegs; ++SubRegs) {
748 if (PhysRegsUsed[*SubRegs] == -2) continue;
750 MF->getRegInfo().setPhysRegUsed(*SubRegs);
751 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
755 // Loop over the implicit defs, spilling them as well.
756 if (TID.ImplicitDefs) {
757 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
758 *ImplicitDefs; ++ImplicitDefs) {
759 unsigned Reg = *ImplicitDefs;
760 if (PhysRegsUsed[Reg] != -2) {
761 spillPhysReg(MBB, MI, Reg, true);
762 PhysRegsUsed[Reg] = 0; // It is free and reserved now
764 MF->getRegInfo().setPhysRegUsed(Reg);
765 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
766 *SubRegs; ++SubRegs) {
767 if (PhysRegsUsed[*SubRegs] == -2) continue;
769 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
770 MF->getRegInfo().setPhysRegUsed(*SubRegs);
775 SmallVector<unsigned, 8> DeadDefs;
776 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
777 MachineOperand &MO = MI->getOperand(i);
778 if (MO.isReg() && MO.isDead())
779 DeadDefs.push_back(MO.getReg());
782 // Okay, we have allocated all of the source operands and spilled any values
783 // that would be destroyed by defs of this instruction. Loop over the
784 // explicit defs and assign them to a register, spilling incoming values if
785 // we need to scavenge a register.
787 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
788 MachineOperand &MO = MI->getOperand(i);
789 if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
790 MO.isEarlyClobber() ||
791 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
794 unsigned DestVirtReg = MO.getReg();
795 unsigned DestPhysReg;
797 // If DestVirtReg already has a value, use it.
798 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
799 // If this is a copy try to reuse the input as the output;
800 // that will make the copy go away.
801 // If this is a copy, the source reg is a phys reg, and
802 // that reg is available, use that phys reg for DestPhysReg.
803 // If this is a copy, the source reg is a virtual reg, and
804 // the phys reg that was assigned to that virtual reg is now
805 // available, use that phys reg for DestPhysReg. (If it's now
806 // available that means this was the last use of the source.)
808 TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
809 isPhysRegAvailable(SrcCopyReg)) {
810 DestPhysReg = SrcCopyReg;
811 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
813 TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
814 SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
815 MF->getRegInfo().getRegClass(DestVirtReg)->
816 contains(SrcCopyPhysReg)) {
817 DestPhysReg = SrcCopyPhysReg;
818 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
820 DestPhysReg = getReg(MBB, MI, DestVirtReg);
822 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
823 markVirtRegModified(DestVirtReg);
824 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
825 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
826 << " to %reg" << DestVirtReg << "\n");
827 MO.setReg(DestPhysReg); // Assign the output register
828 UsedInInstr.set(DestPhysReg);
831 // If this instruction defines any registers that are immediately dead,
834 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
835 unsigned VirtReg = DeadDefs[i];
836 unsigned PhysReg = VirtReg;
837 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
838 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
839 PhysReg = PhysRegSlot;
840 assert(PhysReg != 0);
842 } else if (PhysRegsUsed[PhysReg] == -2) {
843 // Unallocatable register dead, ignore.
848 DEBUG(dbgs() << " Register " << TRI->getName(PhysReg)
849 << " [%reg" << VirtReg
850 << "] is never used, removing it from live set\n");
851 removePhysReg(PhysReg);
852 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
853 *AliasSet; ++AliasSet) {
854 if (PhysRegsUsed[*AliasSet] != -2) {
855 DEBUG(dbgs() << " Register " << TRI->getName(*AliasSet)
856 << " [%reg" << *AliasSet
857 << "] is never used, removing it from live set\n");
858 removePhysReg(*AliasSet);
863 // Finally, if this is a noop copy instruction, zap it. (Except that if
864 // the copy is dead, it must be kept to avoid messing up liveness info for
865 // the register scavenger. See pr4100.)
866 if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
867 SrcCopySubReg, DstCopySubReg) &&
868 SrcCopyReg == DstCopyReg && DeadDefs.empty())
872 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
874 // Spill all physical registers holding virtual registers now.
875 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
876 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
877 if (unsigned VirtReg = PhysRegsUsed[i])
878 spillVirtReg(MBB, MI, VirtReg, i);
884 /// runOnMachineFunction - Register allocate the whole function
886 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
887 DEBUG(dbgs() << "Machine Function\n");
889 TM = &Fn.getTarget();
890 TRI = TM->getRegisterInfo();
891 TII = TM->getInstrInfo();
893 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
894 UsedInInstr.resize(TRI->getNumRegs());
896 // At various places we want to efficiently check to see whether a register
897 // is allocatable. To handle this, we mark all unallocatable registers as
898 // being pinned down, permanently.
900 BitVector Allocable = TRI->getAllocatableSet(Fn);
901 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
903 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
906 // initialize the virtual->physical register map to have a 'null'
907 // mapping for all virtual registers
908 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
909 StackSlotForVirtReg.grow(LastVirtReg);
910 Virt2PhysRegMap.grow(LastVirtReg);
911 Virt2LastUseMap.grow(LastVirtReg);
912 VirtRegModified.resize(LastVirtReg+1 -
913 TargetRegisterInfo::FirstVirtualRegister);
914 UsedInMultipleBlocks.resize(LastVirtReg+1 -
915 TargetRegisterInfo::FirstVirtualRegister);
917 // Loop over all of the basic blocks, eliminating virtual register references
918 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
920 AllocateBasicBlock(*MBB);
922 StackSlotForVirtReg.clear();
923 PhysRegsUsed.clear();
924 VirtRegModified.clear();
925 UsedInMultipleBlocks.clear();
926 Virt2PhysRegMap.clear();
927 Virt2LastUseMap.clear();
931 FunctionPass *llvm::createFastRegisterAllocator() {