Rename FunctionFrameInfo to MachineFrameInfo
[oota-llvm.git] / lib / CodeGen / RegAllocSimple.cpp
1 //===-- RegAllocSimple.cpp - A simple generic register allocator ----------===//
2 //
3 // This file implements a simple register allocator. *Very* simple: It immediate
4 // spills every value right after it is computed, and it reloads all used
5 // operands from the spill area to temporary registers before each instruction.
6 // It does not keep values in registers across instructions.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/MachineFunctionPass.h"
11 #include "llvm/CodeGen/MachineInstr.h"
12 #include "llvm/CodeGen/SSARegMap.h"
13 #include "llvm/CodeGen/MachineFrameInfo.h"
14 #include "llvm/Target/MachineInstrInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "Support/Statistic.h"
17 #include <iostream>
18
19 namespace {
20   Statistic<> NumSpilled ("ra-simple", "Number of registers spilled");
21   Statistic<> NumReloaded("ra-simple", "Number of registers reloaded");
22
23   class RegAllocSimple : public MachineFunctionPass {
24     MachineFunction *MF;
25     const TargetMachine *TM;
26     const MRegisterInfo *RegInfo;
27     
28     // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
29     // these values are spilled
30     std::map<unsigned, int> StackSlotForVirtReg;
31
32     // RegsUsed - Keep track of what registers are currently in use.  This is a
33     // bitset.
34     std::vector<bool> RegsUsed;
35
36     // RegClassIdx - Maps RegClass => which index we can take a register
37     // from. Since this is a simple register allocator, when we need a register
38     // of a certain class, we just take the next available one.
39     std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
40
41   public:
42     virtual const char *getPassName() const {
43       return "Simple Register Allocator";
44     }
45
46     /// runOnMachineFunction - Register allocate the whole function
47     bool runOnMachineFunction(MachineFunction &Fn);
48
49   private:
50     /// AllocateBasicBlock - Register allocate the specified basic block.
51     void AllocateBasicBlock(MachineBasicBlock &MBB);
52
53     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
54     /// in predecessor basic blocks.
55     void EliminatePHINodes(MachineBasicBlock &MBB);
56
57     /// getStackSpaceFor - This returns the offset of the specified virtual
58     /// register on the stack, allocating space if neccesary.
59     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
60
61     /// Given a virtual register, return a compatible physical register that is
62     /// currently unused.
63     ///
64     /// Side effect: marks that register as being used until manually cleared
65     ///
66     unsigned getFreeReg(unsigned virtualReg);
67
68     /// Moves value from memory into that register
69     unsigned reloadVirtReg(MachineBasicBlock &MBB,
70                            MachineBasicBlock::iterator &I, unsigned VirtReg);
71
72     /// Saves reg value on the stack (maps virtual register to stack value)
73     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
74                       unsigned VirtReg, unsigned PhysReg);
75   };
76
77 }
78
79 /// getStackSpaceFor - This allocates space for the specified virtual
80 /// register to be held on the stack.
81 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
82                                      const TargetRegisterClass *RC) {
83   // Find the location VirtReg would belong...
84   std::map<unsigned, int>::iterator I =
85     StackSlotForVirtReg.lower_bound(VirtReg);
86
87   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
88     return I->second;          // Already has space allocated?
89
90   // Allocate a new stack object for this spill location...
91   int FrameIdx =
92     MF->getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment());
93   
94   // Assign the slot...
95   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
96
97   return FrameIdx;
98 }
99
100 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
101   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
102   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
103   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
104
105   while (1) {
106     unsigned regIdx = RegClassIdx[RC]++; 
107     assert(RI+regIdx != RE && "Not enough registers!");
108     unsigned PhysReg = *(RI+regIdx);
109     
110     if (!RegsUsed[PhysReg])
111       return PhysReg;
112   }
113 }
114
115 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
116                                        MachineBasicBlock::iterator &I,
117                                        unsigned VirtReg) {
118   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
119   int FrameIdx = getStackSpaceFor(VirtReg, RC);
120   unsigned PhysReg = getFreeReg(VirtReg);
121
122   // Add move instruction(s)
123   ++NumReloaded;
124   RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
125   return PhysReg;
126 }
127
128 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
129                                   MachineBasicBlock::iterator &I,
130                                   unsigned VirtReg, unsigned PhysReg) {
131   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
132   int FrameIdx = getStackSpaceFor(VirtReg, RC);
133
134   // Add move instruction(s)
135   ++NumSpilled;
136   RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIdx, RC);
137 }
138
139
140 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
141 /// predecessor basic blocks.
142 ///
143 void RegAllocSimple::EliminatePHINodes(MachineBasicBlock &MBB) {
144   const MachineInstrInfo &MII = TM->getInstrInfo();
145
146   while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
147     MachineInstr *MI = MBB.front();
148     // Unlink the PHI node from the basic block... but don't delete the PHI yet
149     MBB.erase(MBB.begin());
150     
151     DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
152     assert(MI->getOperand(0).isVirtualRegister() &&
153            "PHI node doesn't write virt reg?");
154
155     unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
156     
157     for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
158       MachineOperand &opVal = MI->getOperand(i-1);
159       
160       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
161       // source path the phi
162       MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
163
164       // Check to make sure we haven't already emitted the copy for this block.
165       // This can happen because PHI nodes may have multiple entries for the
166       // same basic block.  It doesn't matter which entry we use though, because
167       // all incoming values are guaranteed to be the same for a particular bb.
168       //
169       // Note that this is N^2 in the number of phi node entries, but since the
170       // # of entries is tiny, this is not a problem.
171       //
172       bool HaveNotEmitted = true;
173       for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
174         if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
175           HaveNotEmitted = false;
176           break;
177         }
178
179       if (HaveNotEmitted) {
180         MachineBasicBlock::iterator opI = opBlock.end();
181         MachineInstr *opMI = *--opI;
182         
183         // must backtrack over ALL the branches in the previous block
184         while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
185           opMI = *--opI;
186         
187         // move back to the first branch instruction so new instructions
188         // are inserted right in front of it and not in front of a non-branch
189         //
190         if (!MII.isBranch(opMI->getOpcode()))
191           ++opI;
192
193         const TargetRegisterClass *RC =
194           MF->getSSARegMap()->getRegClass(virtualReg);
195
196         assert(opVal.isVirtualRegister() &&
197                "Machine PHI Operands must all be virtual registers!");
198         RegInfo->copyRegToReg(opBlock, opI, virtualReg, opVal.getReg(), RC);
199       }
200     }
201     
202     // really delete the PHI instruction now!
203     delete MI;
204   }
205 }
206
207
208 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
209   // loop over each instruction
210   for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
211     // Made to combat the incorrect allocation of r2 = add r1, r1
212     std::map<unsigned, unsigned> Virt2PhysRegMap;
213
214     MachineInstr *MI = *I;
215
216     RegsUsed.resize(MRegisterInfo::FirstVirtualRegister);
217     
218     // a preliminary pass that will invalidate any registers that
219     // are used by the instruction (including implicit uses)
220     unsigned Opcode = MI->getOpcode();
221     const MachineInstrDescriptor &Desc = TM->getInstrInfo().get(Opcode);
222     if (const unsigned *Regs = Desc.ImplicitUses)
223       while (*Regs)
224         RegsUsed[*Regs++] = true;
225     
226     if (const unsigned *Regs = Desc.ImplicitDefs)
227       while (*Regs)
228         RegsUsed[*Regs++] = true;
229     
230     // Loop over uses, move from memory into registers
231     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
232       MachineOperand &op = MI->getOperand(i);
233       
234       if (op.isVirtualRegister()) {
235         unsigned virtualReg = (unsigned) op.getAllocatedRegNum();
236         DEBUG(std::cerr << "op: " << op << "\n");
237         DEBUG(std::cerr << "\t inst[" << i << "]: ";
238               MI->print(std::cerr, *TM));
239         
240         // make sure the same virtual register maps to the same physical
241         // register in any given instruction
242         unsigned physReg = Virt2PhysRegMap[virtualReg];
243         if (physReg == 0) {
244           if (op.opIsDef()) {
245             if (TM->getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
246               // must be same register number as the first operand
247               // This maps a = b + c into b += c, and saves b into a's spot
248               assert(MI->getOperand(1).isRegister()  &&
249                      MI->getOperand(1).getAllocatedRegNum() &&
250                      MI->getOperand(1).opIsUse() &&
251                      "Two address instruction invalid!");
252
253               physReg = MI->getOperand(1).getAllocatedRegNum();
254             } else {
255               physReg = getFreeReg(virtualReg);
256             }
257             ++I;
258             spillVirtReg(MBB, I, virtualReg, physReg);
259             --I;
260           } else {
261             physReg = reloadVirtReg(MBB, I, virtualReg);
262             Virt2PhysRegMap[virtualReg] = physReg;
263           }
264         }
265         MI->SetMachineOperandReg(i, physReg);
266         DEBUG(std::cerr << "virt: " << virtualReg << 
267               ", phys: " << op.getAllocatedRegNum() << "\n");
268       }
269     }
270     RegClassIdx.clear();
271     RegsUsed.clear();
272   }
273 }
274
275
276 /// runOnMachineFunction - Register allocate the whole function
277 ///
278 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
279   DEBUG(std::cerr << "Machine Function " << "\n");
280   MF = &Fn;
281   TM = &MF->getTarget();
282   RegInfo = TM->getRegisterInfo();
283
284   // First pass: eliminate PHI instructions by inserting copies into predecessor
285   // blocks.
286   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
287        MBB != MBBe; ++MBB)
288     EliminatePHINodes(*MBB);
289
290   // Loop over all of the basic blocks, eliminating virtual register references
291   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
292        MBB != MBBe; ++MBB)
293     AllocateBasicBlock(*MBB);
294
295   StackSlotForVirtReg.clear();
296   return true;
297 }
298
299 Pass *createSimpleRegisterAllocator() {
300   return new RegAllocSimple();
301 }