Shave another 27K off libllvmgcc.dylib with visibility hidden
[oota-llvm.git] / lib / CodeGen / RegAllocSimple.cpp
1 //===-- RegAllocSimple.cpp - A simple generic register allocator ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple register allocator. *Very* simple: It immediate
11 // spills every value right after it is computed, and it reloads all used
12 // operands from the spill area to temporary registers before each instruction.
13 // It does not keep values in registers across instructions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "regalloc"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Visibility.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include <iostream>
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumStores("ra-simple", "Number of stores added");
34   Statistic<> NumLoads ("ra-simple", "Number of loads added");
35
36   class VISIBILITY_HIDDEN RegAllocSimple : public MachineFunctionPass {
37     MachineFunction *MF;
38     const TargetMachine *TM;
39     const MRegisterInfo *RegInfo;
40     bool *PhysRegsEverUsed;
41
42     // StackSlotForVirtReg - Maps SSA Regs => frame index on the stack where
43     // these values are spilled
44     std::map<unsigned, int> StackSlotForVirtReg;
45
46     // RegsUsed - Keep track of what registers are currently in use.  This is a
47     // bitset.
48     std::vector<bool> RegsUsed;
49
50     // RegClassIdx - Maps RegClass => which index we can take a register
51     // from. Since this is a simple register allocator, when we need a register
52     // of a certain class, we just take the next available one.
53     std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
54
55   public:
56     virtual const char *getPassName() const {
57       return "Simple Register Allocator";
58     }
59
60     /// runOnMachineFunction - Register allocate the whole function
61     bool runOnMachineFunction(MachineFunction &Fn);
62
63     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64       AU.addRequiredID(PHIEliminationID);           // Eliminate PHI nodes
65       MachineFunctionPass::getAnalysisUsage(AU);
66     }
67   private:
68     /// AllocateBasicBlock - Register allocate the specified basic block.
69     void AllocateBasicBlock(MachineBasicBlock &MBB);
70
71     /// getStackSpaceFor - This returns the offset of the specified virtual
72     /// register on the stack, allocating space if necessary.
73     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
74
75     /// Given a virtual register, return a compatible physical register that is
76     /// currently unused.
77     ///
78     /// Side effect: marks that register as being used until manually cleared
79     ///
80     unsigned getFreeReg(unsigned virtualReg);
81
82     /// Moves value from memory into that register
83     unsigned reloadVirtReg(MachineBasicBlock &MBB,
84                            MachineBasicBlock::iterator I, unsigned VirtReg);
85
86     /// Saves reg value on the stack (maps virtual register to stack value)
87     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
88                       unsigned VirtReg, unsigned PhysReg);
89   };
90
91 }
92
93 /// getStackSpaceFor - This allocates space for the specified virtual
94 /// register to be held on the stack.
95 int RegAllocSimple::getStackSpaceFor(unsigned VirtReg,
96                                      const TargetRegisterClass *RC) {
97   // Find the location VirtReg would belong...
98   std::map<unsigned, int>::iterator I =
99     StackSlotForVirtReg.lower_bound(VirtReg);
100
101   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
102     return I->second;          // Already has space allocated?
103
104   // Allocate a new stack object for this spill location...
105   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
106                                                        RC->getAlignment());
107
108   // Assign the slot...
109   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
110
111   return FrameIdx;
112 }
113
114 unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
115   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(virtualReg);
116   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
117   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
118
119   while (1) {
120     unsigned regIdx = RegClassIdx[RC]++;
121     assert(RI+regIdx != RE && "Not enough registers!");
122     unsigned PhysReg = *(RI+regIdx);
123
124     if (!RegsUsed[PhysReg]) {
125       PhysRegsEverUsed[PhysReg] = true;
126       return PhysReg;
127     }
128   }
129 }
130
131 unsigned RegAllocSimple::reloadVirtReg(MachineBasicBlock &MBB,
132                                        MachineBasicBlock::iterator I,
133                                        unsigned VirtReg) {
134   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
135   int FrameIdx = getStackSpaceFor(VirtReg, RC);
136   unsigned PhysReg = getFreeReg(VirtReg);
137
138   // Add move instruction(s)
139   ++NumLoads;
140   RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIdx, RC);
141   return PhysReg;
142 }
143
144 void RegAllocSimple::spillVirtReg(MachineBasicBlock &MBB,
145                                   MachineBasicBlock::iterator I,
146                                   unsigned VirtReg, unsigned PhysReg) {
147   const TargetRegisterClass* RC = MF->getSSARegMap()->getRegClass(VirtReg);
148   int FrameIdx = getStackSpaceFor(VirtReg, RC);
149
150   // Add move instruction(s)
151   ++NumStores;
152   RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIdx, RC);
153 }
154
155
156 void RegAllocSimple::AllocateBasicBlock(MachineBasicBlock &MBB) {
157   // loop over each instruction
158   for (MachineBasicBlock::iterator MI = MBB.begin(); MI != MBB.end(); ++MI) {
159     // Made to combat the incorrect allocation of r2 = add r1, r1
160     std::map<unsigned, unsigned> Virt2PhysRegMap;
161
162     RegsUsed.resize(RegInfo->getNumRegs());
163
164     // This is a preliminary pass that will invalidate any registers that are
165     // used by the instruction (including implicit uses).
166     unsigned Opcode = MI->getOpcode();
167     const TargetInstrDescriptor &Desc = TM->getInstrInfo()->get(Opcode);
168     const unsigned *Regs;
169     for (Regs = Desc.ImplicitUses; *Regs; ++Regs)
170       RegsUsed[*Regs] = true;
171
172     for (Regs = Desc.ImplicitDefs; *Regs; ++Regs) {
173       RegsUsed[*Regs] = true;
174       PhysRegsEverUsed[*Regs] = true;
175     }
176
177     // Loop over uses, move from memory into registers.
178     for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
179       MachineOperand &op = MI->getOperand(i);
180
181       if (op.isRegister() && op.getReg() &&
182           MRegisterInfo::isVirtualRegister(op.getReg())) {
183         unsigned virtualReg = (unsigned) op.getReg();
184         DEBUG(std::cerr << "op: " << op << "\n");
185         DEBUG(std::cerr << "\t inst[" << i << "]: ";
186               MI->print(std::cerr, TM));
187
188         // make sure the same virtual register maps to the same physical
189         // register in any given instruction
190         unsigned physReg = Virt2PhysRegMap[virtualReg];
191         if (physReg == 0) {
192           if (op.isDef()) {
193             if (!TM->getInstrInfo()->isTwoAddrInstr(MI->getOpcode()) || i) {
194               physReg = getFreeReg(virtualReg);
195             } else {
196               // must be same register number as the first operand
197               // This maps a = b + c into b += c, and saves b into a's spot
198               assert(MI->getOperand(1).isRegister()  &&
199                      MI->getOperand(1).getReg() &&
200                      MI->getOperand(1).isUse() &&
201                      "Two address instruction invalid!");
202
203               physReg = MI->getOperand(1).getReg();
204               spillVirtReg(MBB, next(MI), virtualReg, physReg);
205               MI->getOperand(1).setDef();
206               MI->RemoveOperand(0);
207               break; // This is the last operand to process
208             }
209             spillVirtReg(MBB, next(MI), virtualReg, physReg);
210           } else {
211             physReg = reloadVirtReg(MBB, MI, virtualReg);
212             Virt2PhysRegMap[virtualReg] = physReg;
213           }
214         }
215         MI->getOperand(i).setReg(physReg);
216         DEBUG(std::cerr << "virt: " << virtualReg <<
217               ", phys: " << op.getReg() << "\n");
218       }
219     }
220     RegClassIdx.clear();
221     RegsUsed.clear();
222   }
223 }
224
225
226 /// runOnMachineFunction - Register allocate the whole function
227 ///
228 bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
229   DEBUG(std::cerr << "Machine Function " << "\n");
230   MF = &Fn;
231   TM = &MF->getTarget();
232   RegInfo = TM->getRegisterInfo();
233
234   PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
235   std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
236   Fn.setUsedPhysRegs(PhysRegsEverUsed);
237
238   // Loop over all of the basic blocks, eliminating virtual register references
239   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
240        MBB != MBBe; ++MBB)
241     AllocateBasicBlock(*MBB);
242
243   StackSlotForVirtReg.clear();
244   return true;
245 }
246
247 FunctionPass *llvm::createSimpleRegisterAllocator() {
248   return new RegAllocSimple();
249 }