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