blob: a372390d5c9062c2154a51500a39cfee56ef6510 [file] [log] [blame]
Chris Lattner101b8cd2002-12-16 16:15:28 +00001//===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2//
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.
5//
6//===----------------------------------------------------------------------===//
7
8#include "llvm/CodeGen/MachineFunction.h"
9#include "llvm/CodeGen/MachineInstr.h"
10#include "llvm/Target/MachineInstrInfo.h"
11#include "llvm/Target/TargetMachine.h"
12#include "Support/Statistic.h"
13#include <iostream>
14
15/// PhysRegClassMap - Construct a mapping of physical register numbers to their
16/// register classes.
17///
18/// NOTE: This class will eventually be pulled out to somewhere shared.
19///
20class PhysRegClassMap {
21 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
22public:
23 PhysRegClassMap(const MRegisterInfo *RI) {
24 for (MRegisterInfo::const_iterator I = RI->regclass_begin(),
25 E = RI->regclass_end(); I != E; ++I)
26 for (unsigned i=0; i < (*I)->getNumRegs(); ++i)
27 PhysReg2RegClassMap[(*I)->getRegister(i)] = *I;
28 }
29
30 const TargetRegisterClass *operator[](unsigned Reg) {
31 assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
32 return PhysReg2RegClassMap[Reg];
33 }
34
35 const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
36};
37
38namespace {
39 Statistic<> NumSpilled ("ra-local", "Number of registers spilled");
40 Statistic<> NumReloaded("ra-local", "Number of registers reloaded");
41
42 class RA : public FunctionPass {
43 TargetMachine &TM;
44 MachineFunction *MF;
45 const MRegisterInfo *RegInfo;
46 unsigned NumBytesAllocated;
47 PhysRegClassMap PhysRegClasses;
48
49 // Maps SSA Regs => offsets on the stack where these values are stored
50 std::map<unsigned, unsigned> VirtReg2OffsetMap;
51
52 // Virt2PhysRegMap - This map contains entries for each virtual register
53 // that is currently available in a physical register.
54 //
55 std::map<unsigned, unsigned> Virt2PhysRegMap;
56
57 // PhysRegsUsed - This map contains entries for each physical register that
58 // currently has a value (ie, it is in Virt2PhysRegMap). The value mapped
59 // to is the virtual register corresponding to the physical register (the
60 // inverse of the Virt2PhysRegMap), or 0. The value is set to 0 if this
61 // register is pinned because it is used by a future instruction.
62 //
63 std::map<unsigned, unsigned> PhysRegsUsed;
64
65 // PhysRegsUseOrder - This contains a list of the physical registers that
66 // currently have a virtual register value in them. This list provides an
67 // ordering of registers, imposing a reallocation order. This list is only
68 // used if all registers are allocated and we have to spill one, in which
69 // case we spill the least recently used register. Entries at the front of
70 // the list are the least recently used registers, entries at the back are
71 // the most recently used.
72 //
73 std::vector<unsigned> PhysRegsUseOrder;
74
75 void MarkPhysRegRecentlyUsed(unsigned Reg) {
76 assert(std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg) !=
77 PhysRegsUseOrder.end() && "Register isn't used yet!");
78 if (PhysRegsUseOrder.back() != Reg) {
79 for (unsigned i = PhysRegsUseOrder.size(); ; --i)
80 if (PhysRegsUseOrder[i-1] == Reg) { // remove from middle
81 PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
82 PhysRegsUseOrder.push_back(Reg); // Add it to the end of the list
83 return;
84 }
85 }
86 }
87
88 public:
89
90 RA(TargetMachine &tm)
91 : TM(tm), RegInfo(tm.getRegisterInfo()), PhysRegClasses(RegInfo) {
92 cleanupAfterFunction();
93 }
94
95 bool runOnFunction(Function &Fn) {
96 return runOnMachineFunction(MachineFunction::get(&Fn));
97 }
98
99 virtual const char *getPassName() const {
100 return "Local Register Allocator";
101 }
102
103 private:
104 /// runOnMachineFunction - Register allocate the whole function
105 bool runOnMachineFunction(MachineFunction &Fn);
106
107 /// AllocateBasicBlock - Register allocate the specified basic block.
108 void AllocateBasicBlock(MachineBasicBlock &MBB);
109
110 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
111 /// in predecessor basic blocks.
112 void EliminatePHINodes(MachineBasicBlock &MBB);
113
114
115 /// getStackSpaceFor - This returns the offset of the specified virtual
116 /// register on the stack, allocating space if neccesary.
117 unsigned getStackSpaceFor(unsigned VirtReg,
118 const TargetRegisterClass *regClass);
119
120 void cleanupAfterFunction() {
121 VirtReg2OffsetMap.clear();
122 NumBytesAllocated = 4; // FIXME: This is X86 specific
123 }
124
125
126 /// spillVirtReg - This method spills the value specified by PhysReg into
127 /// the virtual register slot specified by VirtReg. It then updates the RA
128 /// data structures to indicate the fact that PhysReg is now available.
129 ///
130 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
131 unsigned VirtReg, unsigned PhysReg);
132
133 void AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
134
135
136 /// getFreeReg - Find a physical register to hold the specified virtual
137 /// register. If all compatible physical registers are used, this method
138 /// spills the last used virtual register to the stack, and uses that
139 /// register.
140 ///
141 unsigned getFreeReg(MachineBasicBlock &MBB,
142 MachineBasicBlock::iterator &I,
143 unsigned virtualReg);
144
145 /// reloadVirtReg - This method loads the specified virtual register into a
146 /// physical register, returning the physical register chosen. This updates
147 /// the regalloc data structures to reflect the fact that the virtual reg is
148 /// now alive in a physical register, and the previous one isn't.
149 ///
150 unsigned reloadVirtReg(MachineBasicBlock &MBB,
151 MachineBasicBlock::iterator &I, unsigned VirtReg);
152 };
153
154}
155
156/// getStackSpaceFor - This allocates space for the specified virtual
157/// register to be held on the stack.
158unsigned RA::getStackSpaceFor(unsigned VirtReg,
159 const TargetRegisterClass *RegClass) {
160 // Find the location VirtReg would belong...
161 std::map<unsigned, unsigned>::iterator I =
162 VirtReg2OffsetMap.lower_bound(VirtReg);
163
164 if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
165 return I->second; // Already has space allocated?
166
167 unsigned RegSize = RegClass->getDataSize();
168
169 // Align NumBytesAllocated. We should be using TargetData alignment stuff
170 // to determine this, but we don't know the LLVM type associated with the
171 // virtual register. Instead, just align to a multiple of the size for now.
172 NumBytesAllocated += RegSize-1;
173 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
174
175 // Assign the slot...
176 VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
177
178 // Reserve the space!
179 NumBytesAllocated += RegSize;
180 return NumBytesAllocated-RegSize;
181}
182
183/// spillVirtReg - This method spills the value specified by PhysReg into the
184/// virtual register slot specified by VirtReg. It then updates the RA data
185/// structures to indicate the fact that PhysReg is now available.
186///
187void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
188 unsigned VirtReg, unsigned PhysReg) {
189 // If this is just a marker register, we don't need to spill it.
190 if (VirtReg != 0) {
191 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
192 unsigned stackOffset = getStackSpaceFor(VirtReg, RegClass);
193
194 // Add move instruction(s)
195 I = RegInfo->storeReg2RegOffset(MBB, I, PhysReg, RegInfo->getFramePointer(),
196 -stackOffset, RegClass->getDataSize());
197 ++NumSpilled; // Update statistics
198 Virt2PhysRegMap.erase(VirtReg); // VirtReg no longer available
199 }
200 PhysRegsUsed.erase(PhysReg); // PhyReg no longer used
201
202 std::vector<unsigned>::iterator It =
203 std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
204 assert(It != PhysRegsUseOrder.end() &&
205 "Spilled a physical register, but it was not in use list!");
206 PhysRegsUseOrder.erase(It);
207}
208
209/// getFreeReg - Find a physical register to hold the specified virtual
210/// register. If all compatible physical registers are used, this method spills
211/// the last used virtual register to the stack, and uses that register.
212///
213unsigned RA::getFreeReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
214 unsigned VirtReg) {
215 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
216 unsigned PhysReg = 0;
217
218 for (TargetRegisterClass::iterator It = RegClass->begin(),E = RegClass->end();
219 It != E; ++It) {
220 unsigned R = *It;
221 if (PhysRegsUsed.find(R) == PhysRegsUsed.end()) // Is reg unused?
222 /// FIXME: Hack
223 if (R != RegInfo->getFramePointer() && R != RegInfo->getStackPointer() &&
224 R != 13 && R != 14) {
225 // Found an unused register!
226 PhysReg = R;
227 break;
228 }
229 }
230
231 // If we didn't find an unused register, scavange one now!
232 if (PhysReg == 0) {
233 unsigned i = 0;
234 while (PhysRegClasses[PhysRegsUseOrder[i]] != RegClass) {
235 ++i;
236 assert(i != PhysRegsUseOrder.size() &&
237 "Couldn't find a register of the appropriate class!");
238 }
239
240 // At this point PhysRegsUseOrder[i] is the least recently used register of
241 // compatible register class. Spill it to memory and reap its remains.
242 PhysReg = PhysRegsUseOrder[i];
243 spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
244 }
245
246 // Now that we know which register we need to assign this to, do it now!
247 AssignVirtToPhysReg(VirtReg, PhysReg);
248 return PhysReg;
249}
250
251void RA::AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
252 assert(PhysRegsUsed.find(PhysReg) == PhysRegsUsed.end() &&
253 "Phys reg already assigned!");
254 // Update information to note the fact that this register was just used, and
255 // it holds VirtReg.
256 PhysRegsUsed[PhysReg] = VirtReg;
257 Virt2PhysRegMap[VirtReg] = PhysReg;
258 PhysRegsUseOrder.push_back(PhysReg); // New use of PhysReg
259}
260
261
262/// reloadVirtReg - This method loads the specified virtual register into a
263/// physical register, returning the physical register chosen. This updates the
264/// regalloc data structures to reflect the fact that the virtual reg is now
265/// alive in a physical register, and the previous one isn't.
266///
267unsigned RA::reloadVirtReg(MachineBasicBlock &MBB,
268 MachineBasicBlock::iterator &I,
269 unsigned VirtReg) {
270 std::map<unsigned, unsigned>::iterator It = Virt2PhysRegMap.find(VirtReg);
271 if (It != Virt2PhysRegMap.end()) {
272 MarkPhysRegRecentlyUsed(It->second);
273 return It->second; // Already have this value available!
274 }
275
276 unsigned PhysReg = getFreeReg(MBB, I, VirtReg);
277
278 const TargetRegisterClass *RegClass = MF->getRegClass(VirtReg);
279 unsigned StackOffset = getStackSpaceFor(VirtReg, RegClass);
280
281 // Add move instruction(s)
282 I = RegInfo->loadRegOffset2Reg(MBB, I, PhysReg, RegInfo->getFramePointer(),
283 -StackOffset, RegClass->getDataSize());
284 ++NumReloaded; // Update statistics
285 return PhysReg;
286}
287
288/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
289/// predecessor basic blocks.
290///
291void RA::EliminatePHINodes(MachineBasicBlock &MBB) {
292 const MachineInstrInfo &MII = TM.getInstrInfo();
293
294 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
295 MachineInstr *MI = MBB.front();
296 // Unlink the PHI node from the basic block... but don't delete the PHI yet
297 MBB.erase(MBB.begin());
298
299 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
300 assert(MI->getOperand(0).isVirtualRegister() &&
301 "PHI node doesn't write virt reg?");
302
303 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
304
305 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
306 MachineOperand &opVal = MI->getOperand(i-1);
307
308 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
309 // source path the phi
310 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
311
312 // Check to make sure we haven't already emitted the copy for this block.
313 // This can happen because PHI nodes may have multiple entries for the
314 // same basic block. It doesn't matter which entry we use though, because
315 // all incoming values are guaranteed to be the same for a particular bb.
316 //
317 // Note that this is N^2 in the number of phi node entries, but since the
318 // # of entries is tiny, this is not a problem.
319 //
320 bool HaveNotEmitted = true;
321 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
322 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
323 HaveNotEmitted = false;
324 break;
325 }
326
327 if (HaveNotEmitted) {
328 MachineBasicBlock::iterator opI = opBlock.end();
329 MachineInstr *opMI = *--opI;
330
331 // must backtrack over ALL the branches in the previous block
332 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
333 opMI = *--opI;
334
335 // move back to the first branch instruction so new instructions
336 // are inserted right in front of it and not in front of a non-branch
337 if (!MII.isBranch(opMI->getOpcode()))
338 ++opI;
339
340 unsigned dataSize = MF->getRegClass(virtualReg)->getDataSize();
341
342 // Retrieve the constant value from this op, move it to target
343 // register of the phi
344 if (opVal.isImmediate()) {
345 opI = RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
346 (unsigned) opVal.getImmedValue(),
347 dataSize);
348 } else {
349 opI = RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
350 opVal.getAllocatedRegNum(), dataSize);
351 }
352 }
353 }
354
355 // really delete the PHI instruction now!
356 delete MI;
357 }
358}
359
360void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
361 // loop over each instruction
362 MachineBasicBlock::iterator I = MBB.begin();
363 for (; I != MBB.end(); ++I) {
364 MachineInstr *MI = *I;
365
366 // Loop over all of the operands of the instruction, spilling registers that
367 // are defined, and marking explicit destinations in the PhysRegsUsed map.
368 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
369 if (MI->getOperand(i).opIsDef() &&
370 MI->getOperand(i).isPhysicalRegister()) {
371 unsigned Reg = MI->getOperand(i).getAllocatedRegNum();
372 unsigned VMap = PhysRegsUsed[Reg];
373 if (VMap) { // Spill the value in this register...
374 spillVirtReg(MBB, I, VMap, Reg);
375 PhysRegsUsed[Reg] = 0; // It's free now, and it's reserved
376 }
377 PhysRegsUseOrder.push_back(Reg);
378 }
379
380 // FIXME: Loop over the implicit defs, spilling them, as above.
381
382
383 // FIXME: Loop over the implicit uses, making sure that they are at the head
384 // of the use order list, so they don't get reallocated.
385
386 // Loop over all of the operands again, getting the used operands into
387 // registers. This has the potiential to spill incoming values because we
388 // are out of registers.
389 //
390 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
391 if (MI->getOperand(i).opIsUse() &&
392 MI->getOperand(i).isVirtualRegister()) {
393 unsigned VirtSrcReg = MI->getOperand(i).getAllocatedRegNum();
394 unsigned PhysSrcReg = reloadVirtReg(MBB, I, VirtSrcReg);
395 MI->SetMachineOperandReg(i, PhysSrcReg); // Assign the input register
396 }
397
398 // Okay, we have allocated all of the source operands and spilled any values
399 // that would be destroyed by defs of this instruction. Loop over the
400 // implicit defs and assign them to a register, spilling the incoming value
401 // if we need to scavange a register.
402
403 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
404 if (MI->getOperand(i).opIsDef() &&
405 !MI->getOperand(i).isPhysicalRegister()) {
406 unsigned DestVirtReg = MI->getOperand(i).getAllocatedRegNum();
407 unsigned DestPhysReg;
408
409 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
410 // must be same register number as the first operand
411 // This maps a = b + c into b += c, and saves b into a's spot
412 assert(MI->getOperand(1).isRegister() &&
413 MI->getOperand(1).getAllocatedRegNum() &&
414 MI->getOperand(1).opIsUse() &&
415 "Two address instruction invalid!");
416 DestPhysReg = MI->getOperand(1).getAllocatedRegNum();
417
418 // Spill the incoming value, because we are about to change the
419 // register contents.
420 spillVirtReg(MBB, I, PhysRegsUsed[DestPhysReg], DestPhysReg);
421 AssignVirtToPhysReg(DestVirtReg, DestPhysReg);
422 } else {
423 DestPhysReg = getFreeReg(MBB, I, DestVirtReg);
424 }
425 MI->SetMachineOperandReg(i, DestPhysReg); // Assign the output register
426 }
427 }
428
429 // Rewind the iterator to point to the first flow control instruction...
430 const MachineInstrInfo &MII = TM.getInstrInfo();
431 I = MBB.end();
432 do {
433 --I;
434 } while ((MII.isReturn((*I)->getOpcode()) ||
435 MII.isBranch((*I)->getOpcode())) && I != MBB.begin());
436
437 if (!MII.isReturn((*I)->getOpcode()) && !MII.isBranch((*I)->getOpcode()))
438 ++I;
439
440 // Spill all physical registers holding virtual registers now.
441 while (!PhysRegsUsed.empty())
442 spillVirtReg(MBB, I, PhysRegsUsed.begin()->second,
443 PhysRegsUsed.begin()->first);
444
445 assert(Virt2PhysRegMap.empty() && "Virtual registers still in phys regs?");
446 assert(PhysRegsUseOrder.empty() && "Physical regs still allocated?");
447}
448
449/// runOnMachineFunction - Register allocate the whole function
450///
451bool RA::runOnMachineFunction(MachineFunction &Fn) {
452 DEBUG(std::cerr << "Machine Function " << "\n");
453 MF = &Fn;
454
455 // First pass: eliminate PHI instructions by inserting copies into predecessor
456 // blocks.
457 // FIXME: In this pass, count how many uses of each VReg exist!
458 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
459 MBB != MBBe; ++MBB)
460 EliminatePHINodes(*MBB);
461
462 // Loop over all of the basic blocks, eliminating virtual register references
463 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
464 MBB != MBBe; ++MBB)
465 AllocateBasicBlock(*MBB);
466
467 // Round stack allocation up to a nice alignment to keep the stack aligned
468 // FIXME: This is X86 specific! Move to frame manager
469 NumBytesAllocated = (NumBytesAllocated + 3) & ~3;
470
471 // Add prologue to the function...
472 RegInfo->emitPrologue(Fn, NumBytesAllocated);
473
474 const MachineInstrInfo &MII = TM.getInstrInfo();
475
476 // Add epilogue to restore the callee-save registers in each exiting block
477 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
478 MBB != MBBe; ++MBB) {
479 // If last instruction is a return instruction, add an epilogue
480 if (MII.isReturn(MBB->back()->getOpcode()))
481 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
482 }
483
484 cleanupAfterFunction();
485 return true;
486}
487
488Pass *createLocalRegisterAllocator(TargetMachine &TM) {
489 return new RA(TM);
490}