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