1 //===- RegAllocBigBlock.cpp - A register allocator for large basic blocks -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Duraid Madina and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the RABigBlock class
12 //===----------------------------------------------------------------------===//
14 // This register allocator is derived from RegAllocLocal.cpp. Like it, this
15 // allocator works on one basic block at a time, oblivious to others.
16 // However, the algorithm used here is suited for long blocks of
17 // instructions - registers are spilled by greedily choosing those holding
18 // values that will not be needed for the longest amount of time. This works
19 // particularly well for blocks with 10 or more times as many instructions
20 // as machine registers, but can be used for general code.
22 //===----------------------------------------------------------------------===//
24 // TODO: - automagically invoke linearscan for (groups of) small BBs?
25 // - break ties when picking regs? (probably not worth it in a
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "regalloc"
31 #include "llvm/BasicBlock.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/SSARegMap.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/LiveVariables.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/ADT/IndexedMap.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/Statistic.h"
52 STATISTIC(NumStores, "Number of stores added");
53 STATISTIC(NumLoads , "Number of loads added");
54 STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
57 static RegisterRegAlloc
58 bigBlockRegAlloc("bigblock", " Big-block register allocator",
59 createBigBlockRegisterAllocator);
61 /// VRegKeyInfo - Defines magic values required to use VirtRegs as DenseMap
64 static inline unsigned getEmptyKey() { return -1U; }
65 static inline unsigned getTombstoneKey() { return -2U; }
66 static unsigned getHashValue(const unsigned &Key) { return Key; }
70 /// This register allocator is derived from RegAllocLocal.cpp. Like it, this
71 /// allocator works on one basic block at a time, oblivious to others.
72 /// However, the algorithm used here is suited for long blocks of
73 /// instructions - registers are spilled by greedily choosing those holding
74 /// values that will not be needed for the longest amount of time. This works
75 /// particularly well for blocks with 10 or more times as many instructions
76 /// as machine registers, but can be used for general code.
78 /// TODO: - automagically invoke linearscan for (groups of) small BBs?
79 /// - break ties when picking regs? (probably not worth it in a
82 class VISIBILITY_HIDDEN RABigBlock : public MachineFunctionPass {
85 RABigBlock() : MachineFunctionPass((intptr_t)&ID) {}
87 /// TM - For getting at TargetMachine info
89 const TargetMachine *TM;
91 /// MF - Our generic MachineFunction pointer
95 /// RegInfo - For dealing with machine register info (aliases, folds
97 const MRegisterInfo *RegInfo;
99 /// LV - Our generic LiveVariables pointer
103 typedef SmallVector<unsigned, 2> VRegTimes;
105 /// VRegReadTable - maps VRegs in a BB to the set of times they are read
107 DenseMap<unsigned, VRegTimes*, VRegKeyInfo> VRegReadTable;
109 /// VRegReadIdx - keeps track of the "current time" in terms of
110 /// positions in VRegReadTable
111 DenseMap<unsigned, unsigned , VRegKeyInfo> VRegReadIdx;
113 /// StackSlotForVirtReg - Maps virtual regs to the frame index where these
114 /// values are spilled.
115 IndexedMap<unsigned, VirtReg2IndexFunctor> StackSlotForVirtReg;
117 /// Virt2PhysRegMap - This map contains entries for each virtual register
118 /// that is currently available in a physical register.
119 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
121 /// PhysRegsUsed - This array is effectively a map, containing entries for
122 /// each physical register that currently has a value (ie, it is in
123 /// Virt2PhysRegMap). The value mapped to is the virtual register
124 /// corresponding to the physical register (the inverse of the
125 /// Virt2PhysRegMap), or 0. The value is set to 0 if this register is pinned
126 /// because it is used by a future instruction, and to -2 if it is not
127 /// allocatable. If the entry for a physical register is -1, then the
128 /// physical register is "not in the map".
130 std::vector<int> PhysRegsUsed;
132 /// VirtRegModified - This bitset contains information about which virtual
133 /// registers need to be spilled back to memory when their registers are
134 /// scavenged. If a virtual register has simply been rematerialized, there
135 /// is no reason to spill it to memory when we need the register back.
137 std::vector<int> VirtRegModified;
139 /// MBBLastInsnTime - the number of the the last instruction in MBB
143 /// MBBCurTime - the number of the the instruction being currently processed
147 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
148 return Virt2PhysRegMap[VirtReg];
151 unsigned &getVirt2StackSlot(unsigned VirtReg) {
152 return StackSlotForVirtReg[VirtReg];
155 /// markVirtRegModified - Lets us flip bits in the VirtRegModified bitset
157 void markVirtRegModified(unsigned Reg, bool Val = true) {
158 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
159 Reg -= MRegisterInfo::FirstVirtualRegister;
160 if (VirtRegModified.size() <= Reg)
161 VirtRegModified.resize(Reg+1);
162 VirtRegModified[Reg] = Val;
165 /// isVirtRegModified - Lets us query the VirtRegModified bitset
167 bool isVirtRegModified(unsigned Reg) const {
168 assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
169 assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
170 && "Illegal virtual register!");
171 return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
175 /// getPassName - returns the BigBlock allocator's name
177 virtual const char *getPassName() const {
178 return "BigBlock Register Allocator";
181 /// getAnalaysisUsage - declares the required analyses
183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.addRequired<LiveVariables>();
185 AU.addRequiredID(PHIEliminationID);
186 AU.addRequiredID(TwoAddressInstructionPassID);
187 MachineFunctionPass::getAnalysisUsage(AU);
191 /// runOnMachineFunction - Register allocate the whole function
193 bool runOnMachineFunction(MachineFunction &Fn);
195 /// AllocateBasicBlock - Register allocate the specified basic block.
197 void AllocateBasicBlock(MachineBasicBlock &MBB);
199 /// FillVRegReadTable - Fill out the table of vreg read times given a BB
201 void FillVRegReadTable(MachineBasicBlock &MBB);
203 /// areRegsEqual - This method returns true if the specified registers are
204 /// related to each other. To do this, it checks to see if they are equal
205 /// or if the first register is in the alias set of the second register.
207 bool areRegsEqual(unsigned R1, unsigned R2) const {
208 if (R1 == R2) return true;
209 for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
210 *AliasSet; ++AliasSet) {
211 if (*AliasSet == R1) return true;
216 /// getStackSpaceFor - This returns the frame index of the specified virtual
217 /// register on the stack, allocating space if necessary.
218 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
220 /// removePhysReg - This method marks the specified physical register as no
221 /// longer being in use.
223 void removePhysReg(unsigned PhysReg);
225 /// spillVirtReg - This method spills the value specified by PhysReg into
226 /// the virtual register slot specified by VirtReg. It then updates the RA
227 /// data structures to indicate the fact that PhysReg is now available.
229 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
230 unsigned VirtReg, unsigned PhysReg);
232 /// spillPhysReg - This method spills the specified physical register into
233 /// the virtual register slot associated with it. If OnlyVirtRegs is set to
234 /// true, then the request is ignored if the physical register does not
235 /// contain a virtual register.
237 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
238 unsigned PhysReg, bool OnlyVirtRegs = false);
240 /// assignVirtToPhysReg - This method updates local state so that we know
241 /// that PhysReg is the proper container for VirtReg now. The physical
242 /// register must not be used for anything else when this is called.
244 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
246 /// isPhysRegAvailable - Return true if the specified physical register is
247 /// free and available for use. This also includes checking to see if
248 /// aliased registers are all free...
250 bool isPhysRegAvailable(unsigned PhysReg) const;
252 /// getFreeReg - Look to see if there is a free register available in the
253 /// specified register class. If not, return 0.
255 unsigned getFreeReg(const TargetRegisterClass *RC);
257 /// chooseReg - Pick a physical register to hold the specified
258 /// virtual register by choosing the one which will be read furthest
261 unsigned chooseReg(MachineBasicBlock &MBB, MachineInstr *MI,
264 /// reloadVirtReg - This method transforms the specified specified virtual
265 /// register use to refer to a physical register. This method may do this
266 /// in one of several ways: if the register is available in a physical
267 /// register already, it uses that physical register. If the value is not
268 /// in a physical register, and if there are physical registers available,
269 /// it loads it into a register. If register pressure is high, and it is
270 /// possible, it tries to fold the load of the virtual register into the
271 /// instruction itself. It avoids doing this if register pressure is low to
272 /// improve the chance that subsequent instructions can use the reloaded
273 /// value. This method returns the modified instruction.
275 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
279 char RABigBlock::ID = 0;
282 /// getStackSpaceFor - This allocates space for the specified virtual register
283 /// to be held on the stack.
284 int RABigBlock::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
285 // Find the location Reg would belong...
286 int FrameIdx = getVirt2StackSlot(VirtReg);
289 return FrameIdx - 1; // Already has space allocated?
291 // Allocate a new stack object for this spill location...
292 FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
295 // Assign the slot...
296 getVirt2StackSlot(VirtReg) = FrameIdx + 1;
301 /// removePhysReg - This method marks the specified physical register as no
302 /// longer being in use.
304 void RABigBlock::removePhysReg(unsigned PhysReg) {
305 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
309 /// spillVirtReg - This method spills the value specified by PhysReg into the
310 /// virtual register slot specified by VirtReg. It then updates the RA data
311 /// structures to indicate the fact that PhysReg is now available.
313 void RABigBlock::spillVirtReg(MachineBasicBlock &MBB,
314 MachineBasicBlock::iterator I,
315 unsigned VirtReg, unsigned PhysReg) {
316 assert(VirtReg && "Spilling a physical register is illegal!"
317 " Must not have appropriate kill for the register or use exists beyond"
318 " the intended one.");
319 DOUT << " Spilling register " << RegInfo->getName(PhysReg)
320 << " containing %reg" << VirtReg;
321 if (!isVirtRegModified(VirtReg))
322 DOUT << " which has not been modified, so no store necessary!";
324 // Otherwise, there is a virtual register corresponding to this physical
325 // register. We only need to spill it into its stack slot if it has been
327 if (isVirtRegModified(VirtReg)) {
328 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
329 int FrameIndex = getStackSpaceFor(VirtReg, RC);
330 DOUT << " to stack slot #" << FrameIndex;
331 RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
332 ++NumStores; // Update statistics
335 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
338 removePhysReg(PhysReg);
342 /// spillPhysReg - This method spills the specified physical register into the
343 /// virtual register slot associated with it. If OnlyVirtRegs is set to true,
344 /// then the request is ignored if the physical register does not contain a
345 /// virtual register.
347 void RABigBlock::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
348 unsigned PhysReg, bool OnlyVirtRegs) {
349 if (PhysRegsUsed[PhysReg] != -1) { // Only spill it if it's used!
350 assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
351 if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
352 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
354 // If the selected register aliases any other registers, we must make
355 // sure that one of the aliases isn't alive.
356 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
357 *AliasSet; ++AliasSet)
358 if (PhysRegsUsed[*AliasSet] != -1 && // Spill aliased register.
359 PhysRegsUsed[*AliasSet] != -2) // If allocatable.
360 if (PhysRegsUsed[*AliasSet] == 0) {
361 // This must have been a dead def due to something like this:
364 // No more use of %EAX, %AH, etc.
365 // %EAX isn't dead upon definition, but %AH is. However %AH isn't
366 // an operand of definition MI so it's not marked as such.
367 DOUT << " Register " << RegInfo->getName(*AliasSet)
368 << " [%reg" << *AliasSet
369 << "] is never used, removing it frame live list\n";
370 removePhysReg(*AliasSet);
372 spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
377 /// assignVirtToPhysReg - This method updates local state so that we know
378 /// that PhysReg is the proper container for VirtReg now. The physical
379 /// register must not be used for anything else when this is called.
381 void RABigBlock::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
382 assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
383 // Update information to note the fact that this register was just used, and
385 PhysRegsUsed[PhysReg] = VirtReg;
386 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
390 /// isPhysRegAvailable - Return true if the specified physical register is free
391 /// and available for use. This also includes checking to see if aliased
392 /// registers are all free...
394 bool RABigBlock::isPhysRegAvailable(unsigned PhysReg) const {
395 if (PhysRegsUsed[PhysReg] != -1) return false;
397 // If the selected register aliases any other allocated registers, it is
399 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
400 *AliasSet; ++AliasSet)
401 if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
402 return false; // Can't use this reg then.
407 /// getFreeReg - Look to see if there is a free register available in the
408 /// specified register class. If not, return 0.
410 unsigned RABigBlock::getFreeReg(const TargetRegisterClass *RC) {
411 // Get iterators defining the range of registers that are valid to allocate in
412 // this class, which also specifies the preferred allocation order.
413 TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
414 TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
416 for (; RI != RE; ++RI)
417 if (isPhysRegAvailable(*RI)) { // Is reg unused?
418 assert(*RI != 0 && "Cannot use register!");
419 return *RI; // Found an unused register!
425 /// chooseReg - Pick a physical register to hold the specified
426 /// virtual register by choosing the one whose value will be read
427 /// furthest in the future.
429 unsigned RABigBlock::chooseReg(MachineBasicBlock &MBB, MachineInstr *I,
431 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
432 // First check to see if we have a free register of the requested type...
433 unsigned PhysReg = getFreeReg(RC);
435 // If we didn't find an unused register, find the one which will be
436 // read at the most distant point in time.
438 unsigned delay=0, longest_delay=0;
439 VRegTimes* ReadTimes;
441 unsigned curTime = MBBCurTime;
443 // for all physical regs in the RC,
444 for(TargetRegisterClass::iterator pReg = RC->begin();
445 pReg != RC->end(); ++pReg) {
446 // how long until they're read?
447 if(PhysRegsUsed[*pReg]>0) { // ignore non-allocatable regs
448 ReadTimes = VRegReadTable[PhysRegsUsed[*pReg]];
449 if(ReadTimes && !ReadTimes->empty()) {
450 unsigned& pt = VRegReadIdx[PhysRegsUsed[*pReg]];
451 while(pt < ReadTimes->size() && (*ReadTimes)[pt] < curTime) {
455 if(pt < ReadTimes->size())
456 delay = (*ReadTimes)[pt] - curTime;
458 delay = MBBLastInsnTime + 1 - curTime;
460 // This register is only defined, but never
461 // read in this MBB. Therefore the next read
462 // happens after the end of this MBB
463 delay = MBBLastInsnTime + 1 - curTime;
467 if(delay > longest_delay) {
468 longest_delay = delay;
474 assert(PhysReg && "couldn't grab a register from the table?");
475 // TODO: assert that RC->contains(PhysReg) / handle aliased registers
477 // since we needed to look in the table we need to spill this register.
478 spillPhysReg(MBB, I, PhysReg);
481 // assign the vreg to our chosen physical register
482 assignVirtToPhysReg(VirtReg, PhysReg);
483 return PhysReg; // and return it
487 /// reloadVirtReg - This method transforms an instruction with a virtual
488 /// register use to one that references a physical register. It does this as
491 /// 1) If the register is already in a physical register, it uses it.
492 /// 2) Otherwise, if there is a free physical register, it uses that.
493 /// 3) Otherwise, it calls chooseReg() to get the physical register
494 /// holding the most distantly needed value, generating a spill in
497 /// This method returns the modified instruction.
498 MachineInstr *RABigBlock::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
500 unsigned VirtReg = MI->getOperand(OpNum).getReg();
502 // If the virtual register is already available in a physical register,
503 // just update the instruction and return.
504 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
505 MI->getOperand(OpNum).setReg(PR);
509 // Otherwise, if we have free physical registers available to hold the
511 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
512 unsigned PhysReg = getFreeReg(RC);
513 int FrameIndex = getStackSpaceFor(VirtReg, RC);
515 if (PhysReg) { // we have a free register, so use it.
516 assignVirtToPhysReg(VirtReg, PhysReg);
517 } else { // no free registers available.
518 // try to fold the spill into the instruction
519 if(MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)) {
521 // Since we changed the address of MI, make sure to update live variables
522 // to know that the new instruction has the properties of the old one.
523 LV->instructionChanged(MI, FMI);
524 return MBB.insert(MBB.erase(MI), FMI);
527 // determine which of the physical registers we'll kill off, since we
529 PhysReg = chooseReg(MBB, MI, VirtReg);
532 // this virtual register is now unmodified (since we just reloaded it)
533 markVirtRegModified(VirtReg, false);
535 DOUT << " Reloading %reg" << VirtReg << " into "
536 << RegInfo->getName(PhysReg) << "\n";
538 // Add move instruction(s)
539 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
540 ++NumLoads; // Update statistics
542 MF->setPhysRegUsed(PhysReg);
543 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
547 /// Fill out the vreg read timetable. Since ReadTime increases
548 /// monotonically, the individual readtime sets will be sorted
549 /// in ascending order.
550 void RABigBlock::FillVRegReadTable(MachineBasicBlock &MBB) {
551 // loop over each instruction
552 MachineBasicBlock::iterator MII;
555 for(ReadTime=0, MII = MBB.begin(); MII != MBB.end(); ++ReadTime, ++MII) {
556 MachineInstr *MI = MII;
558 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
559 MachineOperand& MO = MI->getOperand(i);
560 // look for vreg reads..
561 if (MO.isRegister() && !MO.isDef() && MO.getReg() &&
562 MRegisterInfo::isVirtualRegister(MO.getReg())) {
563 // ..and add them to the read table.
564 VRegTimes* &Times = VRegReadTable[MO.getReg()];
565 if(!VRegReadTable[MO.getReg()]) {
566 Times = new VRegTimes;
567 VRegReadIdx[MO.getReg()] = 0;
569 Times->push_back(ReadTime);
575 MBBLastInsnTime = ReadTime;
577 for(DenseMap<unsigned, VRegTimes*, VRegKeyInfo>::iterator Reads = VRegReadTable.begin();
578 Reads != VRegReadTable.end(); ++Reads) {
580 DOUT << "Reads[" << Reads->first << "]=" << Reads->second->size() << "\n";
586 void RABigBlock::AllocateBasicBlock(MachineBasicBlock &MBB) {
587 // loop over each instruction
588 MachineBasicBlock::iterator MII = MBB.begin();
589 const TargetInstrInfo &TII = *TM->getInstrInfo();
591 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
592 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
594 // If this is the first basic block in the machine function, add live-in
595 // registers as active.
596 if (&MBB == &*MF->begin()) {
597 for (MachineFunction::livein_iterator I = MF->livein_begin(),
598 E = MF->livein_end(); I != E; ++I) {
599 unsigned Reg = I->first;
600 MF->setPhysRegUsed(Reg);
601 PhysRegsUsed[Reg] = 0; // It is free and reserved now
602 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
603 *AliasSet; ++AliasSet) {
604 if (PhysRegsUsed[*AliasSet] != -2) {
605 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
606 MF->setPhysRegUsed(*AliasSet);
612 // Otherwise, sequentially allocate each instruction in the MBB.
614 while (MII != MBB.end()) {
615 MachineInstr *MI = MII++;
617 const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
618 DEBUG(DOUT << "\nTime=" << MBBCurTime << " Starting RegAlloc of: " << *MI;
619 DOUT << " Regs have values: ";
620 for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
621 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
622 DOUT << "[" << RegInfo->getName(i)
623 << ",%reg" << PhysRegsUsed[i] << "] ";
626 SmallVector<unsigned, 8> Kills;
627 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
628 MachineOperand& MO = MI->getOperand(i);
629 if (MO.isRegister() && MO.isKill())
630 Kills.push_back(MO.getReg());
633 // Get the used operands into registers. This has the potential to spill
634 // incoming values if we are out of registers. Note that we completely
635 // ignore physical register uses here. We assume that if an explicit
636 // physical register is referenced by the instruction, that it is guaranteed
637 // to be live-in, or the input is badly hosed.
639 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
640 MachineOperand& MO = MI->getOperand(i);
641 // here we are looking for only used operands (never def&use)
642 if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
643 MRegisterInfo::isVirtualRegister(MO.getReg()))
644 MI = reloadVirtReg(MBB, MI, i);
647 // If this instruction is the last user of this register, kill the
648 // value, freeing the register being used, so it doesn't need to be
649 // spilled to memory.
651 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
652 unsigned VirtReg = Kills[i];
653 unsigned PhysReg = VirtReg;
654 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
655 // If the virtual register was never materialized into a register, it
656 // might not be in the map, but it won't hurt to zero it out anyway.
657 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
658 PhysReg = PhysRegSlot;
660 } else if (PhysRegsUsed[PhysReg] == -2) {
661 // Unallocatable register dead, ignore.
666 DOUT << " Last use of " << RegInfo->getName(PhysReg)
667 << "[%reg" << VirtReg <<"], removing it from live set\n";
668 removePhysReg(PhysReg);
669 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
670 *AliasSet; ++AliasSet) {
671 if (PhysRegsUsed[*AliasSet] != -2) {
672 DOUT << " Last use of "
673 << RegInfo->getName(*AliasSet)
674 << "[%reg" << VirtReg <<"], removing it from live set\n";
675 removePhysReg(*AliasSet);
681 // Loop over all of the operands of the instruction, spilling registers that
682 // are defined, and marking explicit destinations in the PhysRegsUsed map.
683 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
684 MachineOperand& MO = MI->getOperand(i);
685 if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
686 MRegisterInfo::isPhysicalRegister(MO.getReg())) {
687 unsigned Reg = MO.getReg();
688 if (PhysRegsUsed[Reg] == -2) continue; // Something like ESP.
690 MF->setPhysRegUsed(Reg);
691 spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
692 PhysRegsUsed[Reg] = 0; // It is free and reserved now
693 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
694 *AliasSet; ++AliasSet) {
695 if (PhysRegsUsed[*AliasSet] != -2) {
696 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
697 MF->setPhysRegUsed(*AliasSet);
703 // Loop over the implicit defs, spilling them as well.
704 if (TID.ImplicitDefs) {
705 for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
706 *ImplicitDefs; ++ImplicitDefs) {
707 unsigned Reg = *ImplicitDefs;
708 bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
709 if (!IsNonAllocatable) {
710 spillPhysReg(MBB, MI, Reg, true);
711 PhysRegsUsed[Reg] = 0; // It is free and reserved now
713 MF->setPhysRegUsed(Reg);
715 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
716 *AliasSet; ++AliasSet) {
717 if (PhysRegsUsed[*AliasSet] != -2) {
718 if (!IsNonAllocatable) {
719 PhysRegsUsed[*AliasSet] = 0; // It is free and reserved now
721 MF->setPhysRegUsed(*AliasSet);
727 SmallVector<unsigned, 8> DeadDefs;
728 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
729 MachineOperand& MO = MI->getOperand(i);
730 if (MO.isRegister() && MO.isDead())
731 DeadDefs.push_back(MO.getReg());
734 // Okay, we have allocated all of the source operands and spilled any values
735 // that would be destroyed by defs of this instruction. Loop over the
736 // explicit defs and assign them to a register, spilling incoming values if
737 // we need to scavenge a register.
739 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
740 MachineOperand& MO = MI->getOperand(i);
741 if (MO.isRegister() && MO.isDef() && MO.getReg() &&
742 MRegisterInfo::isVirtualRegister(MO.getReg())) {
743 unsigned DestVirtReg = MO.getReg();
744 unsigned DestPhysReg;
746 // If DestVirtReg already has a value, use it.
747 if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
748 DestPhysReg = chooseReg(MBB, MI, DestVirtReg);
749 MF->setPhysRegUsed(DestPhysReg);
750 markVirtRegModified(DestVirtReg);
751 MI->getOperand(i).setReg(DestPhysReg); // Assign the output register
755 // If this instruction defines any registers that are immediately dead,
758 for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
759 unsigned VirtReg = DeadDefs[i];
760 unsigned PhysReg = VirtReg;
761 if (MRegisterInfo::isVirtualRegister(VirtReg)) {
762 unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
763 PhysReg = PhysRegSlot;
764 assert(PhysReg != 0);
766 } else if (PhysRegsUsed[PhysReg] == -2) {
767 // Unallocatable register dead, ignore.
772 DOUT << " Register " << RegInfo->getName(PhysReg)
773 << " [%reg" << VirtReg
774 << "] is never used, removing it frame live list\n";
775 removePhysReg(PhysReg);
776 for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
777 *AliasSet; ++AliasSet) {
778 if (PhysRegsUsed[*AliasSet] != -2) {
779 DOUT << " Register " << RegInfo->getName(*AliasSet)
780 << " [%reg" << *AliasSet
781 << "] is never used, removing it frame live list\n";
782 removePhysReg(*AliasSet);
788 // Finally, if this is a noop copy instruction, zap it.
789 unsigned SrcReg, DstReg;
790 if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
791 LV->removeVirtualRegistersKilled(MI);
792 LV->removeVirtualRegistersDead(MI);
797 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
799 // Spill all physical registers holding virtual registers now.
800 for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
801 if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
802 if (unsigned VirtReg = PhysRegsUsed[i])
803 spillVirtReg(MBB, MI, VirtReg, i);
808 /// runOnMachineFunction - Register allocate the whole function
810 bool RABigBlock::runOnMachineFunction(MachineFunction &Fn) {
811 DOUT << "Machine Function " << "\n";
813 TM = &Fn.getTarget();
814 RegInfo = TM->getRegisterInfo();
815 LV = &getAnalysis<LiveVariables>();
817 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
819 // At various places we want to efficiently check to see whether a register
820 // is allocatable. To handle this, we mark all unallocatable registers as
821 // being pinned down, permanently.
823 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
824 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
826 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
829 // initialize the virtual->physical register map to have a 'null'
830 // mapping for all virtual registers
831 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
832 StackSlotForVirtReg.grow(MF->getSSARegMap()->getLastVirtReg());
833 VirtRegModified.resize(MF->getSSARegMap()->getLastVirtReg() - MRegisterInfo::FirstVirtualRegister + 1,0);
835 // Loop over all of the basic blocks, eliminating virtual register references
836 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
837 MBB != MBBe; ++MBB) {
838 // fill out the read timetable
839 FillVRegReadTable(*MBB);
840 // use it to allocate the BB
841 AllocateBasicBlock(*MBB);
843 VRegReadTable.clear();
846 StackSlotForVirtReg.clear();
847 PhysRegsUsed.clear();
848 VirtRegModified.clear();
849 Virt2PhysRegMap.clear();
853 FunctionPass *llvm::createBigBlockRegisterAllocator() {
854 return new RABigBlock();