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/CodeGen/SSARegMap.h"
10 #include "llvm/Target/MachineInstrInfo.h"
11 #include "llvm/Target/TargetMachine.h"
12 #include "Support/Statistic.h"
17 Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
18 Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
20 class RegAllocSimple : public FunctionPass {
23 const MRegisterInfo *RegInfo;
24 unsigned NumBytesAllocated;
26 // Maps SSA Regs => offsets on the stack where these values are stored
27 std::map<unsigned, unsigned> VirtReg2OffsetMap;
29 // RegsUsed - Keep track of what registers are currently in use.
30 std::set<unsigned> RegsUsed;
32 // RegClassIdx - Maps RegClass => which index we can take a register
33 // from. Since this is a simple register allocator, when we need a register
34 // of a certain class, we just take the next available one.
35 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
39 RegAllocSimple(TargetMachine &tm)
40 : TM(tm), RegInfo(tm.getRegisterInfo()) {
41 RegsUsed.insert(RegInfo->getFramePointer());
42 RegsUsed.insert(RegInfo->getStackPointer());
44 cleanupAfterFunction();
47 bool runOnFunction(Function &Fn) {
48 return runOnMachineFunction(MachineFunction::get(&Fn));
51 virtual const char *getPassName() const {
52 return "Simple Register Allocator";
56 /// runOnMachineFunction - Register allocate the whole function
57 bool runOnMachineFunction(MachineFunction &Fn);
59 /// AllocateBasicBlock - Register allocate the specified basic block.
60 void AllocateBasicBlock(MachineBasicBlock &MBB);
62 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
63 /// in predecessor basic blocks.
64 void EliminatePHINodes(MachineBasicBlock &MBB);
66 /// EmitPrologue/EmitEpilogue - Use the register info object to add a
67 /// prologue/epilogue to the function and save/restore any callee saved
68 /// registers we are responsible for.
71 void EmitEpilogue(MachineBasicBlock &MBB);
74 /// getStackSpaceFor - This returns the offset of the specified virtual
75 /// register on the stack, allocating space if neccesary.
76 unsigned getStackSpaceFor(unsigned VirtReg,
77 const TargetRegisterClass *regClass);
79 /// Given a virtual register, return a compatible physical register that is
82 /// Side effect: marks that register as being used until manually cleared
84 unsigned getFreeReg(unsigned virtualReg);
86 /// Returns all `borrowed' registers back to the free pool
91 /// Invalidates any references, real or implicit, to physical registers
93 void invalidatePhysRegs(const MachineInstr *MI) {
94 unsigned Opcode = MI->getOpcode();
95 const MachineInstrDescriptor &Desc = TM.getInstrInfo().get(Opcode);
96 if (const unsigned *regs = Desc.ImplicitUses)
98 RegsUsed.insert(*regs++);
100 if (const unsigned *regs = Desc.ImplicitDefs)
102 RegsUsed.insert(*regs++);
105 void cleanupAfterFunction() {
106 VirtReg2OffsetMap.clear();
107 NumBytesAllocated = 4; // FIXME: This is X86 specific
110 /// Moves value from memory into that register
111 unsigned reloadVirtReg(MachineBasicBlock &MBB,
112 MachineBasicBlock::iterator &I, unsigned VirtReg);
114 /// Saves reg value on the stack (maps virtual register to stack value)
115 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
116 unsigned VirtReg, unsigned PhysReg);
121 /// getStackSpaceFor - This allocates space for the specified virtual
122 /// register to be held on the stack.
123 unsigned RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
124 const TargetRegisterClass *regClass) {
125 // Find the location VirtReg would belong...
126 std::map<unsigned, unsigned>::iterator I =
127 VirtReg2OffsetMap.lower_bound(VirtReg);
129 if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
130 return I->second; // Already has space allocated?
132 unsigned RegSize = regClass->getDataSize();
134 // Align NumBytesAllocated. We should be using TargetData alignment stuff
135 // to determine this, but we don't know the LLVM type associated with the
136 // virtual register. Instead, just align to a multiple of the size for now.
137 NumBytesAllocated += RegSize-1;
138 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
140 // Assign the slot...
141 VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
143 // Reserve the space!
144 NumBytesAllocated += RegSize;
145 return NumBytesAllocated-RegSize;
148 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
149 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
151 unsigned regIdx = RegClassIdx[RC]++;
152 assert(regIdx < RC->getNumRegs() && "Not enough registers!");
153 unsigned physReg = RC->getRegister(regIdx);
155 if (RegsUsed.find(physReg) == RegsUsed.end())
158 return getFreeReg(virtualReg);
161 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
162 MachineBasicBlock::iterator &I,
164 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
165 unsigned stackOffset = getStackSpaceFor(VirtReg, RC);
166 unsigned PhysReg = getFreeReg(VirtReg);
168 // Add move instruction(s)
170 RegInfo->loadRegOffset2Reg(MBB, I, PhysReg, RegInfo->getFramePointer(),
175 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
176 MachineBasicBlock::iterator &I,
177 unsigned VirtReg, unsigned PhysReg)
179 const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
180 unsigned stackOffset = getStackSpaceFor(VirtReg, RC);
182 // Add move instruction(s)
184 RegInfo->storeReg2RegOffset(MBB, I, PhysReg, RegInfo->getFramePointer(),
189 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
190 /// predecessor basic blocks.
192 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
193 const MachineInstrInfo &MII = TM.getInstrInfo();
195 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
196 MachineInstr *MI = MBB.front();
197 // Unlink the PHI node from the basic block... but don't delete the PHI yet
198 MBB.erase(MBB.begin());
200 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
201 assert(MI->getOperand(0).isVirtualRegister() &&
202 "PHI node doesn't write virt reg?");
204 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
206 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
207 MachineOperand &opVal = MI->getOperand(i-1);
209 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
210 // source path the phi
211 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
213 // Check to make sure we haven't already emitted the copy for this block.
214 // This can happen because PHI nodes may have multiple entries for the
215 // same basic block. It doesn't matter which entry we use though, because
216 // all incoming values are guaranteed to be the same for a particular bb.
218 // Note that this is N^2 in the number of phi node entries, but since the
219 // # of entries is tiny, this is not a problem.
221 bool HaveNotEmitted = true;
222 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
223 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
224 HaveNotEmitted = false;
228 if (HaveNotEmitted) {
229 MachineBasicBlock::iterator opI = opBlock.end();
230 MachineInstr *opMI = *--opI;
232 // must backtrack over ALL the branches in the previous block
233 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
236 // move back to the first branch instruction so new instructions
237 // are inserted right in front of it and not in front of a non-branch
239 if (!MII.isBranch(opMI->getOpcode()))
242 const TargetRegisterClass *RC =
243 MF->getSSARegMap()->getRegClass(virtualReg);
245 // Retrieve the constant value from this op, move it to target
246 // register of the phi
247 if (opVal.isImmediate()) {
248 RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
249 (unsigned) opVal.getImmedValue(), RC);
251 RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
252 opVal.getAllocatedRegNum(), RC);
257 // really delete the PHI instruction now!
263 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
264 // loop over each instruction
265 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
266 // Made to combat the incorrect allocation of r2 = add r1, r1
267 std::map<unsigned, unsigned> Virt2PhysRegMap;
269 MachineInstr *MI = *I;
271 // a preliminary pass that will invalidate any registers that
272 // are used by the instruction (including implicit uses)
273 invalidatePhysRegs(MI);
275 // Loop over uses, move from memory into registers
276 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
277 MachineOperand &op = MI->getOperand(i);
279 if (op.isVirtualRegister()) {
280 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
281 DEBUG(std::cerr << "op: " << op << "\n");
282 DEBUG(std::cerr << "\t inst[" << i << "]: ";
283 MI->print(std::cerr, TM));
285 // make sure the same virtual register maps to the same physical
286 // register in any given instruction
287 unsigned physReg = Virt2PhysRegMap[virtualReg];
290 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
291 // must be same register number as the first operand
292 // This maps a = b + c into b += c, and saves b into a's spot
293 assert(MI->getOperand(1).isRegister() &&
294 MI->getOperand(1).getAllocatedRegNum() &&
295 MI->getOperand(1).opIsUse() &&
296 "Two address instruction invalid!");
298 physReg = MI->getOperand(1).getAllocatedRegNum();
300 physReg = getFreeReg(virtualReg);
303 spillVirtReg(MBB, I, virtualReg, physReg);
306 physReg = reloadVirtReg(MBB, I, virtualReg);
307 Virt2PhysRegMap[virtualReg] = physReg;
310 MI->SetMachineOperandReg(i, physReg);
311 DEBUG(std::cerr << "virt: " << virtualReg <<
312 ", phys: " << op.getAllocatedRegNum() << "\n");
320 /// EmitPrologue - Use the register info object to add a prologue to the
321 /// function and save any callee saved registers we are responsible for.
323 void RegAllocSimple::EmitPrologue() {
324 // Get a list of the callee saved registers, so that we can save them on entry
327 MachineBasicBlock &MBB = MF->front(); // Prolog goes in entry BB
328 MachineBasicBlock::iterator I = MBB.begin();
330 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
331 for (unsigned i = 0; CSRegs[i]; ++i) {
332 const TargetRegisterClass *RegClass = RegInfo->getRegClass(CSRegs[i]);
333 unsigned Offset = getStackSpaceFor(CSRegs[i], RegClass);
335 // Insert the spill to the stack frame...
336 RegInfo->storeReg2RegOffset(MBB, I,CSRegs[i],RegInfo->getFramePointer(),
341 // Add prologue to the function...
342 RegInfo->emitPrologue(*MF, NumBytesAllocated);
346 /// EmitEpilogue - Use the register info object to add a epilogue to the
347 /// function and restore any callee saved registers we are responsible for.
349 void RegAllocSimple::EmitEpilogue(MachineBasicBlock &MBB) {
350 // Insert instructions before the return.
351 MachineBasicBlock::iterator I = MBB.end()-1;
353 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
354 for (unsigned i = 0; CSRegs[i]; ++i) {
355 const TargetRegisterClass *RegClass = RegInfo->getRegClass(CSRegs[i]);
356 unsigned Offset = getStackSpaceFor(CSRegs[i], RegClass);
358 RegInfo->loadRegOffset2Reg(MBB, I, CSRegs[i],RegInfo->getFramePointer(),
360 --I; // Insert in reverse order
364 RegInfo->emitEpilogue(MBB, NumBytesAllocated);
368 /// runOnMachineFunction - Register allocate the whole function
370 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
371 DEBUG(std::cerr << "Machine Function " << "\n");
374 // First pass: eliminate PHI instructions by inserting copies into predecessor
376 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
378 EliminatePHINodes(*MBB);
380 // Loop over all of the basic blocks, eliminating virtual register references
381 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
383 AllocateBasicBlock(*MBB);
385 // Round stack allocation up to a nice alignment to keep the stack aligned
386 // FIXME: This is X86 specific! Move to frame manager
387 NumBytesAllocated = (NumBytesAllocated + 3) & ~3;
389 // Emit a prologue for the function...
392 const MachineInstrInfo &MII = TM.getInstrInfo();
394 // Add epilogue to restore the callee-save registers in each exiting block
395 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
396 MBB != MBBe; ++MBB) {
397 // If last instruction is a return instruction, add an epilogue
398 if (MII.isReturn(MBB->back()->getOpcode()))
402 cleanupAfterFunction();
406 Pass *createSimpleRegisterAllocator(TargetMachine &TM) {
407 return new RegAllocSimple(TM);