1 //===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
3 // This file implements a simple register allocator. *Very* simple.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/MachineFunction.h"
8 #include "llvm/CodeGen/MachineInstr.h"
9 #include "llvm/Target/MachineInstrInfo.h"
10 #include "llvm/Target/TargetMachine.h"
11 #include "Support/Statistic.h"
15 /// PhysRegClassMap - Construct a mapping of physical register numbers to their
18 /// NOTE: This class will eventually be pulled out to somewhere shared.
20 class PhysRegClassMap {
21 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
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;
30 const TargetRegisterClass *operator[](unsigned Reg) {
31 assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
32 return PhysReg2RegClassMap[Reg];
35 const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
40 Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
41 Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
43 class RegAllocSimple : public FunctionPass {
46 const MRegisterInfo *RegInfo;
47 unsigned NumBytesAllocated;
49 // Maps SSA Regs => offsets on the stack where these values are stored
50 std::map<unsigned, unsigned> VirtReg2OffsetMap;
52 // Maps physical register to their register classes
53 PhysRegClassMap PhysRegClasses;
55 // RegsUsed - Keep track of what registers are currently in use.
56 std::set<unsigned> RegsUsed;
58 // RegClassIdx - Maps RegClass => which index we can take a register
59 // from. Since this is a simple register allocator, when we need a register
60 // of a certain class, we just take the next available one.
61 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
65 RegAllocSimple(TargetMachine &tm)
66 : TM(tm), RegInfo(tm.getRegisterInfo()), PhysRegClasses(RegInfo) {
67 RegsUsed.insert(RegInfo->getFramePointer());
68 RegsUsed.insert(RegInfo->getStackPointer());
70 cleanupAfterFunction();
73 bool runOnFunction(Function &Fn) {
74 return runOnMachineFunction(MachineFunction::get(&Fn));
77 virtual const char *getPassName() const {
78 return "Simple Register Allocator";
82 /// runOnMachineFunction - Register allocate the whole function
83 bool runOnMachineFunction(MachineFunction &Fn);
85 /// AllocateBasicBlock - Register allocate the specified basic block.
86 void AllocateBasicBlock(MachineBasicBlock &MBB);
88 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
89 /// in predecessor basic blocks.
90 void EliminatePHINodes(MachineBasicBlock &MBB);
93 bool isAvailableReg(unsigned Reg) {
94 // assert(Reg < MRegisterInfo::FirstVirtualReg && "...");
95 return RegsUsed.find(Reg) == RegsUsed.end();
98 /// allocateStackSpaceFor - This allocates space for the specified virtual
99 /// register to be held on the stack.
100 unsigned allocateStackSpaceFor(unsigned VirtReg,
101 const TargetRegisterClass *regClass);
103 /// Given a virtual register, returns a physical register that is currently
106 /// Side effect: marks that register as being used until manually cleared
108 unsigned getFreeReg(unsigned virtualReg);
110 /// Returns all `borrowed' registers back to the free pool
111 void clearAllRegs() {
115 /// Invalidates any references, real or implicit, to physical registers
117 void invalidatePhysRegs(const MachineInstr *MI) {
118 unsigned Opcode = MI->getOpcode();
119 const MachineInstrDescriptor &Desc = TM.getInstrInfo().get(Opcode);
120 const unsigned *regs = Desc.ImplicitUses;
122 RegsUsed.insert(*regs++);
124 regs = Desc.ImplicitDefs;
126 RegsUsed.insert(*regs++);
129 void cleanupAfterFunction() {
130 VirtReg2OffsetMap.clear();
131 NumBytesAllocated = 4; // FIXME: This is X86 specific
134 /// Moves value from memory into that register
135 MachineBasicBlock::iterator
136 moveUseToReg (MachineBasicBlock &MBB,
137 MachineBasicBlock::iterator I, unsigned VirtReg,
140 /// Saves reg value on the stack (maps virtual register to stack value)
141 MachineBasicBlock::iterator
142 saveVirtRegToStack (MachineBasicBlock &MBB,
143 MachineBasicBlock::iterator I, unsigned VirtReg,
146 MachineBasicBlock::iterator
147 savePhysRegToStack (MachineBasicBlock &MBB,
148 MachineBasicBlock::iterator I, unsigned PhysReg);
153 /// allocateStackSpaceFor - This allocates space for the specified virtual
154 /// register to be held on the stack.
155 unsigned RegAllocSimple::allocateStackSpaceFor(unsigned VirtReg,
156 const TargetRegisterClass *regClass)
158 if (VirtReg2OffsetMap.find(VirtReg) == VirtReg2OffsetMap.end()) {
159 unsigned RegSize = regClass->getDataSize();
161 // Align NumBytesAllocated. We should be using TargetData alignment stuff
162 // to determine this, but we don't know the LLVM type associated with the
163 // virtual register. Instead, just align to a multiple of the size for now.
164 NumBytesAllocated += RegSize-1;
165 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
167 // Assign the slot...
168 VirtReg2OffsetMap[VirtReg] = NumBytesAllocated;
170 // Reserve the space!
171 NumBytesAllocated += RegSize;
173 return VirtReg2OffsetMap[VirtReg];
176 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
177 const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
180 if (RegClassIdx.find(regClass) != RegClassIdx.end()) {
181 unsigned regIdx = RegClassIdx[regClass]++;
182 assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
183 physReg = regClass->getRegister(regIdx);
185 physReg = regClass->getRegister(0);
186 // assert(physReg < regClass->getNumRegs() && "No registers in class!");
187 RegClassIdx[regClass] = 1;
190 if (isAvailableReg(physReg))
193 return getFreeReg(virtualReg);
196 MachineBasicBlock::iterator
197 RegAllocSimple::moveUseToReg (MachineBasicBlock &MBB,
198 MachineBasicBlock::iterator I,
199 unsigned VirtReg, unsigned &PhysReg)
201 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
204 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
205 PhysReg = getFreeReg(VirtReg);
207 // Add move instruction(s)
209 return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
210 RegInfo->getFramePointer(),
211 -stackOffset, regClass->getDataSize());
214 MachineBasicBlock::iterator
215 RegAllocSimple::saveVirtRegToStack (MachineBasicBlock &MBB,
216 MachineBasicBlock::iterator I,
217 unsigned VirtReg, unsigned PhysReg)
219 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
222 unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
224 // Add move instruction(s)
226 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
227 RegInfo->getFramePointer(),
228 -stackOffset, regClass->getDataSize());
231 MachineBasicBlock::iterator
232 RegAllocSimple::savePhysRegToStack (MachineBasicBlock &MBB,
233 MachineBasicBlock::iterator I,
236 const TargetRegisterClass* regClass = MF->getRegClass(PhysReg);
239 unsigned offset = allocateStackSpaceFor(PhysReg, regClass);
241 // Add move instruction(s)
243 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
244 RegInfo->getFramePointer(),
245 offset, regClass->getDataSize());
248 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
249 /// predecessor basic blocks.
250 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
251 const MachineInstrInfo &MII = TM.getInstrInfo();
253 while (MBB.front()->getOpcode() == 0) {
254 MachineInstr *MI = MBB.front();
255 // Unlink the PHI node from the basic block... but don't delete the PHI
256 MBB.erase(MBB.begin());
258 // a preliminary pass that will invalidate any registers that
259 // are used by the instruction (including implicit uses)
260 invalidatePhysRegs(MI);
262 DEBUG(std::cerr << "num invalid regs: " << RegsUsed.size() << "\n");
263 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
264 MachineOperand &targetReg = MI->getOperand(0);
266 // If it's a virtual register, allocate a physical one otherwise, just use
267 // whatever register is there now note: it MUST be a register -- we're
270 unsigned virtualReg = (unsigned) targetReg.getAllocatedRegNum();
272 if (targetReg.isVirtualRegister()) {
273 physReg = getFreeReg(virtualReg);
275 physReg = virtualReg;
278 // Find the register class of the target register: should be the
279 // same as the values we're trying to store there
280 const TargetRegisterClass* regClass = PhysRegClasses[physReg];
281 assert(regClass && "Target register class not found!");
282 unsigned dataSize = regClass->getDataSize();
284 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
285 MachineOperand &opVal = MI->getOperand(i-1);
287 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
288 // source path the phi
289 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
291 // Check to make sure we haven't already emitted the copy for this block.
292 // This can happen because PHI nodes may have multiple entries for the
293 // same basic block. It doesn't matter which entry we use though, because
294 // all incoming values are guaranteed to be the same for a particular bb.
296 // Note that this is N^2 in the number of phi node entries, but since the
297 // # of entries is tiny, this is not a problem.
299 bool HaveNotEmitted = true;
300 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
301 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
302 HaveNotEmitted = false;
306 if (HaveNotEmitted) {
307 MachineBasicBlock::iterator opI = opBlock.end();
308 MachineInstr *opMI = *--opI;
310 // must backtrack over ALL the branches in the previous block
311 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
314 // move back to the first branch instruction so new instructions
315 // are inserted right in front of it and not in front of a non-branch
316 if (!MII.isBranch(opMI->getOpcode()))
319 // Retrieve the constant value from this op, move it to target
320 // register of the phi
321 if (opVal.isImmediate()) {
322 opI = RegInfo->moveImm2Reg(opBlock, opI, physReg,
323 (unsigned) opVal.getImmedValue(),
325 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
327 // Allocate a physical register and add a move in the BB
328 unsigned opVirtualReg = opVal.getAllocatedRegNum();
330 opI = moveUseToReg(opBlock, opI, opVirtualReg, physReg);
332 // Save that register value to the stack of the TARGET REG
333 saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
337 // make regs available to other instructions
341 // really delete the instruction
347 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
348 // Handle PHI instructions specially: add moves to each pred block
349 EliminatePHINodes(MBB);
351 //loop over each basic block
352 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
353 // Made to combat the incorrect allocation of r2 = add r1, r1
354 std::map<unsigned, unsigned> VirtReg2PhysRegMap;
356 MachineInstr *MI = *I;
358 // a preliminary pass that will invalidate any registers that
359 // are used by the instruction (including implicit uses)
360 invalidatePhysRegs(MI);
362 // Loop over uses, move from memory into registers
363 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
364 MachineOperand &op = MI->getOperand(i);
366 if (op.isVirtualRegister()) {
367 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
368 DEBUG(std::cerr << "op: " << op << "\n");
369 DEBUG(std::cerr << "\t inst[" << i << "]: ";
370 MI->print(std::cerr, TM));
372 // make sure the same virtual register maps to the same physical
373 // register in any given instruction
375 if (VirtReg2PhysRegMap.find(virtualReg) != VirtReg2PhysRegMap.end()) {
376 physReg = VirtReg2PhysRegMap[virtualReg];
379 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
380 // must be same register number as the first operand
381 // This maps a = b + c into b += c, and saves b into a's spot
382 assert(MI->getOperand(1).isRegister() &&
383 MI->getOperand(1).getAllocatedRegNum() &&
384 MF->getRegClass(virtualReg) ==
385 PhysRegClasses[MI->getOperand(1).getAllocatedRegNum()] &&
386 "Two address instruction invalid!");
388 physReg = MI->getOperand(1).getAllocatedRegNum();
390 physReg = getFreeReg(virtualReg);
392 MachineBasicBlock::iterator J = I;
393 J = saveVirtRegToStack(MBB, ++J, virtualReg, physReg);
396 I = moveUseToReg(MBB, I, virtualReg, physReg);
398 VirtReg2PhysRegMap[virtualReg] = physReg;
400 MI->SetMachineOperandReg(i, physReg);
401 DEBUG(std::cerr << "virt: " << virtualReg <<
402 ", phys: " << op.getAllocatedRegNum() << "\n");
409 /// runOnMachineFunction - Register allocate the whole function
411 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
412 DEBUG(std::cerr << "Machine Function " << "\n");
415 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
417 AllocateBasicBlock(*MBB);
419 // add prologue we should preserve callee-save registers...
420 RegInfo->emitPrologue(Fn, NumBytesAllocated);
422 const MachineInstrInfo &MII = TM.getInstrInfo();
424 // add epilogue to restore the callee-save registers
425 // loop over the basic block
426 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
427 MBB != MBBe; ++MBB) {
428 // check if last instruction is a RET
429 if (MII.isReturn(MBB->back()->getOpcode())) {
430 // this block has a return instruction, add epilogue
431 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
435 cleanupAfterFunction();
436 return false; // We never modify the LLVM itself.
439 Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
440 return new RegAllocSimple(TM);