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");
41 static RegisterRegAlloc
42 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
45 class RAFast : public MachineFunctionPass {
48 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
50 const TargetMachine *TM;
52 const TargetRegisterInfo *TRI;
53 const TargetInstrInfo *TII;
55 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
56 // values are spilled.
57 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
59 // Virt2PhysRegMap - This map contains entries for each virtual register
60 // that is currently available in a physical register.
61 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
63 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
64 return Virt2PhysRegMap[VirtReg];
67 // PhysRegsUsed - This array is effectively a map, containing entries for
68 // each physical register that currently has a value (ie, it is in
69 // Virt2PhysRegMap). The value mapped to is the virtual register
70 // corresponding to the physical register (the inverse of the
71 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
72 // because it is used by a future instruction, and to -2 if it is not
73 // allocatable. If the entry for a physical register is -1, then the
74 // physical register is "not in the map".
76 std::vector<int> PhysRegsUsed;
78 // UsedInInstr - BitVector of physregs that are used in the current
79 // instruction, and so cannot be allocated.
80 BitVector UsedInInstr;
82 // Virt2LastUseMap - This maps each virtual register to its last use
83 // (MachineInstr*, operand index pair).
84 IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
87 std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
88 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
89 return Virt2LastUseMap[Reg];
92 // VirtRegModified - This bitset contains information about which virtual
93 // registers need to be spilled back to memory when their registers are
94 // scavenged. If a virtual register has simply been rematerialized, there
95 // is no reason to spill it to memory when we need the register back.
97 BitVector VirtRegModified;
99 // UsedInMultipleBlocks - Tracks whether a particular register is used in
100 // more than one block.
101 BitVector UsedInMultipleBlocks;
103 void markVirtRegModified(unsigned Reg, bool Val = true) {
104 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
105 Reg -= TargetRegisterInfo::FirstVirtualRegister;
107 VirtRegModified.set(Reg);
109 VirtRegModified.reset(Reg);
112 bool isVirtRegModified(unsigned Reg) const {
113 assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
114 assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
115 VirtRegModified.size() && "Illegal virtual register!");
116 return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
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 /// runOnMachineFunction - Register allocate the whole function
133 bool runOnMachineFunction(MachineFunction &Fn);
135 /// AllocateBasicBlock - Register allocate the specified basic block.
136 void AllocateBasicBlock(MachineBasicBlock &MBB);
139 /// areRegsEqual - This method returns true if the specified registers are
140 /// related to each other. To do this, it checks to see if they are equal
141 /// or if the first register is in the alias set of the second register.
143 bool areRegsEqual(unsigned R1, unsigned R2) const {
144 if (R1 == R2) return true;
145 for (const unsigned *AliasSet = TRI->getAliasSet(R2);
146 *AliasSet; ++AliasSet) {
147 if (*AliasSet == R1) return true;
152 /// getStackSpaceFor - This returns the frame index of the specified virtual
153 /// register on the stack, allocating space if necessary.
154 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
156 /// removePhysReg - This method marks the specified physical register as no
157 /// longer being in use.
159 void removePhysReg(unsigned PhysReg);
161 /// spillVirtReg - This method spills the value specified by PhysReg into
162 /// the virtual register slot specified by VirtReg. It then updates the RA
163 /// data structures to indicate the fact that PhysReg is now available.
165 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
166 unsigned VirtReg, unsigned PhysReg);
168 /// spillPhysReg - This method spills the specified physical register into
169 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
170 /// true, then the request is ignored if the physical register does not
171 /// contain a virtual register.
173 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
174 unsigned PhysReg, bool OnlyVirtRegs = false);
176 /// assignVirtToPhysReg - This method updates local state so that we know
177 /// that PhysReg is the proper container for VirtReg now. The physical
178 /// register must not be used for anything else when this is called.
180 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
182 /// isPhysRegAvailable - Return true if the specified physical register is
183 /// free and available for use. This also includes checking to see if
184 /// aliased registers are all free...
186 bool isPhysRegAvailable(unsigned PhysReg) const;
188 /// isPhysRegSpillable - Can PhysReg be freed by spilling?
189 bool isPhysRegSpillable(unsigned PhysReg) const;
191 /// getFreeReg - Look to see if there is a free register available in the
192 /// specified register class. If not, return 0.
194 unsigned getFreeReg(const TargetRegisterClass *RC);
196 /// getReg - Find a physical register to hold the specified virtual
197 /// register. If all compatible physical registers are used, this method
198 /// spills the last used virtual register to the stack, and uses that
199 /// register. If NoFree is true, that means the caller knows there isn't
200 /// a free register, do not call getFreeReg().
201 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
202 unsigned VirtReg, bool NoFree = false);
204 /// reloadVirtReg - This method transforms the specified virtual
205 /// register use to refer to a physical register. This method may do this
206 /// in one of several ways: if the register is available in a physical
207 /// register already, it uses that physical register. If the value is not
208 /// in a physical register, and if there are physical registers available,
209 /// it loads it into a register: PhysReg if that is an available physical
210 /// register, otherwise any physical register of the right class.
211 /// If register pressure is high, and it is possible, it tries to fold the
212 /// load of the virtual register into the instruction itself. It avoids
213 /// doing this if register pressure is low to improve the chance that
214 /// subsequent instructions can use the reloaded value. This method
215 /// returns the modified instruction.
217 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
218 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
221 /// ComputeLocalLiveness - Computes liveness of registers within a basic
222 /// block, setting the killed/dead flags as appropriate.
223 void ComputeLocalLiveness(MachineBasicBlock& MBB);
225 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
231 /// getStackSpaceFor - This allocates space for the specified virtual register
232 /// to be held on the stack.
233 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
234 // Find the location Reg would belong...
235 int SS = StackSlotForVirtReg[VirtReg];
237 return SS; // Already has space allocated?
239 // Allocate a new stack object for this spill location...
240 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
244 StackSlotForVirtReg[VirtReg] = FrameIdx;
249 /// removePhysReg - This method marks the specified physical register as no
250 /// longer being in use.
252 void RAFast::removePhysReg(unsigned PhysReg) {
253 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
257 /// spillVirtReg - This method spills the value specified by PhysReg into the
258 /// virtual register slot specified by VirtReg. It then updates the RA data
259 /// structures to indicate the fact that PhysReg is now available.
261 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
262 MachineBasicBlock::iterator I,
263 unsigned VirtReg, unsigned PhysReg) {
264 assert(VirtReg && "Spilling a physical register is illegal!"
265 " Must not have appropriate kill for the register or use exists beyond"
266 " the intended one.");
267 DEBUG(dbgs() << " Spilling register " << TRI->getName(PhysReg)
268 << " containing %reg" << VirtReg);
270 if (!isVirtRegModified(VirtReg)) {
271 DEBUG(dbgs() << " which has not been modified, so no store necessary!");
272 std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
274 LastUse.first->getOperand(LastUse.second).setIsKill();
276 // Otherwise, there is a virtual register corresponding to this physical
277 // register. We only need to spill it into its stack slot if it has been
279 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
280 int FrameIndex = getStackSpaceFor(VirtReg, RC);
281 DEBUG(dbgs() << " to stack slot #" << FrameIndex);
282 // If the instruction reads the register that's spilled, (e.g. this can
283 // happen if it is a move to a physical register), then the spill
284 // instruction is not a kill.
285 bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
286 TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
287 ++NumStores; // Update statistics
290 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
292 DEBUG(dbgs() << '\n');
293 removePhysReg(PhysReg);
297 /// spillPhysReg - This method spills the specified physical register into the
298 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
299 /// then the request is ignored if the physical register does not contain a
300 /// virtual register.
302 void RAFast::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
303 unsigned PhysReg, bool OnlyVirtRegs) {
304 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
305 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
306 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
307 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
311 // If the selected register aliases any other registers, we must make
312 // sure that one of the aliases isn't alive.
313 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
314 *AliasSet; ++AliasSet) {
315 if (PhysRegsUsed[*AliasSet] == -1 || // Spill aliased register.
316 PhysRegsUsed[*AliasSet] == -2) // If allocatable.
319 if (PhysRegsUsed[*AliasSet])
320 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
325 /// assignVirtToPhysReg - This method updates local state so that we know
326 /// that PhysReg is the proper container for VirtReg now. The physical
327 /// register must not be used for anything else when this is called.
329 void RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
330 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
331 // Update information to note the fact that this register was just used, and
333 PhysRegsUsed[PhysReg] = VirtReg;
334 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
335 UsedInInstr.set(PhysReg);
339 /// isPhysRegAvailable - Return true if the specified physical register is free
340 /// and available for use. This also includes checking to see if aliased
341 /// registers are all free...
343 bool RAFast::isPhysRegAvailable(unsigned PhysReg) const {
344 if (PhysRegsUsed[PhysReg] != -1) return false;
346 // If the selected register aliases any other allocated registers, it is
348 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
349 *AliasSet; ++AliasSet)
350 if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
351 return false; // Can't use this reg then.
355 /// isPhysRegSpillable - Return true if the specified physical register can be
356 /// spilled for use in the current instruction.
358 bool RAFast::isPhysRegSpillable(unsigned PhysReg) const {
359 // Test that PhysReg and all aliases are either free or assigned to a VirtReg
360 // that is not used in the instruction.
361 if (PhysRegsUsed[PhysReg] != -1 &&
362 (PhysRegsUsed[PhysReg] <= 0 || UsedInInstr.test(PhysReg)))
365 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
366 *AliasSet; ++AliasSet)
367 if (PhysRegsUsed[*AliasSet] != -1 &&
368 (PhysRegsUsed[*AliasSet] <= 0 || UsedInInstr.test(*AliasSet)))
374 /// getFreeReg - Look to see if there is a free register available in the
375 /// specified register class. If not, return 0.
377 unsigned RAFast::getFreeReg(const TargetRegisterClass *RC) {
378 // Get iterators defining the range of registers that are valid to allocate in
379 // this class, which also specifies the preferred allocation order.
380 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
381 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
383 for (; RI != RE; ++RI)
384 if (isPhysRegAvailable(*RI)) { // Is reg unused?
385 assert(*RI != 0 && "Cannot use register!");
386 return *RI; // Found an unused register!
392 /// getReg - Find a physical register to hold the specified virtual
393 /// register. If all compatible physical registers are used, this method spills
394 /// the last used virtual register to the stack, and uses that register.
396 unsigned RAFast::getReg(MachineBasicBlock &MBB, MachineInstr *I,
397 unsigned VirtReg, bool NoFree) {
398 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
400 // First check to see if we have a free register of the requested type...
401 unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
404 // Assign the register.
405 assignVirtToPhysReg(VirtReg, PhysReg);
409 // If we didn't find an unused register, scavenge one now! Don't be fancy,
410 // just grab the first possible register.
411 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
412 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
414 for (; RI != RE; ++RI)
415 if (isPhysRegSpillable(*RI)) {
420 assert(PhysReg && "Physical register not assigned!?!?");
421 spillPhysReg(MBB, I, PhysReg);
422 assignVirtToPhysReg(VirtReg, PhysReg);
427 /// reloadVirtReg - This method transforms the specified virtual
428 /// register use to refer to a physical register. This method may do this in
429 /// one of several ways: if the register is available in a physical register
430 /// already, it uses that physical register. If the value is not in a physical
431 /// register, and if there are physical registers available, it loads it into a
432 /// register: PhysReg if that is an available physical register, otherwise any
433 /// register. If register pressure is high, and it is possible, it tries to
434 /// fold the load of the virtual register into the instruction itself. It
435 /// avoids doing this if register pressure is low to improve the chance that
436 /// subsequent instructions can use the reloaded value. This method returns
437 /// the modified instruction.
439 MachineInstr *RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
441 SmallSet<unsigned, 4> &ReloadedRegs,
443 unsigned VirtReg = MI->getOperand(OpNum).getReg();
445 // If the virtual register is already available, just update the instruction
447 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
448 MI->getOperand(OpNum).setReg(PR); // Assign the input register
449 if (!MI->isDebugValue()) {
450 // Do not do these for DBG_VALUE as they can affect codegen.
452 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
457 // Otherwise, we need to fold it into the current instruction, or reload it.
458 // If we have registers available to hold the value, use them.
459 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
460 // If we already have a PhysReg (this happens when the instruction is a
461 // reg-to-reg copy with a PhysReg destination) use that.
462 if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
463 !isPhysRegAvailable(PhysReg))
464 PhysReg = getFreeReg(RC);
465 int FrameIndex = getStackSpaceFor(VirtReg, RC);
467 if (PhysReg) { // Register is available, allocate it!
468 assignVirtToPhysReg(VirtReg, PhysReg);
469 } else { // No registers available.
470 // Force some poor hapless value out of the register file to
471 // make room for the new register, and reload it.
472 PhysReg = getReg(MBB, MI, VirtReg, true);
475 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
477 DEBUG(dbgs() << " Reloading %reg" << VirtReg << " into "
478 << TRI->getName(PhysReg) << "\n");
480 // Add move instruction(s)
481 TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
482 ++NumLoads; // Update statistics
484 MF->getRegInfo().setPhysRegUsed(PhysReg);
485 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
486 getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
488 if (!ReloadedRegs.insert(PhysReg)) {
490 raw_string_ostream Msg(msg);
491 Msg << "Ran out of registers during register allocation!";
492 if (MI->isInlineAsm()) {
493 Msg << "\nPlease check your inline asm statement for invalid "
497 report_fatal_error(Msg.str());
499 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
500 *SubRegs; ++SubRegs) {
501 if (ReloadedRegs.insert(*SubRegs)) continue;
504 raw_string_ostream Msg(msg);
505 Msg << "Ran out of registers during register allocation!";
506 if (MI->isInlineAsm()) {
507 Msg << "\nPlease check your inline asm statement for invalid "
511 report_fatal_error(Msg.str());
517 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
518 /// read/mod/write register, i.e. update partial register.
519 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
520 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
521 MachineOperand &MO = MI->getOperand(i);
522 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
523 MO.isDef() && !MO.isDead())
529 /// isReadModWriteImplicitDef - True if this is an implicit def for a
530 /// read/mod/write register, i.e. update partial register.
531 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
532 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
533 MachineOperand &MO = MI->getOperand(i);
534 if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
535 !MO.isDef() && MO.isKill())
541 // precedes - Helper function to determine with MachineInstr A
542 // precedes MachineInstr B within the same MBB.
543 static bool precedes(MachineBasicBlock::iterator A,
544 MachineBasicBlock::iterator B) {
548 MachineBasicBlock::iterator I = A->getParent()->begin();
549 while (I != A->getParent()->end()) {
561 /// ComputeLocalLiveness - Computes liveness of registers within a basic
562 /// block, setting the killed/dead flags as appropriate.
563 void RAFast::ComputeLocalLiveness(MachineBasicBlock& MBB) {
564 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
565 // Keep track of the most recently seen previous use or def of each reg,
566 // so that we can update them with dead/kill markers.
567 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
568 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
570 if (I->isDebugValue())
573 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
574 MachineOperand &MO = I->getOperand(i);
575 // Uses don't trigger any flags, but we need to save
576 // them for later. Also, we have to process these
577 // _before_ processing the defs, since an instr
578 // uses regs before it defs them.
579 if (!MO.isReg() || !MO.getReg() || !MO.isUse())
582 LastUseDef[MO.getReg()] = std::make_pair(I, i);
584 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
586 const unsigned *Aliases = TRI->getAliasSet(MO.getReg());
591 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
592 alias = LastUseDef.find(*Aliases);
594 if (alias != LastUseDef.end() && alias->second.first != I)
595 LastUseDef[*Aliases] = std::make_pair(I, i);
601 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
602 MachineOperand &MO = I->getOperand(i);
603 // Defs others than 2-addr redefs _do_ trigger flag changes:
604 // - A def followed by a def is dead
605 // - A use followed by a def is a kill
606 if (!MO.isReg() || !MO.getReg() || !MO.isDef()) continue;
608 DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
609 last = LastUseDef.find(MO.getReg());
610 if (last != LastUseDef.end()) {
611 // Check if this is a two address instruction. If so, then
612 // the def does not kill the use.
613 if (last->second.first == I &&
614 I->isRegTiedToUseOperand(i))
617 MachineOperand &lastUD =
618 last->second.first->getOperand(last->second.second);
620 lastUD.setIsDead(true);
622 lastUD.setIsKill(true);
625 LastUseDef[MO.getReg()] = std::make_pair(I, i);
629 // Live-out (of the function) registers contain return values of the function,
630 // so we need to make sure they are alive at return time.
631 MachineBasicBlock::iterator Ret = MBB.getFirstTerminator();
632 bool BBEndsInReturn = (Ret != MBB.end() && Ret->getDesc().isReturn());
635 for (MachineRegisterInfo::liveout_iterator
636 I = MF->getRegInfo().liveout_begin(),
637 E = MF->getRegInfo().liveout_end(); I != E; ++I)
638 if (!Ret->readsRegister(*I)) {
639 Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
640 LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
643 // Finally, loop over the final use/def of each reg
644 // in the block and determine if it is dead.
645 for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
646 I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
647 MachineInstr *MI = I->second.first;
648 unsigned idx = I->second.second;
649 MachineOperand &MO = MI->getOperand(idx);
651 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
653 // A crude approximation of "live-out" calculation
654 bool usedOutsideBlock = isPhysReg ? false :
655 UsedInMultipleBlocks.test(MO.getReg() -
656 TargetRegisterInfo::FirstVirtualRegister);
658 // If the machine BB ends in a return instruction, then the value isn't used
659 // outside of the BB.
660 if (!isPhysReg && (!usedOutsideBlock || BBEndsInReturn)) {
661 // DBG_VALUE complicates this: if the only refs of a register outside
662 // this block are DBG_VALUE, we can't keep the reg live just for that,
663 // as it will cause the reg to be spilled at the end of this block when
664 // it wouldn't have been otherwise. Nullify the DBG_VALUEs when that
666 bool UsedByDebugValueOnly = false;
667 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
668 UE = MRI.reg_end(); UI != UE; ++UI) {
670 // - used in another block
671 // - used in the same block before it is defined (loop)
672 if (UI->getParent() == &MBB &&
673 !(MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI)))
676 if (UI->isDebugValue()) {
677 UsedByDebugValueOnly = true;
681 // A non-DBG_VALUE use means we can leave DBG_VALUE uses alone.
682 UsedInMultipleBlocks.set(MO.getReg() -
683 TargetRegisterInfo::FirstVirtualRegister);
684 usedOutsideBlock = true;
685 UsedByDebugValueOnly = false;
689 if (UsedByDebugValueOnly)
690 for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
691 UE = MRI.reg_end(); UI != UE; ++UI)
692 if (UI->isDebugValue() &&
693 (UI->getParent() != &MBB ||
694 (MO.isDef() && precedes(&*UI, MI))))
695 UI.getOperand().setReg(0U);
698 // Physical registers and those that are not live-out of the block are
699 // killed/dead at their last use/def within this block.
700 if (isPhysReg || !usedOutsideBlock || BBEndsInReturn) {
702 // Don't mark uses that are tied to defs as kills.
703 if (!MI->isRegTiedToDefOperand(idx))
712 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
713 // loop over each instruction
714 MachineBasicBlock::iterator MII = MBB.begin();
717 const BasicBlock *LBB = MBB.getBasicBlock();
719 dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
722 // Add live-in registers as active.
723 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
724 E = MBB.livein_end(); I != E; ++I) {
726 MF->getRegInfo().setPhysRegUsed(Reg);
727 PhysRegsUsed[Reg] = 0; // It is free and reserved now
728 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
729 *SubRegs; ++SubRegs) {
730 if (PhysRegsUsed[*SubRegs] == -2) continue;
731 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
732 MF->getRegInfo().setPhysRegUsed(*SubRegs);
736 ComputeLocalLiveness(MBB);
738 // Otherwise, sequentially allocate each instruction in the MBB.
739 while (MII != MBB.end()) {
740 MachineInstr *MI = MII++;
741 const TargetInstrDesc &TID = MI->getDesc();
743 dbgs() << "\nStarting RegAlloc of: " << *MI;
744 dbgs() << " Regs have values: ";
745 for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
746 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
747 dbgs() << "[" << TRI->getName(i)
748 << ",%reg" << PhysRegsUsed[i] << "] ";
752 // Track registers used by instruction.
755 // Determine whether this is a copy instruction. The cases where the
756 // source or destination are phys regs are handled specially.
757 unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
758 unsigned SrcCopyPhysReg = 0U;
759 bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
760 SrcCopySubReg, DstCopySubReg);
761 if (isCopy && TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
762 SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
764 // Loop over the implicit uses, making sure they don't get reallocated.
765 if (TID.ImplicitUses) {
766 for (const unsigned *ImplicitUses = TID.ImplicitUses;
767 *ImplicitUses; ++ImplicitUses)
768 UsedInInstr.set(*ImplicitUses);
771 SmallVector<unsigned, 8> Kills;
772 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
773 MachineOperand &MO = MI->getOperand(i);
774 if (!MO.isReg() || !MO.isKill()) continue;
776 if (!MO.isImplicit())
777 Kills.push_back(MO.getReg());
778 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
779 // These are extra physical register kills when a sub-register
780 // is defined (def of a sub-register is a read/mod/write of the
781 // larger registers). Ignore.
782 Kills.push_back(MO.getReg());
785 // If any physical regs are earlyclobber, spill any value they might
786 // have in them, then mark them unallocatable.
787 // If any virtual regs are earlyclobber, allocate them now (before
788 // freeing inputs that are killed).
789 if (MI->isInlineAsm()) {
790 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
791 MachineOperand &MO = MI->getOperand(i);
792 if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
796 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
797 unsigned DestVirtReg = MO.getReg();
798 unsigned DestPhysReg;
800 // If DestVirtReg already has a value, use it.
801 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
802 DestPhysReg = getReg(MBB, MI, DestVirtReg);
803 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
804 markVirtRegModified(DestVirtReg);
805 getVirtRegLastUse(DestVirtReg) =
806 std::make_pair((MachineInstr*)0, 0);
807 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
808 << " to %reg" << DestVirtReg << "\n");
809 MO.setReg(DestPhysReg); // Assign the earlyclobber register
811 unsigned Reg = MO.getReg();
812 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
813 // These are extra physical register defs when a sub-register
814 // is defined (def of a sub-register is a read/mod/write of the
815 // larger registers). Ignore.
816 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
818 MF->getRegInfo().setPhysRegUsed(Reg);
819 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
820 PhysRegsUsed[Reg] = 0; // It is free and reserved now
822 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
823 *SubRegs; ++SubRegs) {
824 if (PhysRegsUsed[*SubRegs] == -2) continue;
825 MF->getRegInfo().setPhysRegUsed(*SubRegs);
826 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
832 // If a DBG_VALUE says something is located in a spilled register,
833 // change the DBG_VALUE to be undef, which prevents the register
834 // from being reloaded here. Doing that would change the generated
835 // code, unless another use immediately follows this instruction.
836 if (MI->isDebugValue() &&
837 MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
838 unsigned VirtReg = MI->getOperand(0).getReg();
839 if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
840 !getVirt2PhysRegMapSlot(VirtReg))
841 MI->getOperand(0).setReg(0U);
844 // Get the used operands into registers. This has the potential to spill
845 // incoming values if we are out of registers. Note that we completely
846 // ignore physical register uses here. We assume that if an explicit
847 // physical register is referenced by the instruction, that it is guaranteed
848 // to be live-in, or the input is badly hosed.
850 SmallSet<unsigned, 4> ReloadedRegs;
851 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
852 MachineOperand &MO = MI->getOperand(i);
853 // here we are looking for only used operands (never def&use)
854 if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
855 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
856 MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
857 isCopy ? DstCopyReg : 0);
860 // If this instruction is the last user of this register, kill the
861 // value, freeing the register being used, so it doesn't need to be
862 // spilled to memory.
864 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
865 unsigned VirtReg = Kills[i];
866 unsigned PhysReg = VirtReg;
867 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
868 // If the virtual register was never materialized into a register, it
869 // might not be in the map, but it won't hurt to zero it out anyway.
870 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
871 PhysReg = PhysRegSlot;
873 } else if (PhysRegsUsed[PhysReg] == -2) {
874 // Unallocatable register dead, ignore.
877 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
878 "Silently clearing a virtual register?");
881 if (!PhysReg) continue;
883 DEBUG(dbgs() << " Last use of " << TRI->getName(PhysReg)
884 << "[%reg" << VirtReg <<"], removing it from live set\n");
885 removePhysReg(PhysReg);
886 for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
887 *SubRegs; ++SubRegs) {
888 if (PhysRegsUsed[*SubRegs] != -2) {
889 DEBUG(dbgs() << " Last use of "
890 << TRI->getName(*SubRegs) << "[%reg" << VirtReg
891 <<"], removing it from live set\n");
892 removePhysReg(*SubRegs);
897 // Track registers defined by instruction.
900 // Loop over all of the operands of the instruction, spilling registers that
901 // are defined, and marking explicit destinations in the PhysRegsUsed map.
902 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
903 MachineOperand &MO = MI->getOperand(i);
904 if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
905 MO.isEarlyClobber() ||
906 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
909 unsigned Reg = MO.getReg();
910 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
911 // These are extra physical register defs when a sub-register
912 // is defined (def of a sub-register is a read/mod/write of the
913 // larger registers). Ignore.
914 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
916 MF->getRegInfo().setPhysRegUsed(Reg);
917 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
918 PhysRegsUsed[Reg] = 0; // It is free and reserved now
920 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
921 *SubRegs; ++SubRegs) {
922 if (PhysRegsUsed[*SubRegs] == -2) continue;
924 MF->getRegInfo().setPhysRegUsed(*SubRegs);
925 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
929 // Loop over the implicit defs, spilling them as well.
930 if (TID.ImplicitDefs) {
931 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
932 *ImplicitDefs; ++ImplicitDefs) {
933 unsigned Reg = *ImplicitDefs;
934 if (PhysRegsUsed[Reg] != -2) {
935 spillPhysReg(MBB, MI, Reg, true);
936 PhysRegsUsed[Reg] = 0; // It is free and reserved now
938 MF->getRegInfo().setPhysRegUsed(Reg);
939 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
940 *SubRegs; ++SubRegs) {
941 if (PhysRegsUsed[*SubRegs] == -2) continue;
943 PhysRegsUsed[*SubRegs] = 0; // It is free and reserved now
944 MF->getRegInfo().setPhysRegUsed(*SubRegs);
949 SmallVector<unsigned, 8> DeadDefs;
950 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
951 MachineOperand &MO = MI->getOperand(i);
952 if (MO.isReg() && MO.isDead())
953 DeadDefs.push_back(MO.getReg());
956 // Okay, we have allocated all of the source operands and spilled any values
957 // that would be destroyed by defs of this instruction. Loop over the
958 // explicit defs and assign them to a register, spilling incoming values if
959 // we need to scavenge a register.
961 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
962 MachineOperand &MO = MI->getOperand(i);
963 if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
964 MO.isEarlyClobber() ||
965 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
968 unsigned DestVirtReg = MO.getReg();
969 unsigned DestPhysReg;
971 // If DestVirtReg already has a value, use it.
972 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
973 // If this is a copy try to reuse the input as the output;
974 // that will make the copy go away.
975 // If this is a copy, the source reg is a phys reg, and
976 // that reg is available, use that phys reg for DestPhysReg.
977 // If this is a copy, the source reg is a virtual reg, and
978 // the phys reg that was assigned to that virtual reg is now
979 // available, use that phys reg for DestPhysReg. (If it's now
980 // available that means this was the last use of the source.)
982 TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
983 isPhysRegAvailable(SrcCopyReg)) {
984 DestPhysReg = SrcCopyReg;
985 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
987 TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
988 SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
989 MF->getRegInfo().getRegClass(DestVirtReg)->
990 contains(SrcCopyPhysReg)) {
991 DestPhysReg = SrcCopyPhysReg;
992 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
994 DestPhysReg = getReg(MBB, MI, DestVirtReg);
996 MF->getRegInfo().setPhysRegUsed(DestPhysReg);
997 markVirtRegModified(DestVirtReg);
998 getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
999 DEBUG(dbgs() << " Assigning " << TRI->getName(DestPhysReg)
1000 << " to %reg" << DestVirtReg << "\n");
1001 MO.setReg(DestPhysReg); // Assign the output register
1002 UsedInInstr.set(DestPhysReg);
1005 // If this instruction defines any registers that are immediately dead,
1008 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
1009 unsigned VirtReg = DeadDefs[i];
1010 unsigned PhysReg = VirtReg;
1011 if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1012 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
1013 PhysReg = PhysRegSlot;
1014 assert(PhysReg != 0);
1016 } else if (PhysRegsUsed[PhysReg] == -2) {
1017 // Unallocatable register dead, ignore.
1019 } else if (!PhysReg)
1022 DEBUG(dbgs() << " Register " << TRI->getName(PhysReg)
1023 << " [%reg" << VirtReg
1024 << "] is never used, removing it from live set\n");
1025 removePhysReg(PhysReg);
1026 for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
1027 *AliasSet; ++AliasSet) {
1028 if (PhysRegsUsed[*AliasSet] != -2) {
1029 DEBUG(dbgs() << " Register " << TRI->getName(*AliasSet)
1030 << " [%reg" << *AliasSet
1031 << "] is never used, removing it from live set\n");
1032 removePhysReg(*AliasSet);
1037 // Finally, if this is a noop copy instruction, zap it. (Except that if
1038 // the copy is dead, it must be kept to avoid messing up liveness info for
1039 // the register scavenger. See pr4100.)
1040 if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
1041 SrcCopySubReg, DstCopySubReg) &&
1042 SrcCopyReg == DstCopyReg && DeadDefs.empty())
1046 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1048 // Spill all physical registers holding virtual registers now.
1049 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
1050 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
1051 if (unsigned VirtReg = PhysRegsUsed[i])
1052 spillVirtReg(MBB, MI, VirtReg, i);
1058 /// runOnMachineFunction - Register allocate the whole function
1060 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1061 DEBUG(dbgs() << "Machine Function\n");
1063 TM = &Fn.getTarget();
1064 TRI = TM->getRegisterInfo();
1065 TII = TM->getInstrInfo();
1067 PhysRegsUsed.assign(TRI->getNumRegs(), -1);
1068 UsedInInstr.resize(TRI->getNumRegs());
1070 // At various places we want to efficiently check to see whether a register
1071 // is allocatable. To handle this, we mark all unallocatable registers as
1072 // being pinned down, permanently.
1074 BitVector Allocable = TRI->getAllocatableSet(Fn);
1075 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1077 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
1080 // initialize the virtual->physical register map to have a 'null'
1081 // mapping for all virtual registers
1082 unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
1083 StackSlotForVirtReg.grow(LastVirtReg);
1084 Virt2PhysRegMap.grow(LastVirtReg);
1085 Virt2LastUseMap.grow(LastVirtReg);
1086 VirtRegModified.resize(LastVirtReg+1 -
1087 TargetRegisterInfo::FirstVirtualRegister);
1088 UsedInMultipleBlocks.resize(LastVirtReg+1 -
1089 TargetRegisterInfo::FirstVirtualRegister);
1091 // Loop over all of the basic blocks, eliminating virtual register references
1092 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1094 AllocateBasicBlock(*MBB);
1096 StackSlotForVirtReg.clear();
1097 PhysRegsUsed.clear();
1098 VirtRegModified.clear();
1099 UsedInMultipleBlocks.clear();
1100 Virt2PhysRegMap.clear();
1101 Virt2LastUseMap.clear();
1105 FunctionPass *llvm::createFastRegisterAllocator() {
1106 return new RAFast();