d644e4485d69bc618140b46a04a36b71c71cf62a
[oota-llvm.git] / include / llvm / CodeGen / LiveInterval.h
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/SmallVector.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   /// Care must be taken in interpreting the def index of the value. The 
43   /// following rules apply:
44   ///
45   /// If the isDefAccurate() method returns false then def does not contain the
46   /// index of the defining MachineInstr, or even (necessarily) to a
47   /// MachineInstr at all. In general such a def index is not meaningful
48   /// and should not be used. The exception is that, for values originally
49   /// defined by PHI instructions, after PHI elimination def will contain the
50   /// index of the MBB in which the PHI originally existed. This can be used
51   /// to insert code (spills or copies) which deals with the value, which will
52   /// be live in to the block.
53   class VNInfo {
54   private:
55     enum {
56       HAS_PHI_KILL    = 1,                         
57       REDEF_BY_EC     = 1 << 1,
58       IS_PHI_DEF      = 1 << 2,
59       IS_UNUSED       = 1 << 3,
60       IS_DEF_ACCURATE = 1 << 4
61     };
62
63     unsigned char flags;
64     union {
65       MachineInstr *copy;
66       unsigned reg;
67     } cr;
68
69   public:
70     typedef SpecificBumpPtrAllocator<VNInfo> Allocator;
71     typedef SmallVector<SlotIndex, 4> KillSet;
72
73     /// The ID number of this value.
74     unsigned id;
75     
76     /// The index of the defining instruction (if isDefAccurate() returns true).
77     SlotIndex def;
78
79     KillSet kills;
80
81     /*
82     VNInfo(LiveIntervals &li_)
83       : defflags(IS_UNUSED), id(~1U) { cr.copy = 0; }
84     */
85
86     /// VNInfo constructor.
87     /// d is presumed to point to the actual defining instr. If it doesn't
88     /// setIsDefAccurate(false) should be called after construction.
89     VNInfo(unsigned i, SlotIndex d, MachineInstr *c)
90       : flags(IS_DEF_ACCURATE), id(i), def(d) { cr.copy = c; }
91
92     /// VNInfo construtor, copies values from orig, except for the value number.
93     VNInfo(unsigned i, const VNInfo &orig)
94       : flags(orig.flags), cr(orig.cr), id(i), def(orig.def), kills(orig.kills)
95     { }
96
97     /// Copy from the parameter into this VNInfo.
98     void copyFrom(VNInfo &src) {
99       flags = src.flags;
100       cr = src.cr;
101       def = src.def;
102       kills = src.kills;
103     }
104
105     /// Used for copying value number info.
106     unsigned getFlags() const { return flags; }
107     void setFlags(unsigned flags) { this->flags = flags; }
108
109     /// For a register interval, if this VN was definied by a copy instr
110     /// getCopy() returns a pointer to it, otherwise returns 0.
111     /// For a stack interval the behaviour of this method is undefined.
112     MachineInstr* getCopy() const { return cr.copy; }
113     /// For a register interval, set the copy member.
114     /// This method should not be called on stack intervals as it may lead to
115     /// undefined behavior.
116     void setCopy(MachineInstr *c) { cr.copy = c; }
117     
118     /// For a stack interval, returns the reg which this stack interval was
119     /// defined from.
120     /// For a register interval the behaviour of this method is undefined. 
121     unsigned getReg() const { return cr.reg; }
122     /// For a stack interval, set the defining register.
123     /// This method should not be called on register intervals as it may lead
124     /// to undefined behaviour.
125     void setReg(unsigned reg) { cr.reg = reg; }
126
127     /// Returns true if one or more kills are PHI nodes.
128     bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
129     /// Set the PHI kill flag on this value.
130     void setHasPHIKill(bool hasKill) {
131       if (hasKill)
132         flags |= HAS_PHI_KILL;
133       else
134         flags &= ~HAS_PHI_KILL;
135     }
136
137     /// Returns true if this value is re-defined by an early clobber somewhere
138     /// during the live range.
139     bool hasRedefByEC() const { return flags & REDEF_BY_EC; }
140     /// Set the "redef by early clobber" flag on this value.
141     void setHasRedefByEC(bool hasRedef) {
142       if (hasRedef)
143         flags |= REDEF_BY_EC;
144       else
145         flags &= ~REDEF_BY_EC;
146     }
147    
148     /// Returns true if this value is defined by a PHI instruction (or was,
149     /// PHI instrucions may have been eliminated).
150     bool isPHIDef() const { return flags & IS_PHI_DEF; }
151     /// Set the "phi def" flag on this value.
152     void setIsPHIDef(bool phiDef) {
153       if (phiDef)
154         flags |= IS_PHI_DEF;
155       else
156         flags &= ~IS_PHI_DEF;
157     }
158
159     /// Returns true if this value is unused.
160     bool isUnused() const { return flags & IS_UNUSED; }
161     /// Set the "is unused" flag on this value.
162     void setIsUnused(bool unused) {
163       if (unused)
164         flags |= IS_UNUSED;
165       else
166         flags &= ~IS_UNUSED;
167     }
168
169     /// Returns true if the def is accurate.
170     bool isDefAccurate() const { return flags & IS_DEF_ACCURATE; }
171     /// Set the "is def accurate" flag on this value.
172     void setIsDefAccurate(bool defAccurate) {
173       if (defAccurate)
174         flags |= IS_DEF_ACCURATE;
175       else 
176         flags &= ~IS_DEF_ACCURATE;
177     }
178
179     /// Returns true if the given index is a kill of this value.
180     bool isKill(SlotIndex k) const {
181       KillSet::const_iterator
182         i = std::lower_bound(kills.begin(), kills.end(), k);
183       return (i != kills.end() && *i == k);
184     }
185
186     /// addKill - Add a kill instruction index to the specified value
187     /// number.
188     void addKill(SlotIndex k) {
189       if (kills.empty()) {
190         kills.push_back(k);
191       } else {
192         KillSet::iterator
193           i = std::lower_bound(kills.begin(), kills.end(), k);
194         kills.insert(i, k);
195       }
196     }
197
198     /// Remove the specified kill index from this value's kills list.
199     /// Returns true if the value was present, otherwise returns false.
200     bool removeKill(SlotIndex k) {
201       KillSet::iterator i = std::lower_bound(kills.begin(), kills.end(), k);
202       if (i != kills.end() && *i == k) {
203         kills.erase(i);
204         return true;
205       }
206       return false;
207     }
208
209     /// Remove all kills in the range [s, e).
210     void removeKills(SlotIndex s, SlotIndex e) {
211       KillSet::iterator
212         si = std::lower_bound(kills.begin(), kills.end(), s),
213         se = std::upper_bound(kills.begin(), kills.end(), e);
214
215       kills.erase(si, se);
216     }
217
218   };
219
220   /// LiveRange structure - This represents a simple register range in the
221   /// program, with an inclusive start point and an exclusive end point.
222   /// These ranges are rendered as [start,end).
223   struct LiveRange {
224     SlotIndex start;  // Start point of the interval (inclusive)
225     SlotIndex end;    // End point of the interval (exclusive)
226     VNInfo *valno;   // identifier for the value contained in this interval.
227
228     LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
229       : start(S), end(E), valno(V) {
230
231       assert(S < E && "Cannot create empty or backwards range");
232     }
233
234     /// contains - Return true if the index is covered by this range.
235     ///
236     bool contains(SlotIndex I) const {
237       return start <= I && I < end;
238     }
239
240     /// containsRange - Return true if the given range, [S, E), is covered by
241     /// this range. 
242     bool containsRange(SlotIndex S, SlotIndex E) const {
243       assert((S < E) && "Backwards interval?");
244       return (start <= S && S < end) && (start < E && E <= end);
245     }
246
247     bool operator<(const LiveRange &LR) const {
248       return start < LR.start || (start == LR.start && end < LR.end);
249     }
250     bool operator==(const LiveRange &LR) const {
251       return start == LR.start && end == LR.end;
252     }
253
254     void dump() const;
255     void print(raw_ostream &os) const;
256
257   private:
258     LiveRange(); // DO NOT IMPLEMENT
259   };
260
261   template <> struct isPodLike<LiveRange> { static const bool value = true; };
262
263   raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
264
265
266   inline bool operator<(SlotIndex V, const LiveRange &LR) {
267     return V < LR.start;
268   }
269
270   inline bool operator<(const LiveRange &LR, SlotIndex V) {
271     return LR.start < V;
272   }
273
274   /// LiveInterval - This class represents some number of live ranges for a
275   /// register or value.  This class also contains a bit of register allocator
276   /// state.
277   class LiveInterval {
278   public:
279
280     typedef SmallVector<LiveRange,4> Ranges;
281     typedef SmallVector<VNInfo*,4> VNInfoList;
282
283     unsigned reg;        // the register or stack slot of this interval
284                          // if the top bits is set, it represents a stack slot.
285     float weight;        // weight of this interval
286     Ranges ranges;       // the ranges in which this register is live
287     VNInfoList valnos;   // value#'s
288     
289     struct InstrSlots {
290       enum {
291         LOAD  = 0,
292         USE   = 1,
293         DEF   = 2,
294         STORE = 3,
295         NUM   = 4
296       };
297
298     };
299
300     LiveInterval(unsigned Reg, float Weight, bool IsSS = false)
301       : reg(Reg), weight(Weight) {
302       if (IsSS)
303         reg = reg | (1U << (sizeof(unsigned)*CHAR_BIT-1));
304     }
305
306     typedef Ranges::iterator iterator;
307     iterator begin() { return ranges.begin(); }
308     iterator end()   { return ranges.end(); }
309
310     typedef Ranges::const_iterator const_iterator;
311     const_iterator begin() const { return ranges.begin(); }
312     const_iterator end() const  { return ranges.end(); }
313
314     typedef VNInfoList::iterator vni_iterator;
315     vni_iterator vni_begin() { return valnos.begin(); }
316     vni_iterator vni_end() { return valnos.end(); }
317
318     typedef VNInfoList::const_iterator const_vni_iterator;
319     const_vni_iterator vni_begin() const { return valnos.begin(); }
320     const_vni_iterator vni_end() const { return valnos.end(); }
321
322     /// advanceTo - Advance the specified iterator to point to the LiveRange
323     /// containing the specified position, or end() if the position is past the
324     /// end of the interval.  If no LiveRange contains this position, but the
325     /// position is in a hole, this method returns an iterator pointing to the
326     /// LiveRange immediately after the hole.
327     iterator advanceTo(iterator I, SlotIndex Pos) {
328       if (Pos >= endIndex())
329         return end();
330       while (I->end <= Pos) ++I;
331       return I;
332     }
333     
334     void clear() {
335       valnos.clear();
336       ranges.clear();
337     }
338
339     /// isStackSlot - Return true if this is a stack slot interval.
340     ///
341     bool isStackSlot() const {
342       return reg & (1U << (sizeof(unsigned)*CHAR_BIT-1));
343     }
344
345     /// getStackSlotIndex - Return stack slot index if this is a stack slot
346     /// interval.
347     int getStackSlotIndex() const {
348       assert(isStackSlot() && "Interval is not a stack slot interval!");
349       return reg & ~(1U << (sizeof(unsigned)*CHAR_BIT-1));
350     }
351
352     bool hasAtLeastOneValue() const { return !valnos.empty(); }
353
354     bool containsOneValue() const { return valnos.size() == 1; }
355
356     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
357     
358     /// getValNumInfo - Returns pointer to the specified val#.
359     ///
360     inline VNInfo *getValNumInfo(unsigned ValNo) {
361       return valnos[ValNo];
362     }
363     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
364       return valnos[ValNo];
365     }
366
367     /// getNextValue - Create a new value number and return it.  MIIdx specifies
368     /// the instruction that defines the value number.
369     VNInfo *getNextValue(SlotIndex def, MachineInstr *CopyMI,
370                        bool isDefAccurate, VNInfo::Allocator &VNInfoAllocator) {
371       VNInfo *VNI = VNInfoAllocator.Allocate();
372       new (VNI) VNInfo((unsigned)valnos.size(), def, CopyMI);
373       VNI->setIsDefAccurate(isDefAccurate);
374       valnos.push_back(VNI);
375       return VNI;
376     }
377
378     /// Create a copy of the given value. The new value will be identical except
379     /// for the Value number.
380     VNInfo *createValueCopy(const VNInfo *orig,
381                             VNInfo::Allocator &VNInfoAllocator) {
382       VNInfo *VNI = VNInfoAllocator.Allocate();
383       new (VNI) VNInfo((unsigned)valnos.size(), *orig);
384       valnos.push_back(VNI);
385       return VNI;
386     }
387
388     /// addKills - Add a number of kills into the VNInfo kill vector. If this
389     /// interval is live at a kill point, then the kill is not added.
390     void addKills(VNInfo *VNI, const VNInfo::KillSet &kills) {
391       for (unsigned i = 0, e = static_cast<unsigned>(kills.size());
392            i != e; ++i) {
393         if (!liveBeforeAndAt(kills[i])) {
394           VNI->addKill(kills[i]);
395         }
396       }
397     }
398
399     /// isOnlyLROfValNo - Return true if the specified live range is the only
400     /// one defined by the its val#.
401     bool isOnlyLROfValNo(const LiveRange *LR) {
402       for (const_iterator I = begin(), E = end(); I != E; ++I) {
403         const LiveRange *Tmp = I;
404         if (Tmp != LR && Tmp->valno == LR->valno)
405           return false;
406       }
407       return true;
408     }
409     
410     /// MergeValueNumberInto - This method is called when two value nubmers
411     /// are found to be equivalent.  This eliminates V1, replacing all
412     /// LiveRanges with the V1 value number with the V2 value number.  This can
413     /// cause merging of V1/V2 values numbers and compaction of the value space.
414     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
415
416     /// MergeInClobberRanges - For any live ranges that are not defined in the
417     /// current interval, but are defined in the Clobbers interval, mark them
418     /// used with an unknown definition value. Caller must pass in reference to
419     /// VNInfoAllocator since it will create a new val#.
420     void MergeInClobberRanges(LiveIntervals &li_,
421                               const LiveInterval &Clobbers,
422                               VNInfo::Allocator &VNInfoAllocator);
423
424     /// MergeInClobberRange - Same as MergeInClobberRanges except it merge in a
425     /// single LiveRange only.
426     void MergeInClobberRange(LiveIntervals &li_,
427                              SlotIndex Start,
428                              SlotIndex End,
429                              VNInfo::Allocator &VNInfoAllocator);
430
431     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
432     /// in RHS into this live interval as the specified value number.
433     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
434     /// current interval, it will replace the value numbers of the overlaped
435     /// live ranges with the specified value number.
436     void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
437
438     /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
439     /// in RHS into this live interval as the specified value number.
440     /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
441     /// current interval, but only if the overlapping LiveRanges have the
442     /// specified value number.
443     void MergeValueInAsValue(const LiveInterval &RHS,
444                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
445
446     /// Copy - Copy the specified live interval. This copies all the fields
447     /// except for the register of the interval.
448     void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
449               VNInfo::Allocator &VNInfoAllocator);
450     
451     bool empty() const { return ranges.empty(); }
452
453     /// beginIndex - Return the lowest numbered slot covered by interval.
454     SlotIndex beginIndex() const {
455       assert(!empty() && "Call to beginIndex() on empty interval.");
456       return ranges.front().start;
457     }
458
459     /// endNumber - return the maximum point of the interval of the whole,
460     /// exclusive.
461     SlotIndex endIndex() const {
462       assert(!empty() && "Call to endIndex() on empty interval.");
463       return ranges.back().end;
464     }
465
466     bool expiredAt(SlotIndex index) const {
467       return index >= endIndex();
468     }
469
470     bool liveAt(SlotIndex index) const;
471
472     // liveBeforeAndAt - Check if the interval is live at the index and the
473     // index just before it. If index is liveAt, check if it starts a new live
474     // range.If it does, then check if the previous live range ends at index-1.
475     bool liveBeforeAndAt(SlotIndex index) const;
476
477     /// getLiveRangeContaining - Return the live range that contains the
478     /// specified index, or null if there is none.
479     const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
480       const_iterator I = FindLiveRangeContaining(Idx);
481       return I == end() ? 0 : &*I;
482     }
483
484     /// getLiveRangeContaining - Return the live range that contains the
485     /// specified index, or null if there is none.
486     LiveRange *getLiveRangeContaining(SlotIndex Idx) {
487       iterator I = FindLiveRangeContaining(Idx);
488       return I == end() ? 0 : &*I;
489     }
490
491     /// FindLiveRangeContaining - Return an iterator to the live range that
492     /// contains the specified index, or end() if there is none.
493     const_iterator FindLiveRangeContaining(SlotIndex Idx) const;
494
495     /// FindLiveRangeContaining - Return an iterator to the live range that
496     /// contains the specified index, or end() if there is none.
497     iterator FindLiveRangeContaining(SlotIndex Idx);
498
499     /// findDefinedVNInfo - Find the by the specified
500     /// index (register interval) or defined 
501     VNInfo *findDefinedVNInfoForRegInt(SlotIndex Idx) const;
502
503     /// findDefinedVNInfo - Find the VNInfo that's defined by the specified
504     /// register (stack inteval only).
505     VNInfo *findDefinedVNInfoForStackInt(unsigned Reg) const;
506
507     
508     /// overlaps - Return true if the intersection of the two live intervals is
509     /// not empty.
510     bool overlaps(const LiveInterval& other) const {
511       return overlapsFrom(other, other.begin());
512     }
513
514     /// overlaps - Return true if the live interval overlaps a range specified
515     /// by [Start, End).
516     bool overlaps(SlotIndex Start, SlotIndex End) const;
517
518     /// overlapsFrom - Return true if the intersection of the two live intervals
519     /// is not empty.  The specified iterator is a hint that we can begin
520     /// scanning the Other interval starting at I.
521     bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
522
523     /// addRange - Add the specified LiveRange to this interval, merging
524     /// intervals as appropriate.  This returns an iterator to the inserted live
525     /// range (which may have grown since it was inserted.
526     void addRange(LiveRange LR) {
527       addRangeFrom(LR, ranges.begin());
528     }
529
530     /// join - Join two live intervals (this, and other) together.  This applies
531     /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
532     /// the intervals are not joinable, this aborts.
533     void join(LiveInterval &Other,
534               const int *ValNoAssignments,
535               const int *RHSValNoAssignments,
536               SmallVector<VNInfo*, 16> &NewVNInfo,
537               MachineRegisterInfo *MRI);
538
539     /// isInOneLiveRange - Return true if the range specified is entirely in the
540     /// a single LiveRange of the live interval.
541     bool isInOneLiveRange(SlotIndex Start, SlotIndex End);
542
543     /// removeRange - Remove the specified range from this interval.  Note that
544     /// the range must be a single LiveRange in its entirety.
545     void removeRange(SlotIndex Start, SlotIndex End,
546                      bool RemoveDeadValNo = false);
547
548     void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
549       removeRange(LR.start, LR.end, RemoveDeadValNo);
550     }
551
552     /// removeValNo - Remove all the ranges defined by the specified value#.
553     /// Also remove the value# from value# list.
554     void removeValNo(VNInfo *ValNo);
555
556     /// getSize - Returns the sum of sizes of all the LiveRange's.
557     ///
558     unsigned getSize() const;
559
560     /// isSpillable - Can this interval be spilled?
561     bool isSpillable() const {
562       return weight != HUGE_VALF;
563     }
564
565     /// markNotSpillable - Mark interval as not spillable
566     void markNotSpillable() {
567       weight = HUGE_VALF;
568     }
569
570     /// ComputeJoinedWeight - Set the weight of a live interval after
571     /// Other has been merged into it.
572     void ComputeJoinedWeight(const LiveInterval &Other);
573
574     bool operator<(const LiveInterval& other) const {
575       const SlotIndex &thisIndex = beginIndex();
576       const SlotIndex &otherIndex = other.beginIndex();
577       return (thisIndex < otherIndex ||
578               (thisIndex == otherIndex && reg < other.reg));
579     }
580
581     void print(raw_ostream &OS, const TargetRegisterInfo *TRI = 0) const;
582     void dump() const;
583
584   private:
585
586     Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
587     void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
588     Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
589
590     LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
591
592   };
593
594   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
595     LI.print(OS);
596     return OS;
597   }
598 }
599
600 #endif