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