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 /// PhysRegClassMap - Construct a mapping of physical register numbers to their
19 /// NOTE: This class will eventually be pulled out to somewhere shared.
21 class PhysRegClassMap {
22 std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
24 PhysRegClassMap(const MRegisterInfo *RI) {
25 for (MRegisterInfo::const_iterator I = RI->regclass_begin(),
26 E = RI->regclass_end(); I != E; ++I)
27 for (unsigned i=0; i < (*I)->getNumRegs(); ++i)
28 PhysReg2RegClassMap[(*I)->getRegister(i)] = *I;
31 const TargetRegisterClass *operator[](unsigned Reg) {
32 assert(PhysReg2RegClassMap[Reg] && "Register is not a known physreg!");
33 return PhysReg2RegClassMap[Reg];
36 const TargetRegisterClass *get(unsigned Reg) { return operator[](Reg); }
42 Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
43 Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
45 class RegAllocSimple : public FunctionPass {
48 const MRegisterInfo *RegInfo;
49 unsigned NumBytesAllocated;
51 // Maps SSA Regs => offsets on the stack where these values are stored
52 std::map<unsigned, unsigned> VirtReg2OffsetMap;
54 // RegsUsed - Keep track of what registers are currently in use.
55 std::set<unsigned> RegsUsed;
57 // RegClassIdx - Maps RegClass => which index we can take a register
58 // from. Since this is a simple register allocator, when we need a register
59 // of a certain class, we just take the next available one.
60 std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
64 RegAllocSimple(TargetMachine &tm)
65 : TM(tm), RegInfo(tm.getRegisterInfo()) {
66 RegsUsed.insert(RegInfo->getFramePointer());
67 RegsUsed.insert(RegInfo->getStackPointer());
69 cleanupAfterFunction();
72 bool runOnFunction(Function &Fn) {
73 return runOnMachineFunction(MachineFunction::get(&Fn));
76 virtual const char *getPassName() const {
77 return "Simple Register Allocator";
81 /// runOnMachineFunction - Register allocate the whole function
82 bool runOnMachineFunction(MachineFunction &Fn);
84 /// AllocateBasicBlock - Register allocate the specified basic block.
85 void AllocateBasicBlock(MachineBasicBlock &MBB);
87 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
88 /// in predecessor basic blocks.
89 void EliminatePHINodes(MachineBasicBlock &MBB);
92 /// getStackSpaceFor - This returns the offset of the specified virtual
93 /// register on the stack, allocating space if neccesary.
94 unsigned getStackSpaceFor(unsigned VirtReg,
95 const TargetRegisterClass *regClass);
97 /// Given a virtual register, return a compatible physical register that is
100 /// Side effect: marks that register as being used until manually cleared
102 unsigned getFreeReg(unsigned virtualReg);
104 /// Returns all `borrowed' registers back to the free pool
105 void clearAllRegs() {
109 /// Invalidates any references, real or implicit, to physical registers
111 void invalidatePhysRegs(const MachineInstr *MI) {
112 unsigned Opcode = MI->getOpcode();
113 const MachineInstrDescriptor &Desc = TM.getInstrInfo().get(Opcode);
114 const unsigned *regs = Desc.ImplicitUses;
116 RegsUsed.insert(*regs++);
118 regs = Desc.ImplicitDefs;
120 RegsUsed.insert(*regs++);
123 void cleanupAfterFunction() {
124 VirtReg2OffsetMap.clear();
125 NumBytesAllocated = 4; // FIXME: This is X86 specific
128 /// Moves value from memory into that register
129 MachineBasicBlock::iterator
130 moveUseToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
131 unsigned VirtReg, unsigned &PhysReg);
133 /// Saves reg value on the stack (maps virtual register to stack value)
134 MachineBasicBlock::iterator
135 saveVirtRegToStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
136 unsigned VirtReg, unsigned PhysReg);
141 /// getStackSpaceFor - This allocates space for the specified virtual
142 /// register to be held on the stack.
143 unsigned RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
144 const TargetRegisterClass *regClass) {
145 // Find the location VirtReg would belong...
146 std::map<unsigned, unsigned>::iterator I =
147 VirtReg2OffsetMap.lower_bound(VirtReg);
149 if (I != VirtReg2OffsetMap.end() && I->first == VirtReg)
150 return I->second; // Already has space allocated?
152 unsigned RegSize = regClass->getDataSize();
154 // Align NumBytesAllocated. We should be using TargetData alignment stuff
155 // to determine this, but we don't know the LLVM type associated with the
156 // virtual register. Instead, just align to a multiple of the size for now.
157 NumBytesAllocated += RegSize-1;
158 NumBytesAllocated = NumBytesAllocated/RegSize*RegSize;
160 // Assign the slot...
161 VirtReg2OffsetMap.insert(I, std::make_pair(VirtReg, NumBytesAllocated));
163 // Reserve the space!
164 NumBytesAllocated += RegSize;
165 return NumBytesAllocated-RegSize;
168 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
169 const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
171 unsigned regIdx = RegClassIdx[regClass]++;
172 assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
173 unsigned physReg = regClass->getRegister(regIdx);
175 if (RegsUsed.find(physReg) == RegsUsed.end())
178 return getFreeReg(virtualReg);
181 MachineBasicBlock::iterator
182 RegAllocSimple::moveUseToReg (MachineBasicBlock &MBB,
183 MachineBasicBlock::iterator I,
184 unsigned VirtReg, unsigned &PhysReg)
186 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
187 unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
188 PhysReg = getFreeReg(VirtReg);
190 // Add move instruction(s)
192 return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
193 RegInfo->getFramePointer(),
194 -stackOffset, regClass->getDataSize());
197 MachineBasicBlock::iterator
198 RegAllocSimple::saveVirtRegToStack (MachineBasicBlock &MBB,
199 MachineBasicBlock::iterator I,
200 unsigned VirtReg, unsigned PhysReg)
202 const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
203 unsigned stackOffset = getStackSpaceFor(VirtReg, regClass);
205 // Add move instruction(s)
207 return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
208 RegInfo->getFramePointer(),
209 -stackOffset, regClass->getDataSize());
213 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
214 /// predecessor basic blocks.
216 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
217 const MachineInstrInfo &MII = TM.getInstrInfo();
219 while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
220 MachineInstr *MI = MBB.front();
221 // Unlink the PHI node from the basic block... but don't delete the PHI yet
222 MBB.erase(MBB.begin());
224 DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
225 assert(MI->getOperand(0).isVirtualRegister() &&
226 "PHI node doesn't write virt reg?");
228 unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
230 for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
231 MachineOperand &opVal = MI->getOperand(i-1);
233 // Get the MachineBasicBlock equivalent of the BasicBlock that is the
234 // source path the phi
235 MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
237 // Check to make sure we haven't already emitted the copy for this block.
238 // This can happen because PHI nodes may have multiple entries for the
239 // same basic block. It doesn't matter which entry we use though, because
240 // all incoming values are guaranteed to be the same for a particular bb.
242 // Note that this is N^2 in the number of phi node entries, but since the
243 // # of entries is tiny, this is not a problem.
245 bool HaveNotEmitted = true;
246 for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
247 if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
248 HaveNotEmitted = false;
252 if (HaveNotEmitted) {
253 MachineBasicBlock::iterator opI = opBlock.end();
254 MachineInstr *opMI = *--opI;
256 // must backtrack over ALL the branches in the previous block
257 while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
260 // move back to the first branch instruction so new instructions
261 // are inserted right in front of it and not in front of a non-branch
262 if (!MII.isBranch(opMI->getOpcode()))
265 unsigned dataSize = MF->getRegClass(virtualReg)->getDataSize();
267 // Retrieve the constant value from this op, move it to target
268 // register of the phi
269 if (opVal.isImmediate()) {
270 opI = RegInfo->moveImm2Reg(opBlock, opI, virtualReg,
271 (unsigned) opVal.getImmedValue(),
274 opI = RegInfo->moveReg2Reg(opBlock, opI, virtualReg,
275 opVal.getAllocatedRegNum(), dataSize);
280 // really delete the PHI instruction now!
286 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
287 // loop over each instruction
288 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
289 // Made to combat the incorrect allocation of r2 = add r1, r1
290 std::map<unsigned, unsigned> Virt2PhysRegMap;
292 MachineInstr *MI = *I;
294 // a preliminary pass that will invalidate any registers that
295 // are used by the instruction (including implicit uses)
296 invalidatePhysRegs(MI);
298 // Loop over uses, move from memory into registers
299 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
300 MachineOperand &op = MI->getOperand(i);
302 if (op.isVirtualRegister()) {
303 unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
304 DEBUG(std::cerr << "op: " << op << "\n");
305 DEBUG(std::cerr << "\t inst[" << i << "]: ";
306 MI->print(std::cerr, TM));
308 // make sure the same virtual register maps to the same physical
309 // register in any given instruction
310 unsigned physReg = Virt2PhysRegMap[virtualReg];
313 if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
314 // must be same register number as the first operand
315 // This maps a = b + c into b += c, and saves b into a's spot
316 assert(MI->getOperand(1).isRegister() &&
317 MI->getOperand(1).getAllocatedRegNum() &&
318 MI->getOperand(1).opIsUse() &&
319 "Two address instruction invalid!");
321 physReg = MI->getOperand(1).getAllocatedRegNum();
323 physReg = getFreeReg(virtualReg);
325 I = --saveVirtRegToStack(MBB, ++I, virtualReg, physReg);
327 I = moveUseToReg(MBB, I, virtualReg, physReg);
329 Virt2PhysRegMap[virtualReg] = physReg;
331 MI->SetMachineOperandReg(i, physReg);
332 DEBUG(std::cerr << "virt: " << virtualReg <<
333 ", phys: " << op.getAllocatedRegNum() << "\n");
340 /// runOnMachineFunction - Register allocate the whole function
342 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
343 DEBUG(std::cerr << "Machine Function " << "\n");
346 // First pass: eliminate PHI instructions by inserting copies into predecessor
348 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
350 EliminatePHINodes(*MBB);
352 // Loop over all of the basic blocks, eliminating virtual register references
353 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
355 AllocateBasicBlock(*MBB);
357 // Add prologue to the function...
358 RegInfo->emitPrologue(Fn, NumBytesAllocated);
360 const MachineInstrInfo &MII = TM.getInstrInfo();
362 // Add epilogue to restore the callee-save registers in each exiting block
363 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
364 MBB != MBBe; ++MBB) {
365 // If last instruction is a return instruction, add an epilogue
366 if (MII.isReturn(MBB->back()->getOpcode()))
367 RegInfo->emitEpilogue(*MBB, NumBytesAllocated);
370 cleanupAfterFunction();
374 Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
375 return new RegAllocSimple(TM);