Added a new "splitting" spiller.
[oota-llvm.git] / include / llvm / CodeGen / LiveIntervalAnalysis.h
1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
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 // This file implements the LiveInterval analysis pass.  Given some numbering of
11 // each the machine instructions (in this implemention depth-first order) an
12 // interval [i, j) is said to be a live interval for register v if there is no
13 // instruction with number j' > j such that v is live at j' and there is no
14 // instruction with number i' < i such that v is live at i'. In this
15 // implementation intervals can have holes, i.e. an interval might look like
16 // [1,20), [50,65), [1000,1001).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
22
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/SlotIndexes.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/Allocator.h"
32 #include <cmath>
33 #include <iterator>
34
35 namespace llvm {
36
37   class AliasAnalysis;
38   class LiveVariables;
39   class MachineLoopInfo;
40   class TargetRegisterInfo;
41   class MachineRegisterInfo;
42   class TargetInstrInfo;
43   class TargetRegisterClass;
44   class VirtRegMap;
45   
46   class LiveIntervals : public MachineFunctionPass {
47     MachineFunction* mf_;
48     MachineRegisterInfo* mri_;
49     const TargetMachine* tm_;
50     const TargetRegisterInfo* tri_;
51     const TargetInstrInfo* tii_;
52     AliasAnalysis *aa_;
53     LiveVariables* lv_;
54     SlotIndexes* indexes_;
55
56     /// Special pool allocator for VNInfo's (LiveInterval val#).
57     ///
58     BumpPtrAllocator VNInfoAllocator;
59
60     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61     Reg2IntervalMap r2iMap_;
62
63     /// allocatableRegs_ - A bit vector of allocatable registers.
64     BitVector allocatableRegs_;
65
66     /// CloneMIs - A list of clones as result of re-materialization.
67     std::vector<MachineInstr*> CloneMIs;
68
69   public:
70     static char ID; // Pass identification, replacement for typeid
71     LiveIntervals() : MachineFunctionPass(&ID) {}
72
73     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
74       return (isDef + isUse) * powf(10.0F, (float)loopDepth);
75     }
76
77     typedef Reg2IntervalMap::iterator iterator;
78     typedef Reg2IntervalMap::const_iterator const_iterator;
79     const_iterator begin() const { return r2iMap_.begin(); }
80     const_iterator end() const { return r2iMap_.end(); }
81     iterator begin() { return r2iMap_.begin(); }
82     iterator end() { return r2iMap_.end(); }
83     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
84
85     LiveInterval &getInterval(unsigned reg) {
86       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
87       assert(I != r2iMap_.end() && "Interval does not exist for register");
88       return *I->second;
89     }
90
91     const LiveInterval &getInterval(unsigned reg) const {
92       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
93       assert(I != r2iMap_.end() && "Interval does not exist for register");
94       return *I->second;
95     }
96
97     bool hasInterval(unsigned reg) const {
98       return r2iMap_.count(reg);
99     }
100
101     /// getScaledIntervalSize - get the size of an interval in "units,"
102     /// where every function is composed of one thousand units.  This
103     /// measure scales properly with empty index slots in the function.
104     double getScaledIntervalSize(LiveInterval& I) {
105       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
106     }
107     
108     /// getApproximateInstructionCount - computes an estimate of the number
109     /// of instructions in a given LiveInterval.
110     unsigned getApproximateInstructionCount(LiveInterval& I) {
111       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
112       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
113     }
114
115     /// conflictsWithPhysRegDef - Returns true if the specified register
116     /// is defined during the duration of the specified interval.
117     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
118                                  unsigned reg);
119
120     /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
121     /// it can check use as well.
122     bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
123                                  bool CheckUse,
124                                  SmallPtrSet<MachineInstr*,32> &JoinedCopies);
125
126     // Interval creation
127     LiveInterval &getOrCreateInterval(unsigned reg) {
128       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
129       if (I == r2iMap_.end())
130         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
131       return *I->second;
132     }
133
134     /// dupInterval - Duplicate a live interval. The caller is responsible for
135     /// managing the allocated memory.
136     LiveInterval *dupInterval(LiveInterval *li);
137     
138     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
139     /// adds a live range from that instruction to the end of its MBB.
140     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
141                                        MachineInstr* startInst);
142
143     // Interval removal
144
145     void removeInterval(unsigned Reg) {
146       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
147       delete I->second;
148       r2iMap_.erase(I);
149     }
150
151     SlotIndex getZeroIndex() const {
152       return indexes_->getZeroIndex();
153     }
154
155     SlotIndex getInvalidIndex() const {
156       return indexes_->getInvalidIndex();
157     }
158
159     /// isNotInMIMap - returns true if the specified machine instr has been
160     /// removed or was never entered in the map.
161     bool isNotInMIMap(const MachineInstr* Instr) const {
162       return !indexes_->hasIndex(Instr);
163     }
164
165     /// Returns the base index of the given instruction.
166     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
167       return indexes_->getInstructionIndex(instr);
168     }
169     
170     /// Returns the instruction associated with the given index.
171     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
172       return indexes_->getInstructionFromIndex(index);
173     }
174
175     /// Return the first index in the given basic block.
176     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
177       return indexes_->getMBBStartIdx(mbb);
178     } 
179
180     /// Return the last index in the given basic block.
181     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
182       return indexes_->getMBBEndIdx(mbb);
183     } 
184
185     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
186       return indexes_->getMBBFromIndex(index);
187     }
188
189     SlotIndex getMBBTerminatorGap(const MachineBasicBlock *mbb) {
190       return indexes_->getTerminatorGap(mbb);
191     }
192
193     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
194       return indexes_->insertMachineInstrInMaps(MI);
195     }
196
197     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
198       indexes_->removeMachineInstrFromMaps(MI);
199     }
200
201     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
202       indexes_->replaceMachineInstrInMaps(MI, NewMI);
203     }
204
205     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
206                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
207       return indexes_->findLiveInMBBs(Start, End, MBBs);
208     }
209
210     void renumber() {
211       indexes_->renumberIndexes();
212     }
213
214     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
215
216     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
217     /// copy field and returns the source register that defines it.
218     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
219
220     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
221     virtual void releaseMemory();
222
223     /// runOnMachineFunction - pass entry point
224     virtual bool runOnMachineFunction(MachineFunction&);
225
226     /// print - Implement the dump method.
227     virtual void print(raw_ostream &O, const Module* = 0) const;
228
229     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
230     /// the given interval. FIXME: It also returns the weight of the spill slot
231     /// (if any is created) by reference. This is temporary.
232     std::vector<LiveInterval*>
233     addIntervalsForSpills(const LiveInterval& i,
234                           SmallVectorImpl<LiveInterval*> &SpillIs,
235                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
236     
237     /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
238     /// defs / uses without remat or splitting.
239     std::vector<LiveInterval*>
240     addIntervalsForSpillsFast(const LiveInterval &li,
241                               const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
242
243     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
244     /// around all defs and uses of the specified interval. Return true if it
245     /// was able to cut its interval.
246     bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
247                                        unsigned PhysReg, VirtRegMap &vrm);
248
249     /// isReMaterializable - Returns true if every definition of MI of every
250     /// val# of the specified interval is re-materializable. Also returns true
251     /// by reference if all of the defs are load instructions.
252     bool isReMaterializable(const LiveInterval &li,
253                             SmallVectorImpl<LiveInterval*> &SpillIs,
254                             bool &isLoad);
255
256     /// isReMaterializable - Returns true if the definition MI of the specified
257     /// val# of the specified interval is re-materializable.
258     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
259                             MachineInstr *MI);
260
261     /// getRepresentativeReg - Find the largest super register of the specified
262     /// physical register.
263     unsigned getRepresentativeReg(unsigned Reg) const;
264
265     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
266     /// specified interval that conflicts with the specified physical register.
267     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
268                                         unsigned PhysReg) const;
269
270     /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
271     /// marker to implicit_def defs and their uses.
272     void processImplicitDefs();
273
274     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
275     /// within a single basic block.
276     bool intervalIsInOneMBB(const LiveInterval &li) const;
277
278   private:      
279     /// computeIntervals - Compute live intervals.
280     void computeIntervals();
281
282     /// handleRegisterDef - update intervals for a register def
283     /// (calls handlePhysicalRegisterDef and
284     /// handleVirtualRegisterDef)
285     void handleRegisterDef(MachineBasicBlock *MBB,
286                            MachineBasicBlock::iterator MI,
287                            SlotIndex MIIdx,
288                            MachineOperand& MO, unsigned MOIdx);
289
290     /// handleVirtualRegisterDef - update intervals for a virtual
291     /// register def
292     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
293                                   MachineBasicBlock::iterator MI,
294                                   SlotIndex MIIdx, MachineOperand& MO,
295                                   unsigned MOIdx,
296                                   LiveInterval& interval);
297
298     /// handlePhysicalRegisterDef - update intervals for a physical register
299     /// def.
300     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
301                                    MachineBasicBlock::iterator mi,
302                                    SlotIndex MIIdx, MachineOperand& MO,
303                                    LiveInterval &interval,
304                                    MachineInstr *CopyMI);
305
306     /// handleLiveInRegister - Create interval for a livein register.
307     void handleLiveInRegister(MachineBasicBlock* mbb,
308                               SlotIndex MIIdx,
309                               LiveInterval &interval, bool isAlias = false);
310
311     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
312     /// only allow one) virtual register operand, then its uses are implicitly
313     /// using the register. Returns the virtual register.
314     unsigned getReMatImplicitUse(const LiveInterval &li,
315                                  MachineInstr *MI) const;
316
317     /// isValNoAvailableAt - Return true if the val# of the specified interval
318     /// which reaches the given instruction also reaches the specified use
319     /// index.
320     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
321                             SlotIndex UseIdx) const;
322
323     /// isReMaterializable - Returns true if the definition MI of the specified
324     /// val# of the specified interval is re-materializable. Also returns true
325     /// by reference if the def is a load.
326     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
327                             MachineInstr *MI,
328                             SmallVectorImpl<LiveInterval*> &SpillIs,
329                             bool &isLoad);
330
331     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
332     /// slot / to reg or any rematerialized load into ith operand of specified
333     /// MI. If it is successul, MI is updated with the newly created MI and
334     /// returns true.
335     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
336                               MachineInstr *DefMI, SlotIndex InstrIdx,
337                               SmallVector<unsigned, 2> &Ops,
338                               bool isSS, int FrameIndex, unsigned Reg);
339
340     /// canFoldMemoryOperand - Return true if the specified load / store
341     /// folding is possible.
342     bool canFoldMemoryOperand(MachineInstr *MI,
343                               SmallVector<unsigned, 2> &Ops,
344                               bool ReMatLoadSS) const;
345
346     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
347     /// VNInfo that's after the specified index but is within the basic block.
348     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
349                               MachineBasicBlock *MBB,
350                               SlotIndex Idx) const;
351
352     /// hasAllocatableSuperReg - Return true if the specified physical register
353     /// has any super register that's allocatable.
354     bool hasAllocatableSuperReg(unsigned Reg) const;
355
356     /// SRInfo - Spill / restore info.
357     struct SRInfo {
358       SlotIndex index;
359       unsigned vreg;
360       bool canFold;
361       SRInfo(SlotIndex i, unsigned vr, bool f)
362         : index(i), vreg(vr), canFold(f) {}
363     };
364
365     bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
366                           BitVector &RestoreMBBs,
367                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
368     void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
369                           BitVector &RestoreMBBs,
370                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
371
372     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
373     /// spilled and create empty intervals for their uses.
374     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
375                               const TargetRegisterClass* rc,
376                               std::vector<LiveInterval*> &NewLIs);
377
378     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
379     /// interval on to-be re-materialized operands of MI) with new register.
380     void rewriteImplicitOps(const LiveInterval &li,
381                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
382
383     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
384     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
385     /// live range.
386     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
387         bool TrySplit, SlotIndex index, SlotIndex end,
388         MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
389         unsigned Slot, int LdSlot,
390         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
391         VirtRegMap &vrm, const TargetRegisterClass* rc,
392         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
393         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
394         DenseMap<unsigned,unsigned> &MBBVRegsMap,
395         std::vector<LiveInterval*> &NewLIs);
396     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
397         LiveInterval::Ranges::const_iterator &I,
398         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
399         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
400         VirtRegMap &vrm, const TargetRegisterClass* rc,
401         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
402         BitVector &SpillMBBs,
403         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
404         BitVector &RestoreMBBs,
405         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
406         DenseMap<unsigned,unsigned> &MBBVRegsMap,
407         std::vector<LiveInterval*> &NewLIs);
408
409     static LiveInterval* createInterval(unsigned Reg);
410
411     void printInstrs(raw_ostream &O) const;
412     void dumpInstrs() const;
413   };
414 } // End llvm namespace
415
416 #endif