• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
22 #define LLVM_CODEGEN_LIVEINTERVAL_H
23 
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
28 #include <cassert>
29 #include <climits>
30 
31 namespace llvm {
32   class LiveIntervals;
33   class MachineInstr;
34   class MachineRegisterInfo;
35   class TargetRegisterInfo;
36   class raw_ostream;
37 
38   /// VNInfo - Value Number Information.
39   /// This class holds information about a machine level values, including
40   /// definition and use points.
41   ///
42   class VNInfo {
43   private:
44     enum {
45       HAS_PHI_KILL    = 1,
46       REDEF_BY_EC     = 1 << 1,
47       IS_PHI_DEF      = 1 << 2,
48       IS_UNUSED       = 1 << 3
49     };
50 
51     MachineInstr *copy;
52     unsigned char flags;
53 
54   public:
55     typedef BumpPtrAllocator Allocator;
56 
57     /// The ID number of this value.
58     unsigned id;
59 
60     /// The index of the defining instruction (if isDefAccurate() returns true).
61     SlotIndex def;
62 
63     /// VNInfo constructor.
VNInfo(unsigned i,SlotIndex d,MachineInstr * c)64     VNInfo(unsigned i, SlotIndex d, MachineInstr *c)
65       : copy(c), flags(0), id(i), def(d)
66     { }
67 
68     /// VNInfo construtor, copies values from orig, except for the value number.
VNInfo(unsigned i,const VNInfo & orig)69     VNInfo(unsigned i, const VNInfo &orig)
70       : copy(orig.copy), flags(orig.flags), id(i), def(orig.def)
71     { }
72 
73     /// Copy from the parameter into this VNInfo.
copyFrom(VNInfo & src)74     void copyFrom(VNInfo &src) {
75       flags = src.flags;
76       copy = src.copy;
77       def = src.def;
78     }
79 
80     /// Used for copying value number info.
getFlags()81     unsigned getFlags() const { return flags; }
setFlags(unsigned flags)82     void setFlags(unsigned flags) { this->flags = flags; }
83 
84     /// Merge flags from another VNInfo
mergeFlags(const VNInfo * VNI)85     void mergeFlags(const VNInfo *VNI) {
86       flags = (flags | VNI->flags) & ~IS_UNUSED;
87     }
88 
89     /// For a register interval, if this VN was definied by a copy instr
90     /// getCopy() returns a pointer to it, otherwise returns 0.
91     /// For a stack interval the behaviour of this method is undefined.
getCopy()92     MachineInstr* getCopy() const { return copy; }
93     /// For a register interval, set the copy member.
94     /// This method should not be called on stack intervals as it may lead to
95     /// undefined behavior.
setCopy(MachineInstr * c)96     void setCopy(MachineInstr *c) { copy = c; }
97 
98     /// isDefByCopy - Return true when this value was defined by a copy-like
99     /// instruction as determined by MachineInstr::isCopyLike.
isDefByCopy()100     bool isDefByCopy() const { return copy != 0; }
101 
102     /// Returns true if one or more kills are PHI nodes.
103     /// Obsolete, do not use!
hasPHIKill()104     bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
105     /// Set the PHI kill flag on this value.
setHasPHIKill(bool hasKill)106     void setHasPHIKill(bool hasKill) {
107       if (hasKill)
108         flags |= HAS_PHI_KILL;
109       else
110         flags &= ~HAS_PHI_KILL;
111     }
112 
113     /// Returns true if this value is re-defined by an early clobber somewhere
114     /// during the live range.
hasRedefByEC()115     bool hasRedefByEC() const { return flags & REDEF_BY_EC; }
116     /// Set the "redef by early clobber" flag on this value.
setHasRedefByEC(bool hasRedef)117     void setHasRedefByEC(bool hasRedef) {
118       if (hasRedef)
119         flags |= REDEF_BY_EC;
120       else
121         flags &= ~REDEF_BY_EC;
122     }
123 
124     /// Returns true if this value is defined by a PHI instruction (or was,
125     /// PHI instrucions may have been eliminated).
isPHIDef()126     bool isPHIDef() const { return flags & IS_PHI_DEF; }
127     /// Set the "phi def" flag on this value.
setIsPHIDef(bool phiDef)128     void setIsPHIDef(bool phiDef) {
129       if (phiDef)
130         flags |= IS_PHI_DEF;
131       else
132         flags &= ~IS_PHI_DEF;
133     }
134 
135     /// Returns true if this value is unused.
isUnused()136     bool isUnused() const { return flags & IS_UNUSED; }
137     /// Set the "is unused" flag on this value.
setIsUnused(bool unused)138     void setIsUnused(bool unused) {
139       if (unused)
140         flags |= IS_UNUSED;
141       else
142         flags &= ~IS_UNUSED;
143     }
144   };
145 
146   /// LiveRange structure - This represents a simple register range in the
147   /// program, with an inclusive start point and an exclusive end point.
148   /// These ranges are rendered as [start,end).
149   struct LiveRange {
150     SlotIndex start;  // Start point of the interval (inclusive)
151     SlotIndex end;    // End point of the interval (exclusive)
152     VNInfo *valno;   // identifier for the value contained in this interval.
153 
LiveRangeLiveRange154     LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
155       : start(S), end(E), valno(V) {
156 
157       assert(S < E && "Cannot create empty or backwards range");
158     }
159 
160     /// contains - Return true if the index is covered by this range.
161     ///
containsLiveRange162     bool contains(SlotIndex I) const {
163       return start <= I && I < end;
164     }
165 
166     /// containsRange - Return true if the given range, [S, E), is covered by
167     /// this range.
containsRangeLiveRange168     bool containsRange(SlotIndex S, SlotIndex E) const {
169       assert((S < E) && "Backwards interval?");
170       return (start <= S && S < end) && (start < E && E <= end);
171     }
172 
173     bool operator<(const LiveRange &LR) const {
174       return start < LR.start || (start == LR.start && end < LR.end);
175     }
176     bool operator==(const LiveRange &LR) const {
177       return start == LR.start && end == LR.end;
178     }
179 
180     void dump() const;
181     void print(raw_ostream &os) const;
182 
183   private:
184     LiveRange(); // DO NOT IMPLEMENT
185   };
186 
187   template <> struct isPodLike<LiveRange> { static const bool value = true; };
188 
189   raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
190 
191 
192   inline bool operator<(SlotIndex V, const LiveRange &LR) {
193     return V < LR.start;
194   }
195 
196   inline bool operator<(const LiveRange &LR, SlotIndex V) {
197     return LR.start < V;
198   }
199 
200   /// LiveInterval - This class represents some number of live ranges for a
201   /// register or value.  This class also contains a bit of register allocator
202   /// state.
203   class LiveInterval {
204   public:
205 
206     typedef SmallVector<LiveRange,4> Ranges;
207     typedef SmallVector<VNInfo*,4> VNInfoList;
208 
209     const unsigned reg;  // the register or stack slot of this interval.
210     float weight;        // weight of this interval
211     Ranges ranges;       // the ranges in which this register is live
212     VNInfoList valnos;   // value#'s
213 
214     struct InstrSlots {
215       enum {
216         LOAD  = 0,
217         USE   = 1,
218         DEF   = 2,
219         STORE = 3,
220         NUM   = 4
221       };
222 
223     };
224 
225     LiveInterval(unsigned Reg, float Weight)
226       : reg(Reg), weight(Weight) {}
227 
228     typedef Ranges::iterator iterator;
229     iterator begin() { return ranges.begin(); }
230     iterator end()   { return ranges.end(); }
231 
232     typedef Ranges::const_iterator const_iterator;
233     const_iterator begin() const { return ranges.begin(); }
234     const_iterator end() const  { return ranges.end(); }
235 
236     typedef VNInfoList::iterator vni_iterator;
237     vni_iterator vni_begin() { return valnos.begin(); }
238     vni_iterator vni_end() { return valnos.end(); }
239 
240     typedef VNInfoList::const_iterator const_vni_iterator;
241     const_vni_iterator vni_begin() const { return valnos.begin(); }
242     const_vni_iterator vni_end() const { return valnos.end(); }
243 
244     /// advanceTo - Advance the specified iterator to point to the LiveRange
245     /// containing the specified position, or end() if the position is past the
246     /// end of the interval.  If no LiveRange contains this position, but the
247     /// position is in a hole, this method returns an iterator pointing to the
248     /// LiveRange immediately after the hole.
249     iterator advanceTo(iterator I, SlotIndex Pos) {
250       assert(I != end());
251       if (Pos >= endIndex())
252         return end();
253       while (I->end <= Pos) ++I;
254       return I;
255     }
256 
257     /// find - Return an iterator pointing to the first range that ends after
258     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
259     /// when searching large intervals.
260     ///
261     /// If Pos is contained in a LiveRange, that range is returned.
262     /// If Pos is in a hole, the following LiveRange is returned.
263     /// If Pos is beyond endIndex, end() is returned.
264     iterator find(SlotIndex Pos);
265 
266     const_iterator find(SlotIndex Pos) const {
267       return const_cast<LiveInterval*>(this)->find(Pos);
268     }
269 
270     void clear() {
271       valnos.clear();
272       ranges.clear();
273     }
274 
275     bool hasAtLeastOneValue() const { return !valnos.empty(); }
276 
277     bool containsOneValue() const { return valnos.size() == 1; }
278 
279     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
280 
281     /// getValNumInfo - Returns pointer to the specified val#.
282     ///
283     inline VNInfo *getValNumInfo(unsigned ValNo) {
284       return valnos[ValNo];
285     }
286     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
287       return valnos[ValNo];
288     }
289 
290     /// containsValue - Returns true if VNI belongs to this interval.
291     bool containsValue(const VNInfo *VNI) const {
292       return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
293     }
294 
295     /// getNextValue - Create a new value number and return it.  MIIdx specifies
296     /// the instruction that defines the value number.
297     VNInfo *getNextValue(SlotIndex def, MachineInstr *CopyMI,
298                          VNInfo::Allocator &VNInfoAllocator) {
299       VNInfo *VNI =
300         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def, CopyMI);
301       valnos.push_back(VNI);
302       return VNI;
303     }
304 
305     /// Create a copy of the given value. The new value will be identical except
306     /// for the Value number.
307     VNInfo *createValueCopy(const VNInfo *orig,
308                             VNInfo::Allocator &VNInfoAllocator) {
309       VNInfo *VNI =
310         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
311       valnos.push_back(VNI);
312       return VNI;
313     }
314 
315     /// RenumberValues - Renumber all values in order of appearance and remove
316     /// unused values.
317     void RenumberValues(LiveIntervals &lis);
318 
319     /// isOnlyLROfValNo - Return true if the specified live range is the only
320     /// one defined by the its val#.
321     bool isOnlyLROfValNo(const LiveRange *LR) {
322       for (const_iterator I = begin(), E = end(); I != E; ++I) {
323         const LiveRange *Tmp = I;
324         if (Tmp != LR && Tmp->valno == LR->valno)
325           return false;
326       }
327       return true;
328     }
329 
330     /// MergeValueNumberInto - This method is called when two value nubmers
331     /// are found to be equivalent.  This eliminates V1, replacing all
332     /// LiveRanges with the V1 value number with the V2 value number.  This can
333     /// cause merging of V1/V2 values numbers and compaction of the value space.
334     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
335 
336     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
337     /// in RHS into this live interval as the specified value number.
338     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
339     /// current interval, it will replace the value numbers of the overlaped
340     /// live ranges with the specified value number.
341     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
342 
343     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
344     /// in RHS into this live interval as the specified value number.
345     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
346     /// current interval, but only if the overlapping LiveRanges have the
347     /// specified value number.
348     void MergeValueInAsValue(const LiveInterval &RHS,
349                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
350 
351     /// Copy - Copy the specified live interval. This copies all the fields
352     /// except for the register of the interval.
353     void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
354               VNInfo::Allocator &VNInfoAllocator);
355 
356     bool empty() const { return ranges.empty(); }
357 
358     /// beginIndex - Return the lowest numbered slot covered by interval.
359     SlotIndex beginIndex() const {
360       assert(!empty() && "Call to beginIndex() on empty interval.");
361       return ranges.front().start;
362     }
363 
364     /// endNumber - return the maximum point of the interval of the whole,
365     /// exclusive.
366     SlotIndex endIndex() const {
367       assert(!empty() && "Call to endIndex() on empty interval.");
368       return ranges.back().end;
369     }
370 
371     bool expiredAt(SlotIndex index) const {
372       return index >= endIndex();
373     }
374 
375     bool liveAt(SlotIndex index) const {
376       const_iterator r = find(index);
377       return r != end() && r->start <= index;
378     }
379 
380     /// killedAt - Return true if a live range ends at index. Note that the kill
381     /// point is not contained in the half-open live range. It is usually the
382     /// getDefIndex() slot following its last use.
383     bool killedAt(SlotIndex index) const {
384       const_iterator r = find(index.getUseIndex());
385       return r != end() && r->end == index;
386     }
387 
388     /// killedInRange - Return true if the interval has kills in [Start,End).
389     /// Note that the kill point is considered the end of a live range, so it is
390     /// not contained in the live range. If a live range ends at End, it won't
391     /// be counted as a kill by this method.
392     bool killedInRange(SlotIndex Start, SlotIndex End) const;
393 
394     /// getLiveRangeContaining - Return the live range that contains the
395     /// specified index, or null if there is none.
396     const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
397       const_iterator I = FindLiveRangeContaining(Idx);
398       return I == end() ? 0 : &*I;
399     }
400 
401     /// getLiveRangeContaining - Return the live range that contains the
402     /// specified index, or null if there is none.
403     LiveRange *getLiveRangeContaining(SlotIndex Idx) {
404       iterator I = FindLiveRangeContaining(Idx);
405       return I == end() ? 0 : &*I;
406     }
407 
408     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
409     VNInfo *getVNInfoAt(SlotIndex Idx) const {
410       const_iterator I = FindLiveRangeContaining(Idx);
411       return I == end() ? 0 : I->valno;
412     }
413 
414     /// getVNInfoBefore - Return the VNInfo that is live up to but not
415     /// necessarilly including Idx, or NULL. Use this to find the reaching def
416     /// used by an instruction at this SlotIndex position.
417     VNInfo *getVNInfoBefore(SlotIndex Idx) const {
418       const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
419       return I == end() ? 0 : I->valno;
420     }
421 
422     /// FindLiveRangeContaining - Return an iterator to the live range that
423     /// contains the specified index, or end() if there is none.
424     iterator FindLiveRangeContaining(SlotIndex Idx) {
425       iterator I = find(Idx);
426       return I != end() && I->start <= Idx ? I : end();
427     }
428 
429     const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
430       const_iterator I = find(Idx);
431       return I != end() && I->start <= Idx ? I : end();
432     }
433 
434     /// findDefinedVNInfo - Find the by the specified
435     /// index (register interval) or defined
436     VNInfo *findDefinedVNInfoForRegInt(SlotIndex Idx) const;
437 
438 
439     /// overlaps - Return true if the intersection of the two live intervals is
440     /// not empty.
441     bool overlaps(const LiveInterval& other) const {
442       if (other.empty())
443         return false;
444       return overlapsFrom(other, other.begin());
445     }
446 
447     /// overlaps - Return true if the live interval overlaps a range specified
448     /// by [Start, End).
449     bool overlaps(SlotIndex Start, SlotIndex End) const;
450 
451     /// overlapsFrom - Return true if the intersection of the two live intervals
452     /// is not empty.  The specified iterator is a hint that we can begin
453     /// scanning the Other interval starting at I.
454     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
455 
456     /// addRange - Add the specified LiveRange to this interval, merging
457     /// intervals as appropriate.  This returns an iterator to the inserted live
458     /// range (which may have grown since it was inserted.
459     void addRange(LiveRange LR) {
460       addRangeFrom(LR, ranges.begin());
461     }
462 
463     /// extendInBlock - If this interval is live before Kill in the basic block
464     /// that starts at StartIdx, extend it to be live up to Kill, and return
465     /// the value. If there is no live range before Kill, return NULL.
466     VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
467 
468     /// join - Join two live intervals (this, and other) together.  This applies
469     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
470     /// the intervals are not joinable, this aborts.
471     void join(LiveInterval &Other,
472               const int *ValNoAssignments,
473               const int *RHSValNoAssignments,
474               SmallVector<VNInfo*, 16> &NewVNInfo,
475               MachineRegisterInfo *MRI);
476 
477     /// isInOneLiveRange - Return true if the range specified is entirely in the
478     /// a single LiveRange of the live interval.
479     bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
480       const_iterator r = find(Start);
481       return r != end() && r->containsRange(Start, End);
482     }
483 
484     /// removeRange - Remove the specified range from this interval.  Note that
485     /// the range must be a single LiveRange in its entirety.
486     void removeRange(SlotIndex Start, SlotIndex End,
487                      bool RemoveDeadValNo = false);
488 
489     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
490       removeRange(LR.start, LR.end, RemoveDeadValNo);
491     }
492 
493     /// removeValNo - Remove all the ranges defined by the specified value#.
494     /// Also remove the value# from value# list.
495     void removeValNo(VNInfo *ValNo);
496 
497     /// getSize - Returns the sum of sizes of all the LiveRange's.
498     ///
499     unsigned getSize() const;
500 
501     /// Returns true if the live interval is zero length, i.e. no live ranges
502     /// span instructions. It doesn't pay to spill such an interval.
503     bool isZeroLength(SlotIndexes *Indexes) const {
504       for (const_iterator i = begin(), e = end(); i != e; ++i)
505         if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
506             i->end.getBaseIndex())
507           return false;
508       return true;
509     }
510 
511     /// isSpillable - Can this interval be spilled?
512     bool isSpillable() const {
513       return weight != HUGE_VALF;
514     }
515 
516     /// markNotSpillable - Mark interval as not spillable
517     void markNotSpillable() {
518       weight = HUGE_VALF;
519     }
520 
521     /// ComputeJoinedWeight - Set the weight of a live interval after
522     /// Other has been merged into it.
523     void ComputeJoinedWeight(const LiveInterval &Other);
524 
525     bool operator<(const LiveInterval& other) const {
526       const SlotIndex &thisIndex = beginIndex();
527       const SlotIndex &otherIndex = other.beginIndex();
528       return (thisIndex < otherIndex ||
529               (thisIndex == otherIndex && reg < other.reg));
530     }
531 
532     void print(raw_ostream &OS, const TargetRegisterInfo *TRI = 0) const;
533     void dump() const;
534 
535   private:
536 
537     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
538     void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
539     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
540     void markValNoForDeletion(VNInfo *V);
541 
542     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
543 
544   };
545 
546   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
547     LI.print(OS);
548     return OS;
549   }
550 
551   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
552   /// LiveInterval into equivalence clases of connected components. A
553   /// LiveInterval that has multiple connected components can be broken into
554   /// multiple LiveIntervals.
555   ///
556   /// Given a LiveInterval that may have multiple connected components, run:
557   ///
558   ///   unsigned numComps = ConEQ.Classify(LI);
559   ///   if (numComps > 1) {
560   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
561   ///     ConEQ.Distribute(LIS);
562   /// }
563 
564   class ConnectedVNInfoEqClasses {
565     LiveIntervals &LIS;
566     IntEqClasses EqClass;
567 
568     // Note that values a and b are connected.
569     void Connect(unsigned a, unsigned b);
570 
571     unsigned Renumber();
572 
573   public:
574     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
575 
576     /// Classify - Classify the values in LI into connected components.
577     /// Return the number of connected components.
578     unsigned Classify(const LiveInterval *LI);
579 
580     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
581     /// the equivalence class assigned the VNI.
582     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
583 
584     /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
585     /// for each connected component. LIV must have a LiveInterval for each
586     /// connected component. The LiveIntervals in Liv[1..] must be empty.
587     /// Instructions using LIV[0] are rewritten.
588     void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
589 
590   };
591 
592 }
593 #endif
594