93d32d8edba80b4c12071785b5f2d37bed5ffacc
[oota-llvm.git] / lib / CodeGen / LiveInterval.cpp
1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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' abd 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 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Target/MRegisterInfo.h"
24 #include <algorithm>
25 #include <iostream>
26 #include <map>
27 using namespace llvm;
28
29 // An example for liveAt():
30 //
31 // this = [1,4), liveAt(0) will return false. The instruction defining this
32 // spans slots [0,3]. The interval belongs to an spilled definition of the
33 // variable it represents. This is because slot 1 is used (def slot) and spans
34 // up to slot 3 (store slot).
35 //
36 bool LiveInterval::liveAt(unsigned I) const {
37   Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
38
39   if (r == ranges.begin())
40     return false;
41
42   --r;
43   return r->contains(I);
44 }
45
46 // overlaps - Return true if the intersection of the two live intervals is
47 // not empty.
48 //
49 // An example for overlaps():
50 //
51 // 0: A = ...
52 // 4: B = ...
53 // 8: C = A + B ;; last use of A
54 //
55 // The live intervals should look like:
56 //
57 // A = [3, 11)
58 // B = [7, x)
59 // C = [11, y)
60 //
61 // A->overlaps(C) should return false since we want to be able to join
62 // A and C.
63 //
64 bool LiveInterval::overlapsFrom(const LiveInterval& other,
65                                 const_iterator StartPos) const {
66   const_iterator i = begin();
67   const_iterator ie = end();
68   const_iterator j = StartPos;
69   const_iterator je = other.end();
70
71   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
72          StartPos != other.end() && "Bogus start position hint!");
73
74   if (i->start < j->start) {
75     i = std::upper_bound(i, ie, j->start);
76     if (i != ranges.begin()) --i;
77   } else if (j->start < i->start) {
78     ++StartPos;
79     if (StartPos != other.end() && StartPos->start <= i->start) {
80       assert(StartPos < other.end() && i < end());
81       j = std::upper_bound(j, je, i->start);
82       if (j != other.ranges.begin()) --j;
83     }
84   } else {
85     return true;
86   }
87
88   if (j == je) return false;
89
90   while (i != ie) {
91     if (i->start > j->start) {
92       std::swap(i, j);
93       std::swap(ie, je);
94     }
95
96     if (i->end > j->start)
97       return true;
98     ++i;
99   }
100
101   return false;
102 }
103
104 /// NontrivialOverlap - Check to see if the two live ranges specified by i and j
105 /// overlap.  If so, check to see if they have value numbers that are not 
106 /// iIdx/jIdx respectively.  If both conditions are true, return true.
107 static inline bool NontrivialOverlap(LiveInterval::Ranges::const_iterator i,
108                                      LiveInterval::Ranges::const_iterator j,
109                                      unsigned iIdx, unsigned jIdx) {
110   if (i->start == j->start) {
111     // If this is not the allowed value merge, we cannot join.
112     if (i->ValId != iIdx || j->ValId != jIdx)
113       return true;
114   } else if (i->start < j->start) {
115     if (i->end > j->start && i->ValId != iIdx || j->ValId != jIdx) {
116       return true;
117     }
118   } else {
119     if (j->end > i->start &&
120         i->ValId != iIdx || j->ValId != jIdx)
121       return true;
122   }
123   
124   return false;
125 }
126
127 /// joinable - Two intervals are joinable if the either don't overlap at all
128 /// or if the destination of the copy is a single assignment value, and it
129 /// only overlaps with one value in the source interval.
130 bool LiveInterval::joinable(const LiveInterval &other, unsigned CopyIdx) const {
131   const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1);
132   const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
133   assert(SourceLR && DestLR && "Not joining due to a copy?");
134   unsigned OtherValIdx = SourceLR->ValId;
135   unsigned ThisValIdx = DestLR->ValId;
136
137   Ranges::const_iterator i = ranges.begin();
138   Ranges::const_iterator ie = ranges.end();
139   Ranges::const_iterator j = other.ranges.begin();
140   Ranges::const_iterator je = other.ranges.end();
141
142   if (i->start < j->start) {
143     i = std::upper_bound(i, ie, j->start);
144     if (i != ranges.begin()) --i;
145   } else if (j->start < i->start) {
146     j = std::upper_bound(j, je, i->start);
147     if (j != other.ranges.begin()) --j;
148   }
149
150   while (i != ie && j != je) {
151     if (NontrivialOverlap(i, j, ThisValIdx, OtherValIdx))
152       return false;
153     
154     if (i->end < j->end)
155       ++i;
156     else
157       ++j;
158   }
159
160   return true;
161 }
162
163
164 /// extendIntervalEndTo - This method is used when we want to extend the range
165 /// specified by I to end at the specified endpoint.  To do this, we should
166 /// merge and eliminate all ranges that this will overlap with.  The iterator is
167 /// not invalidated.
168 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
169   assert(I != ranges.end() && "Not a valid interval!");
170   unsigned ValId = I->ValId;
171
172   // Search for the first interval that we can't merge with.
173   Ranges::iterator MergeTo = next(I);
174   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
175     assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
176   }
177
178   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
179   I->end = std::max(NewEnd, prior(MergeTo)->end);
180
181   // Erase any dead ranges
182   ranges.erase(next(I), MergeTo);
183 }
184
185
186 /// extendIntervalStartTo - This method is used when we want to extend the range
187 /// specified by I to start at the specified endpoint.  To do this, we should
188 /// merge and eliminate all ranges that this will overlap with.
189 LiveInterval::Ranges::iterator
190 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
191   assert(I != ranges.end() && "Not a valid interval!");
192   unsigned ValId = I->ValId;
193
194   // Search for the first interval that we can't merge with.
195   Ranges::iterator MergeTo = I;
196   do {
197     if (MergeTo == ranges.begin()) {
198       I->start = NewStart;
199       ranges.erase(MergeTo, I);
200       return I;
201     }
202     assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
203     --MergeTo;
204   } while (NewStart <= MergeTo->start);
205
206   // If we start in the middle of another interval, just delete a range and
207   // extend that interval.
208   if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) {
209     MergeTo->end = I->end;
210   } else {
211     // Otherwise, extend the interval right after.
212     ++MergeTo;
213     MergeTo->start = NewStart;
214     MergeTo->end = I->end;
215   }
216
217   ranges.erase(next(MergeTo), next(I));
218   return MergeTo;
219 }
220
221 LiveInterval::Ranges::iterator
222 LiveInterval::addRangeFrom(LiveRange LR, Ranges::iterator From) {
223   unsigned Start = LR.start, End = LR.end;
224   Ranges::iterator it = std::upper_bound(From, ranges.end(), Start);
225
226   // If the inserted interval starts in the middle or right at the end of
227   // another interval, just extend that interval to contain the range of LR.
228   if (it != ranges.begin()) {
229     Ranges::iterator B = prior(it);
230     if (LR.ValId == B->ValId) {
231       if (B->start <= Start && B->end >= Start) {
232         extendIntervalEndTo(B, End);
233         return B;
234       }
235     } else {
236       // Check to make sure that we are not overlapping two live ranges with
237       // different ValId's.
238       assert(B->end <= Start &&
239              "Cannot overlap two LiveRanges with differing ValID's"
240              " (did you def the same reg twice in a MachineInstr?)");
241     }
242   }
243
244   // Otherwise, if this range ends in the middle of, or right next to, another
245   // interval, merge it into that interval.
246   if (it != ranges.end())
247     if (LR.ValId == it->ValId) {
248       if (it->start <= End) {
249         it = extendIntervalStartTo(it, Start);
250
251         // If LR is a complete superset of an interval, we may need to grow its
252         // endpoint as well.
253         if (End > it->end)
254           extendIntervalEndTo(it, End);
255         return it;
256       }
257     } else {
258       // Check to make sure that we are not overlapping two live ranges with
259       // different ValId's.
260       assert(it->start >= End &&
261              "Cannot overlap two LiveRanges with differing ValID's");
262     }
263
264   // Otherwise, this is just a new range that doesn't interact with anything.
265   // Insert it.
266   return ranges.insert(it, LR);
267 }
268
269
270 /// removeRange - Remove the specified range from this interval.  Note that
271 /// the range must already be in this interval in its entirety.
272 void LiveInterval::removeRange(unsigned Start, unsigned End) {
273   // Find the LiveRange containing this span.
274   Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
275   assert(I != ranges.begin() && "Range is not in interval!");
276   --I;
277   assert(I->contains(Start) && I->contains(End-1) &&
278          "Range is not entirely in interval!");
279
280   // If the span we are removing is at the start of the LiveRange, adjust it.
281   if (I->start == Start) {
282     if (I->end == End)
283       ranges.erase(I);  // Removed the whole LiveRange.
284     else
285       I->start = End;
286     return;
287   }
288
289   // Otherwise if the span we are removing is at the end of the LiveRange,
290   // adjust the other way.
291   if (I->end == End) {
292     I->end = Start;
293     return;
294   }
295
296   // Otherwise, we are splitting the LiveRange into two pieces.
297   unsigned OldEnd = I->end;
298   I->end = Start;   // Trim the old interval.
299
300   // Insert the new one.
301   ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId));
302 }
303
304 /// getLiveRangeContaining - Return the live range that contains the
305 /// specified index, or null if there is none.
306 const LiveRange *LiveInterval::getLiveRangeContaining(unsigned Idx) const {
307   Ranges::const_iterator It = std::upper_bound(ranges.begin(),ranges.end(),Idx);
308   if (It != ranges.begin()) {
309     const LiveRange &LR = *prior(It);
310     if (LR.contains(Idx))
311       return &LR;
312   }
313
314   return 0;
315 }
316
317
318
319 /// join - Join two live intervals (this, and other) together.  This operation
320 /// is the result of a copy instruction in the source program, that occurs at
321 /// index 'CopyIdx' that copies from 'Other' to 'this'.
322 void LiveInterval::join(LiveInterval &Other, unsigned CopyIdx) {
323   const LiveRange *SourceLR = Other.getLiveRangeContaining(CopyIdx-1);
324   const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
325   assert(SourceLR && DestLR && "Not joining due to a copy?");
326   unsigned MergedSrcValIdx = SourceLR->ValId;
327   unsigned MergedDstValIdx = DestLR->ValId;
328
329   // Try to do the least amount of work possible.  In particular, if there are
330   // more liverange chunks in the other set than there are in the 'this' set,
331   // swap sets to merge the fewest chunks in possible.
332   if (Other.ranges.size() > ranges.size()) {
333     std::swap(MergedSrcValIdx, MergedDstValIdx);
334     std::swap(ranges, Other.ranges);
335     std::swap(NumValues, Other.NumValues);
336   }
337
338   // Join the ranges of other into the ranges of this interval.
339   Ranges::iterator InsertPos = ranges.begin();
340   std::map<unsigned, unsigned> Dst2SrcIdxMap;
341   for (Ranges::iterator I = Other.ranges.begin(),
342          E = Other.ranges.end(); I != E; ++I) {
343     // Map the ValId in the other live range to the current live range.
344     if (I->ValId == MergedSrcValIdx)
345       I->ValId = MergedDstValIdx;
346     else {
347       unsigned &NV = Dst2SrcIdxMap[I->ValId];
348       if (NV == 0) NV = getNextValue();
349       I->ValId = NV;
350     }
351
352     InsertPos = addRangeFrom(*I, InsertPos);
353   }
354
355   weight += Other.weight;
356 }
357
358 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
359   return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")";
360 }
361
362 void LiveRange::dump() const {
363   std::cerr << *this << "\n";
364 }
365
366 void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const {
367   if (MRI && MRegisterInfo::isPhysicalRegister(reg))
368     OS << MRI->getName(reg);
369   else
370     OS << "%reg" << reg;
371
372   OS << ',' << weight;
373
374   if (empty())
375     OS << "EMPTY";
376   else {
377     OS << " = ";
378     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
379            E = ranges.end(); I != E; ++I)
380     OS << *I;
381   }
382 }
383
384 void LiveInterval::dump() const {
385   std::cerr << *this << "\n";
386 }