Delete dead code.
[oota-llvm.git] / lib / CodeGen / LiveInterval.cpp
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' 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 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/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "RegisterCoalescer.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
35   // This algorithm is basically std::upper_bound.
36   // Unfortunately, std::upper_bound cannot be used with mixed types until we
37   // adopt C++0x. Many libraries can do it, but not all.
38   if (empty() || Pos >= endIndex())
39     return end();
40   iterator I = begin();
41   size_t Len = ranges.size();
42   do {
43     size_t Mid = Len >> 1;
44     if (Pos < I[Mid].end)
45       Len = Mid;
46     else
47       I += Mid + 1, Len -= Mid + 1;
48   } while (Len);
49   return I;
50 }
51
52 VNInfo *LiveInterval::createDeadDef(SlotIndex Def,
53                                     VNInfo::Allocator &VNInfoAllocator) {
54   assert(!Def.isDead() && "Cannot define a value at the dead slot");
55   iterator I = find(Def);
56   if (I == end()) {
57     VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
58     ranges.push_back(LiveRange(Def, Def.getDeadSlot(), VNI));
59     return VNI;
60   }
61   if (SlotIndex::isSameInstr(Def, I->start)) {
62     assert(I->start == Def && "Cannot insert def, already live");
63     assert(I->valno->def == Def && "Inconsistent existing value def");
64     return I->valno;
65   }
66   assert(SlotIndex::isEarlierInstr(Def, I->start) && "Already live at def");
67   VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
68   ranges.insert(I, LiveRange(Def, Def.getDeadSlot(), VNI));
69   return VNI;
70 }
71
72 // overlaps - Return true if the intersection of the two live intervals is
73 // not empty.
74 //
75 // An example for overlaps():
76 //
77 // 0: A = ...
78 // 4: B = ...
79 // 8: C = A + B ;; last use of A
80 //
81 // The live intervals should look like:
82 //
83 // A = [3, 11)
84 // B = [7, x)
85 // C = [11, y)
86 //
87 // A->overlaps(C) should return false since we want to be able to join
88 // A and C.
89 //
90 bool LiveInterval::overlapsFrom(const LiveInterval& other,
91                                 const_iterator StartPos) const {
92   assert(!empty() && "empty interval");
93   const_iterator i = begin();
94   const_iterator ie = end();
95   const_iterator j = StartPos;
96   const_iterator je = other.end();
97
98   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
99          StartPos != other.end() && "Bogus start position hint!");
100
101   if (i->start < j->start) {
102     i = std::upper_bound(i, ie, j->start);
103     if (i != ranges.begin()) --i;
104   } else if (j->start < i->start) {
105     ++StartPos;
106     if (StartPos != other.end() && StartPos->start <= i->start) {
107       assert(StartPos < other.end() && i < end());
108       j = std::upper_bound(j, je, i->start);
109       if (j != other.ranges.begin()) --j;
110     }
111   } else {
112     return true;
113   }
114
115   if (j == je) return false;
116
117   while (i != ie) {
118     if (i->start > j->start) {
119       std::swap(i, j);
120       std::swap(ie, je);
121     }
122
123     if (i->end > j->start)
124       return true;
125     ++i;
126   }
127
128   return false;
129 }
130
131 bool LiveInterval::overlaps(const LiveInterval &Other,
132                             const CoalescerPair &CP,
133                             const SlotIndexes &Indexes) const {
134   assert(!empty() && "empty interval");
135   if (Other.empty())
136     return false;
137
138   // Use binary searches to find initial positions.
139   const_iterator I = find(Other.beginIndex());
140   const_iterator IE = end();
141   if (I == IE)
142     return false;
143   const_iterator J = Other.find(I->start);
144   const_iterator JE = Other.end();
145   if (J == JE)
146     return false;
147
148   for (;;) {
149     // J has just been advanced to satisfy:
150     assert(J->end >= I->start);
151     // Check for an overlap.
152     if (J->start < I->end) {
153       // I and J are overlapping. Find the later start.
154       SlotIndex Def = std::max(I->start, J->start);
155       // Allow the overlap if Def is a coalescable copy.
156       if (Def.isBlock() ||
157           !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
158         return true;
159     }
160     // Advance the iterator that ends first to check for more overlaps.
161     if (J->end > I->end) {
162       std::swap(I, J);
163       std::swap(IE, JE);
164     }
165     // Advance J until J->end >= I->start.
166     do
167       if (++J == JE)
168         return false;
169     while (J->end < I->start);
170   }
171 }
172
173 /// overlaps - Return true if the live interval overlaps a range specified
174 /// by [Start, End).
175 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
176   assert(Start < End && "Invalid range");
177   const_iterator I = std::lower_bound(begin(), end(), End);
178   return I != begin() && (--I)->end > Start;
179 }
180
181
182 /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
183 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
184 /// it can be nuked later.
185 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
186   if (ValNo->id == getNumValNums()-1) {
187     do {
188       valnos.pop_back();
189     } while (!valnos.empty() && valnos.back()->isUnused());
190   } else {
191     ValNo->markUnused();
192   }
193 }
194
195 /// RenumberValues - Renumber all values in order of appearance and delete the
196 /// remaining unused values.
197 void LiveInterval::RenumberValues(LiveIntervals &lis) {
198   SmallPtrSet<VNInfo*, 8> Seen;
199   valnos.clear();
200   for (const_iterator I = begin(), E = end(); I != E; ++I) {
201     VNInfo *VNI = I->valno;
202     if (!Seen.insert(VNI))
203       continue;
204     assert(!VNI->isUnused() && "Unused valno used by live range");
205     VNI->id = (unsigned)valnos.size();
206     valnos.push_back(VNI);
207   }
208 }
209
210 /// extendIntervalEndTo - This method is used when we want to extend the range
211 /// specified by I to end at the specified endpoint.  To do this, we should
212 /// merge and eliminate all ranges that this will overlap with.  The iterator is
213 /// not invalidated.
214 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
215   assert(I != ranges.end() && "Not a valid interval!");
216   VNInfo *ValNo = I->valno;
217
218   // Search for the first interval that we can't merge with.
219   Ranges::iterator MergeTo = llvm::next(I);
220   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
221     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
222   }
223
224   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
225   I->end = std::max(NewEnd, prior(MergeTo)->end);
226
227   // If the newly formed range now touches the range after it and if they have
228   // the same value number, merge the two ranges into one range.
229   if (MergeTo != ranges.end() && MergeTo->start <= I->end &&
230       MergeTo->valno == ValNo) {
231     I->end = MergeTo->end;
232     ++MergeTo;
233   }
234
235   // Erase any dead ranges.
236   ranges.erase(llvm::next(I), MergeTo);
237 }
238
239
240 /// extendIntervalStartTo - This method is used when we want to extend the range
241 /// specified by I to start at the specified endpoint.  To do this, we should
242 /// merge and eliminate all ranges that this will overlap with.
243 LiveInterval::Ranges::iterator
244 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
245   assert(I != ranges.end() && "Not a valid interval!");
246   VNInfo *ValNo = I->valno;
247
248   // Search for the first interval that we can't merge with.
249   Ranges::iterator MergeTo = I;
250   do {
251     if (MergeTo == ranges.begin()) {
252       I->start = NewStart;
253       ranges.erase(MergeTo, I);
254       return I;
255     }
256     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
257     --MergeTo;
258   } while (NewStart <= MergeTo->start);
259
260   // If we start in the middle of another interval, just delete a range and
261   // extend that interval.
262   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
263     MergeTo->end = I->end;
264   } else {
265     // Otherwise, extend the interval right after.
266     ++MergeTo;
267     MergeTo->start = NewStart;
268     MergeTo->end = I->end;
269   }
270
271   ranges.erase(llvm::next(MergeTo), llvm::next(I));
272   return MergeTo;
273 }
274
275 LiveInterval::iterator
276 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
277   SlotIndex Start = LR.start, End = LR.end;
278   iterator it = std::upper_bound(From, ranges.end(), Start);
279
280   // If the inserted interval starts in the middle or right at the end of
281   // another interval, just extend that interval to contain the range of LR.
282   if (it != ranges.begin()) {
283     iterator B = prior(it);
284     if (LR.valno == B->valno) {
285       if (B->start <= Start && B->end >= Start) {
286         extendIntervalEndTo(B, End);
287         return B;
288       }
289     } else {
290       // Check to make sure that we are not overlapping two live ranges with
291       // different valno's.
292       assert(B->end <= Start &&
293              "Cannot overlap two LiveRanges with differing ValID's"
294              " (did you def the same reg twice in a MachineInstr?)");
295     }
296   }
297
298   // Otherwise, if this range ends in the middle of, or right next to, another
299   // interval, merge it into that interval.
300   if (it != ranges.end()) {
301     if (LR.valno == it->valno) {
302       if (it->start <= End) {
303         it = extendIntervalStartTo(it, Start);
304
305         // If LR is a complete superset of an interval, we may need to grow its
306         // endpoint as well.
307         if (End > it->end)
308           extendIntervalEndTo(it, End);
309         return it;
310       }
311     } else {
312       // Check to make sure that we are not overlapping two live ranges with
313       // different valno's.
314       assert(it->start >= End &&
315              "Cannot overlap two LiveRanges with differing ValID's");
316     }
317   }
318
319   // Otherwise, this is just a new range that doesn't interact with anything.
320   // Insert it.
321   return ranges.insert(it, LR);
322 }
323
324 /// extendInBlock - If this interval is live before Kill in the basic
325 /// block that starts at StartIdx, extend it to be live up to Kill and return
326 /// the value. If there is no live range before Kill, return NULL.
327 VNInfo *LiveInterval::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
328   if (empty())
329     return 0;
330   iterator I = std::upper_bound(begin(), end(), Kill.getPrevSlot());
331   if (I == begin())
332     return 0;
333   --I;
334   if (I->end <= StartIdx)
335     return 0;
336   if (I->end < Kill)
337     extendIntervalEndTo(I, Kill);
338   return I->valno;
339 }
340
341 /// removeRange - Remove the specified range from this interval.  Note that
342 /// the range must be in a single LiveRange in its entirety.
343 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
344                                bool RemoveDeadValNo) {
345   // Find the LiveRange containing this span.
346   Ranges::iterator I = find(Start);
347   assert(I != ranges.end() && "Range is not in interval!");
348   assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
349
350   // If the span we are removing is at the start of the LiveRange, adjust it.
351   VNInfo *ValNo = I->valno;
352   if (I->start == Start) {
353     if (I->end == End) {
354       if (RemoveDeadValNo) {
355         // Check if val# is dead.
356         bool isDead = true;
357         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
358           if (II != I && II->valno == ValNo) {
359             isDead = false;
360             break;
361           }
362         if (isDead) {
363           // Now that ValNo is dead, remove it.
364           markValNoForDeletion(ValNo);
365         }
366       }
367
368       ranges.erase(I);  // Removed the whole LiveRange.
369     } else
370       I->start = End;
371     return;
372   }
373
374   // Otherwise if the span we are removing is at the end of the LiveRange,
375   // adjust the other way.
376   if (I->end == End) {
377     I->end = Start;
378     return;
379   }
380
381   // Otherwise, we are splitting the LiveRange into two pieces.
382   SlotIndex OldEnd = I->end;
383   I->end = Start;   // Trim the old interval.
384
385   // Insert the new one.
386   ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
387 }
388
389 /// removeValNo - Remove all the ranges defined by the specified value#.
390 /// Also remove the value# from value# list.
391 void LiveInterval::removeValNo(VNInfo *ValNo) {
392   if (empty()) return;
393   Ranges::iterator I = ranges.end();
394   Ranges::iterator E = ranges.begin();
395   do {
396     --I;
397     if (I->valno == ValNo)
398       ranges.erase(I);
399   } while (I != E);
400   // Now that ValNo is dead, remove it.
401   markValNoForDeletion(ValNo);
402 }
403
404 /// join - Join two live intervals (this, and other) together.  This applies
405 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
406 /// the intervals are not joinable, this aborts.
407 void LiveInterval::join(LiveInterval &Other,
408                         const int *LHSValNoAssignments,
409                         const int *RHSValNoAssignments,
410                         SmallVector<VNInfo*, 16> &NewVNInfo,
411                         MachineRegisterInfo *MRI) {
412   verify();
413
414   // Determine if any of our live range values are mapped.  This is uncommon, so
415   // we want to avoid the interval scan if not.
416   bool MustMapCurValNos = false;
417   unsigned NumVals = getNumValNums();
418   unsigned NumNewVals = NewVNInfo.size();
419   for (unsigned i = 0; i != NumVals; ++i) {
420     unsigned LHSValID = LHSValNoAssignments[i];
421     if (i != LHSValID ||
422         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
423       MustMapCurValNos = true;
424       break;
425     }
426   }
427
428   // If we have to apply a mapping to our base interval assignment, rewrite it
429   // now.
430   if (MustMapCurValNos) {
431     // Map the first live range.
432
433     iterator OutIt = begin();
434     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
435     for (iterator I = next(OutIt), E = end(); I != E; ++I) {
436       VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
437       assert(nextValNo != 0 && "Huh?");
438
439       // If this live range has the same value # as its immediate predecessor,
440       // and if they are neighbors, remove one LiveRange.  This happens when we
441       // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
442       if (OutIt->valno == nextValNo && OutIt->end == I->start) {
443         OutIt->end = I->end;
444       } else {
445         // Didn't merge. Move OutIt to the next interval,
446         ++OutIt;
447         OutIt->valno = nextValNo;
448         if (OutIt != I) {
449           OutIt->start = I->start;
450           OutIt->end = I->end;
451         }
452       }
453     }
454     // If we merge some live ranges, chop off the end.
455     ++OutIt;
456     ranges.erase(OutIt, end());
457   }
458
459   // Remember assignements because val# ids are changing.
460   SmallVector<unsigned, 16> OtherAssignments;
461   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
462     OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
463
464   // Update val# info. Renumber them and make sure they all belong to this
465   // LiveInterval now. Also remove dead val#'s.
466   unsigned NumValNos = 0;
467   for (unsigned i = 0; i < NumNewVals; ++i) {
468     VNInfo *VNI = NewVNInfo[i];
469     if (VNI) {
470       if (NumValNos >= NumVals)
471         valnos.push_back(VNI);
472       else
473         valnos[NumValNos] = VNI;
474       VNI->id = NumValNos++;  // Renumber val#.
475     }
476   }
477   if (NumNewVals < NumVals)
478     valnos.resize(NumNewVals);  // shrinkify
479
480   // Okay, now insert the RHS live ranges into the LHS.
481   unsigned RangeNo = 0;
482   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
483     // Map the valno in the other live range to the current live range.
484     I->valno = NewVNInfo[OtherAssignments[RangeNo]];
485     assert(I->valno && "Adding a dead range?");
486   }
487   mergeIntervalRanges(Other);
488
489   verify();
490 }
491
492 /// \brief Helper function for merging in another LiveInterval's ranges.
493 ///
494 /// This is a helper routine implementing an efficient merge of another
495 /// LiveIntervals ranges into the current interval.
496 ///
497 /// \param LHSValNo If non-NULL, set as the new value number for every range
498 ///                 from RHS which is merged into the LHS.
499 /// \param RHSValNo If non-NULL, then only ranges in RHS whose original value
500 ///                 number maches this value number will be merged into LHS.
501 void LiveInterval::mergeIntervalRanges(const LiveInterval &RHS,
502                                        VNInfo *LHSValNo,
503                                        const VNInfo *RHSValNo) {
504   if (RHS.empty())
505     return;
506
507   // Ensure we're starting with a valid range. Note that we don't verify RHS
508   // because it may have had its value numbers adjusted in preparation for
509   // merging.
510   verify();
511
512   // The strategy for merging these efficiently is as follows:
513   //
514   // 1) Find the beginning of the impacted ranges in the LHS.
515   // 2) Create a new, merged sub-squence of ranges merging from the position in
516   //    #1 until either LHS or RHS is exhausted. Any part of LHS between RHS
517   //    entries being merged will be copied into this new range.
518   // 3) Replace the relevant section in LHS with these newly merged ranges.
519   // 4) Append any remaning ranges from RHS if LHS is exhausted in #2.
520   //
521   // We don't follow the typical in-place merge strategy for sorted ranges of
522   // appending the new ranges to the back and then using std::inplace_merge
523   // because one step of the merge can both mutate the original elements and
524   // remove elements from the original. Essentially, because the merge includes
525   // collapsing overlapping ranges, a more complex approach is required.
526
527   // We do an initial binary search to optimize for a common pattern: a large
528   // LHS, and a very small RHS.
529   const_iterator RI = RHS.begin(), RE = RHS.end();
530   iterator LE = end(), LI = std::upper_bound(begin(), LE, *RI);
531
532   // Merge into NewRanges until one of the ranges is exhausted.
533   SmallVector<LiveRange, 4> NewRanges;
534
535   // Keep track of where to begin the replacement.
536   iterator ReplaceI = LI;
537
538   // If there are preceding ranges in the LHS, put the last one into NewRanges
539   // so we can optionally extend it. Adjust the replacement point accordingly.
540   if (LI != begin()) {
541     ReplaceI = llvm::prior(LI);
542     NewRanges.push_back(*ReplaceI);
543   }
544
545   // Now loop over the mergable portions of both LHS and RHS, merging into
546   // NewRanges.
547   while (LI != LE && RI != RE) {
548     // Skip incoming ranges with the wrong value.
549     if (RHSValNo && RI->valno != RHSValNo) {
550       ++RI;
551       continue;
552     }
553
554     // Select the first range. We pick the earliest start point, and then the
555     // largest range.
556     LiveRange R = *LI;
557     if (*RI < R) {
558       R = *RI;
559       ++RI;
560       if (LHSValNo)
561         R.valno = LHSValNo;
562     } else {
563       ++LI;
564     }
565
566     if (NewRanges.empty()) {
567       NewRanges.push_back(R);
568       continue;
569     }
570
571     LiveRange &LastR = NewRanges.back();
572     if (R.valno == LastR.valno) {
573       // Try to merge this range into the last one.
574       if (R.start <= LastR.end) {
575         LastR.end = std::max(LastR.end, R.end);
576         continue;
577       }
578     } else {
579       // We can't merge ranges across a value number.
580       assert(R.start >= LastR.end &&
581              "Cannot overlap two LiveRanges with differing ValID's");
582     }
583
584     // If all else fails, just append the range.
585     NewRanges.push_back(R);
586   }
587   assert(RI == RE || LI == LE);
588
589   // Check for being able to merge into the trailing sequence of ranges on the LHS.
590   if (!NewRanges.empty())
591     for (; LI != LE && (LI->valno == NewRanges.back().valno &&
592                         LI->start <= NewRanges.back().end);
593          ++LI)
594       NewRanges.back().end = std::max(NewRanges.back().end, LI->end);
595
596   // Replace the ranges in the LHS with the newly merged ones. It would be
597   // really nice if there were a move-supporting 'replace' directly in
598   // SmallVector, but as there is not, we pay the price of copies to avoid
599   // wasted memory allocations.
600   SmallVectorImpl<LiveRange>::iterator NRI = NewRanges.begin(),
601                                        NRE = NewRanges.end();
602   for (; ReplaceI != LI && NRI != NRE; ++ReplaceI, ++NRI)
603     *ReplaceI = *NRI;
604   if (NRI == NRE)
605     ranges.erase(ReplaceI, LI);
606   else
607     ranges.insert(LI, NRI, NRE);
608
609   // And finally insert any trailing end of RHS (if we have one).
610   for (; RI != RE; ++RI) {
611     LiveRange R = *RI;
612     if (LHSValNo)
613       R.valno = LHSValNo;
614     if (!ranges.empty() &&
615         ranges.back().valno == R.valno && R.start <= ranges.back().end)
616       ranges.back().end = std::max(ranges.back().end, R.end);
617     else
618       ranges.push_back(R);
619   }
620
621   // Ensure we finished with a valid new sequence of ranges.
622   verify();
623 }
624
625 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
626 /// interval as the specified value number.  The LiveRanges in RHS are
627 /// allowed to overlap with LiveRanges in the current interval, but only if
628 /// the overlapping LiveRanges have the specified value number.
629 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
630                                         VNInfo *LHSValNo) {
631   mergeIntervalRanges(RHS, LHSValNo);
632 }
633
634 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
635 /// in RHS into this live interval as the specified value number.
636 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
637 /// current interval, it will replace the value numbers of the overlaped
638 /// live ranges with the specified value number.
639 void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS,
640                                        const VNInfo *RHSValNo,
641                                        VNInfo *LHSValNo) {
642   mergeIntervalRanges(RHS, LHSValNo, RHSValNo);
643 }
644
645 /// MergeValueNumberInto - This method is called when two value nubmers
646 /// are found to be equivalent.  This eliminates V1, replacing all
647 /// LiveRanges with the V1 value number with the V2 value number.  This can
648 /// cause merging of V1/V2 values numbers and compaction of the value space.
649 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
650   assert(V1 != V2 && "Identical value#'s are always equivalent!");
651
652   // This code actually merges the (numerically) larger value number into the
653   // smaller value number, which is likely to allow us to compactify the value
654   // space.  The only thing we have to be careful of is to preserve the
655   // instruction that defines the result value.
656
657   // Make sure V2 is smaller than V1.
658   if (V1->id < V2->id) {
659     V1->copyFrom(*V2);
660     std::swap(V1, V2);
661   }
662
663   // Merge V1 live ranges into V2.
664   for (iterator I = begin(); I != end(); ) {
665     iterator LR = I++;
666     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
667
668     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
669     // range, extend it.
670     if (LR != begin()) {
671       iterator Prev = LR-1;
672       if (Prev->valno == V2 && Prev->end == LR->start) {
673         Prev->end = LR->end;
674
675         // Erase this live-range.
676         ranges.erase(LR);
677         I = Prev+1;
678         LR = Prev;
679       }
680     }
681
682     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
683     // Ensure that it is a V2 live-range.
684     LR->valno = V2;
685
686     // If we can merge it into later V2 live ranges, do so now.  We ignore any
687     // following V1 live ranges, as they will be merged in subsequent iterations
688     // of the loop.
689     if (I != end()) {
690       if (I->start == LR->end && I->valno == V2) {
691         LR->end = I->end;
692         ranges.erase(I);
693         I = LR+1;
694       }
695     }
696   }
697
698   // Now that V1 is dead, remove it.
699   markValNoForDeletion(V1);
700
701   return V2;
702 }
703
704 unsigned LiveInterval::getSize() const {
705   unsigned Sum = 0;
706   for (const_iterator I = begin(), E = end(); I != E; ++I)
707     Sum += I->start.distance(I->end);
708   return Sum;
709 }
710
711 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
712   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
713 }
714
715 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
716 void LiveRange::dump() const {
717   dbgs() << *this << "\n";
718 }
719 #endif
720
721 void LiveInterval::print(raw_ostream &OS) const {
722   if (empty())
723     OS << "EMPTY";
724   else {
725     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
726            E = ranges.end(); I != E; ++I) {
727       OS << *I;
728       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
729     }
730   }
731
732   // Print value number info.
733   if (getNumValNums()) {
734     OS << "  ";
735     unsigned vnum = 0;
736     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
737          ++i, ++vnum) {
738       const VNInfo *vni = *i;
739       if (vnum) OS << " ";
740       OS << vnum << "@";
741       if (vni->isUnused()) {
742         OS << "x";
743       } else {
744         OS << vni->def;
745         if (vni->isPHIDef())
746           OS << "-phi";
747       }
748     }
749   }
750 }
751
752 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
753 void LiveInterval::dump() const {
754   dbgs() << *this << "\n";
755 }
756 #endif
757
758 #ifndef NDEBUG
759 void LiveInterval::verify() const {
760   for (const_iterator I = begin(), E = end(); I != E; ++I) {
761     assert(I->start.isValid());
762     assert(I->end.isValid());
763     assert(I->start < I->end);
764     assert(I->valno != 0);
765     assert(I->valno == valnos[I->valno->id]);
766     if (llvm::next(I) != E) {
767       assert(I->end <= llvm::next(I)->start);
768       if (I->end == llvm::next(I)->start)
769         assert(I->valno != llvm::next(I)->valno);
770     }
771   }
772 }
773 #endif
774
775
776 void LiveRange::print(raw_ostream &os) const {
777   os << *this;
778 }
779
780 unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
781   // Create initial equivalence classes.
782   EqClass.clear();
783   EqClass.grow(LI->getNumValNums());
784
785   const VNInfo *used = 0, *unused = 0;
786
787   // Determine connections.
788   for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
789        I != E; ++I) {
790     const VNInfo *VNI = *I;
791     // Group all unused values into one class.
792     if (VNI->isUnused()) {
793       if (unused)
794         EqClass.join(unused->id, VNI->id);
795       unused = VNI;
796       continue;
797     }
798     used = VNI;
799     if (VNI->isPHIDef()) {
800       const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
801       assert(MBB && "Phi-def has no defining MBB");
802       // Connect to values live out of predecessors.
803       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
804            PE = MBB->pred_end(); PI != PE; ++PI)
805         if (const VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
806           EqClass.join(VNI->id, PVNI->id);
807     } else {
808       // Normal value defined by an instruction. Check for two-addr redef.
809       // FIXME: This could be coincidental. Should we really check for a tied
810       // operand constraint?
811       // Note that VNI->def may be a use slot for an early clobber def.
812       if (const VNInfo *UVNI = LI->getVNInfoBefore(VNI->def))
813         EqClass.join(VNI->id, UVNI->id);
814     }
815   }
816
817   // Lump all the unused values in with the last used value.
818   if (used && unused)
819     EqClass.join(used->id, unused->id);
820
821   EqClass.compress();
822   return EqClass.getNumClasses();
823 }
824
825 void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[],
826                                           MachineRegisterInfo &MRI) {
827   assert(LIV[0] && "LIV[0] must be set");
828   LiveInterval &LI = *LIV[0];
829
830   // Rewrite instructions.
831   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
832        RE = MRI.reg_end(); RI != RE;) {
833     MachineOperand &MO = RI.getOperand();
834     MachineInstr *MI = MO.getParent();
835     ++RI;
836     // DBG_VALUE instructions should have been eliminated earlier.
837     LiveRangeQuery LRQ(LI, LIS.getInstructionIndex(MI));
838     const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
839     // In the case of an <undef> use that isn't tied to any def, VNI will be
840     // NULL. If the use is tied to a def, VNI will be the defined value.
841     if (!VNI)
842       continue;
843     MO.setReg(LIV[getEqClass(VNI)]->reg);
844   }
845
846   // Move runs to new intervals.
847   LiveInterval::iterator J = LI.begin(), E = LI.end();
848   while (J != E && EqClass[J->valno->id] == 0)
849     ++J;
850   for (LiveInterval::iterator I = J; I != E; ++I) {
851     if (unsigned eq = EqClass[I->valno->id]) {
852       assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
853              "New intervals should be empty");
854       LIV[eq]->ranges.push_back(*I);
855     } else
856       *J++ = *I;
857   }
858   LI.ranges.erase(J, E);
859
860   // Transfer VNInfos to their new owners and renumber them.
861   unsigned j = 0, e = LI.getNumValNums();
862   while (j != e && EqClass[j] == 0)
863     ++j;
864   for (unsigned i = j; i != e; ++i) {
865     VNInfo *VNI = LI.getValNumInfo(i);
866     if (unsigned eq = EqClass[i]) {
867       VNI->id = LIV[eq]->getNumValNums();
868       LIV[eq]->valnos.push_back(VNI);
869     } else {
870       VNI->id = j;
871       LI.valnos[j++] = VNI;
872     }
873   }
874   LI.valnos.resize(j);
875 }