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"
16 Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
17 Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
19 class RegAllocSimple : public FunctionPass {
22 const MRegisterInfo *RegInfo;
23 unsigned NumBytesAllocated;
25 // Maps SSA Regs => offsets on the stack where these values are stored
26 std::map<unsigned, unsigned> VirtReg2OffsetMap;
28 // RegsUsed - Keep track of what registers are currently in use.
29 std::set<unsigned> RegsUsed;
31 // RegClassIdx - Maps RegClass => which index we can take a register
32 // from. Since this is a simple register allocator, when we need a register
33 // of a certain class, we just take the next available one.
34 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
38 RegAllocSimple(TargetMachine &tm)
39 : TM(tm), RegInfo(tm.getRegisterInfo()) {
40 RegsUsed.insert(RegInfo->getFramePointer());
41 RegsUsed.insert(RegInfo->getStackPointer());
43 cleanupAfterFunction();
46 bool runOnFunction(Function &Fn) {
47 return runOnMachineFunction(MachineFunction::get(&Fn));
50 virtual const char *getPassName() const {
51 return "Simple Register Allocator";
55 /// runOnMachineFunction - Register allocate the whole function
56 bool runOnMachineFunction(MachineFunction &Fn);
58 /// AllocateBasicBlock - Register allocate the specified basic block.
59 void AllocateBasicBlock(MachineBasicBlock &MBB);
61 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
62 /// in predecessor basic blocks.
63 void EliminatePHINodes(MachineBasicBlock &MBB);
66 /// getStackSpaceFor - This returns the offset of the specified virtual
67 /// register on the stack, allocating space if neccesary.
68 unsigned getStackSpaceFor(unsigned VirtReg,
69 const TargetRegisterClass *regClass);
71 /// Given a virtual register, return a compatible physical register that is
74 /// Side effect: marks that register as being used until manually cleared
76 unsigned getFreeReg(unsigned virtualReg);
78 /// Returns all `borrowed' registers back to the free pool
83 /// Invalidates any references, real or implicit, to physical registers
85 void invalidatePhysRegs(const MachineInstr *MI) {
86 unsigned Opcode = MI->getOpcode();
87 const MachineInstrDescriptor &Desc = TM.getInstrInfo().get(Opcode);
88 const unsigned *regs = Desc.ImplicitUses;
90 RegsUsed.insert(*regs++);
92 regs = Desc.ImplicitDefs;
94 RegsUsed.insert(*regs++);
97 void cleanupAfterFunction() {
98 VirtReg2OffsetMap.clear();
99 NumBytesAllocated = 4; // FIXME: This is X86 specific
102 /// Moves value from memory into that register
103 unsigned reloadVirtReg(MachineBasicBlock &MBB,
104 MachineBasicBlock::iterator &I, unsigned VirtReg);
106 /// Saves reg value on the stack (maps virtual register to stack value)
107 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
108 unsigned VirtReg, unsigned PhysReg);
113 /// getStackSpaceFor - This allocates space for the specified virtual
114 /// register to be held on the stack.
115 unsigned RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
116 const TargetRegisterClass *regClass) {
117 // Find the location VirtReg would belong...
118 std::map<unsigned, unsigned>::iterator I =
119 VirtReg2OffsetMap.lower_bound(VirtReg);
121 if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
122 return I->second; // Already has space allocated?
124 unsigned RegSize = regClass->getDataSize();
126 // Align NumBytesAllocated. We should be using TargetData alignment stuff
127 // to determine this, but we don't know the LLVM type associated with the
128 // virtual register. Instead, just align to a multiple of the size for now.
129 NumBytesAllocated += RegSize-1;
130 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
132 // Assign the slot...
133 VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
135 // Reserve the space!
136 NumBytesAllocated += RegSize;
137 return NumBytesAllocated-RegSize;
140 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
141 const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
143 unsigned regIdx = RegClassIdx[regClass]++;
144 assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
145 unsigned physReg = regClass->getRegister(regIdx);
147 if (RegsUsed.find(physReg) == RegsUsed.end())
150 return getFreeReg(virtualReg);
153 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
154 MachineBasicBlock::iterator &I,
156 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
157 unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
158 unsigned PhysReg = getFreeReg(VirtReg);
160 // Add move instruction(s)
162 I = RegInfo->loadRegOffset2Reg(MBB, I, PhysReg, RegInfo->getFramePointer(),
163 -stackOffset, regClass->getDataSize());
167 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
168 MachineBasicBlock::iterator &I,
169 unsigned VirtReg, unsigned PhysReg)
171 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
172 unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
174 // Add move instruction(s)
176 I = RegInfo->storeReg2RegOffset(MBB, I, PhysReg, RegInfo->getFramePointer(),
177 -stackOffset, regClass->getDataSize());
181 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
182 /// predecessor basic blocks.
184 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
185 const MachineInstrInfo &MII = TM.getInstrInfo();
187 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
188 MachineInstr *MI = MBB.front();
189 // Unlink the PHI node from the basic block... but don't delete the PHI yet
190 MBB.erase(MBB.begin());
192 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
193 assert(MI->getOperand(0).isVirtualRegister() &&
194 "PHI node doesn't write virt reg?");
196 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
198 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
199 MachineOperand &opVal = MI->getOperand(i-1);
201 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
202 // source path the phi
203 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
205 // Check to make sure we haven't already emitted the copy for this block.
206 // This can happen because PHI nodes may have multiple entries for the
207 // same basic block. It doesn't matter which entry we use though, because
208 // all incoming values are guaranteed to be the same for a particular bb.
210 // Note that this is N^2 in the number of phi node entries, but since the
211 // # of entries is tiny, this is not a problem.
213 bool HaveNotEmitted = true;
214 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
215 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
216 HaveNotEmitted = false;
220 if (HaveNotEmitted) {
221 MachineBasicBlock::iterator opI = opBlock.end();
222 MachineInstr *opMI = *--opI;
224 // must backtrack over ALL the branches in the previous block
225 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
228 // move back to the first branch instruction so new instructions
229 // are inserted right in front of it and not in front of a non-branch
230 if (!MII.isBranch(opMI->getOpcode()))
233 unsigned dataSize = MF->getRegClass(virtualReg)->getDataSize();
235 // Retrieve the constant value from this op, move it to target
236 // register of the phi
237 if (opVal.isImmediate()) {
238 opI = RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
239 (unsigned) opVal.getImmedValue(),
242 opI = RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
243 opVal.getAllocatedRegNum(), dataSize);
248 // really delete the PHI instruction now!
254 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
255 // loop over each instruction
256 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
257 // Made to combat the incorrect allocation of r2 = add r1, r1
258 std::map<unsigned, unsigned> Virt2PhysRegMap;
260 MachineInstr *MI = *I;
262 // a preliminary pass that will invalidate any registers that
263 // are used by the instruction (including implicit uses)
264 invalidatePhysRegs(MI);
266 // Loop over uses, move from memory into registers
267 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
268 MachineOperand &op = MI->getOperand(i);
270 if (op.isVirtualRegister()) {
271 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
272 DEBUG(std::cerr << "op: " << op << "\n");
273 DEBUG(std::cerr << "\t inst[" << i << "]: ";
274 MI->print(std::cerr, TM));
276 // make sure the same virtual register maps to the same physical
277 // register in any given instruction
278 unsigned physReg = Virt2PhysRegMap[virtualReg];
281 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
282 // must be same register number as the first operand
283 // This maps a = b + c into b += c, and saves b into a's spot
284 assert(MI->getOperand(1).isRegister() &&
285 MI->getOperand(1).getAllocatedRegNum() &&
286 MI->getOperand(1).opIsUse() &&
287 "Two address instruction invalid!");
289 physReg = MI->getOperand(1).getAllocatedRegNum();
291 physReg = getFreeReg(virtualReg);
294 spillVirtReg(MBB, I, virtualReg, physReg);
297 physReg = reloadVirtReg(MBB, I, virtualReg);
298 Virt2PhysRegMap[virtualReg] = physReg;
301 MI->SetMachineOperandReg(i, physReg);
302 DEBUG(std::cerr << "virt: " << virtualReg <<
303 ", phys: " << op.getAllocatedRegNum() << "\n");
310 /// runOnMachineFunction - Register allocate the whole function
312 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
313 DEBUG(std::cerr << "Machine Function " << "\n");
316 // First pass: eliminate PHI instructions by inserting copies into predecessor
318 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
320 EliminatePHINodes(*MBB);
322 // Loop over all of the basic blocks, eliminating virtual register references
323 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
325 AllocateBasicBlock(*MBB);
327 // Round stack allocation up to a nice alignment to keep the stack aligned
328 // FIXME: This is X86 specific! Move to frame manager
329 NumBytesAllocated = (NumBytesAllocated + 3) & ~3;
331 // Add prologue to the function...
332 RegInfo->emitPrologue(Fn, NumBytesAllocated);
334 const MachineInstrInfo &MII = TM.getInstrInfo();
336 // Add epilogue to restore the callee-save registers in each exiting block
337 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
338 MBB != MBBe; ++MBB) {
339 // If last instruction is a return instruction, add an epilogue
340 if (MII.isReturn(MBB->back()->getOpcode()))
341 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
344 cleanupAfterFunction();
348 Pass *createSimpleRegisterAllocator(TargetMachine &TM) {
349 return new RegAllocSimple(TM);