Factor GC metadata table assembly generation out of Collector in preparation for...
[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/MachineFunctionPass.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
30 #include <cmath>
31
32 namespace llvm {
33
34   class AliasAnalysis;
35   class LiveVariables;
36   class MachineLoopInfo;
37   class TargetRegisterInfo;
38   class MachineRegisterInfo;
39   class TargetInstrInfo;
40   class TargetRegisterClass;
41   class VirtRegMap;
42   typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
43
44   inline bool operator<(unsigned V, const IdxMBBPair &IM) {
45     return V < IM.first;
46   }
47
48   inline bool operator<(const IdxMBBPair &IM, unsigned V) {
49     return IM.first < V;
50   }
51
52   struct Idx2MBBCompare {
53     bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
54       return LHS.first < RHS.first;
55     }
56   };
57   
58   // Provide DenseMapInfo for unsigned.
59   template<>
60   struct DenseMapInfo<unsigned> {
61     static inline unsigned getEmptyKey() { return (unsigned)-1; }
62     static inline unsigned getTombstoneKey() { return (unsigned)-2; }
63     static unsigned getHashValue(const unsigned Val) {
64       return Val * 37;
65     }
66     static bool isEqual(const unsigned LHS, const unsigned RHS) {
67       return LHS == RHS;
68     }
69     static bool isPod() { return true; }
70   };
71
72   class LiveIntervals : public MachineFunctionPass {
73     MachineFunction* mf_;
74     MachineRegisterInfo* mri_;
75     const TargetMachine* tm_;
76     const TargetRegisterInfo* tri_;
77     const TargetInstrInfo* tii_;
78     AliasAnalysis *aa_;
79     LiveVariables* lv_;
80
81     /// Special pool allocator for VNInfo's (LiveInterval val#).
82     ///
83     BumpPtrAllocator VNInfoAllocator;
84
85     /// MBB2IdxMap - The indexes of the first and last instructions in the
86     /// specified basic block.
87     std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
88
89     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
90     /// and MBB id.
91     std::vector<IdxMBBPair> Idx2MBBMap;
92
93     /// FunctionSize - The number of instructions present in the function
94     uint64_t FunctionSize;
95
96     typedef DenseMap<MachineInstr*, unsigned> Mi2IndexMap;
97     Mi2IndexMap mi2iMap_;
98
99     typedef std::vector<MachineInstr*> Index2MiMap;
100     Index2MiMap i2miMap_;
101
102     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
103     Reg2IntervalMap r2iMap_;
104
105     BitVector allocatableRegs_;
106
107     std::vector<MachineInstr*> ClonedMIs;
108
109   public:
110     static char ID; // Pass identification, replacement for typeid
111     LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
112
113     struct InstrSlots {
114       enum {
115         LOAD  = 0,
116         USE   = 1,
117         DEF   = 2,
118         STORE = 3,
119         NUM   = 4
120       };
121     };
122
123     static unsigned getBaseIndex(unsigned index) {
124       return index - (index % InstrSlots::NUM);
125     }
126     static unsigned getBoundaryIndex(unsigned index) {
127       return getBaseIndex(index + InstrSlots::NUM - 1);
128     }
129     static unsigned getLoadIndex(unsigned index) {
130       return getBaseIndex(index) + InstrSlots::LOAD;
131     }
132     static unsigned getUseIndex(unsigned index) {
133       return getBaseIndex(index) + InstrSlots::USE;
134     }
135     static unsigned getDefIndex(unsigned index) {
136       return getBaseIndex(index) + InstrSlots::DEF;
137     }
138     static unsigned getStoreIndex(unsigned index) {
139       return getBaseIndex(index) + InstrSlots::STORE;
140     }
141
142     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
143       return (isDef + isUse) * powf(10.0F, (float)loopDepth);
144     }
145
146     typedef Reg2IntervalMap::iterator iterator;
147     typedef Reg2IntervalMap::const_iterator const_iterator;
148     const_iterator begin() const { return r2iMap_.begin(); }
149     const_iterator end() const { return r2iMap_.end(); }
150     iterator begin() { return r2iMap_.begin(); }
151     iterator end() { return r2iMap_.end(); }
152     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
153
154     LiveInterval &getInterval(unsigned reg) {
155       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
156       assert(I != r2iMap_.end() && "Interval does not exist for register");
157       return *I->second;
158     }
159
160     const LiveInterval &getInterval(unsigned reg) const {
161       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
162       assert(I != r2iMap_.end() && "Interval does not exist for register");
163       return *I->second;
164     }
165
166     bool hasInterval(unsigned reg) const {
167       return r2iMap_.count(reg);
168     }
169
170     /// getMBBStartIdx - Return the base index of the first instruction in the
171     /// specified MachineBasicBlock.
172     unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
173       return getMBBStartIdx(MBB->getNumber());
174     }
175     unsigned getMBBStartIdx(unsigned MBBNo) const {
176       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
177       return MBB2IdxMap[MBBNo].first;
178     }
179
180     /// getMBBEndIdx - Return the store index of the last instruction in the
181     /// specified MachineBasicBlock.
182     unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
183       return getMBBEndIdx(MBB->getNumber());
184     }
185     unsigned getMBBEndIdx(unsigned MBBNo) const {
186       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
187       return MBB2IdxMap[MBBNo].second;
188     }
189
190     /// getScaledIntervalSize - get the size of an interval in "units,"
191     /// where every function is composed of one thousand units.  This
192     /// measure scales properly with empty index slots in the function.
193     double getScaledIntervalSize(LiveInterval& I) {
194       return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
195     }
196     
197     /// getApproximateInstructionCount - computes an estimate of the number
198     /// of instructions in a given LiveInterval.
199     unsigned getApproximateInstructionCount(LiveInterval& I) {
200       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
201       return (unsigned)(IntervalPercentage * FunctionSize);
202     }
203
204     /// getMBBFromIndex - given an index in any instruction of an
205     /// MBB return a pointer the MBB
206     MachineBasicBlock* getMBBFromIndex(unsigned index) const {
207       std::vector<IdxMBBPair>::const_iterator I =
208         std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
209       // Take the pair containing the index
210       std::vector<IdxMBBPair>::const_iterator J =
211         ((I != Idx2MBBMap.end() && I->first > index) ||
212          (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
213
214       assert(J != Idx2MBBMap.end() && J->first < index+1 &&
215              index <= getMBBEndIdx(J->second) &&
216              "index does not correspond to an MBB");
217       return J->second;
218     }
219
220     /// getInstructionIndex - returns the base index of instr
221     unsigned getInstructionIndex(MachineInstr* instr) const {
222       Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
223       assert(it != mi2iMap_.end() && "Invalid instruction!");
224       return it->second;
225     }
226
227     /// getInstructionFromIndex - given an index in any slot of an
228     /// instruction return a pointer the instruction
229     MachineInstr* getInstructionFromIndex(unsigned index) const {
230       index /= InstrSlots::NUM; // convert index to vector index
231       assert(index < i2miMap_.size() &&
232              "index does not correspond to an instruction");
233       return i2miMap_[index];
234     }
235
236     /// conflictsWithPhysRegDef - Returns true if the specified register
237     /// is defined during the duration of the specified interval.
238     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
239                                  unsigned reg);
240
241     /// findLiveInMBBs - Given a live range, if the value of the range
242     /// is live in any MBB returns true as well as the list of basic blocks
243     /// in which the value is live.
244     bool findLiveInMBBs(const LiveRange &LR,
245                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
246
247     // Interval creation
248
249     LiveInterval &getOrCreateInterval(unsigned reg) {
250       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
251       if (I == r2iMap_.end())
252         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
253       return *I->second;
254     }
255     
256     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
257     /// adds a live range from that instruction to the end of its MBB.
258     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
259                                         MachineInstr* startInst);
260
261     // Interval removal
262
263     void removeInterval(unsigned Reg) {
264       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
265       delete I->second;
266       r2iMap_.erase(I);
267     }
268
269     /// isRemoved - returns true if the specified machine instr has been
270     /// removed.
271     bool isRemoved(MachineInstr* instr) const {
272       return !mi2iMap_.count(instr);
273     }
274
275     /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
276     /// deleted.
277     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
278       // remove index -> MachineInstr and
279       // MachineInstr -> index mappings
280       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
281       if (mi2i != mi2iMap_.end()) {
282         i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
283         mi2iMap_.erase(mi2i);
284       }
285     }
286
287     /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
288     /// maps used by register allocator.
289     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
290       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
291       if (mi2i == mi2iMap_.end())
292         return;
293       i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
294       Mi2IndexMap::iterator it = mi2iMap_.find(MI);
295       assert(it != mi2iMap_.end() && "Invalid instruction!");
296       unsigned Index = it->second;
297       mi2iMap_.erase(it);
298       mi2iMap_[NewMI] = Index;
299     }
300
301     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
302
303     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
304     /// copy field and returns the source register that defines it.
305     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
306
307     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
308     virtual void releaseMemory();
309
310     /// runOnMachineFunction - pass entry point
311     virtual bool runOnMachineFunction(MachineFunction&);
312
313     /// print - Implement the dump method.
314     virtual void print(std::ostream &O, const Module* = 0) const;
315     void print(std::ostream *O, const Module* M = 0) const {
316       if (O) print(*O, M);
317     }
318
319     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
320     /// the given interval. FIXME: It also returns the weight of the spill slot
321     /// (if any is created) by reference. This is temporary.
322     std::vector<LiveInterval*>
323     addIntervalsForSpills(const LiveInterval& i,
324                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
325                           float &SSWeight);
326
327     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
328     /// around all defs and uses of the specified interval.
329     void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
330                                        unsigned PhysReg, VirtRegMap &vrm);
331
332     /// isReMaterializable - Returns true if every definition of MI of every
333     /// val# of the specified interval is re-materializable. Also returns true
334     /// by reference if all of the defs are load instructions.
335     bool isReMaterializable(const LiveInterval &li, bool &isLoad);
336
337     /// getRepresentativeReg - Find the largest super register of the specified
338     /// physical register.
339     unsigned getRepresentativeReg(unsigned Reg) const;
340
341     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
342     /// specified interval that conflicts with the specified physical register.
343     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
344                                         unsigned PhysReg) const;
345
346     /// computeNumbering - Compute the index numbering.
347     void computeNumbering();
348
349   private:      
350     /// computeIntervals - Compute live intervals.
351     void computeIntervals();
352     
353     /// handleRegisterDef - update intervals for a register def
354     /// (calls handlePhysicalRegisterDef and
355     /// handleVirtualRegisterDef)
356     void handleRegisterDef(MachineBasicBlock *MBB,
357                            MachineBasicBlock::iterator MI, unsigned MIIdx,
358                            MachineOperand& MO, unsigned MOIdx);
359
360     /// handleVirtualRegisterDef - update intervals for a virtual
361     /// register def
362     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
363                                   MachineBasicBlock::iterator MI,
364                                   unsigned MIIdx, MachineOperand& MO,
365                                   unsigned MOIdx, LiveInterval& interval);
366
367     /// handlePhysicalRegisterDef - update intervals for a physical register
368     /// def.
369     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
370                                    MachineBasicBlock::iterator mi,
371                                    unsigned MIIdx, MachineOperand& MO,
372                                    LiveInterval &interval,
373                                    MachineInstr *CopyMI);
374
375     /// handleLiveInRegister - Create interval for a livein register.
376     void handleLiveInRegister(MachineBasicBlock* mbb,
377                               unsigned MIIdx,
378                               LiveInterval &interval, bool isAlias = false);
379
380     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
381     /// only allow one) virtual register operand, then its uses are implicitly
382     /// using the register. Returns the virtual register.
383     unsigned getReMatImplicitUse(const LiveInterval &li,
384                                  MachineInstr *MI) const;
385
386     /// isValNoAvailableAt - Return true if the val# of the specified interval
387     /// which reaches the given instruction also reaches the specified use
388     /// index.
389     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
390                             unsigned UseIdx) const;
391
392     /// isReMaterializable - Returns true if the definition MI of the specified
393     /// val# of the specified interval is re-materializable. Also returns true
394     /// by reference if the def is a load.
395     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
396                             MachineInstr *MI, bool &isLoad);
397
398     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
399     /// slot / to reg or any rematerialized load into ith operand of specified
400     /// MI. If it is successul, MI is updated with the newly created MI and
401     /// returns true.
402     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
403                               MachineInstr *DefMI, unsigned InstrIdx,
404                               SmallVector<unsigned, 2> &Ops,
405                               bool isSS, int Slot, unsigned Reg);
406
407     /// canFoldMemoryOperand - Return true if the specified load / store
408     /// folding is possible.
409     bool canFoldMemoryOperand(MachineInstr *MI,
410                               SmallVector<unsigned, 2> &Ops,
411                               bool ReMatLoadSS) const;
412
413     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
414     /// VNInfo that's after the specified index but is within the basic block.
415     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
416                               MachineBasicBlock *MBB, unsigned Idx) const;
417
418     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
419     /// within a single basic block.
420     bool intervalIsInOneMBB(const LiveInterval &li) const;
421
422     /// hasAllocatableSuperReg - Return true if the specified physical register
423     /// has any super register that's allocatable.
424     bool hasAllocatableSuperReg(unsigned Reg) const;
425
426     /// SRInfo - Spill / restore info.
427     struct SRInfo {
428       int index;
429       unsigned vreg;
430       bool canFold;
431       SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
432     };
433
434     bool alsoFoldARestore(int Id, int index, unsigned vr,
435                           BitVector &RestoreMBBs,
436                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
437     void eraseRestoreInfo(int Id, int index, unsigned vr,
438                           BitVector &RestoreMBBs,
439                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
440
441     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
442     /// spilled and create empty intervals for their uses.
443     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
444                               const TargetRegisterClass* rc,
445                               std::vector<LiveInterval*> &NewLIs);
446
447     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
448     /// interval on to-be re-materialized operands of MI) with new register.
449     void rewriteImplicitOps(const LiveInterval &li,
450                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
451
452     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
453     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
454     /// live range.
455     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
456         bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
457         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
458         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
459         VirtRegMap &vrm, const TargetRegisterClass* rc,
460         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
461         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
462         DenseMap<unsigned,unsigned> &MBBVRegsMap,
463         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
464     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
465         LiveInterval::Ranges::const_iterator &I,
466         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
467         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
468         VirtRegMap &vrm, const TargetRegisterClass* rc,
469         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
470         BitVector &SpillMBBs,
471         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
472         BitVector &RestoreMBBs,
473         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
474         DenseMap<unsigned,unsigned> &MBBVRegsMap,
475         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
476
477     static LiveInterval* createInterval(unsigned Reg);
478
479     void printRegName(unsigned reg) const;
480   };
481
482 } // End llvm namespace
483
484 #endif