472165069746d216da6916e19be109a95a425822
[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/SmallSet.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include <algorithm>
27 #include <map>
28 #include <ostream>
29 using namespace llvm;
30
31 // An example for liveAt():
32 //
33 // this = [1,4), liveAt(0) will return false. The instruction defining this
34 // spans slots [0,3]. The interval belongs to an spilled definition of the
35 // variable it represents. This is because slot 1 is used (def slot) and spans
36 // up to slot 3 (store slot).
37 //
38 bool LiveInterval::liveAt(unsigned I) const {
39   Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
40
41   if (r == ranges.begin())
42     return false;
43
44   --r;
45   return r->contains(I);
46 }
47
48 // overlaps - Return true if the intersection of the two live intervals is
49 // not empty.
50 //
51 // An example for overlaps():
52 //
53 // 0: A = ...
54 // 4: B = ...
55 // 8: C = A + B ;; last use of A
56 //
57 // The live intervals should look like:
58 //
59 // A = [3, 11)
60 // B = [7, x)
61 // C = [11, y)
62 //
63 // A->overlaps(C) should return false since we want to be able to join
64 // A and C.
65 //
66 bool LiveInterval::overlapsFrom(const LiveInterval& other,
67                                 const_iterator StartPos) const {
68   const_iterator i = begin();
69   const_iterator ie = end();
70   const_iterator j = StartPos;
71   const_iterator je = other.end();
72
73   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
74          StartPos != other.end() && "Bogus start position hint!");
75
76   if (i->start < j->start) {
77     i = std::upper_bound(i, ie, j->start);
78     if (i != ranges.begin()) --i;
79   } else if (j->start < i->start) {
80     ++StartPos;
81     if (StartPos != other.end() && StartPos->start <= i->start) {
82       assert(StartPos < other.end() && i < end());
83       j = std::upper_bound(j, je, i->start);
84       if (j != other.ranges.begin()) --j;
85     }
86   } else {
87     return true;
88   }
89
90   if (j == je) return false;
91
92   while (i != ie) {
93     if (i->start > j->start) {
94       std::swap(i, j);
95       std::swap(ie, je);
96     }
97
98     if (i->end > j->start)
99       return true;
100     ++i;
101   }
102
103   return false;
104 }
105
106 /// extendIntervalEndTo - This method is used when we want to extend the range
107 /// specified by I to end at the specified endpoint.  To do this, we should
108 /// merge and eliminate all ranges that this will overlap with.  The iterator is
109 /// not invalidated.
110 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
111   assert(I != ranges.end() && "Not a valid interval!");
112   VNInfo *ValNo = I->valno;
113   unsigned OldEnd = I->end;
114
115   // Search for the first interval that we can't merge with.
116   Ranges::iterator MergeTo = next(I);
117   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
118     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
119   }
120
121   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
122   I->end = std::max(NewEnd, prior(MergeTo)->end);
123
124   // Erase any dead ranges.
125   ranges.erase(next(I), MergeTo);
126
127   // Update kill info.
128   removeKills(ValNo, OldEnd, I->end-1);
129
130   // If the newly formed range now touches the range after it and if they have
131   // the same value number, merge the two ranges into one range.
132   Ranges::iterator Next = next(I);
133   if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
134     I->end = Next->end;
135     ranges.erase(Next);
136   }
137 }
138
139
140 /// extendIntervalStartTo - This method is used when we want to extend the range
141 /// specified by I to start at the specified endpoint.  To do this, we should
142 /// merge and eliminate all ranges that this will overlap with.
143 LiveInterval::Ranges::iterator
144 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
145   assert(I != ranges.end() && "Not a valid interval!");
146   VNInfo *ValNo = I->valno;
147
148   // Search for the first interval that we can't merge with.
149   Ranges::iterator MergeTo = I;
150   do {
151     if (MergeTo == ranges.begin()) {
152       I->start = NewStart;
153       ranges.erase(MergeTo, I);
154       return I;
155     }
156     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
157     --MergeTo;
158   } while (NewStart <= MergeTo->start);
159
160   // If we start in the middle of another interval, just delete a range and
161   // extend that interval.
162   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
163     MergeTo->end = I->end;
164   } else {
165     // Otherwise, extend the interval right after.
166     ++MergeTo;
167     MergeTo->start = NewStart;
168     MergeTo->end = I->end;
169   }
170
171   ranges.erase(next(MergeTo), next(I));
172   return MergeTo;
173 }
174
175 LiveInterval::iterator
176 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
177   unsigned Start = LR.start, End = LR.end;
178   iterator it = std::upper_bound(From, ranges.end(), Start);
179
180   // If the inserted interval starts in the middle or right at the end of
181   // another interval, just extend that interval to contain the range of LR.
182   if (it != ranges.begin()) {
183     iterator B = prior(it);
184     if (LR.valno == B->valno) {
185       if (B->start <= Start && B->end >= Start) {
186         extendIntervalEndTo(B, End);
187         return B;
188       }
189     } else {
190       // Check to make sure that we are not overlapping two live ranges with
191       // different valno's.
192       assert(B->end <= Start &&
193              "Cannot overlap two LiveRanges with differing ValID's"
194              " (did you def the same reg twice in a MachineInstr?)");
195     }
196   }
197
198   // Otherwise, if this range ends in the middle of, or right next to, another
199   // interval, merge it into that interval.
200   if (it != ranges.end())
201     if (LR.valno == it->valno) {
202       if (it->start <= End) {
203         it = extendIntervalStartTo(it, Start);
204
205         // If LR is a complete superset of an interval, we may need to grow its
206         // endpoint as well.
207         if (End > it->end)
208           extendIntervalEndTo(it, End);
209         else if (End < it->end)
210           // Overlapping intervals, there might have been a kill here.
211           removeKill(it->valno, End);
212         return it;
213       }
214     } else {
215       // Check to make sure that we are not overlapping two live ranges with
216       // different valno's.
217       assert(it->start >= End &&
218              "Cannot overlap two LiveRanges with differing ValID's");
219     }
220
221   // Otherwise, this is just a new range that doesn't interact with anything.
222   // Insert it.
223   return ranges.insert(it, LR);
224 }
225
226
227 /// removeRange - Remove the specified range from this interval.  Note that
228 /// the range must already be in this interval in its entirety.
229 void LiveInterval::removeRange(unsigned Start, unsigned End) {
230   // Find the LiveRange containing this span.
231   Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
232   assert(I != ranges.begin() && "Range is not in interval!");
233   --I;
234   assert(I->contains(Start) && I->contains(End-1) &&
235          "Range is not entirely in interval!");
236
237   // If the span we are removing is at the start of the LiveRange, adjust it.
238   if (I->start == Start) {
239     if (I->end == End) {
240       removeKills(I->valno, Start, End);
241       ranges.erase(I);  // Removed the whole LiveRange.
242     } else
243       I->start = End;
244     return;
245   }
246
247   // Otherwise if the span we are removing is at the end of the LiveRange,
248   // adjust the other way.
249   if (I->end == End) {
250     removeKills(I->valno, Start, End);
251     I->end = Start;
252     return;
253   }
254
255   // Otherwise, we are splitting the LiveRange into two pieces.
256   unsigned OldEnd = I->end;
257   I->end = Start;   // Trim the old interval.
258
259   // Insert the new one.
260   ranges.insert(next(I), LiveRange(End, OldEnd, I->valno));
261 }
262
263 /// getLiveRangeContaining - Return the live range that contains the
264 /// specified index, or null if there is none.
265 LiveInterval::const_iterator 
266 LiveInterval::FindLiveRangeContaining(unsigned Idx) const {
267   const_iterator It = std::upper_bound(begin(), end(), Idx);
268   if (It != ranges.begin()) {
269     --It;
270     if (It->contains(Idx))
271       return It;
272   }
273
274   return end();
275 }
276
277 LiveInterval::iterator 
278 LiveInterval::FindLiveRangeContaining(unsigned Idx) {
279   iterator It = std::upper_bound(begin(), end(), Idx);
280   if (It != begin()) {
281     --It;
282     if (It->contains(Idx))
283       return It;
284   }
285   
286   return end();
287 }
288
289 /// join - Join two live intervals (this, and other) together.  This applies
290 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
291 /// the intervals are not joinable, this aborts.
292 void LiveInterval::join(LiveInterval &Other, const int *LHSValNoAssignments,
293                         const int *RHSValNoAssignments, 
294                         SmallVector<VNInfo*, 16> &NewVNInfo) {
295   // Determine if any of our live range values are mapped.  This is uncommon, so
296   // we want to avoid the interval scan if not. 
297   bool MustMapCurValNos = false;
298   unsigned NumVals = getNumValNums();
299   unsigned NumNewVals = NewVNInfo.size();
300   for (unsigned i = 0; i != NumVals; ++i) {
301     unsigned LHSValID = LHSValNoAssignments[i];
302     if (i != LHSValID ||
303         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
304       MustMapCurValNos = true;
305   }
306
307   // If we have to apply a mapping to our base interval assignment, rewrite it
308   // now.
309   if (MustMapCurValNos) {
310     // Map the first live range.
311     iterator OutIt = begin();
312     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
313     ++OutIt;
314     for (iterator I = OutIt, E = end(); I != E; ++I) {
315       OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
316       
317       // If this live range has the same value # as its immediate predecessor,
318       // and if they are neighbors, remove one LiveRange.  This happens when we
319       // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
320       if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
321         (OutIt-1)->end = OutIt->end;
322       } else {
323         if (I != OutIt) {
324           OutIt->start = I->start;
325           OutIt->end = I->end;
326         }
327         
328         // Didn't merge, on to the next one.
329         ++OutIt;
330       }
331     }
332     
333     // If we merge some live ranges, chop off the end.
334     ranges.erase(OutIt, end());
335   }
336
337   // Remember assignements because val# ids are changing.
338   SmallVector<unsigned, 16> OtherAssignments;
339   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
340     OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
341
342   // Update val# info. Renumber them and make sure they all belong to this
343   // LiveInterval now. Also remove dead val#'s.
344   unsigned NumValNos = 0;
345   for (unsigned i = 0; i < NumNewVals; ++i) {
346     VNInfo *VNI = NewVNInfo[i];
347     if (VNI) {
348       if (i >= NumVals)
349         valnos.push_back(VNI);
350       else 
351         valnos[NumValNos] = VNI;
352       VNI->id = NumValNos++;  // Renumber val#.
353     }
354   }
355   if (NumNewVals < NumVals)
356     valnos.resize(NumNewVals);  // shrinkify
357
358   // Okay, now insert the RHS live ranges into the LHS.
359   iterator InsertPos = begin();
360   unsigned RangeNo = 0;
361   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
362     // Map the valno in the other live range to the current live range.
363     I->valno = NewVNInfo[OtherAssignments[RangeNo]];
364     assert(I->valno && "Adding a dead range?");
365     InsertPos = addRangeFrom(*I, InsertPos);
366   }
367
368   weight += Other.weight;
369   if (Other.preference && !preference)
370     preference = Other.preference;
371 }
372
373 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
374 /// interval as the specified value number.  The LiveRanges in RHS are
375 /// allowed to overlap with LiveRanges in the current interval, but only if
376 /// the overlapping LiveRanges have the specified value number.
377 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS, 
378                                         VNInfo *LHSValNo) {
379   // TODO: Make this more efficient.
380   iterator InsertPos = begin();
381   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
382     // Map the valno in the other live range to the current live range.
383     LiveRange Tmp = *I;
384     Tmp.valno = LHSValNo;
385     InsertPos = addRangeFrom(Tmp, InsertPos);
386   }
387 }
388
389
390 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
391 /// in RHS into this live interval as the specified value number.
392 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
393 /// current interval, it will replace the value numbers of the overlaped
394 /// live ranges with the specified value number.
395 void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS,
396                                      const VNInfo *RHSValNo, VNInfo *LHSValNo) {
397   SmallVector<VNInfo*, 4> ReplacedValNos;
398   iterator IP = begin();
399   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
400     if (I->valno != RHSValNo)
401       continue;
402     unsigned Start = I->start, End = I->end;
403     IP = std::upper_bound(IP, end(), Start);
404     // If the start of this range overlaps with an existing liverange, trim it.
405     if (IP != begin() && IP[-1].end > Start) {
406       if (IP->valno != LHSValNo) {
407         ReplacedValNos.push_back(IP->valno);
408         IP->valno = LHSValNo; // Update val#.
409       }
410       Start = IP[-1].end;
411       // Trimmed away the whole range?
412       if (Start >= End) continue;
413     }
414     // If the end of this range overlaps with an existing liverange, trim it.
415     if (IP != end() && End > IP->start) {
416       if (IP->valno != LHSValNo) {
417         ReplacedValNos.push_back(IP->valno);
418         IP->valno = LHSValNo;  // Update val#.
419       }
420       End = IP->start;
421       // If this trimmed away the whole range, ignore it.
422       if (Start == End) continue;
423     }
424     
425     // Map the valno in the other live range to the current live range.
426     IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
427   }
428
429
430   SmallSet<VNInfo*, 4> Seen;
431   for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
432     VNInfo *V1 = ReplacedValNos[i];
433     if (Seen.insert(V1)) {
434       bool isDead = true;
435       for (const_iterator I = begin(), E = end(); I != E; ++I)
436         if (I->valno == V1) {
437           isDead = false;
438           break;
439         }          
440       if (isDead) {
441         // Now that V1 is dead, remove it.  If it is the largest value number,
442         // just nuke it (and any other deleted values neighboring it), otherwise
443         // mark it as ~1U so it can be nuked later.
444         if (V1->id == getNumValNums()-1) {
445           do {
446             VNInfo *VNI = valnos.back();
447             valnos.pop_back();
448             VNI->~VNInfo();
449           } while (valnos.back()->def == ~1U);
450         } else {
451           V1->def = ~1U;
452         }
453       }
454     }
455   }
456 }
457
458
459 /// MergeInClobberRanges - For any live ranges that are not defined in the
460 /// current interval, but are defined in the Clobbers interval, mark them
461 /// used with an unknown definition value.
462 void LiveInterval::MergeInClobberRanges(const LiveInterval &Clobbers,
463                                         BumpPtrAllocator &VNInfoAllocator) {
464   if (Clobbers.begin() == Clobbers.end()) return;
465   
466   // Find a value # to use for the clobber ranges.  If there is already a value#
467   // for unknown values, use it.
468   // FIXME: Use a single sentinal number for these!
469   VNInfo *ClobberValNo = getNextValue(~0U, 0, VNInfoAllocator);
470   
471   iterator IP = begin();
472   for (const_iterator I = Clobbers.begin(), E = Clobbers.end(); I != E; ++I) {
473     unsigned Start = I->start, End = I->end;
474     IP = std::upper_bound(IP, end(), Start);
475     
476     // If the start of this range overlaps with an existing liverange, trim it.
477     if (IP != begin() && IP[-1].end > Start) {
478       Start = IP[-1].end;
479       // Trimmed away the whole range?
480       if (Start >= End) continue;
481     }
482     // If the end of this range overlaps with an existing liverange, trim it.
483     if (IP != end() && End > IP->start) {
484       End = IP->start;
485       // If this trimmed away the whole range, ignore it.
486       if (Start == End) continue;
487     }
488     
489     // Insert the clobber interval.
490     IP = addRangeFrom(LiveRange(Start, End, ClobberValNo), IP);
491   }
492 }
493
494 /// MergeValueNumberInto - This method is called when two value nubmers
495 /// are found to be equivalent.  This eliminates V1, replacing all
496 /// LiveRanges with the V1 value number with the V2 value number.  This can
497 /// cause merging of V1/V2 values numbers and compaction of the value space.
498 void LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
499   assert(V1 != V2 && "Identical value#'s are always equivalent!");
500
501   // This code actually merges the (numerically) larger value number into the
502   // smaller value number, which is likely to allow us to compactify the value
503   // space.  The only thing we have to be careful of is to preserve the
504   // instruction that defines the result value.
505
506   // Make sure V2 is smaller than V1.
507   if (V1->id < V2->id) {
508     copyValNumInfo(V1, V2);
509     std::swap(V1, V2);
510   }
511
512   // Merge V1 live ranges into V2.
513   for (iterator I = begin(); I != end(); ) {
514     iterator LR = I++;
515     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
516     
517     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
518     // range, extend it.
519     if (LR != begin()) {
520       iterator Prev = LR-1;
521       if (Prev->valno == V2 && Prev->end == LR->start) {
522         Prev->end = LR->end;
523
524         // Erase this live-range.
525         ranges.erase(LR);
526         I = Prev+1;
527         LR = Prev;
528       }
529     }
530     
531     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
532     // Ensure that it is a V2 live-range.
533     LR->valno = V2;
534     
535     // If we can merge it into later V2 live ranges, do so now.  We ignore any
536     // following V1 live ranges, as they will be merged in subsequent iterations
537     // of the loop.
538     if (I != end()) {
539       if (I->start == LR->end && I->valno == V2) {
540         LR->end = I->end;
541         ranges.erase(I);
542         I = LR+1;
543       }
544     }
545   }
546   
547   // Now that V1 is dead, remove it.  If it is the largest value number, just
548   // nuke it (and any other deleted values neighboring it), otherwise mark it as
549   // ~1U so it can be nuked later.
550   if (V1->id == getNumValNums()-1) {
551     do {
552       VNInfo *VNI = valnos.back();
553       valnos.pop_back();
554       VNI->~VNInfo();
555     } while (valnos.back()->def == ~1U);
556   } else {
557     V1->def = ~1U;
558   }
559 }
560
561 void LiveInterval::Copy(const LiveInterval &RHS,
562                         BumpPtrAllocator &VNInfoAllocator) {
563   ranges.clear();
564   valnos.clear();
565   preference = RHS.preference;
566   weight = RHS.weight;
567   for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
568     const VNInfo *VNI = RHS.getValNumInfo(i);
569     VNInfo *NewVNI = getNextValue(~0U, 0, VNInfoAllocator);
570     copyValNumInfo(NewVNI, VNI);
571   }
572   for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
573     const LiveRange &LR = RHS.ranges[i];
574     addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
575   }
576 }
577
578 unsigned LiveInterval::getSize() const {
579   unsigned Sum = 0;
580   for (const_iterator I = begin(), E = end(); I != E; ++I)
581     Sum += I->end - I->start;
582   return Sum;
583 }
584
585 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
586   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
587 }
588
589 void LiveRange::dump() const {
590   cerr << *this << "\n";
591 }
592
593 void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const {
594   if (MRI && MRegisterInfo::isPhysicalRegister(reg))
595     OS << MRI->getName(reg);
596   else
597     OS << "%reg" << reg;
598
599   OS << ',' << weight;
600
601   if (empty())
602     OS << "EMPTY";
603   else {
604     OS << " = ";
605     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
606            E = ranges.end(); I != E; ++I)
607     OS << *I;
608   }
609   
610   // Print value number info.
611   if (getNumValNums()) {
612     OS << "  ";
613     unsigned vnum = 0;
614     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
615          ++i, ++vnum) {
616       const VNInfo *vni = *i;
617       if (vnum) OS << " ";
618       OS << vnum << "@";
619       if (vni->def == ~1U) {
620         OS << "x";
621       } else {
622         if (vni->def == ~0U)
623           OS << "?";
624         else
625           OS << vni->def;
626         unsigned ee = vni->kills.size();
627         if (ee) {
628           OS << "-(";
629           for (unsigned j = 0; j != ee; ++j) {
630             OS << vni->kills[j];
631             if (j != ee-1)
632               OS << " ";
633           }
634           if (vni->hasPHIKill)
635             OS << " phi";
636           OS << ")";
637         }
638       }
639     }
640   }
641 }
642
643 void LiveInterval::dump() const {
644   cerr << *this << "\n";
645 }
646
647
648 void LiveRange::print(std::ostream &os) const {
649   os << *this;
650 }