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/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 MarkPhysRegRecentlyUsed(unsigned Reg
) {
110 if (PhysRegsUseOrder
.empty() ||
111 PhysRegsUseOrder
.back() == Reg
) return; // Already most recently used
113 for (unsigned i
= PhysRegsUseOrder
.size(); i
!= 0; --i
)
114 if (areRegsEqual(Reg
, PhysRegsUseOrder
[i
-1])) {
115 unsigned RegMatch
= PhysRegsUseOrder
[i
-1]; // remove from middle
116 PhysRegsUseOrder
.erase(PhysRegsUseOrder
.begin()+i
-1);
117 // Add it to the end of the list
118 PhysRegsUseOrder
.push_back(RegMatch
);
120 return; // Found an exact match, exit early
125 virtual const char *getPassName() const {
126 return "Local Register Allocator";
129 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
130 AU
.addRequired
<LiveVariables
>();
131 AU
.addRequiredID(PHIEliminationID
);
132 AU
.addRequiredID(TwoAddressInstructionPassID
);
133 MachineFunctionPass::getAnalysisUsage(AU
);
137 /// runOnMachineFunction - Register allocate the whole function
138 bool runOnMachineFunction(MachineFunction
&Fn
);
140 /// AllocateBasicBlock - Register allocate the specified basic block.
141 void AllocateBasicBlock(MachineBasicBlock
&MBB
);
144 /// areRegsEqual - This method returns true if the specified registers are
145 /// related to each other. To do this, it checks to see if they are equal
146 /// or if the first register is in the alias set of the second register.
148 bool areRegsEqual(unsigned R1
, unsigned R2
) const {
149 if (R1
== R2
) return true;
150 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(R2
);
151 *AliasSet
; ++AliasSet
) {
152 if (*AliasSet
== R1
) return true;
157 /// getStackSpaceFor - This returns the frame index of the specified virtual
158 /// register on the stack, allocating space if necessary.
159 int getStackSpaceFor(unsigned VirtReg
, const TargetRegisterClass
*RC
);
161 /// removePhysReg - This method marks the specified physical register as no
162 /// longer being in use.
164 void removePhysReg(unsigned PhysReg
);
166 /// spillVirtReg - This method spills the value specified by PhysReg into
167 /// the virtual register slot specified by VirtReg. It then updates the RA
168 /// data structures to indicate the fact that PhysReg is now available.
170 void spillVirtReg(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MI
,
171 unsigned VirtReg
, unsigned PhysReg
);
173 /// spillPhysReg - This method spills the specified physical register into
174 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
175 /// true, then the request is ignored if the physical register does not
176 /// contain a virtual register.
178 void spillPhysReg(MachineBasicBlock
&MBB
, MachineInstr
*I
,
179 unsigned PhysReg
, bool OnlyVirtRegs
= false);
181 /// assignVirtToPhysReg - This method updates local state so that we know
182 /// that PhysReg is the proper container for VirtReg now. The physical
183 /// register must not be used for anything else when this is called.
185 void assignVirtToPhysReg(unsigned VirtReg
, unsigned PhysReg
);
187 /// liberatePhysReg - Make sure the specified physical register is available
188 /// for use. If there is currently a value in it, it is either moved out of
189 /// the way or spilled to memory.
191 void liberatePhysReg(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator
&I
,
194 /// isPhysRegAvailable - Return true if the specified physical register is
195 /// free and available for use. This also includes checking to see if
196 /// aliased registers are all free...
198 bool isPhysRegAvailable(unsigned PhysReg
) const;
200 /// getFreeReg - Look to see if there is a free register available in the
201 /// specified register class. If not, return 0.
203 unsigned getFreeReg(const TargetRegisterClass
*RC
);
205 /// getReg - Find a physical register to hold the specified virtual
206 /// register. If all compatible physical registers are used, this method
207 /// spills the last used virtual register to the stack, and uses that
210 unsigned getReg(MachineBasicBlock
&MBB
, MachineInstr
*MI
,
213 /// reloadVirtReg - This method transforms the specified specified virtual
214 /// register use to refer to a physical register. This method may do this
215 /// in one of several ways: if the register is available in a physical
216 /// register already, it uses that physical register. If the value is not
217 /// in a physical register, and if there are physical registers available,
218 /// it loads it into a register. If register pressure is high, and it is
219 /// possible, it tries to fold the load of the virtual register into the
220 /// instruction itself. It avoids doing this if register pressure is low to
221 /// improve the chance that subsequent instructions can use the reloaded
222 /// value. This method returns the modified instruction.
224 MachineInstr
*reloadVirtReg(MachineBasicBlock
&MBB
, MachineInstr
*MI
,
228 void reloadPhysReg(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator
&I
,
231 char RALocal::ID
= 0;
234 /// getStackSpaceFor - This allocates space for the specified virtual register
235 /// to be held on the stack.
236 int RALocal::getStackSpaceFor(unsigned VirtReg
, const TargetRegisterClass
*RC
) {
237 // Find the location Reg would belong...
238 std::map
<unsigned, int>::iterator I
=StackSlotForVirtReg
.lower_bound(VirtReg
);
240 if (I
!= StackSlotForVirtReg
.end() && I
->first
== VirtReg
)
241 return I
->second
; // Already has space allocated?
243 // Allocate a new stack object for this spill location...
244 int FrameIdx
= MF
->getFrameInfo()->CreateStackObject(RC
->getSize(),
247 // Assign the slot...
248 StackSlotForVirtReg
.insert(I
, std::make_pair(VirtReg
, FrameIdx
));
253 /// removePhysReg - This method marks the specified physical register as no
254 /// longer being in use.
256 void RALocal::removePhysReg(unsigned PhysReg
) {
257 PhysRegsUsed
[PhysReg
] = -1; // PhyReg no longer used
259 std::vector
<unsigned>::iterator It
=
260 std::find(PhysRegsUseOrder
.begin(), PhysRegsUseOrder
.end(), PhysReg
);
261 if (It
!= PhysRegsUseOrder
.end())
262 PhysRegsUseOrder
.erase(It
);
266 /// spillVirtReg - This method spills the value specified by PhysReg into the
267 /// virtual register slot specified by VirtReg. It then updates the RA data
268 /// structures to indicate the fact that PhysReg is now available.
270 void RALocal::spillVirtReg(MachineBasicBlock
&MBB
,
271 MachineBasicBlock::iterator I
,
272 unsigned VirtReg
, unsigned PhysReg
) {
273 assert(VirtReg
&& "Spilling a physical register is illegal!"
274 " Must not have appropriate kill for the register or use exists beyond"
275 " the intended one.");
276 DOUT
<< " Spilling register " << RegInfo
->getName(PhysReg
)
277 << " containing %reg" << VirtReg
;
278 if (!isVirtRegModified(VirtReg
))
279 DOUT
<< " which has not been modified, so no store necessary!";
281 // Otherwise, there is a virtual register corresponding to this physical
282 // register. We only need to spill it into its stack slot if it has been
284 if (isVirtRegModified(VirtReg
)) {
285 const TargetRegisterClass
*RC
= MF
->getSSARegMap()->getRegClass(VirtReg
);
286 int FrameIndex
= getStackSpaceFor(VirtReg
, RC
);
287 DOUT
<< " to stack slot #" << FrameIndex
;
288 RegInfo
->storeRegToStackSlot(MBB
, I
, PhysReg
, FrameIndex
, RC
);
289 ++NumStores
; // Update statistics
292 getVirt2PhysRegMapSlot(VirtReg
) = 0; // VirtReg no longer available
295 removePhysReg(PhysReg
);
299 /// spillPhysReg - This method spills the specified physical register into the
300 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
301 /// then the request is ignored if the physical register does not contain a
302 /// virtual register.
304 void RALocal::spillPhysReg(MachineBasicBlock
&MBB
, MachineInstr
*I
,
305 unsigned PhysReg
, bool OnlyVirtRegs
) {
306 if (PhysRegsUsed
[PhysReg
] != -1) { // Only spill it if it's used!
307 assert(PhysRegsUsed
[PhysReg
] != -2 && "Non allocable reg used!");
308 if (PhysRegsUsed
[PhysReg
] || !OnlyVirtRegs
)
309 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
= RegInfo
->getAliasSet(PhysReg
);
314 *AliasSet
; ++AliasSet
)
315 if (PhysRegsUsed
[*AliasSet
] != -1 && // Spill aliased register.
316 PhysRegsUsed
[*AliasSet
] != -2) // If allocatable.
317 if (PhysRegsUsed
[*AliasSet
] == 0) {
318 // This must have been a dead def due to something like this:
321 // No more use of %EAX, %AH, etc.
322 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
323 // an operand of definition MI so it's not marked as such.
324 DOUT
<< " Register " << RegInfo
->getName(*AliasSet
)
325 << " [%reg" << *AliasSet
326 << "] is never used, removing it frame live list\n";
327 removePhysReg(*AliasSet
);
329 spillVirtReg(MBB
, I
, PhysRegsUsed
[*AliasSet
], *AliasSet
);
334 /// assignVirtToPhysReg - This method updates local state so that we know
335 /// that PhysReg is the proper container for VirtReg now. The physical
336 /// register must not be used for anything else when this is called.
338 void RALocal::assignVirtToPhysReg(unsigned VirtReg
, unsigned PhysReg
) {
339 assert(PhysRegsUsed
[PhysReg
] == -1 && "Phys reg already assigned!");
340 // Update information to note the fact that this register was just used, and
342 PhysRegsUsed
[PhysReg
] = VirtReg
;
343 getVirt2PhysRegMapSlot(VirtReg
) = PhysReg
;
344 PhysRegsUseOrder
.push_back(PhysReg
); // New use of PhysReg
348 /// isPhysRegAvailable - Return true if the specified physical register is free
349 /// and available for use. This also includes checking to see if aliased
350 /// registers are all free...
352 bool RALocal::isPhysRegAvailable(unsigned PhysReg
) const {
353 if (PhysRegsUsed
[PhysReg
] != -1) return false;
355 // If the selected register aliases any other allocated registers, it is
357 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(PhysReg
);
358 *AliasSet
; ++AliasSet
)
359 if (PhysRegsUsed
[*AliasSet
] != -1) // Aliased register in use?
360 return false; // Can't use this reg then.
365 /// getFreeReg - Look to see if there is a free register available in the
366 /// specified register class. If not, return 0.
368 unsigned RALocal::getFreeReg(const TargetRegisterClass
*RC
) {
369 // Get iterators defining the range of registers that are valid to allocate in
370 // this class, which also specifies the preferred allocation order.
371 TargetRegisterClass::iterator RI
= RC
->allocation_order_begin(*MF
);
372 TargetRegisterClass::iterator RE
= RC
->allocation_order_end(*MF
);
374 for (; RI
!= RE
; ++RI
)
375 if (isPhysRegAvailable(*RI
)) { // Is reg unused?
376 assert(*RI
!= 0 && "Cannot use register!");
377 return *RI
; // Found an unused register!
383 /// liberatePhysReg - Make sure the specified physical register is available for
384 /// use. If there is currently a value in it, it is either moved out of the way
385 /// or spilled to memory.
387 void RALocal::liberatePhysReg(MachineBasicBlock
&MBB
,
388 MachineBasicBlock::iterator
&I
,
390 spillPhysReg(MBB
, I
, PhysReg
);
394 /// getReg - Find a physical register to hold the specified virtual
395 /// register. If all compatible physical registers are used, this method spills
396 /// the last used virtual register to the stack, and uses that register.
398 unsigned RALocal::getReg(MachineBasicBlock
&MBB
, MachineInstr
*I
,
400 const TargetRegisterClass
*RC
= MF
->getSSARegMap()->getRegClass(VirtReg
);
402 // First check to see if we have a free register of the requested type...
403 unsigned PhysReg
= getFreeReg(RC
);
405 // If we didn't find an unused register, scavenge one now!
407 assert(!PhysRegsUseOrder
.empty() && "No allocated registers??");
409 // Loop over all of the preallocated registers from the least recently used
410 // to the most recently used. When we find one that is capable of holding
411 // our register, use it.
412 for (unsigned i
= 0; PhysReg
== 0; ++i
) {
413 assert(i
!= PhysRegsUseOrder
.size() &&
414 "Couldn't find a register of the appropriate class!");
416 unsigned R
= PhysRegsUseOrder
[i
];
418 // We can only use this register if it holds a virtual register (ie, it
419 // can be spilled). Do not use it if it is an explicitly allocated
420 // physical register!
421 assert(PhysRegsUsed
[R
] != -1 &&
422 "PhysReg in PhysRegsUseOrder, but is not allocated?");
423 if (PhysRegsUsed
[R
] && PhysRegsUsed
[R
] != -2) {
424 // If the current register is compatible, use it.
425 if (RC
->contains(R
)) {
429 // If one of the registers aliased to the current register is
430 // compatible, use it.
431 for (const unsigned *AliasIt
= RegInfo
->getAliasSet(R
);
432 *AliasIt
; ++AliasIt
) {
433 if (RC
->contains(*AliasIt
) &&
434 // If this is pinned down for some reason, don't use it. For
435 // example, if CL is pinned, and we run across CH, don't use
436 // CH as justification for using scavenging ECX (which will
438 PhysRegsUsed
[*AliasIt
] != 0 &&
440 // Make sure the register is allocatable. Don't allocate SIL on
442 PhysRegsUsed
[*AliasIt
] != -2) {
443 PhysReg
= *AliasIt
; // Take an aliased register
451 assert(PhysReg
&& "Physical register not assigned!?!?");
453 // At this point PhysRegsUseOrder[i] is the least recently used register of
454 // compatible register class. Spill it to memory and reap its remains.
455 spillPhysReg(MBB
, I
, PhysReg
);
458 // Now that we know which register we need to assign this to, do it now!
459 assignVirtToPhysReg(VirtReg
, PhysReg
);
464 /// reloadVirtReg - This method transforms the specified specified virtual
465 /// register use to refer to a physical register. This method may do this in
466 /// one of several ways: if the register is available in a physical register
467 /// already, it uses that physical register. If the value is not in a physical
468 /// register, and if there are physical registers available, it loads it into a
469 /// register. If register pressure is high, and it is possible, it tries to
470 /// fold the load of the virtual register into the instruction itself. It
471 /// avoids doing this if register pressure is low to improve the chance that
472 /// subsequent instructions can use the reloaded value. This method returns the
473 /// modified instruction.
475 MachineInstr
*RALocal::reloadVirtReg(MachineBasicBlock
&MBB
, MachineInstr
*MI
,
477 unsigned VirtReg
= MI
->getOperand(OpNum
).getReg();
479 // If the virtual register is already available, just update the instruction
481 if (unsigned PR
= getVirt2PhysRegMapSlot(VirtReg
)) {
482 MarkPhysRegRecentlyUsed(PR
); // Already have this value available!
483 MI
->getOperand(OpNum
).setReg(PR
); // Assign the input register
487 // Otherwise, we need to fold it into the current instruction, or reload it.
488 // If we have registers available to hold the value, use them.
489 const TargetRegisterClass
*RC
= MF
->getSSARegMap()->getRegClass(VirtReg
);
490 unsigned PhysReg
= getFreeReg(RC
);
491 int FrameIndex
= getStackSpaceFor(VirtReg
, RC
);
493 if (PhysReg
) { // Register is available, allocate it!
494 assignVirtToPhysReg(VirtReg
, PhysReg
);
495 } else { // No registers available.
496 // If we can fold this spill into this instruction, do so now.
497 if (MachineInstr
* FMI
= RegInfo
->foldMemoryOperand(MI
, OpNum
, FrameIndex
)){
499 // Since we changed the address of MI, make sure to update live variables
500 // to know that the new instruction has the properties of the old one.
501 LV
->instructionChanged(MI
, FMI
);
502 return MBB
.insert(MBB
.erase(MI
), FMI
);
505 // It looks like we can't fold this virtual register load into this
506 // instruction. Force some poor hapless value out of the register file to
507 // make room for the new register, and reload it.
508 PhysReg
= getReg(MBB
, MI
, VirtReg
);
511 markVirtRegModified(VirtReg
, false); // Note that this reg was just reloaded
513 DOUT
<< " Reloading %reg" << VirtReg
<< " into "
514 << RegInfo
->getName(PhysReg
) << "\n";
516 // Add move instruction(s)
517 RegInfo
->loadRegFromStackSlot(MBB
, MI
, PhysReg
, FrameIndex
, RC
);
518 ++NumLoads
; // Update statistics
520 MF
->setPhysRegUsed(PhysReg
);
521 MI
->getOperand(OpNum
).setReg(PhysReg
); // Assign the input register
527 void RALocal::AllocateBasicBlock(MachineBasicBlock
&MBB
) {
528 // loop over each instruction
529 MachineBasicBlock::iterator MII
= MBB
.begin();
530 const TargetInstrInfo
&TII
= *TM
->getInstrInfo();
532 DEBUG(const BasicBlock
*LBB
= MBB
.getBasicBlock();
533 if (LBB
) DOUT
<< "\nStarting RegAlloc of BB: " << LBB
->getName());
535 // If this is the first basic block in the machine function, add live-in
536 // registers as active.
537 if (&MBB
== &*MF
->begin()) {
538 for (MachineFunction::livein_iterator I
= MF
->livein_begin(),
539 E
= MF
->livein_end(); I
!= E
; ++I
) {
540 unsigned Reg
= I
->first
;
541 MF
->setPhysRegUsed(Reg
);
542 PhysRegsUsed
[Reg
] = 0; // It is free and reserved now
543 PhysRegsUseOrder
.push_back(Reg
);
544 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(Reg
);
545 *AliasSet
; ++AliasSet
) {
546 if (PhysRegsUsed
[*AliasSet
] != -2) {
547 PhysRegsUseOrder
.push_back(*AliasSet
);
548 PhysRegsUsed
[*AliasSet
] = 0; // It is free and reserved now
549 MF
->setPhysRegUsed(*AliasSet
);
555 // Otherwise, sequentially allocate each instruction in the MBB.
556 while (MII
!= MBB
.end()) {
557 MachineInstr
*MI
= MII
++;
558 const TargetInstrDescriptor
&TID
= TII
.get(MI
->getOpcode());
559 DEBUG(DOUT
<< "\nStarting RegAlloc of: " << *MI
;
560 DOUT
<< " Regs have values: ";
561 for (unsigned i
= 0; i
!= RegInfo
->getNumRegs(); ++i
)
562 if (PhysRegsUsed
[i
] != -1 && PhysRegsUsed
[i
] != -2)
563 DOUT
<< "[" << RegInfo
->getName(i
)
564 << ",%reg" << PhysRegsUsed
[i
] << "] ";
567 // Loop over the implicit uses, making sure that they are at the head of the
568 // use order list, so they don't get reallocated.
569 if (TID
.ImplicitUses
) {
570 for (const unsigned *ImplicitUses
= TID
.ImplicitUses
;
571 *ImplicitUses
; ++ImplicitUses
)
572 MarkPhysRegRecentlyUsed(*ImplicitUses
);
575 SmallVector
<unsigned, 8> Kills
;
576 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
577 MachineOperand
& MO
= MI
->getOperand(i
);
578 if (MO
.isRegister() && MO
.isKill())
579 Kills
.push_back(MO
.getReg());
582 // Get the used operands into registers. This has the potential to spill
583 // incoming values if we are out of registers. Note that we completely
584 // ignore physical register uses here. We assume that if an explicit
585 // physical register is referenced by the instruction, that it is guaranteed
586 // to be live-in, or the input is badly hosed.
588 for (unsigned i
= 0; i
!= MI
->getNumOperands(); ++i
) {
589 MachineOperand
& MO
= MI
->getOperand(i
);
590 // here we are looking for only used operands (never def&use)
591 if (MO
.isRegister() && !MO
.isDef() && MO
.getReg() && !MO
.isImplicit() &&
592 MRegisterInfo::isVirtualRegister(MO
.getReg()))
593 MI
= reloadVirtReg(MBB
, MI
, i
);
596 // If this instruction is the last user of this register, kill the
597 // value, freeing the register being used, so it doesn't need to be
598 // spilled to memory.
600 for (unsigned i
= 0, e
= Kills
.size(); i
!= e
; ++i
) {
601 unsigned VirtReg
= Kills
[i
];
602 unsigned PhysReg
= VirtReg
;
603 if (MRegisterInfo::isVirtualRegister(VirtReg
)) {
604 // If the virtual register was never materialized into a register, it
605 // might not be in the map, but it won't hurt to zero it out anyway.
606 unsigned &PhysRegSlot
= getVirt2PhysRegMapSlot(VirtReg
);
607 PhysReg
= PhysRegSlot
;
609 } else if (PhysRegsUsed
[PhysReg
] == -2) {
610 // Unallocatable register dead, ignore.
615 DOUT
<< " Last use of " << RegInfo
->getName(PhysReg
)
616 << "[%reg" << VirtReg
<<"], removing it from live set\n";
617 removePhysReg(PhysReg
);
618 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(PhysReg
);
619 *AliasSet
; ++AliasSet
) {
620 if (PhysRegsUsed
[*AliasSet
] != -2) {
621 DOUT
<< " Last use of "
622 << RegInfo
->getName(*AliasSet
)
623 << "[%reg" << VirtReg
<<"], removing it from live set\n";
624 removePhysReg(*AliasSet
);
630 // Loop over all of the operands of the instruction, spilling registers that
631 // are defined, and marking explicit destinations in the PhysRegsUsed map.
632 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
633 MachineOperand
& MO
= MI
->getOperand(i
);
634 if (MO
.isRegister() && MO
.isDef() && !MO
.isImplicit() && MO
.getReg() &&
635 MRegisterInfo::isPhysicalRegister(MO
.getReg())) {
636 unsigned Reg
= MO
.getReg();
637 if (PhysRegsUsed
[Reg
] == -2) continue; // Something like ESP.
639 MF
->setPhysRegUsed(Reg
);
640 spillPhysReg(MBB
, MI
, Reg
, true); // Spill any existing value in reg
641 PhysRegsUsed
[Reg
] = 0; // It is free and reserved now
642 PhysRegsUseOrder
.push_back(Reg
);
643 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(Reg
);
644 *AliasSet
; ++AliasSet
) {
645 if (PhysRegsUsed
[*AliasSet
] != -2) {
646 PhysRegsUseOrder
.push_back(*AliasSet
);
647 PhysRegsUsed
[*AliasSet
] = 0; // It is free and reserved now
648 MF
->setPhysRegUsed(*AliasSet
);
654 // Loop over the implicit defs, spilling them as well.
655 if (TID
.ImplicitDefs
) {
656 for (const unsigned *ImplicitDefs
= TID
.ImplicitDefs
;
657 *ImplicitDefs
; ++ImplicitDefs
) {
658 unsigned Reg
= *ImplicitDefs
;
659 bool IsNonAllocatable
= PhysRegsUsed
[Reg
] == -2;
660 if (!IsNonAllocatable
) {
661 spillPhysReg(MBB
, MI
, Reg
, true);
662 PhysRegsUseOrder
.push_back(Reg
);
663 PhysRegsUsed
[Reg
] = 0; // It is free and reserved now
665 MF
->setPhysRegUsed(Reg
);
667 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(Reg
);
668 *AliasSet
; ++AliasSet
) {
669 if (PhysRegsUsed
[*AliasSet
] != -2) {
670 if (!IsNonAllocatable
) {
671 PhysRegsUseOrder
.push_back(*AliasSet
);
672 PhysRegsUsed
[*AliasSet
] = 0; // It is free and reserved now
674 MF
->setPhysRegUsed(*AliasSet
);
680 SmallVector
<unsigned, 8> DeadDefs
;
681 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
682 MachineOperand
& MO
= MI
->getOperand(i
);
683 if (MO
.isRegister() && MO
.isDead())
684 DeadDefs
.push_back(MO
.getReg());
687 // Okay, we have allocated all of the source operands and spilled any values
688 // that would be destroyed by defs of this instruction. Loop over the
689 // explicit defs and assign them to a register, spilling incoming values if
690 // we need to scavenge a register.
692 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
693 MachineOperand
& MO
= MI
->getOperand(i
);
694 if (MO
.isRegister() && MO
.isDef() && MO
.getReg() &&
695 MRegisterInfo::isVirtualRegister(MO
.getReg())) {
696 unsigned DestVirtReg
= MO
.getReg();
697 unsigned DestPhysReg
;
699 // If DestVirtReg already has a value, use it.
700 if (!(DestPhysReg
= getVirt2PhysRegMapSlot(DestVirtReg
)))
701 DestPhysReg
= getReg(MBB
, MI
, DestVirtReg
);
702 MF
->setPhysRegUsed(DestPhysReg
);
703 markVirtRegModified(DestVirtReg
);
704 MI
->getOperand(i
).setReg(DestPhysReg
); // Assign the output register
708 // If this instruction defines any registers that are immediately dead,
711 for (unsigned i
= 0, e
= DeadDefs
.size(); i
!= e
; ++i
) {
712 unsigned VirtReg
= DeadDefs
[i
];
713 unsigned PhysReg
= VirtReg
;
714 if (MRegisterInfo::isVirtualRegister(VirtReg
)) {
715 unsigned &PhysRegSlot
= getVirt2PhysRegMapSlot(VirtReg
);
716 PhysReg
= PhysRegSlot
;
717 assert(PhysReg
!= 0);
719 } else if (PhysRegsUsed
[PhysReg
] == -2) {
720 // Unallocatable register dead, ignore.
725 DOUT
<< " Register " << RegInfo
->getName(PhysReg
)
726 << " [%reg" << VirtReg
727 << "] is never used, removing it frame live list\n";
728 removePhysReg(PhysReg
);
729 for (const unsigned *AliasSet
= RegInfo
->getAliasSet(PhysReg
);
730 *AliasSet
; ++AliasSet
) {
731 if (PhysRegsUsed
[*AliasSet
] != -2) {
732 DOUT
<< " Register " << RegInfo
->getName(*AliasSet
)
733 << " [%reg" << *AliasSet
734 << "] is never used, removing it frame live list\n";
735 removePhysReg(*AliasSet
);
741 // Finally, if this is a noop copy instruction, zap it.
742 unsigned SrcReg
, DstReg
;
743 if (TII
.isMoveInstr(*MI
, SrcReg
, DstReg
) && SrcReg
== DstReg
) {
744 LV
->removeVirtualRegistersKilled(MI
);
745 LV
->removeVirtualRegistersDead(MI
);
750 MachineBasicBlock::iterator MI
= MBB
.getFirstTerminator();
752 // Spill all physical registers holding virtual registers now.
753 for (unsigned i
= 0, e
= RegInfo
->getNumRegs(); i
!= e
; ++i
)
754 if (PhysRegsUsed
[i
] != -1 && PhysRegsUsed
[i
] != -2)
755 if (unsigned VirtReg
= PhysRegsUsed
[i
])
756 spillVirtReg(MBB
, MI
, VirtReg
, i
);
761 // This checking code is very expensive.
763 for (unsigned i
= MRegisterInfo::FirstVirtualRegister
,
764 e
= MF
->getSSARegMap()->getLastVirtReg(); i
<= e
; ++i
)
765 if (unsigned PR
= Virt2PhysRegMap
[i
]) {
766 cerr
<< "Register still mapped: " << i
<< " -> " << PR
<< "\n";
769 assert(AllOk
&& "Virtual registers still in phys regs?");
772 // Clear any physical register which appear live at the end of the basic
773 // block, but which do not hold any virtual registers. e.g., the stack
775 PhysRegsUseOrder
.clear();
779 /// runOnMachineFunction - Register allocate the whole function
781 bool RALocal::runOnMachineFunction(MachineFunction
&Fn
) {
782 DOUT
<< "Machine Function " << "\n";
784 TM
= &Fn
.getTarget();
785 RegInfo
= TM
->getRegisterInfo();
786 LV
= &getAnalysis
<LiveVariables
>();
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 BitVector 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() {
817 return new RALocal();