make MachineFunction keep track of its ID and make
[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     /// conflictsWithPhysReg - Returns true if the specified register is used or
116     /// defined during the duration of the specified interval. Copies to and
117     /// from li.reg are allowed. This method is only able to analyze simple
118     /// ranges that stay within a single basic block. Anything else is
119     /// considered a conflict.
120     bool conflictsWithPhysReg(const LiveInterval &li, VirtRegMap &vrm,
121                               unsigned reg);
122
123     /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
124     /// it can check use as well.
125     bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
126                                  bool CheckUse,
127                                  SmallPtrSet<MachineInstr*,32> &JoinedCopies);
128
129     // Interval creation
130     LiveInterval &getOrCreateInterval(unsigned reg) {
131       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
132       if (I == r2iMap_.end())
133         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
134       return *I->second;
135     }
136
137     /// dupInterval - Duplicate a live interval. The caller is responsible for
138     /// managing the allocated memory.
139     LiveInterval *dupInterval(LiveInterval *li);
140     
141     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
142     /// adds a live range from that instruction to the end of its MBB.
143     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
144                                        MachineInstr* startInst);
145
146     // Interval removal
147
148     void removeInterval(unsigned Reg) {
149       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
150       delete I->second;
151       r2iMap_.erase(I);
152     }
153
154     SlotIndex getZeroIndex() const {
155       return indexes_->getZeroIndex();
156     }
157
158     SlotIndex getInvalidIndex() const {
159       return indexes_->getInvalidIndex();
160     }
161
162     /// isNotInMIMap - returns true if the specified machine instr has been
163     /// removed or was never entered in the map.
164     bool isNotInMIMap(const MachineInstr* Instr) const {
165       return !indexes_->hasIndex(Instr);
166     }
167
168     /// Returns the base index of the given instruction.
169     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
170       return indexes_->getInstructionIndex(instr);
171     }
172     
173     /// Returns the instruction associated with the given index.
174     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
175       return indexes_->getInstructionFromIndex(index);
176     }
177
178     /// Return the first index in the given basic block.
179     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
180       return indexes_->getMBBStartIdx(mbb);
181     } 
182
183     /// Return the last index in the given basic block.
184     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
185       return indexes_->getMBBEndIdx(mbb);
186     } 
187
188     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
189       return indexes_->getMBBFromIndex(index);
190     }
191
192     SlotIndex getMBBTerminatorGap(const MachineBasicBlock *mbb) {
193       return indexes_->getTerminatorGap(mbb);
194     }
195
196     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
197       return indexes_->insertMachineInstrInMaps(MI);
198     }
199
200     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
201       indexes_->removeMachineInstrFromMaps(MI);
202     }
203
204     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
205       indexes_->replaceMachineInstrInMaps(MI, NewMI);
206     }
207
208     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
209                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
210       return indexes_->findLiveInMBBs(Start, End, MBBs);
211     }
212
213     void renumber() {
214       indexes_->renumberIndexes();
215     }
216
217     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
218
219     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
220     /// copy field and returns the source register that defines it.
221     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
222
223     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
224     virtual void releaseMemory();
225
226     /// runOnMachineFunction - pass entry point
227     virtual bool runOnMachineFunction(MachineFunction&);
228
229     /// print - Implement the dump method.
230     virtual void print(raw_ostream &O, const Module* = 0) const;
231
232     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
233     /// the given interval. FIXME: It also returns the weight of the spill slot
234     /// (if any is created) by reference. This is temporary.
235     std::vector<LiveInterval*>
236     addIntervalsForSpills(const LiveInterval& i,
237                           SmallVectorImpl<LiveInterval*> &SpillIs,
238                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
239     
240     /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
241     /// defs / uses without remat or splitting.
242     std::vector<LiveInterval*>
243     addIntervalsForSpillsFast(const LiveInterval &li,
244                               const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
245
246     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
247     /// around all defs and uses of the specified interval. Return true if it
248     /// was able to cut its interval.
249     bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
250                                        unsigned PhysReg, VirtRegMap &vrm);
251
252     /// isReMaterializable - Returns true if every definition of MI of every
253     /// val# of the specified interval is re-materializable. Also returns true
254     /// by reference if all of the defs are load instructions.
255     bool isReMaterializable(const LiveInterval &li,
256                             SmallVectorImpl<LiveInterval*> &SpillIs,
257                             bool &isLoad);
258
259     /// isReMaterializable - Returns true if the definition MI of the specified
260     /// val# of the specified interval is re-materializable.
261     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
262                             MachineInstr *MI);
263
264     /// getRepresentativeReg - Find the largest super register of the specified
265     /// physical register.
266     unsigned getRepresentativeReg(unsigned Reg) const;
267
268     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
269     /// specified interval that conflicts with the specified physical register.
270     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
271                                         unsigned PhysReg) const;
272
273     /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
274     /// marker to implicit_def defs and their uses.
275     void processImplicitDefs();
276
277     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
278     /// within a single basic block.
279     bool intervalIsInOneMBB(const LiveInterval &li) const;
280
281   private:      
282     /// computeIntervals - Compute live intervals.
283     void computeIntervals();
284
285     /// handleRegisterDef - update intervals for a register def
286     /// (calls handlePhysicalRegisterDef and
287     /// handleVirtualRegisterDef)
288     void handleRegisterDef(MachineBasicBlock *MBB,
289                            MachineBasicBlock::iterator MI,
290                            SlotIndex MIIdx,
291                            MachineOperand& MO, unsigned MOIdx);
292
293     /// handleVirtualRegisterDef - update intervals for a virtual
294     /// register def
295     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
296                                   MachineBasicBlock::iterator MI,
297                                   SlotIndex MIIdx, MachineOperand& MO,
298                                   unsigned MOIdx,
299                                   LiveInterval& interval);
300
301     /// handlePhysicalRegisterDef - update intervals for a physical register
302     /// def.
303     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
304                                    MachineBasicBlock::iterator mi,
305                                    SlotIndex MIIdx, MachineOperand& MO,
306                                    LiveInterval &interval,
307                                    MachineInstr *CopyMI);
308
309     /// handleLiveInRegister - Create interval for a livein register.
310     void handleLiveInRegister(MachineBasicBlock* mbb,
311                               SlotIndex MIIdx,
312                               LiveInterval &interval, bool isAlias = false);
313
314     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
315     /// only allow one) virtual register operand, then its uses are implicitly
316     /// using the register. Returns the virtual register.
317     unsigned getReMatImplicitUse(const LiveInterval &li,
318                                  MachineInstr *MI) const;
319
320     /// isValNoAvailableAt - Return true if the val# of the specified interval
321     /// which reaches the given instruction also reaches the specified use
322     /// index.
323     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
324                             SlotIndex UseIdx) const;
325
326     /// isReMaterializable - Returns true if the definition MI of the specified
327     /// val# of the specified interval is re-materializable. Also returns true
328     /// by reference if the def is a load.
329     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
330                             MachineInstr *MI,
331                             SmallVectorImpl<LiveInterval*> &SpillIs,
332                             bool &isLoad);
333
334     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
335     /// slot / to reg or any rematerialized load into ith operand of specified
336     /// MI. If it is successul, MI is updated with the newly created MI and
337     /// returns true.
338     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
339                               MachineInstr *DefMI, SlotIndex InstrIdx,
340                               SmallVector<unsigned, 2> &Ops,
341                               bool isSS, int FrameIndex, unsigned Reg);
342
343     /// canFoldMemoryOperand - Return true if the specified load / store
344     /// folding is possible.
345     bool canFoldMemoryOperand(MachineInstr *MI,
346                               SmallVector<unsigned, 2> &Ops,
347                               bool ReMatLoadSS) const;
348
349     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
350     /// VNInfo that's after the specified index but is within the basic block.
351     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
352                               MachineBasicBlock *MBB,
353                               SlotIndex Idx) const;
354
355     /// hasAllocatableSuperReg - Return true if the specified physical register
356     /// has any super register that's allocatable.
357     bool hasAllocatableSuperReg(unsigned Reg) const;
358
359     /// SRInfo - Spill / restore info.
360     struct SRInfo {
361       SlotIndex index;
362       unsigned vreg;
363       bool canFold;
364       SRInfo(SlotIndex i, unsigned vr, bool f)
365         : index(i), vreg(vr), canFold(f) {}
366     };
367
368     bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
369                           BitVector &RestoreMBBs,
370                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
371     void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
372                           BitVector &RestoreMBBs,
373                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
374
375     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
376     /// spilled and create empty intervals for their uses.
377     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
378                               const TargetRegisterClass* rc,
379                               std::vector<LiveInterval*> &NewLIs);
380
381     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
382     /// interval on to-be re-materialized operands of MI) with new register.
383     void rewriteImplicitOps(const LiveInterval &li,
384                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
385
386     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
387     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
388     /// live range.
389     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
390         bool TrySplit, SlotIndex index, SlotIndex end,
391         MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
392         unsigned Slot, int LdSlot,
393         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
394         VirtRegMap &vrm, const TargetRegisterClass* rc,
395         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
396         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
397         DenseMap<unsigned,unsigned> &MBBVRegsMap,
398         std::vector<LiveInterval*> &NewLIs);
399     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
400         LiveInterval::Ranges::const_iterator &I,
401         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
402         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
403         VirtRegMap &vrm, const TargetRegisterClass* rc,
404         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
405         BitVector &SpillMBBs,
406         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
407         BitVector &RestoreMBBs,
408         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
409         DenseMap<unsigned,unsigned> &MBBVRegsMap,
410         std::vector<LiveInterval*> &NewLIs);
411
412     static LiveInterval* createInterval(unsigned Reg);
413
414     void printInstrs(raw_ostream &O) const;
415     void dumpInstrs() const;
416   };
417 } // End llvm namespace
418
419 #endif