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"
36 static Statistic NumStores("ra-local", "Number of stores added");
37 static Statistic NumLoads ("ra-local", "Number of loads added");
38 static Statistic NumFolded("ra-local", "Number of loads/stores folded "
41 static RegisterRegAlloc
42 localRegAlloc("local", " local register allocator",
43 createLocalRegisterAllocator);
46 class VISIBILITY_HIDDEN RA : public MachineFunctionPass {
47 const TargetMachine *TM;
49 const MRegisterInfo *RegInfo;
51 bool *PhysRegsEverUsed;
53 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
54 // values are spilled.
55 std::map<unsigned, int> StackSlotForVirtReg;
57 // Virt2PhysRegMap - This map contains entries for each virtual register
58 // that is currently available in a physical register.
59 DenseMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
61 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
62 return Virt2PhysRegMap[VirtReg];
65 // PhysRegsUsed - This array is effectively a map, containing entries for
66 // each physical register that currently has a value (ie, it is in
67 // Virt2PhysRegMap). The value mapped to is the virtual register
68 // corresponding to the physical register (the inverse of the
69 // Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
70 // because it is used by a future instruction, and to -2 if it is not
71 // allocatable. If the entry for a physical register is -1, then the
72 // physical register is "not in the map".
74 std::vector<int> PhysRegsUsed;
76 // PhysRegsUseOrder - This contains a list of the physical registers that
77 // currently have a virtual register value in them. This list provides an
78 // ordering of registers, imposing a reallocation order. This list is only
79 // used if all registers are allocated and we have to spill one, in which
80 // case we spill the least recently used register. Entries at the front of
81 // the list are the least recently used registers, entries at the back are
82 // the most recently used.
84 std::vector<unsigned> PhysRegsUseOrder;
86 // VirtRegModified - This bitset contains information about which virtual
87 // registers need to be spilled back to memory when their registers are
88 // scavenged. If a virtual register has simply been rematerialized, there
89 // is no reason to spill it to memory when we need the register back.
91 std::vector<bool> VirtRegModified;
93 void markVirtRegModified(unsigned Reg, bool Val = true) {
94 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
95 Reg -= MRegisterInfo::FirstVirtualRegister;
96 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
97 VirtRegModified[Reg] = Val;
100 bool isVirtRegModified(unsigned Reg) const {
101 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
102 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
103 && "Illegal virtual register!");
104 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
107 void MarkPhysRegRecentlyUsed(unsigned Reg) {
108 if (PhysRegsUseOrder.empty() ||
109 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
111 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
112 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
113 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
114 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
115 // Add it to the end of the list
116 PhysRegsUseOrder.push_back(RegMatch);
118 return; // Found an exact match, exit early
123 virtual const char *getPassName() const {
124 return "Local Register Allocator";
127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128 AU.addRequired<LiveVariables>();
129 AU.addRequiredID(PHIEliminationID);
130 AU.addRequiredID(TwoAddressInstructionPassID);
131 MachineFunctionPass::getAnalysisUsage(AU);
135 /// runOnMachineFunction - Register allocate the whole function
136 bool runOnMachineFunction(MachineFunction &Fn);
138 /// AllocateBasicBlock - Register allocate the specified basic block.
139 void AllocateBasicBlock(MachineBasicBlock &MBB);
142 /// areRegsEqual - This method returns true if the specified registers are
143 /// related to each other. To do this, it checks to see if they are equal
144 /// or if the first register is in the alias set of the second register.
146 bool areRegsEqual(unsigned R1, unsigned R2) const {
147 if (R1 == R2) return true;
148 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
149 *AliasSet; ++AliasSet) {
150 if (*AliasSet == R1) return true;
155 /// getStackSpaceFor - This returns the frame index of the specified virtual
156 /// register on the stack, allocating space if necessary.
157 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
159 /// removePhysReg - This method marks the specified physical register as no
160 /// longer being in use.
162 void removePhysReg(unsigned PhysReg);
164 /// spillVirtReg - This method spills the value specified by PhysReg into
165 /// the virtual register slot specified by VirtReg. It then updates the RA
166 /// data structures to indicate the fact that PhysReg is now available.
168 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
169 unsigned VirtReg, unsigned PhysReg);
171 /// spillPhysReg - This method spills the specified physical register into
172 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
173 /// true, then the request is ignored if the physical register does not
174 /// contain a virtual register.
176 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
177 unsigned PhysReg, bool OnlyVirtRegs = false);
179 /// assignVirtToPhysReg - This method updates local state so that we know
180 /// that PhysReg is the proper container for VirtReg now. The physical
181 /// register must not be used for anything else when this is called.
183 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
185 /// liberatePhysReg - Make sure the specified physical register is available
186 /// for use. If there is currently a value in it, it is either moved out of
187 /// the way or spilled to memory.
189 void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
192 /// isPhysRegAvailable - Return true if the specified physical register is
193 /// free and available for use. This also includes checking to see if
194 /// aliased registers are all free...
196 bool isPhysRegAvailable(unsigned PhysReg) const;
198 /// getFreeReg - Look to see if there is a free register available in the
199 /// specified register class. If not, return 0.
201 unsigned getFreeReg(const TargetRegisterClass *RC);
203 /// getReg - Find a physical register to hold the specified virtual
204 /// register. If all compatible physical registers are used, this method
205 /// spills the last used virtual register to the stack, and uses that
208 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
211 /// reloadVirtReg - This method transforms the specified specified virtual
212 /// register use to refer to a physical register. This method may do this
213 /// in one of several ways: if the register is available in a physical
214 /// register already, it uses that physical register. If the value is not
215 /// in a physical register, and if there are physical registers available,
216 /// it loads it into a register. If register pressure is high, and it is
217 /// possible, it tries to fold the load of the virtual register into the
218 /// instruction itself. It avoids doing this if register pressure is low to
219 /// improve the chance that subsequent instructions can use the reloaded
220 /// value. This method returns the modified instruction.
222 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
226 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 RA::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
234 // Find the location Reg would belong...
235 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
237 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
238 return I->second; // Already has space allocated?
240 // Allocate a new stack object for this spill location...
241 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
244 // Assign the slot...
245 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
250 /// removePhysReg - This method marks the specified physical register as no
251 /// longer being in use.
253 void RA::removePhysReg(unsigned PhysReg) {
254 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
256 std::vector<unsigned>::iterator It =
257 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
258 if (It != PhysRegsUseOrder.end())
259 PhysRegsUseOrder.erase(It);
263 /// spillVirtReg - This method spills the value specified by PhysReg into the
264 /// virtual register slot specified by VirtReg. It then updates the RA data
265 /// structures to indicate the fact that PhysReg is now available.
267 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
268 unsigned VirtReg, unsigned PhysReg) {
269 assert(VirtReg && "Spilling a physical register is illegal!"
270 " Must not have appropriate kill for the register or use exists beyond"
271 " the intended one.");
272 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
273 << " containing %reg" << VirtReg;
274 if (!isVirtRegModified(VirtReg))
275 DOUT << " which has not been modified, so no store necessary!";
277 // Otherwise, there is a virtual register corresponding to this physical
278 // register. We only need to spill it into its stack slot if it has been
280 if (isVirtRegModified(VirtReg)) {
281 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
282 int FrameIndex = getStackSpaceFor(VirtReg, RC);
283 DOUT << " to stack slot #" << FrameIndex;
284 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
285 ++NumStores; // Update statistics
288 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
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 RA::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);
307 // If the selected register aliases any other registers, we must make
308 // sure that one of the aliases isn't alive.
309 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
310 *AliasSet; ++AliasSet)
311 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
312 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
313 if (PhysRegsUsed[*AliasSet] == 0) {
314 // This must have been a dead def due to something like this:
317 // No more use of %EAX, %AH, etc.
318 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
319 // an operand of definition MI so it's not marked as such.
320 DOUT << " Register " << RegInfo->getName(*AliasSet)
321 << " [%reg" << *AliasSet
322 << "] is never used, removing it frame live list\n";
323 removePhysReg(*AliasSet);
325 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
330 /// assignVirtToPhysReg - This method updates local state so that we know
331 /// that PhysReg is the proper container for VirtReg now. The physical
332 /// register must not be used for anything else when this is called.
334 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
335 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
336 // Update information to note the fact that this register was just used, and
338 PhysRegsUsed[PhysReg] = VirtReg;
339 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
340 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
344 /// isPhysRegAvailable - Return true if the specified physical register is free
345 /// and available for use. This also includes checking to see if aliased
346 /// registers are all free...
348 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
349 if (PhysRegsUsed[PhysReg] != -1) return false;
351 // If the selected register aliases any other allocated registers, it is
353 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
354 *AliasSet; ++AliasSet)
355 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
356 return false; // Can't use this reg then.
361 /// getFreeReg - Look to see if there is a free register available in the
362 /// specified register class. If not, return 0.
364 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
365 // Get iterators defining the range of registers that are valid to allocate in
366 // this class, which also specifies the preferred allocation order.
367 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
368 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
370 for (; RI != RE; ++RI)
371 if (isPhysRegAvailable(*RI)) { // Is reg unused?
372 assert(*RI != 0 && "Cannot use register!");
373 return *RI; // Found an unused register!
379 /// liberatePhysReg - Make sure the specified physical register is available for
380 /// use. If there is currently a value in it, it is either moved out of the way
381 /// or spilled to memory.
383 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
385 spillPhysReg(MBB, I, PhysReg);
389 /// getReg - Find a physical register to hold the specified virtual
390 /// register. If all compatible physical registers are used, this method spills
391 /// the last used virtual register to the stack, and uses that register.
393 unsigned RA::getReg(MachineBasicBlock &MBB, MachineInstr *I,
395 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
397 // First check to see if we have a free register of the requested type...
398 unsigned PhysReg = getFreeReg(RC);
400 // If we didn't find an unused register, scavenge one now!
402 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
404 // Loop over all of the preallocated registers from the least recently used
405 // to the most recently used. When we find one that is capable of holding
406 // our register, use it.
407 for (unsigned i = 0; PhysReg == 0; ++i) {
408 assert(i != PhysRegsUseOrder.size() &&
409 "Couldn't find a register of the appropriate class!");
411 unsigned R = PhysRegsUseOrder[i];
413 // We can only use this register if it holds a virtual register (ie, it
414 // can be spilled). Do not use it if it is an explicitly allocated
415 // physical register!
416 assert(PhysRegsUsed[R] != -1 &&
417 "PhysReg in PhysRegsUseOrder, but is not allocated?");
418 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
419 // If the current register is compatible, use it.
420 if (RC->contains(R)) {
424 // If one of the registers aliased to the current register is
425 // compatible, use it.
426 for (const unsigned *AliasIt = RegInfo->getAliasSet(R);
427 *AliasIt; ++AliasIt) {
428 if (RC->contains(*AliasIt) &&
429 // If this is pinned down for some reason, don't use it. For
430 // example, if CL is pinned, and we run across CH, don't use
431 // CH as justification for using scavenging ECX (which will
433 PhysRegsUsed[*AliasIt] != 0 &&
435 // Make sure the register is allocatable. Don't allocate SIL on
437 PhysRegsUsed[*AliasIt] != -2) {
438 PhysReg = *AliasIt; // Take an aliased register
446 assert(PhysReg && "Physical register not assigned!?!?");
448 // At this point PhysRegsUseOrder[i] is the least recently used register of
449 // compatible register class. Spill it to memory and reap its remains.
450 spillPhysReg(MBB, I, PhysReg);
453 // Now that we know which register we need to assign this to, do it now!
454 assignVirtToPhysReg(VirtReg, PhysReg);
459 /// reloadVirtReg - This method transforms the specified specified virtual
460 /// register use to refer to a physical register. This method may do this in
461 /// one of several ways: if the register is available in a physical register
462 /// already, it uses that physical register. If the value is not in a physical
463 /// register, and if there are physical registers available, it loads it into a
464 /// register. If register pressure is high, and it is possible, it tries to
465 /// fold the load of the virtual register into the instruction itself. It
466 /// avoids doing this if register pressure is low to improve the chance that
467 /// subsequent instructions can use the reloaded value. This method returns the
468 /// modified instruction.
470 MachineInstr *RA::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
472 unsigned VirtReg = MI->getOperand(OpNum).getReg();
474 // If the virtual register is already available, just update the instruction
476 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
477 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
478 MI->getOperand(OpNum).setReg(PR); // Assign the input register
482 // Otherwise, we need to fold it into the current instruction, or reload it.
483 // If we have registers available to hold the value, use them.
484 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
485 unsigned PhysReg = getFreeReg(RC);
486 int FrameIndex = getStackSpaceFor(VirtReg, RC);
488 if (PhysReg) { // Register is available, allocate it!
489 assignVirtToPhysReg(VirtReg, PhysReg);
490 } else { // No registers available.
491 // If we can fold this spill into this instruction, do so now.
492 if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)){
494 // Since we changed the address of MI, make sure to update live variables
495 // to know that the new instruction has the properties of the old one.
496 LV->instructionChanged(MI, FMI);
497 return MBB.insert(MBB.erase(MI), FMI);
500 // It looks like we can't fold this virtual register load into this
501 // instruction. Force some poor hapless value out of the register file to
502 // make room for the new register, and reload it.
503 PhysReg = getReg(MBB, MI, VirtReg);
506 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
508 DOUT << " Reloading %reg" << VirtReg << " into "
509 << RegInfo->getName(PhysReg) << "\n";
511 // Add move instruction(s)
512 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
513 ++NumLoads; // Update statistics
515 PhysRegsEverUsed[PhysReg] = true;
516 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
522 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
523 // loop over each instruction
524 MachineBasicBlock::iterator MII = MBB.begin();
525 const TargetInstrInfo &TII = *TM->getInstrInfo();
527 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
528 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
530 // If this is the first basic block in the machine function, add live-in
531 // registers as active.
532 if (&MBB == &*MF->begin()) {
533 for (MachineFunction::livein_iterator I = MF->livein_begin(),
534 E = MF->livein_end(); I != E; ++I) {
535 unsigned Reg = I->first;
536 PhysRegsEverUsed[Reg] = true;
537 PhysRegsUsed[Reg] = 0; // It is free and reserved now
538 PhysRegsUseOrder.push_back(Reg);
539 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
540 *AliasSet; ++AliasSet) {
541 if (PhysRegsUsed[*AliasSet] != -2) {
542 PhysRegsUseOrder.push_back(*AliasSet);
543 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
544 PhysRegsEverUsed[*AliasSet] = true;
550 // Otherwise, sequentially allocate each instruction in the MBB.
551 while (MII != MBB.end()) {
552 MachineInstr *MI = MII++;
553 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
554 DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
555 DOUT << " Regs have values: ";
556 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
557 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
558 DOUT << "[" << RegInfo->getName(i)
559 << ",%reg" << PhysRegsUsed[i] << "] ";
562 // Loop over the implicit uses, making sure that they are at the head of the
563 // use order list, so they don't get reallocated.
564 if (TID.ImplicitUses) {
565 for (const unsigned *ImplicitUses = TID.ImplicitUses;
566 *ImplicitUses; ++ImplicitUses)
567 MarkPhysRegRecentlyUsed(*ImplicitUses);
570 SmallVector<unsigned, 8> Kills;
571 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
572 MachineOperand& MO = MI->getOperand(i);
573 if (MO.isRegister() && MO.isKill())
574 Kills.push_back(MO.getReg());
577 // Get the used operands into registers. This has the potential to spill
578 // incoming values if we are out of registers. Note that we completely
579 // ignore physical register uses here. We assume that if an explicit
580 // physical register is referenced by the instruction, that it is guaranteed
581 // to be live-in, or the input is badly hosed.
583 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
584 MachineOperand& MO = MI->getOperand(i);
585 // here we are looking for only used operands (never def&use)
586 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
587 MRegisterInfo::isVirtualRegister(MO.getReg()))
588 MI = reloadVirtReg(MBB, MI, i);
591 // If this instruction is the last user of this register, kill the
592 // value, freeing the register being used, so it doesn't need to be
593 // spilled to memory.
595 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
596 unsigned VirtReg = Kills[i];
597 unsigned PhysReg = VirtReg;
598 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
599 // If the virtual register was never materialized into a register, it
600 // might not be in the map, but it won't hurt to zero it out anyway.
601 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
602 PhysReg = PhysRegSlot;
604 } else if (PhysRegsUsed[PhysReg] == -2) {
605 // Unallocatable register dead, ignore.
610 DOUT << " Last use of " << RegInfo->getName(PhysReg)
611 << "[%reg" << VirtReg <<"], removing it from live set\n";
612 removePhysReg(PhysReg);
613 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
614 *AliasSet; ++AliasSet) {
615 if (PhysRegsUsed[*AliasSet] != -2) {
616 DOUT << " Last use of "
617 << RegInfo->getName(*AliasSet)
618 << "[%reg" << VirtReg <<"], removing it from live set\n";
619 removePhysReg(*AliasSet);
625 // Loop over all of the operands of the instruction, spilling registers that
626 // are defined, and marking explicit destinations in the PhysRegsUsed map.
627 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
628 MachineOperand& MO = MI->getOperand(i);
629 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
630 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
631 unsigned Reg = MO.getReg();
632 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
634 PhysRegsEverUsed[Reg] = true;
635 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
636 PhysRegsUsed[Reg] = 0; // It is free and reserved now
637 PhysRegsUseOrder.push_back(Reg);
638 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
639 *AliasSet; ++AliasSet) {
640 if (PhysRegsUsed[*AliasSet] != -2) {
641 PhysRegsUseOrder.push_back(*AliasSet);
642 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
643 PhysRegsEverUsed[*AliasSet] = true;
649 // Loop over the implicit defs, spilling them as well.
650 if (TID.ImplicitDefs) {
651 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
652 *ImplicitDefs; ++ImplicitDefs) {
653 unsigned Reg = *ImplicitDefs;
654 bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
655 if (!IsNonAllocatable) {
656 spillPhysReg(MBB, MI, Reg, true);
657 PhysRegsUseOrder.push_back(Reg);
658 PhysRegsUsed[Reg] = 0; // It is free and reserved now
660 PhysRegsEverUsed[Reg] = true;
662 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
663 *AliasSet; ++AliasSet) {
664 if (PhysRegsUsed[*AliasSet] != -2) {
665 if (!IsNonAllocatable) {
666 PhysRegsUseOrder.push_back(*AliasSet);
667 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
669 PhysRegsEverUsed[*AliasSet] = true;
675 SmallVector<unsigned, 8> DeadDefs;
676 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
677 MachineOperand& MO = MI->getOperand(i);
678 if (MO.isRegister() && MO.isDead())
679 DeadDefs.push_back(MO.getReg());
682 // Okay, we have allocated all of the source operands and spilled any values
683 // that would be destroyed by defs of this instruction. Loop over the
684 // explicit defs and assign them to a register, spilling incoming values if
685 // we need to scavenge a register.
687 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
688 MachineOperand& MO = MI->getOperand(i);
689 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
690 MRegisterInfo::isVirtualRegister(MO.getReg())) {
691 unsigned DestVirtReg = MO.getReg();
692 unsigned DestPhysReg;
694 // If DestVirtReg already has a value, use it.
695 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
696 DestPhysReg = getReg(MBB, MI, DestVirtReg);
697 PhysRegsEverUsed[DestPhysReg] = true;
698 markVirtRegModified(DestVirtReg);
699 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
703 // If this instruction defines any registers that are immediately dead,
706 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
707 unsigned VirtReg = DeadDefs[i];
708 unsigned PhysReg = VirtReg;
709 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
710 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
711 PhysReg = PhysRegSlot;
712 assert(PhysReg != 0);
714 } else if (PhysRegsUsed[PhysReg] == -2) {
715 // Unallocatable register dead, ignore.
720 DOUT << " Register " << RegInfo->getName(PhysReg)
721 << " [%reg" << VirtReg
722 << "] is never used, removing it frame live list\n";
723 removePhysReg(PhysReg);
724 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
725 *AliasSet; ++AliasSet) {
726 if (PhysRegsUsed[*AliasSet] != -2) {
727 DOUT << " Register " << RegInfo->getName(*AliasSet)
728 << " [%reg" << *AliasSet
729 << "] is never used, removing it frame live list\n";
730 removePhysReg(*AliasSet);
736 // Finally, if this is a noop copy instruction, zap it.
737 unsigned SrcReg, DstReg;
738 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
739 LV->removeVirtualRegistersKilled(MI);
740 LV->removeVirtualRegistersDead(MI);
745 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
747 // Spill all physical registers holding virtual registers now.
748 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
749 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
750 if (unsigned VirtReg = PhysRegsUsed[i])
751 spillVirtReg(MBB, MI, VirtReg, i);
756 // This checking code is very expensive.
758 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
759 e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
760 if (unsigned PR = Virt2PhysRegMap[i]) {
761 std::cerr << "Register still mapped: " << i << " -> " << PR << "\n";
764 assert(AllOk && "Virtual registers still in phys regs?");
767 // Clear any physical register which appear live at the end of the basic
768 // block, but which do not hold any virtual registers. e.g., the stack
770 PhysRegsUseOrder.clear();
774 /// runOnMachineFunction - Register allocate the whole function
776 bool RA::runOnMachineFunction(MachineFunction &Fn) {
777 DOUT << "Machine Function " << "\n";
779 TM = &Fn.getTarget();
780 RegInfo = TM->getRegisterInfo();
781 LV = &getAnalysis<LiveVariables>();
783 PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
784 std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
785 Fn.setUsedPhysRegs(PhysRegsEverUsed);
787 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
789 // At various places we want to efficiently check to see whether a register
790 // is allocatable. To handle this, we mark all unallocatable registers as
791 // being pinned down, permanently.
793 std::vector<bool> Allocable = RegInfo->getAllocatableSet(Fn);
794 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
796 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
799 // initialize the virtual->physical register map to have a 'null'
800 // mapping for all virtual registers
801 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
803 // Loop over all of the basic blocks, eliminating virtual register references
804 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
806 AllocateBasicBlock(*MBB);
808 StackSlotForVirtReg.clear();
809 PhysRegsUsed.clear();
810 VirtRegModified.clear();
811 Virt2PhysRegMap.clear();
815 FunctionPass *llvm::createLocalRegisterAllocator() {