1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
3 // This register allocator allocates registers to a basic block at a time,
4 // attempting to keep values in registers and reusing registers as appropriate.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/Passes.h"
9 #include "llvm/CodeGen/MachineFunctionPass.h"
10 #include "llvm/CodeGen/MachineInstr.h"
11 #include "llvm/CodeGen/SSARegMap.h"
12 #include "llvm/CodeGen/MachineFrameInfo.h"
13 #include "llvm/CodeGen/LiveVariables.h"
14 #include "llvm/Target/TargetInstrInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "Support/CommandLine.h"
17 #include "Support/Debug.h"
18 #include "Support/Statistic.h"
22 Statistic<> NumSpilled ("ra-local", "Number of registers spilled");
23 Statistic<> NumReloaded("ra-local", "Number of registers reloaded");
24 cl::opt<bool> DisableKill("no-kill", cl::Hidden,
25 cl::desc("Disable register kill in local-ra"));
27 class RA : public MachineFunctionPass {
28 const TargetMachine *TM;
30 const MRegisterInfo *RegInfo;
33 // StackSlotForVirtReg - Maps SSA Regs => frame index where these values are
35 std::map<unsigned, int> StackSlotForVirtReg;
37 // Virt2PhysRegMap - This map contains entries for each virtual register
38 // that is currently available in a physical register.
40 std::map<unsigned, unsigned> Virt2PhysRegMap;
42 // PhysRegsUsed - This map contains entries for each physical register that
43 // currently has a value (ie, it is in Virt2PhysRegMap). The value mapped
44 // to is the virtual register corresponding to the physical register (the
45 // inverse of the Virt2PhysRegMap), or 0. The value is set to 0 if this
46 // register is pinned because it is used by a future instruction.
48 std::map<unsigned, unsigned> PhysRegsUsed;
50 // PhysRegsUseOrder - This contains a list of the physical registers that
51 // currently have a virtual register value in them. This list provides an
52 // ordering of registers, imposing a reallocation order. This list is only
53 // used if all registers are allocated and we have to spill one, in which
54 // case we spill the least recently used register. Entries at the front of
55 // the list are the least recently used registers, entries at the back are
56 // the most recently used.
58 std::vector<unsigned> PhysRegsUseOrder;
60 // VirtRegModified - This bitset contains information about which virtual
61 // registers need to be spilled back to memory when their registers are
62 // scavenged. If a virtual register has simply been rematerialized, there
63 // is no reason to spill it to memory when we need the register back.
65 std::vector<bool> VirtRegModified;
67 void markVirtRegModified(unsigned Reg, bool Val = true) {
68 assert(Reg >= MRegisterInfo::FirstVirtualRegister && "Illegal VirtReg!");
69 Reg -= MRegisterInfo::FirstVirtualRegister;
70 if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
71 VirtRegModified[Reg] = Val;
74 bool isVirtRegModified(unsigned Reg) const {
75 assert(Reg >= MRegisterInfo::FirstVirtualRegister && "Illegal VirtReg!");
76 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
77 && "Illegal virtual register!");
78 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
81 void MarkPhysRegRecentlyUsed(unsigned Reg) {
82 assert(!PhysRegsUseOrder.empty() && "No registers used!");
83 if (PhysRegsUseOrder.back() == Reg) return; // Already most recently used
85 for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
86 if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
87 unsigned RegMatch = PhysRegsUseOrder[i-1]; // remove from middle
88 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
89 // Add it to the end of the list
90 PhysRegsUseOrder.push_back(RegMatch);
92 return; // Found an exact match, exit early
97 virtual const char *getPassName() const {
98 return "Local Register Allocator";
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
103 AU.addRequired<LiveVariables>();
104 AU.addRequiredID(PHIEliminationID);
105 MachineFunctionPass::getAnalysisUsage(AU);
109 /// runOnMachineFunction - Register allocate the whole function
110 bool runOnMachineFunction(MachineFunction &Fn);
112 /// AllocateBasicBlock - Register allocate the specified basic block.
113 void AllocateBasicBlock(MachineBasicBlock &MBB);
116 /// areRegsEqual - This method returns true if the specified registers are
117 /// related to each other. To do this, it checks to see if they are equal
118 /// or if the first register is in the alias set of the second register.
120 bool areRegsEqual(unsigned R1, unsigned R2) const {
121 if (R1 == R2) return true;
122 if (const unsigned *AliasSet = RegInfo->getAliasSet(R2))
123 for (unsigned i = 0; AliasSet[i]; ++i)
124 if (AliasSet[i] == R1) return true;
128 /// getStackSpaceFor - This returns the frame index of the specified virtual
129 /// register on the stack, allocating space if neccesary.
130 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
132 void removePhysReg(unsigned PhysReg);
134 /// spillVirtReg - This method spills the value specified by PhysReg into
135 /// the virtual register slot specified by VirtReg. It then updates the RA
136 /// data structures to indicate the fact that PhysReg is now available.
138 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
139 unsigned VirtReg, unsigned PhysReg);
141 /// spillPhysReg - This method spills the specified physical register into
142 /// the virtual register slot associated with it.
144 void spillPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
147 /// assignVirtToPhysReg - This method updates local state so that we know
148 /// that PhysReg is the proper container for VirtReg now. The physical
149 /// register must not be used for anything else when this is called.
151 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
153 /// liberatePhysReg - Make sure the specified physical register is available
154 /// for use. If there is currently a value in it, it is either moved out of
155 /// the way or spilled to memory.
157 void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
160 /// isPhysRegAvailable - Return true if the specified physical register is
161 /// free and available for use. This also includes checking to see if
162 /// aliased registers are all free...
164 bool isPhysRegAvailable(unsigned PhysReg) const;
166 /// getFreeReg - Look to see if there is a free register available in the
167 /// specified register class. If not, return 0.
169 unsigned getFreeReg(const TargetRegisterClass *RC);
171 /// getReg - Find a physical register to hold the specified virtual
172 /// register. If all compatible physical registers are used, this method
173 /// spills the last used virtual register to the stack, and uses that
176 unsigned getReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
179 /// reloadVirtReg - This method loads the specified virtual register into a
180 /// physical register, returning the physical register chosen. This updates
181 /// the regalloc data structures to reflect the fact that the virtual reg is
182 /// now alive in a physical register, and the previous one isn't.
184 unsigned reloadVirtReg(MachineBasicBlock &MBB,
185 MachineBasicBlock::iterator &I, unsigned VirtReg);
190 /// getStackSpaceFor - This allocates space for the specified virtual
191 /// register to be held on the stack.
192 int RA::getStackSpaceFor(unsigned VirtReg,
193 const TargetRegisterClass *RC) {
194 // Find the location VirtReg would belong...
195 std::map<unsigned, int>::iterator I =
196 StackSlotForVirtReg.lower_bound(VirtReg);
198 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
199 return I->second; // Already has space allocated?
201 // Allocate a new stack object for this spill location...
202 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC);
204 // Assign the slot...
205 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
210 /// removePhysReg - This method marks the specified physical register as no
211 /// longer being in use.
213 void RA::removePhysReg(unsigned PhysReg) {
214 PhysRegsUsed.erase(PhysReg); // PhyReg no longer used
216 std::vector<unsigned>::iterator It =
217 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
218 assert(It != PhysRegsUseOrder.end() &&
219 "Spilled a physical register, but it was not in use list!");
220 PhysRegsUseOrder.erase(It);
224 /// spillVirtReg - This method spills the value specified by PhysReg into the
225 /// virtual register slot specified by VirtReg. It then updates the RA data
226 /// structures to indicate the fact that PhysReg is now available.
228 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
229 unsigned VirtReg, unsigned PhysReg) {
230 // If this is just a marker register, we don't need to spill it.
232 const TargetRegisterClass *RegClass =
233 MF->getSSARegMap()->getRegClass(VirtReg);
234 int FrameIndex = getStackSpaceFor(VirtReg, RegClass);
236 // If we need to spill this value, do so now...
237 if (isVirtRegModified(VirtReg)) {
238 // Add move instruction(s)
239 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RegClass);
240 ++NumSpilled; // Update statistics
242 Virt2PhysRegMap.erase(VirtReg); // VirtReg no longer available
245 removePhysReg(PhysReg);
249 /// spillPhysReg - This method spills the specified physical register into the
250 /// virtual register slot associated with it.
252 void RA::spillPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
254 std::map<unsigned, unsigned>::iterator PI = PhysRegsUsed.find(PhysReg);
255 if (PI != PhysRegsUsed.end()) { // Only spill it if it's used!
256 spillVirtReg(MBB, I, PI->second, PhysReg);
257 } else if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg)) {
258 // If the selected register aliases any other registers, we must make
259 // sure that one of the aliases isn't alive...
260 for (unsigned i = 0; AliasSet[i]; ++i) {
261 PI = PhysRegsUsed.find(AliasSet[i]);
262 if (PI != PhysRegsUsed.end()) // Spill aliased register...
263 spillVirtReg(MBB, I, PI->second, AliasSet[i]);
269 /// assignVirtToPhysReg - This method updates local state so that we know
270 /// that PhysReg is the proper container for VirtReg now. The physical
271 /// register must not be used for anything else when this is called.
273 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
274 assert(PhysRegsUsed.find(PhysReg) == PhysRegsUsed.end() &&
275 "Phys reg already assigned!");
276 // Update information to note the fact that this register was just used, and
278 PhysRegsUsed[PhysReg] = VirtReg;
279 Virt2PhysRegMap[VirtReg] = PhysReg;
280 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
284 /// isPhysRegAvailable - Return true if the specified physical register is free
285 /// and available for use. This also includes checking to see if aliased
286 /// registers are all free...
288 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
289 if (PhysRegsUsed.count(PhysReg)) return false;
291 // If the selected register aliases any other allocated registers, it is
293 if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg))
294 for (unsigned i = 0; AliasSet[i]; ++i)
295 if (PhysRegsUsed.count(AliasSet[i])) // Aliased register in use?
296 return false; // Can't use this reg then.
301 /// getFreeReg - Look to see if there is a free register available in the
302 /// specified register class. If not, return 0.
304 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
305 // Get iterators defining the range of registers that are valid to allocate in
306 // this class, which also specifies the preferred allocation order.
307 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
308 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
310 for (; RI != RE; ++RI)
311 if (isPhysRegAvailable(*RI)) { // Is reg unused?
312 assert(*RI != 0 && "Cannot use register!");
313 return *RI; // Found an unused register!
319 /// liberatePhysReg - Make sure the specified physical register is available for
320 /// use. If there is currently a value in it, it is either moved out of the way
321 /// or spilled to memory.
323 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
325 // FIXME: This code checks to see if a register is available, but it really
326 // wants to know if a reg is available BEFORE the instruction executes. If
327 // called after killed operands are freed, it runs the risk of reallocating a
330 if (isPhysRegAvailable(PhysReg)) return; // Already available...
332 // Check to see if the register is directly used, not indirectly used through
333 // aliases. If aliased registers are the ones actually used, we cannot be
334 // sure that we will be able to save the whole thing if we do a reg-reg copy.
335 std::map<unsigned, unsigned>::iterator PRUI = PhysRegsUsed.find(PhysReg);
336 if (PRUI != PhysRegsUsed.end()) {
337 unsigned VirtReg = PRUI->second; // The virtual register held...
339 // Check to see if there is a compatible register available. If so, we can
340 // move the value into the new register...
342 const TargetRegisterClass *RC = RegInfo->getRegClass(PhysReg);
343 if (unsigned NewReg = getFreeReg(RC)) {
344 // Emit the code to copy the value...
345 RegInfo->copyRegToReg(MBB, I, NewReg, PhysReg, RC);
347 // Update our internal state to indicate that PhysReg is available and Reg
349 Virt2PhysRegMap.erase(VirtReg);
350 removePhysReg(PhysReg); // Free the physreg
352 // Move reference over to new register...
353 assignVirtToPhysReg(VirtReg, NewReg);
358 spillPhysReg(MBB, I, PhysReg);
362 /// getReg - Find a physical register to hold the specified virtual
363 /// register. If all compatible physical registers are used, this method spills
364 /// the last used virtual register to the stack, and uses that register.
366 unsigned RA::getReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
368 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
370 // First check to see if we have a free register of the requested type...
371 unsigned PhysReg = getFreeReg(RC);
373 // If we didn't find an unused register, scavenge one now!
375 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
377 // Loop over all of the preallocated registers from the least recently used
378 // to the most recently used. When we find one that is capable of holding
379 // our register, use it.
380 for (unsigned i = 0; PhysReg == 0; ++i) {
381 assert(i != PhysRegsUseOrder.size() &&
382 "Couldn't find a register of the appropriate class!");
384 unsigned R = PhysRegsUseOrder[i];
385 // If the current register is compatible, use it.
386 if (RegInfo->getRegClass(R) == RC) {
390 // If one of the registers aliased to the current register is
391 // compatible, use it.
392 if (const unsigned *AliasSet = RegInfo->getAliasSet(R))
393 for (unsigned a = 0; AliasSet[a]; ++a)
394 if (RegInfo->getRegClass(AliasSet[a]) == RC) {
395 PhysReg = AliasSet[a]; // Take an aliased register
401 assert(PhysReg && "Physical register not assigned!?!?");
403 // At this point PhysRegsUseOrder[i] is the least recently used register of
404 // compatible register class. Spill it to memory and reap its remains.
405 spillPhysReg(MBB, I, PhysReg);
408 // Now that we know which register we need to assign this to, do it now!
409 assignVirtToPhysReg(VirtReg, PhysReg);
414 /// reloadVirtReg - This method loads the specified virtual register into a
415 /// physical register, returning the physical register chosen. This updates the
416 /// regalloc data structures to reflect the fact that the virtual reg is now
417 /// alive in a physical register, and the previous one isn't.
419 unsigned RA::reloadVirtReg(MachineBasicBlock &MBB,
420 MachineBasicBlock::iterator &I,
422 std::map<unsigned, unsigned>::iterator It = Virt2PhysRegMap.find(VirtReg);
423 if (It != Virt2PhysRegMap.end()) {
424 MarkPhysRegRecentlyUsed(It->second);
425 return It->second; // Already have this value available!
428 unsigned PhysReg = getReg(MBB, I, VirtReg);
430 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
431 int FrameIndex = getStackSpaceFor(VirtReg, RC);
433 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
435 // Add move instruction(s)
436 RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIndex, RC);
437 ++NumReloaded; // Update statistics
441 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
442 // loop over each instruction
443 MachineBasicBlock::iterator I = MBB.begin();
444 for (; I != MBB.end(); ++I) {
445 MachineInstr *MI = *I;
446 const TargetInstrDescriptor &TID = TM->getInstrInfo().get(MI->getOpcode());
448 // Loop over the implicit uses, making sure that they are at the head of the
449 // use order list, so they don't get reallocated.
450 if (const unsigned *ImplicitUses = TID.ImplicitUses)
451 for (unsigned i = 0; ImplicitUses[i]; ++i)
452 MarkPhysRegRecentlyUsed(ImplicitUses[i]);
454 // Get the used operands into registers. This has the potiential to spill
455 // incoming values if we are out of registers.
457 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
458 if (MI->getOperand(i).opIsUse() &&
459 MI->getOperand(i).isVirtualRegister()) {
460 unsigned VirtSrcReg = MI->getOperand(i).getAllocatedRegNum();
461 unsigned PhysSrcReg = reloadVirtReg(MBB, I, VirtSrcReg);
462 MI->SetMachineOperandReg(i, PhysSrcReg); // Assign the input register
466 // If this instruction is the last user of anything in registers, kill the
467 // value, freeing the register being used, so it doesn't need to be
468 // spilled to memory.
470 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
471 KE = LV->killed_end(MI); KI != KE; ++KI) {
472 unsigned VirtReg = KI->second;
473 unsigned PhysReg = VirtReg;
474 if (VirtReg >= MRegisterInfo::FirstVirtualRegister) {
475 std::map<unsigned, unsigned>::iterator I =
476 Virt2PhysRegMap.find(VirtReg);
477 assert(I != Virt2PhysRegMap.end());
479 Virt2PhysRegMap.erase(I);
483 DEBUG(std::cerr << "V: " << VirtReg << " P: " << PhysReg
484 << " Killed by: " << *MI);
485 removePhysReg(PhysReg);
490 // Loop over all of the operands of the instruction, spilling registers that
491 // are defined, and marking explicit destinations in the PhysRegsUsed map.
492 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
493 if ((MI->getOperand(i).opIsDefOnly() ||
494 MI->getOperand(i).opIsDefAndUse()) &&
495 MI->getOperand(i).isPhysicalRegister()) {
496 unsigned Reg = MI->getOperand(i).getAllocatedRegNum();
497 spillPhysReg(MBB, I, Reg); // Spill any existing value in the reg
498 PhysRegsUsed[Reg] = 0; // It is free and reserved now
499 PhysRegsUseOrder.push_back(Reg);
502 // Loop over the implicit defs, spilling them as well.
503 if (const unsigned *ImplicitDefs = TID.ImplicitDefs)
504 for (unsigned i = 0; ImplicitDefs[i]; ++i) {
505 unsigned Reg = ImplicitDefs[i];
506 spillPhysReg(MBB, I, Reg);
507 PhysRegsUseOrder.push_back(Reg);
508 PhysRegsUsed[Reg] = 0; // It is free and reserved now
511 // Okay, we have allocated all of the source operands and spilled any values
512 // that would be destroyed by defs of this instruction. Loop over the
513 // implicit defs and assign them to a register, spilling incoming values if
514 // we need to scavenge a register.
516 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
517 if ((MI->getOperand(i).opIsDefOnly() || MI->getOperand(i).opIsDefAndUse())
518 && MI->getOperand(i).isVirtualRegister()) {
519 unsigned DestVirtReg = MI->getOperand(i).getAllocatedRegNum();
520 unsigned DestPhysReg;
522 // If DestVirtReg already has a value, forget about it. Why doesn't
523 // getReg do this right?
524 std::map<unsigned, unsigned>::iterator DestI =
525 Virt2PhysRegMap.find(DestVirtReg);
526 if (DestI != Virt2PhysRegMap.end()) {
527 unsigned PhysReg = DestI->second;
528 Virt2PhysRegMap.erase(DestI);
529 removePhysReg(PhysReg);
532 if (TM->getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
533 // must be same register number as the first operand
534 // This maps a = b + c into b += c, and saves b into a's spot
535 assert(MI->getOperand(1).isRegister() &&
536 MI->getOperand(1).getAllocatedRegNum() &&
537 MI->getOperand(1).opIsUse() &&
538 "Two address instruction invalid!");
539 DestPhysReg = MI->getOperand(1).getAllocatedRegNum();
541 liberatePhysReg(MBB, I, DestPhysReg);
542 assignVirtToPhysReg(DestVirtReg, DestPhysReg);
544 DestPhysReg = getReg(MBB, I, DestVirtReg);
546 markVirtRegModified(DestVirtReg);
547 MI->SetMachineOperandReg(i, DestPhysReg); // Assign the output register
551 // If this instruction defines any registers that are immediately dead,
554 for (LiveVariables::killed_iterator KI = LV->dead_begin(MI),
555 KE = LV->dead_end(MI); KI != KE; ++KI) {
556 unsigned VirtReg = KI->second;
557 unsigned PhysReg = VirtReg;
558 if (VirtReg >= MRegisterInfo::FirstVirtualRegister) {
559 std::map<unsigned, unsigned>::iterator I =
560 Virt2PhysRegMap.find(VirtReg);
561 assert(I != Virt2PhysRegMap.end());
563 Virt2PhysRegMap.erase(I);
567 DEBUG(std::cerr << "V: " << VirtReg << " P: " << PhysReg
568 << " dead after: " << *MI);
569 removePhysReg(PhysReg);
575 // Rewind the iterator to point to the first flow control instruction...
576 const TargetInstrInfo &TII = TM->getInstrInfo();
578 while (I != MBB.begin() && TII.isTerminatorInstr((*(I-1))->getOpcode()))
581 // Spill all physical registers holding virtual registers now.
582 while (!PhysRegsUsed.empty())
583 spillVirtReg(MBB, I, PhysRegsUsed.begin()->second,
584 PhysRegsUsed.begin()->first);
586 for (std::map<unsigned, unsigned>::iterator I = Virt2PhysRegMap.begin(),
587 E = Virt2PhysRegMap.end(); I != E; ++I)
588 std::cerr << "Register still mapped: " << I->first << " -> "
589 << I->second << "\n";
591 assert(Virt2PhysRegMap.empty() && "Virtual registers still in phys regs?");
592 assert(PhysRegsUseOrder.empty() && "Physical regs still allocated?");
596 /// runOnMachineFunction - Register allocate the whole function
598 bool RA::runOnMachineFunction(MachineFunction &Fn) {
599 DEBUG(std::cerr << "Machine Function " << "\n");
601 TM = &Fn.getTarget();
602 RegInfo = TM->getRegisterInfo();
605 LV = &getAnalysis<LiveVariables>();
607 // Loop over all of the basic blocks, eliminating virtual register references
608 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
610 AllocateBasicBlock(*MBB);
612 StackSlotForVirtReg.clear();
613 VirtRegModified.clear();
617 Pass *createLocalRegisterAllocator() {