blob: a666184b96e9e914556ff7607ee14b18eaa9a4a0 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
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"
32#include <algorithm>
33using namespace llvm;
34
35STATISTIC(NumStores, "Number of stores added");
36STATISTIC(NumLoads , "Number of loads added");
37STATISTIC(NumFolded, "Number of loads/stores folded into instructions");
38
39namespace {
40 static RegisterRegAlloc
41 localRegAlloc("local", " local register allocator",
42 createLocalRegisterAllocator);
43
44
45 class VISIBILITY_HIDDEN RALocal : public MachineFunctionPass {
46 public:
47 static char ID;
48 RALocal() : MachineFunctionPass((intptr_t)&ID) {}
49 private:
50 const TargetMachine *TM;
51 MachineFunction *MF;
52 const MRegisterInfo *RegInfo;
53 LiveVariables *LV;
54
55 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
56 // values are spilled.
57 std::map<unsigned, int> StackSlotForVirtReg;
58
59 // Virt2PhysRegMap - This map contains entries for each virtual register
60 // that is currently available in a physical register.
61 IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
62
63 unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
64 return Virt2PhysRegMap[VirtReg];
65 }
66
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".
75 //
76 std::vector<int> PhysRegsUsed;
77
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.
85 //
86 std::vector<unsigned> PhysRegsUseOrder;
87
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.
92 //
93 std::vector<bool> VirtRegModified;
94
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;
100 }
101
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];
107 }
108
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);
115 }
116
117 void MarkPhysRegRecentlyUsed(unsigned Reg) {
118 if (PhysRegsUseOrder.empty() ||
119 PhysRegsUseOrder.back() == Reg) return; // Already most recently used
120
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);
127 if (RegMatch == Reg)
128 return; // Found an exact match, exit early
129 }
130 }
131
132 public:
133 virtual const char *getPassName() const {
134 return "Local Register Allocator";
135 }
136
137 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
138 AU.addRequired<LiveVariables>();
139 AU.addRequiredID(PHIEliminationID);
140 AU.addRequiredID(TwoAddressInstructionPassID);
141 MachineFunctionPass::getAnalysisUsage(AU);
142 }
143
144 private:
145 /// runOnMachineFunction - Register allocate the whole function
146 bool runOnMachineFunction(MachineFunction &Fn);
147
148 /// AllocateBasicBlock - Register allocate the specified basic block.
149 void AllocateBasicBlock(MachineBasicBlock &MBB);
150
151
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.
155 ///
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;
161 }
162 return false;
163 }
164
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);
168
169 /// removePhysReg - This method marks the specified physical register as no
170 /// longer being in use.
171 ///
172 void removePhysReg(unsigned PhysReg);
173
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.
177 ///
178 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
179 unsigned VirtReg, unsigned PhysReg);
180
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.
185 ///
186 void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
187 unsigned PhysReg, bool OnlyVirtRegs = false);
188
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.
192 ///
193 void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
194
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...
198 ///
199 bool isPhysRegAvailable(unsigned PhysReg) const;
200
201 /// getFreeReg - Look to see if there is a free register available in the
202 /// specified register class. If not, return 0.
203 ///
204 unsigned getFreeReg(const TargetRegisterClass *RC);
205
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
209 /// register.
210 ///
211 unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
212 unsigned VirtReg);
213
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.
224 ///
225 MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
226 unsigned OpNum);
227
228
229 void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
230 unsigned PhysReg);
231 };
232 char RALocal::ID = 0;
233}
234
235/// getStackSpaceFor - This allocates space for the specified virtual register
236/// to be held on the stack.
237int 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);
240
241 if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
242 return I->second; // Already has space allocated?
243
244 // Allocate a new stack object for this spill location...
245 int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
246 RC->getAlignment());
247
248 // Assign the slot...
249 StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
250 return FrameIdx;
251}
252
253
254/// removePhysReg - This method marks the specified physical register as no
255/// longer being in use.
256///
257void RALocal::removePhysReg(unsigned PhysReg) {
258 PhysRegsUsed[PhysReg] = -1; // PhyReg no longer used
259
260 std::vector<unsigned>::iterator It =
261 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
262 if (It != PhysRegsUseOrder.end())
263 PhysRegsUseOrder.erase(It);
264}
265
266
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.
270///
271void 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!";
281
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
284 // modified.
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, FrameIndex, RC);
290 ++NumStores; // Update statistics
291 }
292
293 getVirt2PhysRegMapSlot(VirtReg) = 0; // VirtReg no longer available
294
295 DOUT << "\n";
296 removePhysReg(PhysReg);
297}
298
299
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.
304///
305void 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);
311 } else {
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);
320 }
321}
322
323
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.
327///
328void 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
331 // it holds VirtReg.
332 PhysRegsUsed[PhysReg] = VirtReg;
333 getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
334 AddToPhysRegsUseOrder(PhysReg); // New use of PhysReg
335}
336
337
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...
341///
342bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
343 if (PhysRegsUsed[PhysReg] != -1) return false;
344
345 // If the selected register aliases any other allocated registers, it is
346 // not free!
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.
351 return true;
352}
353
354
355/// getFreeReg - Look to see if there is a free register available in the
356/// specified register class. If not, return 0.
357///
358unsigned 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);
363
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!
368 }
369 return 0;
370}
371
372
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.
376///
377unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
378 unsigned VirtReg) {
379 const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
380
381 // First check to see if we have a free register of the requested type...
382 unsigned PhysReg = getFreeReg(RC);
383
384 // If we didn't find an unused register, scavenge one now!
385 if (PhysReg == 0) {
386 assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
387
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!");
394
395 unsigned R = PhysRegsUseOrder[i];
396
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)) {
405 PhysReg = R;
406 break;
407 } else {
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
416 // fail).
417 PhysRegsUsed[*AliasIt] != 0 &&
418
419 // Make sure the register is allocatable. Don't allocate SIL on
420 // x86-32.
421 PhysRegsUsed[*AliasIt] != -2) {
422 PhysReg = *AliasIt; // Take an aliased register
423 break;
424 }
425 }
426 }
427 }
428 }
429
430 assert(PhysReg && "Physical register not assigned!?!?");
431
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);
435 }
436
437 // Now that we know which register we need to assign this to, do it now!
438 assignVirtToPhysReg(VirtReg, PhysReg);
439 return PhysReg;
440}
441
442
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.
453///
454MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
455 unsigned OpNum) {
456 unsigned VirtReg = MI->getOperand(OpNum).getReg();
457
458 // If the virtual register is already available, just update the instruction
459 // and return.
460 if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
461 MarkPhysRegRecentlyUsed(PR); // Already have this value available!
462 MI->getOperand(OpNum).setReg(PR); // Assign the input register
463 return MI;
464 }
465
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);
471
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.
Evan Chengfd0bd3c2007-12-02 08:30:39 +0000476 SmallVector<unsigned, 2> Ops;
477 Ops.push_back(OpNum);
478 if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, Ops, FrameIndex)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 ++NumFolded;
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);
484 }
485
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);
490 }
491
492 markVirtRegModified(VirtReg, false); // Note that this reg was just reloaded
493
494 DOUT << " Reloading %reg" << VirtReg << " into "
495 << RegInfo->getName(PhysReg) << "\n";
496
497 // Add move instruction(s)
498 RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
499 ++NumLoads; // Update statistics
500
501 MF->setPhysRegUsed(PhysReg);
502 MI->getOperand(OpNum).setReg(PhysReg); // Assign the input register
503 return MI;
504}
505
506/// isReadModWriteImplicitKill - True if this is an implicit kill for a
507/// read/mod/write register, i.e. update partial register.
508static 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())
513 return true;
514 }
515 return false;
516}
517
518/// isReadModWriteImplicitDef - True if this is an implicit def for a
519/// read/mod/write register, i.e. update partial register.
520static 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())
525 return true;
526 }
527 return false;
528}
529
530void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
531 // loop over each instruction
532 MachineBasicBlock::iterator MII = MBB.begin();
533 const TargetInstrInfo &TII = *TM->getInstrInfo();
534
535 DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
536 if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
537
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);
553 }
554 }
555 }
556 }
557
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] << "] ";
568 DOUT << "\n");
569
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);
576 }
577
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());
589 }
590 }
591
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.
597 //
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);
604 }
605
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.
609 //
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;
618 PhysRegSlot = 0;
619 } else if (PhysRegsUsed[PhysReg] == -2) {
620 // Unallocatable register dead, ignore.
621 continue;
622 } else {
Evan Cheng358d8dd2007-10-22 19:42:28 +0000623 assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 "Silently clearing a virtual register?");
625 }
626
627 if (PhysReg) {
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);
638 }
639 }
640 }
641 }
642
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;
655
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);
660
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);
667 }
668 }
669 }
670 }
671
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
681 }
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);
689 }
690 }
691 }
692 }
693
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());
699 }
700
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.
705 //
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;
712
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
719 }
720 }
721
722 // If this instruction defines any registers that are immediately dead,
723 // kill them now.
724 //
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);
732 PhysRegSlot = 0;
733 } else if (PhysRegsUsed[PhysReg] == -2) {
734 // Unallocatable register dead, ignore.
735 continue;
736 }
737
738 if (PhysReg) {
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);
750 }
751 }
752 }
753 }
754
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);
760 MBB.erase(MI);
761 }
762 }
763
764 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
765
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);
771 else
772 removePhysReg(i);
773
774#if 0
775 // This checking code is very expensive.
776 bool AllOk = true;
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";
781 AllOk = false;
782 }
783 assert(AllOk && "Virtual registers still in phys regs?");
784#endif
785
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
788 // pointer.
789 PhysRegsUseOrder.clear();
790}
791
792
793/// runOnMachineFunction - Register allocate the whole function
794///
795bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
796 DOUT << "Machine Function " << "\n";
797 MF = &Fn;
798 TM = &Fn.getTarget();
799 RegInfo = TM->getRegisterInfo();
800 LV = &getAnalysis<LiveVariables>();
801
802 PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
803
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.
807 {
808 BitVector Allocable = RegInfo->getAllocatableSet(Fn);
809 for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
810 if (!Allocable[i])
811 PhysRegsUsed[i] = -2; // Mark the reg unallocable.
812 }
813
814 // initialize the virtual->physical register map to have a 'null'
815 // mapping for all virtual registers
816 Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
817
818 // Loop over all of the basic blocks, eliminating virtual register references
819 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
820 MBB != MBBe; ++MBB)
821 AllocateBasicBlock(*MBB);
822
823 StackSlotForVirtReg.clear();
824 PhysRegsUsed.clear();
825 VirtRegModified.clear();
826 Virt2PhysRegMap.clear();
827 return true;
828}
829
830FunctionPass *llvm::createLocalRegisterAllocator() {
831 return new RALocal();
832}