Added an API to the SlotIndexes pass to allow new instructions to be inserted into...
[oota-llvm.git] / lib / CodeGen / Spiller.cpp
1 //===-- llvm/CodeGen/Spiller.cpp -  Spiller -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "spiller"
11
12 #include "Spiller.h"
13 #include "VirtRegMap.h"
14 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
15 #include "llvm/CodeGen/LiveStackAnalysis.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace llvm;
25
26 Spiller::~Spiller() {}
27
28 namespace {
29
30 /// Utility class for spillers.
31 class SpillerBase : public Spiller {
32 protected:
33
34   MachineFunction *mf;
35   LiveIntervals *lis;
36   LiveStacks *ls;
37   MachineFrameInfo *mfi;
38   MachineRegisterInfo *mri;
39   const TargetInstrInfo *tii;
40   VirtRegMap *vrm;
41   
42   /// Construct a spiller base. 
43   SpillerBase(MachineFunction *mf, LiveIntervals *lis, LiveStacks *ls,
44               VirtRegMap *vrm) :
45     mf(mf), lis(lis), ls(ls), vrm(vrm)
46   {
47     mfi = mf->getFrameInfo();
48     mri = &mf->getRegInfo();
49     tii = mf->getTarget().getInstrInfo();
50   }
51
52   /// Ensures there is space before the given machine instruction, returns the
53   /// instruction's new number.
54   SlotIndex makeSpaceBefore(MachineInstr *mi) {
55     //if (!lis->hasGapBeforeInstr(lis->getInstructionIndex(mi))) {
56       // FIXME: Should be updated to use rewrite-in-place methods when they're
57       // introduced. Currently broken.
58       //lis->scaleNumbering(2);
59       //ls->scaleNumbering(2);
60     //}
61
62     SlotIndex miIdx = lis->getInstructionIndex(mi);
63
64     //assert(lis->hasGapBeforeInstr(miIdx));
65     
66     return miIdx;
67   }
68
69   /// Ensure there is space after the given machine instruction, returns the
70   /// instruction's new number.
71   SlotIndex makeSpaceAfter(MachineInstr *mi) {
72     //if (!lis->hasGapAfterInstr(lis->getInstructionIndex(mi))) {
73       // FIXME: Should be updated to use rewrite-in-place methods when they're
74       // introduced. Currently broken.
75       // lis->scaleNumbering(2);
76       // ls->scaleNumbering(2);
77     //}
78
79     SlotIndex miIdx = lis->getInstructionIndex(mi);
80
81     //assert(lis->hasGapAfterInstr(miIdx));
82
83     return miIdx;
84   }  
85
86   /// Insert a store of the given vreg to the given stack slot immediately
87   /// after the given instruction. Returns the base index of the inserted
88   /// instruction. The caller is responsible for adding an appropriate
89   /// LiveInterval to the LiveIntervals analysis.
90   SlotIndex insertStoreAfter(MachineInstr *mi, unsigned ss,
91                                      unsigned vreg,
92                                      const TargetRegisterClass *trc) {
93
94     MachineBasicBlock::iterator nextInstItr(next(mi)); 
95
96     SlotIndex miIdx = makeSpaceAfter(mi);
97
98     tii->storeRegToStackSlot(*mi->getParent(), nextInstItr, vreg,
99                              true, ss, trc);
100     MachineBasicBlock::iterator storeInstItr(next(mi));
101     MachineInstr *storeInst = &*storeInstItr;
102     
103     return lis->InsertMachineInstrInMaps(storeInst);
104   }
105
106   /// Insert a store of the given vreg to the given stack slot immediately
107   /// before the given instructnion. Returns the base index of the inserted
108   /// Instruction.
109   SlotIndex insertStoreBefore(MachineInstr *mi, unsigned ss,
110                                       unsigned vreg,
111                                       const TargetRegisterClass *trc) {
112     SlotIndex miIdx = makeSpaceBefore(mi);
113   
114     tii->storeRegToStackSlot(*mi->getParent(), mi, vreg, true, ss, trc);
115     MachineBasicBlock::iterator storeInstItr(prior(mi));
116     MachineInstr *storeInst = &*storeInstItr;
117
118     return lis->InsertMachineInstrInMaps(storeInst);
119   }
120
121   void insertStoreAfterInstOnInterval(LiveInterval *li,
122                                       MachineInstr *mi, unsigned ss,
123                                       unsigned vreg,
124                                       const TargetRegisterClass *trc) {
125
126     SlotIndex storeInstIdx = insertStoreAfter(mi, ss, vreg, trc);
127     SlotIndex start = lis->getInstructionIndex(mi).getDefIndex(),
128               end = storeInstIdx.getUseIndex();
129
130     VNInfo *vni =
131       li->getNextValue(storeInstIdx, 0, true, lis->getVNInfoAllocator());
132     vni->addKill(storeInstIdx);
133     DEBUG(errs() << "    Inserting store range: [" << start
134                  << ", " << end << ")\n");
135     LiveRange lr(start, end, vni);
136       
137     li->addRange(lr);
138   }
139
140   /// Insert a load of the given vreg from the given stack slot immediately
141   /// after the given instruction. Returns the base index of the inserted
142   /// instruction. The caller is responsibel for adding/removing an appropriate
143   /// range vreg's LiveInterval.
144   SlotIndex insertLoadAfter(MachineInstr *mi, unsigned ss,
145                                     unsigned vreg,
146                                     const TargetRegisterClass *trc) {
147
148     MachineBasicBlock::iterator nextInstItr(next(mi)); 
149
150     SlotIndex miIdx = makeSpaceAfter(mi);
151
152     tii->loadRegFromStackSlot(*mi->getParent(), nextInstItr, vreg, ss, trc);
153     MachineBasicBlock::iterator loadInstItr(next(mi));
154     MachineInstr *loadInst = &*loadInstItr;
155     
156     return lis->InsertMachineInstrInMaps(loadInst);
157   }
158
159   /// Insert a load of the given vreg from the given stack slot immediately
160   /// before the given instruction. Returns the base index of the inserted
161   /// instruction. The caller is responsible for adding an appropriate
162   /// LiveInterval to the LiveIntervals analysis.
163   SlotIndex insertLoadBefore(MachineInstr *mi, unsigned ss,
164                                      unsigned vreg,
165                                      const TargetRegisterClass *trc) {  
166     SlotIndex miIdx = makeSpaceBefore(mi);
167   
168     tii->loadRegFromStackSlot(*mi->getParent(), mi, vreg, ss, trc);
169     MachineBasicBlock::iterator loadInstItr(prior(mi));
170     MachineInstr *loadInst = &*loadInstItr;
171
172     return lis->InsertMachineInstrInMaps(loadInst);
173   }
174
175   void insertLoadBeforeInstOnInterval(LiveInterval *li,
176                                       MachineInstr *mi, unsigned ss, 
177                                       unsigned vreg,
178                                       const TargetRegisterClass *trc) {
179
180     SlotIndex loadInstIdx = insertLoadBefore(mi, ss, vreg, trc);
181     SlotIndex start = loadInstIdx.getDefIndex(),
182               end = lis->getInstructionIndex(mi).getUseIndex();
183
184     VNInfo *vni =
185       li->getNextValue(loadInstIdx, 0, true, lis->getVNInfoAllocator());
186     vni->addKill(lis->getInstructionIndex(mi));
187     DEBUG(errs() << "    Intserting load range: [" << start
188                  << ", " << end << ")\n");
189     LiveRange lr(start, end, vni);
190
191     li->addRange(lr);
192   }
193
194
195
196   /// Add spill ranges for every use/def of the live interval, inserting loads
197   /// immediately before each use, and stores after each def. No folding is
198   /// attempted.
199   std::vector<LiveInterval*> trivialSpillEverywhere(LiveInterval *li) {
200     DEBUG(errs() << "Spilling everywhere " << *li << "\n");
201
202     assert(li->weight != HUGE_VALF &&
203            "Attempting to spill already spilled value.");
204
205     assert(!li->isStackSlot() &&
206            "Trying to spill a stack slot.");
207
208     DEBUG(errs() << "Trivial spill everywhere of reg" << li->reg << "\n");
209
210     std::vector<LiveInterval*> added;
211     
212     const TargetRegisterClass *trc = mri->getRegClass(li->reg);
213     unsigned ss = vrm->assignVirt2StackSlot(li->reg);
214
215     for (MachineRegisterInfo::reg_iterator
216          regItr = mri->reg_begin(li->reg); regItr != mri->reg_end();) {
217
218       MachineInstr *mi = &*regItr;
219
220       DEBUG(errs() << "  Processing " << *mi);
221
222       do {
223         ++regItr;
224       } while (regItr != mri->reg_end() && (&*regItr == mi));
225       
226       SmallVector<unsigned, 2> indices;
227       bool hasUse = false;
228       bool hasDef = false;
229     
230       for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
231         MachineOperand &op = mi->getOperand(i);
232
233         if (!op.isReg() || op.getReg() != li->reg)
234           continue;
235       
236         hasUse |= mi->getOperand(i).isUse();
237         hasDef |= mi->getOperand(i).isDef();
238       
239         indices.push_back(i);
240       }
241
242       unsigned newVReg = mri->createVirtualRegister(trc);
243       vrm->grow();
244       vrm->assignVirt2StackSlot(newVReg, ss);
245
246       LiveInterval *newLI = &lis->getOrCreateInterval(newVReg);
247       newLI->weight = HUGE_VALF;
248       
249       for (unsigned i = 0; i < indices.size(); ++i) {
250         mi->getOperand(indices[i]).setReg(newVReg);
251
252         if (mi->getOperand(indices[i]).isUse()) {
253           mi->getOperand(indices[i]).setIsKill(true);
254         }
255       }
256
257       assert(hasUse || hasDef);
258
259       if (hasUse) {
260         insertLoadBeforeInstOnInterval(newLI, mi, ss, newVReg, trc);
261       }
262
263       if (hasDef) {
264         insertStoreAfterInstOnInterval(newLI, mi, ss, newVReg, trc);
265       }
266
267       added.push_back(newLI);
268     }
269
270     return added;
271   }
272
273 };
274
275
276 /// Spills any live range using the spill-everywhere method with no attempt at
277 /// folding.
278 class TrivialSpiller : public SpillerBase {
279 public:
280
281   TrivialSpiller(MachineFunction *mf, LiveIntervals *lis, LiveStacks *ls,
282                  VirtRegMap *vrm) :
283     SpillerBase(mf, lis, ls, vrm) {}
284
285   std::vector<LiveInterval*> spill(LiveInterval *li) {
286     return trivialSpillEverywhere(li);
287   }
288
289   std::vector<LiveInterval*> intraBlockSplit(LiveInterval *li, VNInfo *valno)  {
290     std::vector<LiveInterval*> spillIntervals;
291
292     if (!valno->isDefAccurate() && !valno->isPHIDef()) {
293       // Early out for values which have no well defined def point.
294       return spillIntervals;
295     }
296
297     // Ok.. we should be able to proceed...
298     const TargetRegisterClass *trc = mri->getRegClass(li->reg);
299     unsigned ss = vrm->assignVirt2StackSlot(li->reg);    
300     vrm->grow();
301     vrm->assignVirt2StackSlot(li->reg, ss);
302
303     MachineInstr *mi = 0;
304     SlotIndex storeIdx = SlotIndex();
305
306     if (valno->isDefAccurate()) {
307       // If we have an accurate def we can just grab an iterator to the instr
308       // after the def.
309       mi = lis->getInstructionFromIndex(valno->def);
310       storeIdx = insertStoreAfter(mi, ss, li->reg, trc).getDefIndex();
311     } else {
312       // if we get here we have a PHI def.
313       mi = &lis->getMBBFromIndex(valno->def)->front();
314       storeIdx = insertStoreBefore(mi, ss, li->reg, trc).getDefIndex();
315     }
316
317     MachineBasicBlock *defBlock = mi->getParent();
318     SlotIndex loadIdx = SlotIndex();
319
320     // Now we need to find the load...
321     MachineBasicBlock::iterator useItr(mi);
322     for (; !useItr->readsRegister(li->reg); ++useItr) {}
323
324     if (useItr != defBlock->end()) {
325       MachineInstr *loadInst = useItr;
326       loadIdx = insertLoadBefore(loadInst, ss, li->reg, trc).getUseIndex();
327     }
328     else {
329       MachineInstr *loadInst = &defBlock->back();
330       loadIdx = insertLoadAfter(loadInst, ss, li->reg, trc).getUseIndex();
331     }
332
333     li->removeRange(storeIdx, loadIdx, true);
334
335     return spillIntervals;
336   }
337
338 };
339
340 }
341
342 llvm::Spiller* llvm::createSpiller(MachineFunction *mf, LiveIntervals *lis,
343                                    LiveStacks *ls, VirtRegMap *vrm) {
344   return new TrivialSpiller(mf, lis, ls, vrm);
345 }