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