4d379cfa115c7e3a6fee4ca0d5f866dc63fb1c47
[oota-llvm.git] / lib / CodeGen / LiveIntervalUnion.h
1 //===-- LiveIntervalUnion.h - Live interval union data struct --*- 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 // LiveIntervalUnion is a union of live segments across multiple live virtual
11 // registers. This may be used during coalescing to represent a congruence
12 // class, or during register allocation to model liveness of a physical
13 // register.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_CODEGEN_LIVEINTERVALUNION
18 #define LLVM_CODEGEN_LIVEINTERVALUNION
19
20 #include "llvm/CodeGen/LiveInterval.h"
21 #include <vector>
22 #include <set>
23
24 namespace llvm {
25
26 #ifndef NDEBUG
27 // forward declaration
28 template <unsigned Element> class SparseBitVector;
29 typedef SparseBitVector<128> LvrBitSet;
30 #endif
31
32 /// A LiveSegment is a copy of a LiveRange object used within
33 /// LiveIntervalUnion. LiveSegment additionally contains a pointer to its
34 /// original live virtual register (LiveInterval). This allows quick lookup of
35 /// the live virtual register as we iterate over live segments in a union. Note
36 /// that LiveRange is misnamed and actually represents only a single contiguous
37 /// interval within a virtual register's liveness. To limit confusion, in this
38 /// file we refer it as a live segment.
39 ///
40 /// Note: This currently represents a half-open interval [start,end).
41 /// If LiveRange is modified to represent a closed interval, so should this.
42 struct LiveSegment {
43   SlotIndex start;
44   SlotIndex end;
45   LiveInterval *liveVirtReg;
46
47   LiveSegment(SlotIndex s, SlotIndex e, LiveInterval *lvr)
48     : start(s), end(e), liveVirtReg(lvr) {}
49
50   bool operator==(const LiveSegment &ls) const {
51     return start == ls.start && end == ls.end && liveVirtReg == ls.liveVirtReg;
52   }
53
54   bool operator!=(const LiveSegment &ls) const {
55     return !operator==(ls);
56   }
57
58   // Order segments by starting point only--we expect them to be disjoint.
59   bool operator<(const LiveSegment &ls) const { return start < ls.start; }
60
61   void dump() const;
62   void print(raw_ostream &os) const;
63 };
64
65 inline bool operator<(SlotIndex V, const LiveSegment &ls) {
66   return V < ls.start;
67 }
68
69 inline bool operator<(const LiveSegment &ls, SlotIndex V) {
70   return ls.start < V;
71 }
72
73 /// Compare a live virtual register segment to a LiveIntervalUnion segment.
74 inline bool overlap(const LiveRange &lvrSeg, const LiveSegment &liuSeg) {
75   return lvrSeg.start < liuSeg.end && liuSeg.start < lvrSeg.end;
76 }
77
78 template <> struct isPodLike<LiveSegment> { static const bool value = true; };
79
80 raw_ostream& operator<<(raw_ostream& os, const LiveSegment &ls);
81
82 /// Abstraction to provide info for the representative register.
83 class AbstractRegisterDescription {
84 public:
85   virtual const char *getName(unsigned reg) const = 0;
86 };
87   
88 /// Union of live intervals that are strong candidates for coalescing into a
89 /// single register (either physical or virtual depending on the context).  We
90 /// expect the constituent live intervals to be disjoint, although we may
91 /// eventually make exceptions to handle value-based interference.
92 class LiveIntervalUnion {
93   // A set of live virtual register segments that supports fast insertion,
94   // intersection, and removal. 
95   //
96   // FIXME: std::set is a placeholder until we decide how to
97   // efficiently represent it. Probably need to roll our own B-tree.
98   typedef std::set<LiveSegment> LiveSegments;
99
100   // A set of live virtual registers. Elements have type LiveInterval, where
101   // each element represents the liveness of a single live virtual register.
102   // This is traditionally known as a live range, but we refer is as a live
103   // virtual register to avoid confusing it with the misnamed LiveRange
104   // class.
105   typedef std::vector<LiveInterval*> LiveVirtRegs;
106
107 public:
108   // SegmentIter can advance to the next segment ordered by starting position
109   // which may belong to a different live virtual register. We also must be able
110   // to reach the current segment's containing virtual register.
111   typedef LiveSegments::iterator SegmentIter;
112
113   class InterferenceResult;
114   class Query;
115
116 private:
117   unsigned repReg_;        // representative register number
118   LiveSegments segments_;  // union of virtual reg segements
119
120 public:
121   // default ctor avoids placement new
122   LiveIntervalUnion() : repReg_(0) {}
123
124   // Initialize the union by associating it with a representative register
125   // number.
126   void init(unsigned repReg) { repReg_ = repReg; }
127
128   // Iterate over all segments in the union of live virtual registers ordered
129   // by their starting position.
130   SegmentIter begin() { return segments_.begin(); }
131   SegmentIter end() { return segments_.end(); }
132
133   // Return an iterator to the first segment after or including begin that
134   // intersects with lvrSeg.
135   SegmentIter upperBound(SegmentIter begin, const LiveSegment &seg);
136
137   // Add a live virtual register to this union and merge its segments.
138   // Holds a nonconst reference to the LVR for later maniplution.
139   void unify(LiveInterval &lvr);
140
141   // Remove a live virtual register's segments from this union.
142   void extract(const LiveInterval &lvr);
143
144   void dump(const AbstractRegisterDescription *regInfo) const;
145
146   // If tri != NULL, use it to decode repReg_
147   void print(raw_ostream &os, const AbstractRegisterDescription *rdesc) const;
148   
149 #ifndef NDEBUG
150   // Verify the live intervals in this union and add them to the visited set.
151   void verify(LvrBitSet& visitedVRegs);
152 #endif
153
154   /// Cache a single interference test result in the form of two intersecting
155   /// segments. This allows efficiently iterating over the interferences. The
156   /// iteration logic is handled by LiveIntervalUnion::Query which may
157   /// filter interferences depending on the type of query.
158   class InterferenceResult {
159     friend class Query;
160
161     LiveInterval::iterator lvrSegI_; // current position in _lvr
162     SegmentIter liuSegI_;            // current position in _liu
163     
164     // Internal ctor.
165     InterferenceResult(LiveInterval::iterator lvrSegI, SegmentIter liuSegI)
166       : lvrSegI_(lvrSegI), liuSegI_(liuSegI) {}
167
168   public:
169     // Public default ctor.
170     InterferenceResult(): lvrSegI_(), liuSegI_() {}
171
172     // Note: this interface provides raw access to the iterators because the
173     // result has no way to tell if it's valid to dereference them.
174
175     // Access the lvr segment. 
176     const LiveInterval::iterator &lvrSegPos() const { return lvrSegI_; }
177
178     // Access the liu segment.
179     const SegmentIter &liuSegPos() const { return liuSegI_; }
180
181     bool operator==(const InterferenceResult &ir) const {
182       return lvrSegI_ == ir.lvrSegI_ && liuSegI_ == ir.liuSegI_;
183     }
184     bool operator!=(const InterferenceResult &ir) const {
185       return !operator==(ir);
186     }
187   };
188
189   /// Query interferences between a single live virtual register and a live
190   /// interval union.
191   class Query {
192     LiveIntervalUnion *liu_;
193     LiveInterval *lvr_;
194     InterferenceResult firstInterference_;
195     // TBD: interfering vregs
196
197   public:
198     Query(): liu_(), lvr_() {}
199
200     Query(LiveInterval *lvr, LiveIntervalUnion *liu): liu_(liu), lvr_(lvr) {}
201
202     void clear() {
203       liu_ = NULL;
204       lvr_ = NULL;
205       firstInterference_ = InterferenceResult();
206     }
207     
208     void init(LiveInterval *lvr, LiveIntervalUnion *liu) {
209       if (lvr_ == lvr) {
210         // We currently allow query objects to be reused acrossed live virtual
211         // registers, but always for the same live interval union.
212         assert(liu_ == liu && "inconsistent initialization");
213         // Retain cached results, e.g. firstInterference.
214         return;
215       }
216       liu_ = liu;
217       lvr_ = lvr;
218       // Clear cached results.
219       firstInterference_ = InterferenceResult();
220     }
221
222     LiveInterval &lvr() const { assert(lvr_ && "uninitialized"); return *lvr_; }
223
224     bool isInterference(const InterferenceResult &ir) const {
225       if (ir.lvrSegI_ != lvr_->end()) {
226         assert(overlap(*ir.lvrSegI_, *ir.liuSegI_) &&
227                "invalid segment iterators");
228         return true;
229       }
230       return false;
231     }
232
233     // Does this live virtual register interfere with the union.
234     bool checkInterference() { return isInterference(firstInterference()); }
235
236     // Get the first pair of interfering segments, or a noninterfering result.
237     // This initializes the firstInterference_ cache.
238     InterferenceResult firstInterference();
239
240     // Treat the result as an iterator and advance to the next interfering pair
241     // of segments. Visiting each unique interfering pairs means that the same
242     // lvr or liu segment may be visited multiple times.
243     bool nextInterference(InterferenceResult &ir) const;
244         
245     // TBD: bool collectInterferingVirtRegs(unsigned maxInterference)
246
247   private:
248     // Private interface for queries
249     void findIntersection(InterferenceResult &ir) const;
250   };
251 };
252
253 } // end namespace llvm
254
255 #endif // !defined(LLVM_CODEGEN_LIVEINTERVALUNION)