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