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