1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
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/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/IndexedMap.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
35 STATISTIC(NumStores, "Number of stores added");
36 STATISTIC(NumLoads , "Number of loads added");
37 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
40 static RegisterRegAlloc
41 localRegAlloc("local", " local register allocator",
42 createLocalRegisterAllocator);
45 class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
48 RALocal() : MachineFunctionPass((intptr_t)&ID) {}
50 const TargetMachine *TM;
52 const MRegisterInfo *RegInfo;
55 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
56 // values are spilled.
57 std::map<unsigned, int> 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 // PhysRegsUseOrder - This contains a list of the physical registers that
79 // currently have a virtual register value in them. This list provides an
80 // ordering of registers, imposing a reallocation order. This list is only
81 // used if all registers are allocated and we have to spill one, in which
82 // case we spill the least recently used register. Entries at the front of
83 // the list are the least recently used registers, entries at the back are
84 // the most recently used.
86 std::vector<unsigned> PhysRegsUseOrder;
88 // VirtRegModified - This bitset contains information about which virtual
89 // registers need to be spilled back to memory when their registers are
90 // scavenged. If a virtual register has simply been rematerialized, there
91 // is no reason to spill it to memory when we need the register back.
93 std::vector<bool> VirtRegModified;
95 void markVirtRegModified(unsigned Reg, bool Val = true) {
96 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
97 Reg -= MRegisterInfo::FirstVirtualRegister;
98 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
99 VirtRegModified[Reg] = Val;
102 bool isVirtRegModified(unsigned Reg) const {
103 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
104 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
105 && "Illegal virtual register!");
106 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
109 void AddToPhysRegsUseOrder(unsigned Reg) {
110 std::vector<unsigned>::iterator It =
111 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
112 if (It != PhysRegsUseOrder.end())
113 PhysRegsUseOrder.erase(It);
114 PhysRegsUseOrder.push_back(Reg);
117 void MarkPhysRegRecentlyUsed(unsigned Reg) {
118 if (PhysRegsUseOrder.empty() ||
119 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
121 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
122 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
123 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
124 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
125 // Add it to the end of the list
126 PhysRegsUseOrder.push_back(RegMatch);
128 return; // Found an exact match, exit early
133 virtual const char *getPassName() const {
134 return "Local Register Allocator";
137 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
138 AU.addRequired<LiveVariables>();
139 AU.addRequiredID(PHIEliminationID);
140 AU.addRequiredID(TwoAddressInstructionPassID);
141 MachineFunctionPass::getAnalysisUsage(AU);
145 /// runOnMachineFunction - Register allocate the whole function
146 bool runOnMachineFunction(MachineFunction &Fn);
148 /// AllocateBasicBlock - Register allocate the specified basic block.
149 void AllocateBasicBlock(MachineBasicBlock &MBB);
152 /// areRegsEqual - This method returns true if the specified registers are
153 /// related to each other. To do this, it checks to see if they are equal
154 /// or if the first register is in the alias set of the second register.
156 bool areRegsEqual(unsigned R1, unsigned R2) const {
157 if (R1 == R2) return true;
158 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
159 *AliasSet; ++AliasSet) {
160 if (*AliasSet == R1) return true;
165 /// getStackSpaceFor - This returns the frame index of the specified virtual
166 /// register on the stack, allocating space if necessary.
167 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
169 /// removePhysReg - This method marks the specified physical register as no
170 /// longer being in use.
172 void removePhysReg(unsigned PhysReg);
174 /// spillVirtReg - This method spills the value specified by PhysReg into
175 /// the virtual register slot specified by VirtReg. It then updates the RA
176 /// data structures to indicate the fact that PhysReg is now available.
178 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
179 unsigned VirtReg, unsigned PhysReg);
181 /// spillPhysReg - This method spills the specified physical register into
182 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
183 /// true, then the request is ignored if the physical register does not
184 /// contain a virtual register.
186 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
187 unsigned PhysReg, bool OnlyVirtRegs = false);
189 /// assignVirtToPhysReg - This method updates local state so that we know
190 /// that PhysReg is the proper container for VirtReg now. The physical
191 /// register must not be used for anything else when this is called.
193 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
195 /// isPhysRegAvailable - Return true if the specified physical register is
196 /// free and available for use. This also includes checking to see if
197 /// aliased registers are all free...
199 bool isPhysRegAvailable(unsigned PhysReg) const;
201 /// getFreeReg - Look to see if there is a free register available in the
202 /// specified register class. If not, return 0.
204 unsigned getFreeReg(const TargetRegisterClass *RC);
206 /// getReg - Find a physical register to hold the specified virtual
207 /// register. If all compatible physical registers are used, this method
208 /// spills the last used virtual register to the stack, and uses that
211 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
214 /// reloadVirtReg - This method transforms the specified specified virtual
215 /// register use to refer to a physical register. This method may do this
216 /// in one of several ways: if the register is available in a physical
217 /// register already, it uses that physical register. If the value is not
218 /// in a physical register, and if there are physical registers available,
219 /// it loads it into a register. If register pressure is high, and it is
220 /// possible, it tries to fold the load of the virtual register into the
221 /// instruction itself. It avoids doing this if register pressure is low to
222 /// improve the chance that subsequent instructions can use the reloaded
223 /// value. This method returns the modified instruction.
225 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
229 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
232 char RALocal::ID = 0;
235 /// getStackSpaceFor - This allocates space for the specified virtual register
236 /// to be held on the stack.
237 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
238 // Find the location Reg would belong...
239 std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
241 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
242 return I->second; // Already has space allocated?
244 // Allocate a new stack object for this spill location...
245 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
248 // Assign the slot...
249 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
254 /// removePhysReg - This method marks the specified physical register as no
255 /// longer being in use.
257 void RALocal::removePhysReg(unsigned PhysReg) {
258 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
260 std::vector<unsigned>::iterator It =
261 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
262 if (It != PhysRegsUseOrder.end())
263 PhysRegsUseOrder.erase(It);
267 /// spillVirtReg - This method spills the value specified by PhysReg into the
268 /// virtual register slot specified by VirtReg. It then updates the RA data
269 /// structures to indicate the fact that PhysReg is now available.
271 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
272 MachineBasicBlock::iterator I,
273 unsigned VirtReg, unsigned PhysReg) {
274 assert(VirtReg && "Spilling a physical register is illegal!"
275 " Must not have appropriate kill for the register or use exists beyond"
276 " the intended one.");
277 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
278 << " containing %reg" << VirtReg;
279 if (!isVirtRegModified(VirtReg))
280 DOUT << " which has not been modified, so no store necessary!";
282 // Otherwise, there is a virtual register corresponding to this physical
283 // register. We only need to spill it into its stack slot if it has been
285 if (isVirtRegModified(VirtReg)) {
286 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
287 int FrameIndex = getStackSpaceFor(VirtReg, RC);
288 DOUT << " to stack slot #" << FrameIndex;
289 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, true, FrameIndex, RC);
290 ++NumStores; // Update statistics
293 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
296 removePhysReg(PhysReg);
300 /// spillPhysReg - This method spills the specified physical register into the
301 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
302 /// then the request is ignored if the physical register does not contain a
303 /// virtual register.
305 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
306 unsigned PhysReg, bool OnlyVirtRegs) {
307 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
308 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
309 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
310 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
312 // If the selected register aliases any other registers, we must make
313 // sure that one of the aliases isn't alive.
314 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
315 *AliasSet; ++AliasSet)
316 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
317 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
318 if (PhysRegsUsed[*AliasSet])
319 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
324 /// assignVirtToPhysReg - This method updates local state so that we know
325 /// that PhysReg is the proper container for VirtReg now. The physical
326 /// register must not be used for anything else when this is called.
328 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
329 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
330 // Update information to note the fact that this register was just used, and
332 PhysRegsUsed[PhysReg] = VirtReg;
333 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
334 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
338 /// isPhysRegAvailable - Return true if the specified physical register is free
339 /// and available for use. This also includes checking to see if aliased
340 /// registers are all free...
342 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
343 if (PhysRegsUsed[PhysReg] != -1) return false;
345 // If the selected register aliases any other allocated registers, it is
347 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
348 *AliasSet; ++AliasSet)
349 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
350 return false; // Can't use this reg then.
355 /// getFreeReg - Look to see if there is a free register available in the
356 /// specified register class. If not, return 0.
358 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
359 // Get iterators defining the range of registers that are valid to allocate in
360 // this class, which also specifies the preferred allocation order.
361 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
362 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
364 for (; RI != RE; ++RI)
365 if (isPhysRegAvailable(*RI)) { // Is reg unused?
366 assert(*RI != 0 && "Cannot use register!");
367 return *RI; // Found an unused register!
373 /// getReg - Find a physical register to hold the specified virtual
374 /// register. If all compatible physical registers are used, this method spills
375 /// the last used virtual register to the stack, and uses that register.
377 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
379 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
381 // First check to see if we have a free register of the requested type...
382 unsigned PhysReg = getFreeReg(RC);
384 // If we didn't find an unused register, scavenge one now!
386 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
388 // Loop over all of the preallocated registers from the least recently used
389 // to the most recently used. When we find one that is capable of holding
390 // our register, use it.
391 for (unsigned i = 0; PhysReg == 0; ++i) {
392 assert(i != PhysRegsUseOrder.size() &&
393 "Couldn't find a register of the appropriate class!");
395 unsigned R = PhysRegsUseOrder[i];
397 // We can only use this register if it holds a virtual register (ie, it
398 // can be spilled). Do not use it if it is an explicitly allocated
399 // physical register!
400 assert(PhysRegsUsed[R] != -1 &&
401 "PhysReg in PhysRegsUseOrder, but is not allocated?");
402 if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
403 // If the current register is compatible, use it.
404 if (RC->contains(R)) {
408 // If one of the registers aliased to the current register is
409 // compatible, use it.
410 for (const unsigned *AliasIt = RegInfo->getAliasSet(R);
411 *AliasIt; ++AliasIt) {
412 if (RC->contains(*AliasIt) &&
413 // If this is pinned down for some reason, don't use it. For
414 // example, if CL is pinned, and we run across CH, don't use
415 // CH as justification for using scavenging ECX (which will
417 PhysRegsUsed[*AliasIt] != 0 &&
419 // Make sure the register is allocatable. Don't allocate SIL on
421 PhysRegsUsed[*AliasIt] != -2) {
422 PhysReg = *AliasIt; // Take an aliased register
430 assert(PhysReg && "Physical register not assigned!?!?");
432 // At this point PhysRegsUseOrder[i] is the least recently used register of
433 // compatible register class. Spill it to memory and reap its remains.
434 spillPhysReg(MBB, I, PhysReg);
437 // Now that we know which register we need to assign this to, do it now!
438 assignVirtToPhysReg(VirtReg, PhysReg);
443 /// reloadVirtReg - This method transforms the specified specified virtual
444 /// register use to refer to a physical register. This method may do this in
445 /// one of several ways: if the register is available in a physical register
446 /// already, it uses that physical register. If the value is not in a physical
447 /// register, and if there are physical registers available, it loads it into a
448 /// register. If register pressure is high, and it is possible, it tries to
449 /// fold the load of the virtual register into the instruction itself. It
450 /// avoids doing this if register pressure is low to improve the chance that
451 /// subsequent instructions can use the reloaded value. This method returns the
452 /// modified instruction.
454 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
456 unsigned VirtReg = MI->getOperand(OpNum).getReg();
458 // If the virtual register is already available, just update the instruction
460 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
461 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
462 MI->getOperand(OpNum).setReg(PR); // Assign the input register
466 // Otherwise, we need to fold it into the current instruction, or reload it.
467 // If we have registers available to hold the value, use them.
468 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
469 unsigned PhysReg = getFreeReg(RC);
470 int FrameIndex = getStackSpaceFor(VirtReg, RC);
472 if (PhysReg) { // Register is available, allocate it!
473 assignVirtToPhysReg(VirtReg, PhysReg);
474 } else { // No registers available.
475 // If we can fold this spill into this instruction, do so now.
476 SmallVector<unsigned, 2> Ops;
477 Ops.push_back(OpNum);
478 if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, Ops, FrameIndex)) {
480 // Since we changed the address of MI, make sure to update live variables
481 // to know that the new instruction has the properties of the old one.
482 LV->instructionChanged(MI, FMI);
483 return MBB.insert(MBB.erase(MI), FMI);
486 // It looks like we can't fold this virtual register load into this
487 // instruction. Force some poor hapless value out of the register file to
488 // make room for the new register, and reload it.
489 PhysReg = getReg(MBB, MI, VirtReg);
492 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
494 DOUT << " Reloading %reg" << VirtReg << " into "
495 << RegInfo->getName(PhysReg) << "\n";
497 // Add move instruction(s)
498 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
499 ++NumLoads; // Update statistics
501 MF->setPhysRegUsed(PhysReg);
502 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
506 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
507 /// read/mod/write register, i.e. update partial register.
508 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
509 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
510 MachineOperand& MO = MI->getOperand(i);
511 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
512 MO.isDef() && !MO.isDead())
518 /// isReadModWriteImplicitDef - True if this is an implicit def for a
519 /// read/mod/write register, i.e. update partial register.
520 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
521 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
522 MachineOperand& MO = MI->getOperand(i);
523 if (MO.isRegister() && MO.getReg() == Reg && MO.isImplicit() &&
524 !MO.isDef() && MO.isKill())
530 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
531 // loop over each instruction
532 MachineBasicBlock::iterator MII = MBB.begin();
533 const TargetInstrInfo &TII = *TM->getInstrInfo();
535 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
536 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
538 // If this is the first basic block in the machine function, add live-in
539 // registers as active.
540 if (&MBB == &*MF->begin()) {
541 for (MachineFunction::livein_iterator I = MF->livein_begin(),
542 E = MF->livein_end(); I != E; ++I) {
543 unsigned Reg = I->first;
544 MF->setPhysRegUsed(Reg);
545 PhysRegsUsed[Reg] = 0; // It is free and reserved now
546 AddToPhysRegsUseOrder(Reg);
547 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
548 *AliasSet; ++AliasSet) {
549 if (PhysRegsUsed[*AliasSet] != -2) {
550 AddToPhysRegsUseOrder(*AliasSet);
551 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
552 MF->setPhysRegUsed(*AliasSet);
558 // Otherwise, sequentially allocate each instruction in the MBB.
559 while (MII != MBB.end()) {
560 MachineInstr *MI = MII++;
561 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
562 DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
563 DOUT << " Regs have values: ";
564 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
565 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
566 DOUT << "[" << RegInfo->getName(i)
567 << ",%reg" << PhysRegsUsed[i] << "] ";
570 // Loop over the implicit uses, making sure that they are at the head of the
571 // use order list, so they don't get reallocated.
572 if (TID.ImplicitUses) {
573 for (const unsigned *ImplicitUses = TID.ImplicitUses;
574 *ImplicitUses; ++ImplicitUses)
575 MarkPhysRegRecentlyUsed(*ImplicitUses);
578 SmallVector<unsigned, 8> Kills;
579 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
580 MachineOperand& MO = MI->getOperand(i);
581 if (MO.isRegister() && MO.isKill()) {
582 if (!MO.isImplicit())
583 Kills.push_back(MO.getReg());
584 else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
585 // These are extra physical register kills when a sub-register
586 // is defined (def of a sub-register is a read/mod/write of the
587 // larger registers). Ignore.
588 Kills.push_back(MO.getReg());
592 // Get the used operands into registers. This has the potential to spill
593 // incoming values if we are out of registers. Note that we completely
594 // ignore physical register uses here. We assume that if an explicit
595 // physical register is referenced by the instruction, that it is guaranteed
596 // to be live-in, or the input is badly hosed.
598 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
599 MachineOperand& MO = MI->getOperand(i);
600 // here we are looking for only used operands (never def&use)
601 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
602 MRegisterInfo::isVirtualRegister(MO.getReg()))
603 MI = reloadVirtReg(MBB, MI, i);
606 // If this instruction is the last user of this register, kill the
607 // value, freeing the register being used, so it doesn't need to be
608 // spilled to memory.
610 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
611 unsigned VirtReg = Kills[i];
612 unsigned PhysReg = VirtReg;
613 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
614 // If the virtual register was never materialized into a register, it
615 // might not be in the map, but it won't hurt to zero it out anyway.
616 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
617 PhysReg = PhysRegSlot;
619 } else if (PhysRegsUsed[PhysReg] == -2) {
620 // Unallocatable register dead, ignore.
623 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
624 "Silently clearing a virtual register?");
628 DOUT << " Last use of " << RegInfo->getName(PhysReg)
629 << "[%reg" << VirtReg <<"], removing it from live set\n";
630 removePhysReg(PhysReg);
631 for (const unsigned *AliasSet = RegInfo->getSubRegisters(PhysReg);
632 *AliasSet; ++AliasSet) {
633 if (PhysRegsUsed[*AliasSet] != -2) {
634 DOUT << " Last use of "
635 << RegInfo->getName(*AliasSet)
636 << "[%reg" << VirtReg <<"], removing it from live set\n";
637 removePhysReg(*AliasSet);
643 // Loop over all of the operands of the instruction, spilling registers that
644 // are defined, and marking explicit destinations in the PhysRegsUsed map.
645 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
646 MachineOperand& MO = MI->getOperand(i);
647 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
648 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
649 unsigned Reg = MO.getReg();
650 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
651 // These are extra physical register defs when a sub-register
652 // is defined (def of a sub-register is a read/mod/write of the
653 // larger registers). Ignore.
654 if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
656 MF->setPhysRegUsed(Reg);
657 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
658 PhysRegsUsed[Reg] = 0; // It is free and reserved now
659 AddToPhysRegsUseOrder(Reg);
661 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
662 *AliasSet; ++AliasSet) {
663 if (PhysRegsUsed[*AliasSet] != -2) {
664 MF->setPhysRegUsed(*AliasSet);
665 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
666 AddToPhysRegsUseOrder(*AliasSet);
672 // Loop over the implicit defs, spilling them as well.
673 if (TID.ImplicitDefs) {
674 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
675 *ImplicitDefs; ++ImplicitDefs) {
676 unsigned Reg = *ImplicitDefs;
677 if (PhysRegsUsed[Reg] != -2) {
678 spillPhysReg(MBB, MI, Reg, true);
679 AddToPhysRegsUseOrder(Reg);
680 PhysRegsUsed[Reg] = 0; // It is free and reserved now
682 MF->setPhysRegUsed(Reg);
683 for (const unsigned *AliasSet = RegInfo->getSubRegisters(Reg);
684 *AliasSet; ++AliasSet) {
685 if (PhysRegsUsed[*AliasSet] != -2) {
686 AddToPhysRegsUseOrder(*AliasSet);
687 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
688 MF->setPhysRegUsed(*AliasSet);
694 SmallVector<unsigned, 8> DeadDefs;
695 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
696 MachineOperand& MO = MI->getOperand(i);
697 if (MO.isRegister() && MO.isDead())
698 DeadDefs.push_back(MO.getReg());
701 // Okay, we have allocated all of the source operands and spilled any values
702 // that would be destroyed by defs of this instruction. Loop over the
703 // explicit defs and assign them to a register, spilling incoming values if
704 // we need to scavenge a register.
706 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
707 MachineOperand& MO = MI->getOperand(i);
708 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
709 MRegisterInfo::isVirtualRegister(MO.getReg())) {
710 unsigned DestVirtReg = MO.getReg();
711 unsigned DestPhysReg;
713 // If DestVirtReg already has a value, use it.
714 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
715 DestPhysReg = getReg(MBB, MI, DestVirtReg);
716 MF->setPhysRegUsed(DestPhysReg);
717 markVirtRegModified(DestVirtReg);
718 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
722 // If this instruction defines any registers that are immediately dead,
725 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
726 unsigned VirtReg = DeadDefs[i];
727 unsigned PhysReg = VirtReg;
728 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
729 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
730 PhysReg = PhysRegSlot;
731 assert(PhysReg != 0);
733 } else if (PhysRegsUsed[PhysReg] == -2) {
734 // Unallocatable register dead, ignore.
739 DOUT << " Register " << RegInfo->getName(PhysReg)
740 << " [%reg" << VirtReg
741 << "] is never used, removing it frame live list\n";
742 removePhysReg(PhysReg);
743 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
744 *AliasSet; ++AliasSet) {
745 if (PhysRegsUsed[*AliasSet] != -2) {
746 DOUT << " Register " << RegInfo->getName(*AliasSet)
747 << " [%reg" << *AliasSet
748 << "] is never used, removing it frame live list\n";
749 removePhysReg(*AliasSet);
755 // Finally, if this is a noop copy instruction, zap it.
756 unsigned SrcReg, DstReg;
757 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
758 LV->removeVirtualRegistersKilled(MI);
759 LV->removeVirtualRegistersDead(MI);
764 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
766 // Spill all physical registers holding virtual registers now.
767 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
768 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
769 if (unsigned VirtReg = PhysRegsUsed[i])
770 spillVirtReg(MBB, MI, VirtReg, i);
775 // This checking code is very expensive.
777 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
778 e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
779 if (unsigned PR = Virt2PhysRegMap[i]) {
780 cerr << "Register still mapped: " << i << " -> " << PR << "\n";
783 assert(AllOk && "Virtual registers still in phys regs?");
786 // Clear any physical register which appear live at the end of the basic
787 // block, but which do not hold any virtual registers. e.g., the stack
789 PhysRegsUseOrder.clear();
793 /// runOnMachineFunction - Register allocate the whole function
795 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
796 DOUT << "Machine Function " << "\n";
798 TM = &Fn.getTarget();
799 RegInfo = TM->getRegisterInfo();
800 LV = &getAnalysis<LiveVariables>();
802 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
804 // At various places we want to efficiently check to see whether a register
805 // is allocatable. To handle this, we mark all unallocatable registers as
806 // being pinned down, permanently.
808 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
809 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
811 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
814 // initialize the virtual->physical register map to have a 'null'
815 // mapping for all virtual registers
816 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
818 // Loop over all of the basic blocks, eliminating virtual register references
819 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
821 AllocateBasicBlock(*MBB);
823 StackSlotForVirtReg.clear();
824 PhysRegsUsed.clear();
825 VirtRegModified.clear();
826 Virt2PhysRegMap.clear();
830 FunctionPass *llvm::createLocalRegisterAllocator() {
831 return new RALocal();