Completely eliminate VNInfo flags.
[oota-llvm.git] / include / llvm / CodeGen / LiveInterval.h
1 //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- 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 LiveRange and LiveInterval classes.  Given some
11 // numbering of each the machine instructions an interval [i, j) is said to be a
12 // live interval for register v if there is no instruction with number j' >= j
13 // such that v is live at j' and there is no instruction with number i' < i such
14 // that v is live at i'. In this implementation intervals can have holes,
15 // i.e. an interval might look like [1,20), [50,65), [1000,1001).  Each
16 // individual range is represented as an instance of LiveRange, and the whole
17 // interval is represented as an instance of LiveInterval.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
22 #define LLVM_CODEGEN_LIVEINTERVAL_H
23
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
28 #include <cassert>
29 #include <climits>
30
31 namespace llvm {
32   class LiveIntervals;
33   class MachineInstr;
34   class MachineRegisterInfo;
35   class TargetRegisterInfo;
36   class raw_ostream;
37
38   /// VNInfo - Value Number Information.
39   /// This class holds information about a machine level values, including
40   /// definition and use points.
41   ///
42   class VNInfo {
43   public:
44     typedef BumpPtrAllocator Allocator;
45
46     /// The ID number of this value.
47     unsigned id;
48
49     /// The index of the defining instruction.
50     SlotIndex def;
51
52     /// VNInfo constructor.
53     VNInfo(unsigned i, SlotIndex d)
54       : id(i), def(d)
55     { }
56
57     /// VNInfo construtor, copies values from orig, except for the value number.
58     VNInfo(unsigned i, const VNInfo &orig)
59       : id(i), def(orig.def)
60     { }
61
62     /// Copy from the parameter into this VNInfo.
63     void copyFrom(VNInfo &src) {
64       def = src.def;
65     }
66
67     /// Returns true if this value is defined by a PHI instruction (or was,
68     /// PHI instrucions may have been eliminated).
69     /// PHI-defs begin at a block boundary, all other defs begin at register or
70     /// EC slots.
71     bool isPHIDef() const { return def.isBlock(); }
72
73     /// Returns true if this value is unused.
74     bool isUnused() const { return !def.isValid(); }
75
76     /// Mark this value as unused.
77     void markUnused() { def = SlotIndex(); }
78   };
79
80   /// LiveRange structure - This represents a simple register range in the
81   /// program, with an inclusive start point and an exclusive end point.
82   /// These ranges are rendered as [start,end).
83   struct LiveRange {
84     SlotIndex start;  // Start point of the interval (inclusive)
85     SlotIndex end;    // End point of the interval (exclusive)
86     VNInfo *valno;   // identifier for the value contained in this interval.
87
88     LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
89       : start(S), end(E), valno(V) {
90
91       assert(S < E && "Cannot create empty or backwards range");
92     }
93
94     /// contains - Return true if the index is covered by this range.
95     ///
96     bool contains(SlotIndex I) const {
97       return start <= I && I < end;
98     }
99
100     /// containsRange - Return true if the given range, [S, E), is covered by
101     /// this range.
102     bool containsRange(SlotIndex S, SlotIndex E) const {
103       assert((S < E) && "Backwards interval?");
104       return (start <= S && S < end) && (start < E && E <= end);
105     }
106
107     bool operator<(const LiveRange &LR) const {
108       return start < LR.start || (start == LR.start && end < LR.end);
109     }
110     bool operator==(const LiveRange &LR) const {
111       return start == LR.start && end == LR.end;
112     }
113
114     void dump() const;
115     void print(raw_ostream &os) const;
116
117   private:
118     LiveRange(); // DO NOT IMPLEMENT
119   };
120
121   template <> struct isPodLike<LiveRange> { static const bool value = true; };
122
123   raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
124
125
126   inline bool operator<(SlotIndex V, const LiveRange &LR) {
127     return V < LR.start;
128   }
129
130   inline bool operator<(const LiveRange &LR, SlotIndex V) {
131     return LR.start < V;
132   }
133
134   /// LiveInterval - This class represents some number of live ranges for a
135   /// register or value.  This class also contains a bit of register allocator
136   /// state.
137   class LiveInterval {
138   public:
139
140     typedef SmallVector<LiveRange,4> Ranges;
141     typedef SmallVector<VNInfo*,4> VNInfoList;
142
143     const unsigned reg;  // the register or stack slot of this interval.
144     float weight;        // weight of this interval
145     Ranges ranges;       // the ranges in which this register is live
146     VNInfoList valnos;   // value#'s
147
148     struct InstrSlots {
149       enum {
150         LOAD  = 0,
151         USE   = 1,
152         DEF   = 2,
153         STORE = 3,
154         NUM   = 4
155       };
156
157     };
158
159     LiveInterval(unsigned Reg, float Weight)
160       : reg(Reg), weight(Weight) {}
161
162     typedef Ranges::iterator iterator;
163     iterator begin() { return ranges.begin(); }
164     iterator end()   { return ranges.end(); }
165
166     typedef Ranges::const_iterator const_iterator;
167     const_iterator begin() const { return ranges.begin(); }
168     const_iterator end() const  { return ranges.end(); }
169
170     typedef VNInfoList::iterator vni_iterator;
171     vni_iterator vni_begin() { return valnos.begin(); }
172     vni_iterator vni_end() { return valnos.end(); }
173
174     typedef VNInfoList::const_iterator const_vni_iterator;
175     const_vni_iterator vni_begin() const { return valnos.begin(); }
176     const_vni_iterator vni_end() const { return valnos.end(); }
177
178     /// advanceTo - Advance the specified iterator to point to the LiveRange
179     /// containing the specified position, or end() if the position is past the
180     /// end of the interval.  If no LiveRange contains this position, but the
181     /// position is in a hole, this method returns an iterator pointing to the
182     /// LiveRange immediately after the hole.
183     iterator advanceTo(iterator I, SlotIndex Pos) {
184       assert(I != end());
185       if (Pos >= endIndex())
186         return end();
187       while (I->end <= Pos) ++I;
188       return I;
189     }
190
191     /// find - Return an iterator pointing to the first range that ends after
192     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
193     /// when searching large intervals.
194     ///
195     /// If Pos is contained in a LiveRange, that range is returned.
196     /// If Pos is in a hole, the following LiveRange is returned.
197     /// If Pos is beyond endIndex, end() is returned.
198     iterator find(SlotIndex Pos);
199
200     const_iterator find(SlotIndex Pos) const {
201       return const_cast<LiveInterval*>(this)->find(Pos);
202     }
203
204     void clear() {
205       valnos.clear();
206       ranges.clear();
207     }
208
209     bool hasAtLeastOneValue() const { return !valnos.empty(); }
210
211     bool containsOneValue() const { return valnos.size() == 1; }
212
213     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
214
215     /// getValNumInfo - Returns pointer to the specified val#.
216     ///
217     inline VNInfo *getValNumInfo(unsigned ValNo) {
218       return valnos[ValNo];
219     }
220     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
221       return valnos[ValNo];
222     }
223
224     /// containsValue - Returns true if VNI belongs to this interval.
225     bool containsValue(const VNInfo *VNI) const {
226       return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
227     }
228
229     /// getNextValue - Create a new value number and return it.  MIIdx specifies
230     /// the instruction that defines the value number.
231     VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
232       VNInfo *VNI =
233         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
234       valnos.push_back(VNI);
235       return VNI;
236     }
237
238     /// createDeadDef - Make sure the interval has a value defined at Def.
239     /// If one already exists, return it. Otherwise allocate a new value and
240     /// add liveness for a dead def.
241     VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
242
243     /// Create a copy of the given value. The new value will be identical except
244     /// for the Value number.
245     VNInfo *createValueCopy(const VNInfo *orig,
246                             VNInfo::Allocator &VNInfoAllocator) {
247       VNInfo *VNI =
248         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
249       valnos.push_back(VNI);
250       return VNI;
251     }
252
253     /// RenumberValues - Renumber all values in order of appearance and remove
254     /// unused values.
255     void RenumberValues(LiveIntervals &lis);
256
257     /// MergeValueNumberInto - This method is called when two value nubmers
258     /// are found to be equivalent.  This eliminates V1, replacing all
259     /// LiveRanges with the V1 value number with the V2 value number.  This can
260     /// cause merging of V1/V2 values numbers and compaction of the value space.
261     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
262
263     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
264     /// in RHS into this live interval as the specified value number.
265     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
266     /// current interval, it will replace the value numbers of the overlaped
267     /// live ranges with the specified value number.
268     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
269
270     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
271     /// in RHS into this live interval as the specified value number.
272     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
273     /// current interval, but only if the overlapping LiveRanges have the
274     /// specified value number.
275     void MergeValueInAsValue(const LiveInterval &RHS,
276                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
277
278     /// Copy - Copy the specified live interval. This copies all the fields
279     /// except for the register of the interval.
280     void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
281               VNInfo::Allocator &VNInfoAllocator);
282
283     bool empty() const { return ranges.empty(); }
284
285     /// beginIndex - Return the lowest numbered slot covered by interval.
286     SlotIndex beginIndex() const {
287       assert(!empty() && "Call to beginIndex() on empty interval.");
288       return ranges.front().start;
289     }
290
291     /// endNumber - return the maximum point of the interval of the whole,
292     /// exclusive.
293     SlotIndex endIndex() const {
294       assert(!empty() && "Call to endIndex() on empty interval.");
295       return ranges.back().end;
296     }
297
298     bool expiredAt(SlotIndex index) const {
299       return index >= endIndex();
300     }
301
302     bool liveAt(SlotIndex index) const {
303       const_iterator r = find(index);
304       return r != end() && r->start <= index;
305     }
306
307     /// killedAt - Return true if a live range ends at index. Note that the kill
308     /// point is not contained in the half-open live range. It is usually the
309     /// getDefIndex() slot following its last use.
310     bool killedAt(SlotIndex index) const {
311       const_iterator r = find(index.getRegSlot(true));
312       return r != end() && r->end == index;
313     }
314
315     /// killedInRange - Return true if the interval has kills in [Start,End).
316     /// Note that the kill point is considered the end of a live range, so it is
317     /// not contained in the live range. If a live range ends at End, it won't
318     /// be counted as a kill by this method.
319     bool killedInRange(SlotIndex Start, SlotIndex End) const;
320
321     /// getLiveRangeContaining - Return the live range that contains the
322     /// specified index, or null if there is none.
323     const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
324       const_iterator I = FindLiveRangeContaining(Idx);
325       return I == end() ? 0 : &*I;
326     }
327
328     /// getLiveRangeContaining - Return the live range that contains the
329     /// specified index, or null if there is none.
330     LiveRange *getLiveRangeContaining(SlotIndex Idx) {
331       iterator I = FindLiveRangeContaining(Idx);
332       return I == end() ? 0 : &*I;
333     }
334
335     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
336     VNInfo *getVNInfoAt(SlotIndex Idx) const {
337       const_iterator I = FindLiveRangeContaining(Idx);
338       return I == end() ? 0 : I->valno;
339     }
340
341     /// getVNInfoBefore - Return the VNInfo that is live up to but not
342     /// necessarilly including Idx, or NULL. Use this to find the reaching def
343     /// used by an instruction at this SlotIndex position.
344     VNInfo *getVNInfoBefore(SlotIndex Idx) const {
345       const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
346       return I == end() ? 0 : I->valno;
347     }
348
349     /// FindLiveRangeContaining - Return an iterator to the live range that
350     /// contains the specified index, or end() if there is none.
351     iterator FindLiveRangeContaining(SlotIndex Idx) {
352       iterator I = find(Idx);
353       return I != end() && I->start <= Idx ? I : end();
354     }
355
356     const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
357       const_iterator I = find(Idx);
358       return I != end() && I->start <= Idx ? I : end();
359     }
360
361     /// overlaps - Return true if the intersection of the two live intervals is
362     /// not empty.
363     bool overlaps(const LiveInterval& other) const {
364       if (other.empty())
365         return false;
366       return overlapsFrom(other, other.begin());
367     }
368
369     /// overlaps - Return true if the live interval overlaps a range specified
370     /// by [Start, End).
371     bool overlaps(SlotIndex Start, SlotIndex End) const;
372
373     /// overlapsFrom - Return true if the intersection of the two live intervals
374     /// is not empty.  The specified iterator is a hint that we can begin
375     /// scanning the Other interval starting at I.
376     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
377
378     /// addRange - Add the specified LiveRange to this interval, merging
379     /// intervals as appropriate.  This returns an iterator to the inserted live
380     /// range (which may have grown since it was inserted.
381     void addRange(LiveRange LR) {
382       addRangeFrom(LR, ranges.begin());
383     }
384
385     /// extendInBlock - If this interval is live before Kill in the basic block
386     /// that starts at StartIdx, extend it to be live up to Kill, and return
387     /// the value. If there is no live range before Kill, return NULL.
388     VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
389
390     /// join - Join two live intervals (this, and other) together.  This applies
391     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
392     /// the intervals are not joinable, this aborts.
393     void join(LiveInterval &Other,
394               const int *ValNoAssignments,
395               const int *RHSValNoAssignments,
396               SmallVector<VNInfo*, 16> &NewVNInfo,
397               MachineRegisterInfo *MRI);
398
399     /// isInOneLiveRange - Return true if the range specified is entirely in the
400     /// a single LiveRange of the live interval.
401     bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
402       const_iterator r = find(Start);
403       return r != end() && r->containsRange(Start, End);
404     }
405
406     /// removeRange - Remove the specified range from this interval.  Note that
407     /// the range must be a single LiveRange in its entirety.
408     void removeRange(SlotIndex Start, SlotIndex End,
409                      bool RemoveDeadValNo = false);
410
411     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
412       removeRange(LR.start, LR.end, RemoveDeadValNo);
413     }
414
415     /// removeValNo - Remove all the ranges defined by the specified value#.
416     /// Also remove the value# from value# list.
417     void removeValNo(VNInfo *ValNo);
418
419     /// getSize - Returns the sum of sizes of all the LiveRange's.
420     ///
421     unsigned getSize() const;
422
423     /// Returns true if the live interval is zero length, i.e. no live ranges
424     /// span instructions. It doesn't pay to spill such an interval.
425     bool isZeroLength(SlotIndexes *Indexes) const {
426       for (const_iterator i = begin(), e = end(); i != e; ++i)
427         if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
428             i->end.getBaseIndex())
429           return false;
430       return true;
431     }
432
433     /// isSpillable - Can this interval be spilled?
434     bool isSpillable() const {
435       return weight != HUGE_VALF;
436     }
437
438     /// markNotSpillable - Mark interval as not spillable
439     void markNotSpillable() {
440       weight = HUGE_VALF;
441     }
442
443     bool operator<(const LiveInterval& other) const {
444       const SlotIndex &thisIndex = beginIndex();
445       const SlotIndex &otherIndex = other.beginIndex();
446       return (thisIndex < otherIndex ||
447               (thisIndex == otherIndex && reg < other.reg));
448     }
449
450     void print(raw_ostream &OS) const;
451     void dump() const;
452
453     /// \brief Walk the interval and assert if any invariants fail to hold.
454     ///
455     /// Note that this is a no-op when asserts are disabled.
456 #ifdef NDEBUG
457     void verify() const {}
458 #else
459     void verify() const;
460 #endif
461
462   private:
463
464     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
465     void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
466     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
467     void markValNoForDeletion(VNInfo *V);
468     void mergeIntervalRanges(const LiveInterval &RHS,
469                              VNInfo *LHSValNo = 0,
470                              const VNInfo *RHSValNo = 0);
471
472     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
473
474   };
475
476   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
477     LI.print(OS);
478     return OS;
479   }
480
481   /// LiveRangeQuery - Query information about a live range around a given
482   /// instruction. This class hides the implementation details of live ranges,
483   /// and it should be used as the primary interface for examining live ranges
484   /// around instructions.
485   ///
486   class LiveRangeQuery {
487     VNInfo *EarlyVal;
488     VNInfo *LateVal;
489     SlotIndex EndPoint;
490     bool Kill;
491
492   public:
493     /// Create a LiveRangeQuery for the given live range and instruction index.
494     /// The sub-instruction slot of Idx doesn't matter, only the instruction it
495     /// refers to is considered.
496     LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
497       : EarlyVal(0), LateVal(0), Kill(false) {
498       // Find the segment that enters the instruction.
499       LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
500       LiveInterval::const_iterator E = LI.end();
501       if (I == E)
502         return;
503       // Is this an instruction live-in segment?
504       if (SlotIndex::isEarlierInstr(I->start, Idx)) {
505         EarlyVal = I->valno;
506         EndPoint = I->end;
507         // Move to the potentially live-out segment.
508         if (SlotIndex::isSameInstr(Idx, I->end)) {
509           Kill = true;
510           if (++I == E)
511             return;
512         }
513       }
514       // I now points to the segment that may be live-through, or defined by
515       // this instr. Ignore segments starting after the current instr.
516       if (SlotIndex::isEarlierInstr(Idx, I->start))
517         return;
518       LateVal = I->valno;
519       EndPoint = I->end;
520     }
521
522     /// Return the value that is live-in to the instruction. This is the value
523     /// that will be read by the instruction's use operands. Return NULL if no
524     /// value is live-in.
525     VNInfo *valueIn() const {
526       return EarlyVal;
527     }
528
529     /// Return true if the live-in value is killed by this instruction. This
530     /// means that either the live range ends at the instruction, or it changes
531     /// value.
532     bool isKill() const {
533       return Kill;
534     }
535
536     /// Return true if this instruction has a dead def.
537     bool isDeadDef() const {
538       return EndPoint.isDead();
539     }
540
541     /// Return the value leaving the instruction, if any. This can be a
542     /// live-through value, or a live def. A dead def returns NULL.
543     VNInfo *valueOut() const {
544       return isDeadDef() ? 0 : LateVal;
545     }
546
547     /// Return the value defined by this instruction, if any. This includes
548     /// dead defs, it is the value created by the instruction's def operands.
549     VNInfo *valueDefined() const {
550       return EarlyVal == LateVal ? 0 : LateVal;
551     }
552
553     /// Return the end point of the last live range segment to interact with
554     /// the instruction, if any.
555     ///
556     /// The end point is an invalid SlotIndex only if the live range doesn't
557     /// intersect the instruction at all.
558     ///
559     /// The end point may be at or past the end of the instruction's basic
560     /// block. That means the value was live out of the block.
561     SlotIndex endPoint() const {
562       return EndPoint;
563     }
564   };
565
566   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
567   /// LiveInterval into equivalence clases of connected components. A
568   /// LiveInterval that has multiple connected components can be broken into
569   /// multiple LiveIntervals.
570   ///
571   /// Given a LiveInterval that may have multiple connected components, run:
572   ///
573   ///   unsigned numComps = ConEQ.Classify(LI);
574   ///   if (numComps > 1) {
575   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
576   ///     ConEQ.Distribute(LIS);
577   /// }
578
579   class ConnectedVNInfoEqClasses {
580     LiveIntervals &LIS;
581     IntEqClasses EqClass;
582
583     // Note that values a and b are connected.
584     void Connect(unsigned a, unsigned b);
585
586     unsigned Renumber();
587
588   public:
589     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
590
591     /// Classify - Classify the values in LI into connected components.
592     /// Return the number of connected components.
593     unsigned Classify(const LiveInterval *LI);
594
595     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
596     /// the equivalence class assigned the VNI.
597     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
598
599     /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
600     /// for each connected component. LIV must have a LiveInterval for each
601     /// connected component. The LiveIntervals in Liv[1..] must be empty.
602     /// Instructions using LIV[0] are rewritten.
603     void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
604
605   };
606
607 }
608 #endif