1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Passes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/LiveVariables.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/Compiler.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
37 static Statistic<> NumStores("ra-local", "Number of stores added");
38 static Statistic<> NumLoads ("ra-local", "Number of loads added");
39 static Statistic<> NumFolded("ra-local", "Number of loads/stores folded "
42 static RegisterRegAlloc
43 localRegAlloc("local", " local register allocator",
44 createLocalRegisterAllocator);
47 class VISIBILITY_HIDDEN RA : public MachineFunctionPass {
48 const TargetMachine *TM;
50 const MRegisterInfo *RegInfo;
52 bool *PhysRegsEverUsed;
54 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
55 // values are spilled.
56 std::map<unsigned, int> StackSlotForVirtReg;
58 // Virt2PhysRegMap - This map contains entries for each virtual register
59 // that is currently available in a physical register.
60 DenseMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
62 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
63 return Virt2PhysRegMap[VirtReg];
66 // PhysRegsUsed - This array is effectively a map, containing entries for
67 // each physical register that currently has a value (ie, it is in
68 // Virt2PhysRegMap). The value mapped to is the virtual register
69 // corresponding to the physical register (the inverse of the
70 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
71 // because it is used by a future instruction, and to -2 if it is not
72 // allocatable. If the entry for a physical register is -1, then the
73 // physical register is "not in the map".
75 std::vector<int> PhysRegsUsed;
77 // PhysRegsUseOrder - This contains a list of the physical registers that
78 // currently have a virtual register value in them. This list provides an
79 // ordering of registers, imposing a reallocation order. This list is only
80 // used if all registers are allocated and we have to spill one, in which
81 // case we spill the least recently used register. Entries at the front of
82 // the list are the least recently used registers, entries at the back are
83 // the most recently used.
85 std::vector<unsigned> PhysRegsUseOrder;
87 // VirtRegModified - This bitset contains information about which virtual
88 // registers need to be spilled back to memory when their registers are
89 // scavenged. If a virtual register has simply been rematerialized, there
90 // is no reason to spill it to memory when we need the register back.
92 std::vector<bool> VirtRegModified;
94 void markVirtRegModified(unsigned Reg, bool Val = true) {
95 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
96 Reg -= MRegisterInfo::FirstVirtualRegister;
97 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
98 VirtRegModified[Reg] = Val;
101 bool isVirtRegModified(unsigned Reg) const {
102 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
103 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
104 && "Illegal virtual register!");
105 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
108 void MarkPhysRegRecentlyUsed(unsigned Reg) {
109 if (PhysRegsUseOrder.empty() ||
110 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
112 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
113 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
114 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
115 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
116 // Add it to the end of the list
117 PhysRegsUseOrder.push_back(RegMatch);
119 return; // Found an exact match, exit early
124 virtual const char *getPassName() const {
125 return "Local Register Allocator";
128 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
129 AU.addRequired<LiveVariables>();
130 AU.addRequiredID(PHIEliminationID);
131 AU.addRequiredID(TwoAddressInstructionPassID);
132 MachineFunctionPass::getAnalysisUsage(AU);
136 /// runOnMachineFunction - Register allocate the whole function
137 bool runOnMachineFunction(MachineFunction &Fn);
139 /// AllocateBasicBlock - Register allocate the specified basic block.
140 void AllocateBasicBlock(MachineBasicBlock &MBB);
143 /// areRegsEqual - This method returns true if the specified registers are
144 /// related to each other. To do this, it checks to see if they are equal
145 /// or if the first register is in the alias set of the second register.
147 bool areRegsEqual(unsigned R1, unsigned R2) const {
148 if (R1 == R2) return true;
149 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
150 *AliasSet; ++AliasSet) {
151 if (*AliasSet == R1) return true;
156 /// getStackSpaceFor - This returns the frame index of the specified virtual
157 /// register on the stack, allocating space if necessary.
158 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
160 /// removePhysReg - This method marks the specified physical register as no
161 /// longer being in use.
163 void removePhysReg(unsigned PhysReg);
165 /// spillVirtReg - This method spills the value specified by PhysReg into
166 /// the virtual register slot specified by VirtReg. It then updates the RA
167 /// data structures to indicate the fact that PhysReg is now available.
169 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
170 unsigned VirtReg, unsigned PhysReg);
172 /// spillPhysReg - This method spills the specified physical register into
173 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
174 /// true, then the request is ignored if the physical register does not
175 /// contain a virtual register.
177 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
178 unsigned PhysReg, bool OnlyVirtRegs = false);
180 /// assignVirtToPhysReg - This method updates local state so that we know
181 /// that PhysReg is the proper container for VirtReg now. The physical
182 /// register must not be used for anything else when this is called.
184 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
186 /// liberatePhysReg - Make sure the specified physical register is available
187 /// for use. If there is currently a value in it, it is either moved out of
188 /// the way or spilled to memory.
190 void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
193 /// isPhysRegAvailable - Return true if the specified physical register is
194 /// free and available for use. This also includes checking to see if
195 /// aliased registers are all free...
197 bool isPhysRegAvailable(unsigned PhysReg) const;
199 /// getFreeReg - Look to see if there is a free register available in the
200 /// specified register class. If not, return 0.
202 unsigned getFreeReg(const TargetRegisterClass *RC);
204 /// getReg - Find a physical register to hold the specified virtual
205 /// register. If all compatible physical registers are used, this method
206 /// spills the last used virtual register to the stack, and uses that
209 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
212 /// reloadVirtReg - This method transforms the specified specified virtual
213 /// register use to refer to a physical register. This method may do this
214 /// in one of several ways: if the register is available in a physical
215 /// register already, it uses that physical register. If the value is not
216 /// in a physical register, and if there are physical registers available,
217 /// it loads it into a register. If register pressure is high, and it is
218 /// possible, it tries to fold the load of the virtual register into the
219 /// instruction itself. It avoids doing this if register pressure is low to
220 /// improve the chance that subsequent instructions can use the reloaded
221 /// value. This method returns the modified instruction.
223 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
227 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
232 /// getStackSpaceFor - This allocates space for the specified virtual register
233 /// to be held on the stack.
234 int RA::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
235 // Find the location Reg would belong...
236 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
238 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
239 return I->second; // Already has space allocated?
241 // Allocate a new stack object for this spill location...
242 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
245 // Assign the slot...
246 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
251 /// removePhysReg - This method marks the specified physical register as no
252 /// longer being in use.
254 void RA::removePhysReg(unsigned PhysReg) {
255 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
257 std::vector<unsigned>::iterator It =
258 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
259 if (It != PhysRegsUseOrder.end())
260 PhysRegsUseOrder.erase(It);
264 /// spillVirtReg - This method spills the value specified by PhysReg into the
265 /// virtual register slot specified by VirtReg. It then updates the RA data
266 /// structures to indicate the fact that PhysReg is now available.
268 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
269 unsigned VirtReg, unsigned PhysReg) {
270 assert(VirtReg && "Spilling a physical register is illegal!"
271 " Must not have appropriate kill for the register or use exists beyond"
272 " the intended one.");
273 DEBUG(std::cerr << " Spilling register " << RegInfo->getName(PhysReg);
274 std::cerr << " containing %reg" << VirtReg;
275 if (!isVirtRegModified(VirtReg))
276 std::cerr << " which has not been modified, so no store necessary!");
278 // Otherwise, there is a virtual register corresponding to this physical
279 // register. We only need to spill it into its stack slot if it has been
281 if (isVirtRegModified(VirtReg)) {
282 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
283 int FrameIndex = getStackSpaceFor(VirtReg, RC);
284 DEBUG(std::cerr << " to stack slot #" << FrameIndex);
285 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
286 ++NumStores; // Update statistics
289 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
291 DEBUG(std::cerr << "\n");
292 removePhysReg(PhysReg);
296 /// spillPhysReg - This method spills the specified physical register into the
297 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
298 /// then the request is ignored if the physical register does not contain a
299 /// virtual register.
301 void RA::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
302 unsigned PhysReg, bool OnlyVirtRegs) {
303 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
304 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
305 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
306 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
308 // If the selected register aliases any other registers, we must make
309 // sure that one of the aliases isn't alive.
310 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
311 *AliasSet; ++AliasSet)
312 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
313 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
314 if (PhysRegsUsed[*AliasSet] == 0) {
315 // This must have been a dead def due to something like this:
318 // No more use of %EAX, %AH, etc.
319 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
320 // an operand of definition MI so it's not marked as such.
321 DEBUG(std::cerr << " Register " << RegInfo->getName(*AliasSet)
322 << " [%reg" << *AliasSet
323 << "] is never used, removing it frame live list\n");
324 removePhysReg(*AliasSet);
326 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
331 /// assignVirtToPhysReg - This method updates local state so that we know
332 /// that PhysReg is the proper container for VirtReg now. The physical
333 /// register must not be used for anything else when this is called.
335 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
336 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
337 // Update information to note the fact that this register was just used, and
339 PhysRegsUsed[PhysReg] = VirtReg;
340 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
341 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
345 /// isPhysRegAvailable - Return true if the specified physical register is free
346 /// and available for use. This also includes checking to see if aliased
347 /// registers are all free...
349 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
350 if (PhysRegsUsed[PhysReg] != -1) return false;
352 // If the selected register aliases any other allocated registers, it is
354 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
355 *AliasSet; ++AliasSet)
356 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
357 return false; // Can't use this reg then.
362 /// getFreeReg - Look to see if there is a free register available in the
363 /// specified register class. If not, return 0.
365 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
366 // Get iterators defining the range of registers that are valid to allocate in
367 // this class, which also specifies the preferred allocation order.
368 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
369 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
371 for (; RI != RE; ++RI)
372 if (isPhysRegAvailable(*RI)) { // Is reg unused?
373 assert(*RI != 0 && "Cannot use register!");
374 return *RI; // Found an unused register!
380 /// liberatePhysReg - Make sure the specified physical register is available for
381 /// use. If there is currently a value in it, it is either moved out of the way
382 /// or spilled to memory.
384 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
386 spillPhysReg(MBB, I, PhysReg);
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 RA::getReg(MachineBasicBlock &MBB, MachineInstr *I,
396 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
398 // First check to see if we have a free register of the requested type...
399 unsigned PhysReg = getFreeReg(RC);
401 // If we didn't find an unused register, scavenge one now!
403 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
405 // Loop over all of the preallocated registers from the least recently used
406 // to the most recently used. When we find one that is capable of holding
407 // our register, use it.
408 for (unsigned i = 0; PhysReg == 0; ++i) {
409 assert(i != PhysRegsUseOrder.size() &&
410 "Couldn't find a register of the appropriate class!");
412 unsigned R = PhysRegsUseOrder[i];
414 // We can only use this register if it holds a virtual register (ie, it
415 // can be spilled). Do not use it if it is an explicitly allocated
416 // physical register!
417 assert(PhysRegsUsed[R] != -1 &&
418 "PhysReg in PhysRegsUseOrder, but is not allocated?");
419 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
420 // If the current register is compatible, use it.
421 if (RC->contains(R)) {
425 // If one of the registers aliased to the current register is
426 // compatible, use it.
427 for (const unsigned *AliasIt = RegInfo->getAliasSet(R);
428 *AliasIt; ++AliasIt) {
429 if (RC->contains(*AliasIt) &&
430 // If this is pinned down for some reason, don't use it. For
431 // example, if CL is pinned, and we run across CH, don't use
432 // CH as justification for using scavenging ECX (which will
434 PhysRegsUsed[*AliasIt] != 0 &&
436 // Make sure the register is allocatable. Don't allocate SIL on
438 PhysRegsUsed[*AliasIt] != -2) {
439 PhysReg = *AliasIt; // Take an aliased register
447 assert(PhysReg && "Physical register not assigned!?!?");
449 // At this point PhysRegsUseOrder[i] is the least recently used register of
450 // compatible register class. Spill it to memory and reap its remains.
451 spillPhysReg(MBB, I, PhysReg);
454 // Now that we know which register we need to assign this to, do it now!
455 assignVirtToPhysReg(VirtReg, PhysReg);
460 /// reloadVirtReg - This method transforms the specified specified virtual
461 /// register use to refer to a physical register. This method may do this in
462 /// one of several ways: if the register is available in a physical register
463 /// already, it uses that physical register. If the value is not in a physical
464 /// register, and if there are physical registers available, it loads it into a
465 /// register. If register pressure is high, and it is possible, it tries to
466 /// fold the load of the virtual register into the instruction itself. It
467 /// avoids doing this if register pressure is low to improve the chance that
468 /// subsequent instructions can use the reloaded value. This method returns the
469 /// modified instruction.
471 MachineInstr *RA::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
473 unsigned VirtReg = MI->getOperand(OpNum).getReg();
475 // If the virtual register is already available, just update the instruction
477 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
478 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
479 MI->getOperand(OpNum).setReg(PR); // Assign the input register
483 // Otherwise, we need to fold it into the current instruction, or reload it.
484 // If we have registers available to hold the value, use them.
485 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
486 unsigned PhysReg = getFreeReg(RC);
487 int FrameIndex = getStackSpaceFor(VirtReg, RC);
489 if (PhysReg) { // Register is available, allocate it!
490 assignVirtToPhysReg(VirtReg, PhysReg);
491 } else { // No registers available.
492 // If we can fold this spill into this instruction, do so now.
493 if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)){
495 // Since we changed the address of MI, make sure to update live variables
496 // to know that the new instruction has the properties of the old one.
497 LV->instructionChanged(MI, FMI);
498 return MBB.insert(MBB.erase(MI), FMI);
501 // It looks like we can't fold this virtual register load into this
502 // instruction. Force some poor hapless value out of the register file to
503 // make room for the new register, and reload it.
504 PhysReg = getReg(MBB, MI, VirtReg);
507 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
509 DEBUG(std::cerr << " Reloading %reg" << VirtReg << " into "
510 << RegInfo->getName(PhysReg) << "\n");
512 // Add move instruction(s)
513 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
514 ++NumLoads; // Update statistics
516 PhysRegsEverUsed[PhysReg] = true;
517 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
523 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
524 // loop over each instruction
525 MachineBasicBlock::iterator MII = MBB.begin();
526 const TargetInstrInfo &TII = *TM->getInstrInfo();
528 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
529 if (LBB) std::cerr << "\nStarting RegAlloc of BB: " << LBB->getName());
531 // If this is the first basic block in the machine function, add live-in
532 // registers as active.
533 if (&MBB == &*MF->begin()) {
534 for (MachineFunction::livein_iterator I = MF->livein_begin(),
535 E = MF->livein_end(); I != E; ++I) {
536 unsigned Reg = I->first;
537 PhysRegsEverUsed[Reg] = true;
538 PhysRegsUsed[Reg] = 0; // It is free and reserved now
539 PhysRegsUseOrder.push_back(Reg);
540 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
541 *AliasSet; ++AliasSet) {
542 if (PhysRegsUsed[*AliasSet] != -2) {
543 PhysRegsUseOrder.push_back(*AliasSet);
544 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
545 PhysRegsEverUsed[*AliasSet] = true;
551 // Otherwise, sequentially allocate each instruction in the MBB.
552 while (MII != MBB.end()) {
553 MachineInstr *MI = MII++;
554 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
555 DEBUG(std::cerr << "\nStarting RegAlloc of: " << *MI;
556 std::cerr << " Regs have values: ";
557 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
558 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
559 std::cerr << "[" << RegInfo->getName(i)
560 << ",%reg" << PhysRegsUsed[i] << "] ";
563 // Loop over the implicit uses, making sure that they are at the head of the
564 // use order list, so they don't get reallocated.
565 if (TID.ImplicitUses) {
566 for (const unsigned *ImplicitUses = TID.ImplicitUses;
567 *ImplicitUses; ++ImplicitUses)
568 MarkPhysRegRecentlyUsed(*ImplicitUses);
571 SmallVector<unsigned, 8> Kills;
572 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
573 MachineOperand& MO = MI->getOperand(i);
574 if (MO.isRegister() && MO.isKill())
575 Kills.push_back(MO.getReg());
578 // Get the used operands into registers. This has the potential to spill
579 // incoming values if we are out of registers. Note that we completely
580 // ignore physical register uses here. We assume that if an explicit
581 // physical register is referenced by the instruction, that it is guaranteed
582 // to be live-in, or the input is badly hosed.
584 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
585 MachineOperand& MO = MI->getOperand(i);
586 // here we are looking for only used operands (never def&use)
587 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
588 MRegisterInfo::isVirtualRegister(MO.getReg()))
589 MI = reloadVirtReg(MBB, MI, i);
592 // If this instruction is the last user of this register, kill the
593 // value, freeing the register being used, so it doesn't need to be
594 // spilled to memory.
596 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
597 unsigned VirtReg = Kills[i];
598 unsigned PhysReg = VirtReg;
599 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
600 // If the virtual register was never materialized into a register, it
601 // might not be in the map, but it won't hurt to zero it out anyway.
602 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
603 PhysReg = PhysRegSlot;
605 } else if (PhysRegsUsed[PhysReg] == -2) {
606 // Unallocatable register dead, ignore.
611 DEBUG(std::cerr << " Last use of " << RegInfo->getName(PhysReg)
612 << "[%reg" << VirtReg <<"], removing it from live set\n");
613 removePhysReg(PhysReg);
614 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
615 *AliasSet; ++AliasSet) {
616 if (PhysRegsUsed[*AliasSet] != -2) {
617 DEBUG(std::cerr << " Last use of "
618 << RegInfo->getName(*AliasSet)
619 << "[%reg" << VirtReg <<"], removing it from live set\n");
620 removePhysReg(*AliasSet);
626 // Loop over all of the operands of the instruction, spilling registers that
627 // are defined, and marking explicit destinations in the PhysRegsUsed map.
628 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
629 MachineOperand& MO = MI->getOperand(i);
630 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
631 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
632 unsigned Reg = MO.getReg();
633 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
635 PhysRegsEverUsed[Reg] = true;
636 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
637 PhysRegsUsed[Reg] = 0; // It is free and reserved now
638 PhysRegsUseOrder.push_back(Reg);
639 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
640 *AliasSet; ++AliasSet) {
641 if (PhysRegsUsed[*AliasSet] != -2) {
642 PhysRegsUseOrder.push_back(*AliasSet);
643 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
644 PhysRegsEverUsed[*AliasSet] = true;
650 // Loop over the implicit defs, spilling them as well.
651 if (TID.ImplicitDefs) {
652 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
653 *ImplicitDefs; ++ImplicitDefs) {
654 unsigned Reg = *ImplicitDefs;
655 bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
656 if (!IsNonAllocatable) {
657 spillPhysReg(MBB, MI, Reg, true);
658 PhysRegsUseOrder.push_back(Reg);
659 PhysRegsUsed[Reg] = 0; // It is free and reserved now
661 PhysRegsEverUsed[Reg] = true;
663 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
664 *AliasSet; ++AliasSet) {
665 if (PhysRegsUsed[*AliasSet] != -2) {
666 if (!IsNonAllocatable) {
667 PhysRegsUseOrder.push_back(*AliasSet);
668 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
670 PhysRegsEverUsed[*AliasSet] = true;
676 SmallVector<unsigned, 8> DeadDefs;
677 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
678 MachineOperand& MO = MI->getOperand(i);
679 if (MO.isRegister() && MO.isDead())
680 DeadDefs.push_back(MO.getReg());
683 // Okay, we have allocated all of the source operands and spilled any values
684 // that would be destroyed by defs of this instruction. Loop over the
685 // explicit defs and assign them to a register, spilling incoming values if
686 // we need to scavenge a register.
688 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
689 MachineOperand& MO = MI->getOperand(i);
690 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
691 MRegisterInfo::isVirtualRegister(MO.getReg())) {
692 unsigned DestVirtReg = MO.getReg();
693 unsigned DestPhysReg;
695 // If DestVirtReg already has a value, use it.
696 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
697 DestPhysReg = getReg(MBB, MI, DestVirtReg);
698 PhysRegsEverUsed[DestPhysReg] = true;
699 markVirtRegModified(DestVirtReg);
700 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
704 // If this instruction defines any registers that are immediately dead,
707 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
708 unsigned VirtReg = DeadDefs[i];
709 unsigned PhysReg = VirtReg;
710 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
711 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
712 PhysReg = PhysRegSlot;
713 assert(PhysReg != 0);
715 } else if (PhysRegsUsed[PhysReg] == -2) {
716 // Unallocatable register dead, ignore.
721 DEBUG(std::cerr << " Register " << RegInfo->getName(PhysReg)
722 << " [%reg" << VirtReg
723 << "] is never used, removing it frame live list\n");
724 removePhysReg(PhysReg);
725 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
726 *AliasSet; ++AliasSet) {
727 if (PhysRegsUsed[*AliasSet] != -2) {
728 DEBUG(std::cerr << " Register " << RegInfo->getName(*AliasSet)
729 << " [%reg" << *AliasSet
730 << "] is never used, removing it frame live list\n");
731 removePhysReg(*AliasSet);
737 // Finally, if this is a noop copy instruction, zap it.
738 unsigned SrcReg, DstReg;
739 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
740 LV->removeVirtualRegistersKilled(MI);
741 LV->removeVirtualRegistersDead(MI);
746 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
748 // Spill all physical registers holding virtual registers now.
749 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
750 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
751 if (unsigned VirtReg = PhysRegsUsed[i])
752 spillVirtReg(MBB, MI, VirtReg, i);
757 // This checking code is very expensive.
759 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
760 e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
761 if (unsigned PR = Virt2PhysRegMap[i]) {
762 std::cerr << "Register still mapped: " << i << " -> " << PR << "\n";
765 assert(AllOk && "Virtual registers still in phys regs?");
768 // Clear any physical register which appear live at the end of the basic
769 // block, but which do not hold any virtual registers. e.g., the stack
771 PhysRegsUseOrder.clear();
775 /// runOnMachineFunction - Register allocate the whole function
777 bool RA::runOnMachineFunction(MachineFunction &Fn) {
778 DEBUG(std::cerr << "Machine Function " << "\n");
780 TM = &Fn.getTarget();
781 RegInfo = TM->getRegisterInfo();
782 LV = &getAnalysis<LiveVariables>();
784 PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
785 std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
786 Fn.setUsedPhysRegs(PhysRegsEverUsed);
788 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
790 // At various places we want to efficiently check to see whether a register
791 // is allocatable. To handle this, we mark all unallocatable registers as
792 // being pinned down, permanently.
794 std::vector<bool> Allocable = RegInfo->getAllocatableSet(Fn);
795 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
797 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
800 // initialize the virtual->physical register map to have a 'null'
801 // mapping for all virtual registers
802 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
804 // Loop over all of the basic blocks, eliminating virtual register references
805 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
807 AllocateBasicBlock(*MBB);
809 StackSlotForVirtReg.clear();
810 PhysRegsUsed.clear();
811 VirtRegModified.clear();
812 Virt2PhysRegMap.clear();
816 FunctionPass *llvm::createLocalRegisterAllocator() {