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