LiveInterval.h revision f3bb2e65d12857f83b273f4ecab013680310bbbc
1//===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Streams.h"
27#include <iosfwd>
28#include <vector>
29#include <cassert>
30
31namespace llvm {
32  class MachineInstr;
33  class MRegisterInfo;
34  struct LiveInterval;
35
36  /// VNInfo - If the value number definition is undefined (e.g. phi
37  /// merge point), it contains ~0u,x. If the value number is not in use, it
38  /// contains ~1u,x to indicate that the value # is not used.
39  ///   def   - Instruction # of the definition.
40  ///   reg   - Source reg iff val# is defined by a copy; zero otherwise.
41  ///   kills - Instruction # of the kills. If a kill is an odd #, it means
42  ///           the kill is a phi join point.
43  struct VNInfo {
44    unsigned id;
45    unsigned def;
46    unsigned reg;
47    SmallVector<unsigned, 4> kills;
48    VNInfo() : id(~1U), def(~1U), reg(0) {}
49    VNInfo(unsigned i, unsigned d, unsigned r)
50      : id(i), def(d), reg(r) {}
51  };
52
53  /// LiveRange structure - This represents a simple register range in the
54  /// program, with an inclusive start point and an exclusive end point.
55  /// These ranges are rendered as [start,end).
56  struct LiveRange {
57    unsigned start;  // Start point of the interval (inclusive)
58    unsigned end;    // End point of the interval (exclusive)
59    VNInfo *valno;   // identifier for the value contained in this interval.
60
61    LiveRange(unsigned S, unsigned E, VNInfo *V) : start(S), end(E), valno(V) {
62      assert(S < E && "Cannot create empty or backwards range");
63    }
64
65    /// contains - Return true if the index is covered by this range.
66    ///
67    bool contains(unsigned I) const {
68      return start <= I && I < end;
69    }
70
71    bool operator<(const LiveRange &LR) const {
72      return start < LR.start || (start == LR.start && end < LR.end);
73    }
74    bool operator==(const LiveRange &LR) const {
75      return start == LR.start && end == LR.end;
76    }
77
78    void dump() const;
79    void print(std::ostream &os) const;
80    void print(std::ostream *os) const { if (os) print(*os); }
81
82  private:
83    LiveRange(); // DO NOT IMPLEMENT
84  };
85
86  std::ostream& operator<<(std::ostream& os, const LiveRange &LR);
87
88
89  inline bool operator<(unsigned V, const LiveRange &LR) {
90    return V < LR.start;
91  }
92
93  inline bool operator<(const LiveRange &LR, unsigned V) {
94    return LR.start < V;
95  }
96
97  /// LiveInterval - This class represents some number of live ranges for a
98  /// register or value.  This class also contains a bit of register allocator
99  /// state.
100  struct LiveInterval {
101    typedef SmallVector<LiveRange,4> Ranges;
102    typedef SmallVector<VNInfo*,4> VNInfoList;
103
104    unsigned reg;        // the register of this interval
105    unsigned preference; // preferred register to allocate for this interval
106    float weight;        // weight of this interval
107    Ranges ranges;       // the ranges in which this register is live
108    VNInfoList valnos;   // value#'s
109
110  public:
111    LiveInterval(unsigned Reg, float Weight)
112      : reg(Reg), preference(0), weight(Weight) {
113    }
114
115    typedef Ranges::iterator iterator;
116    iterator begin() { return ranges.begin(); }
117    iterator end()   { return ranges.end(); }
118
119    typedef Ranges::const_iterator const_iterator;
120    const_iterator begin() const { return ranges.begin(); }
121    const_iterator end() const  { return ranges.end(); }
122
123    typedef VNInfoList::iterator vni_iterator;
124    vni_iterator vni_begin() { return valnos.begin(); }
125    vni_iterator vni_end() { return valnos.end(); }
126
127    typedef VNInfoList::const_iterator const_vni_iterator;
128    const_vni_iterator vni_begin() const { return valnos.begin(); }
129    const_vni_iterator vni_end() const { return valnos.end(); }
130
131    /// advanceTo - Advance the specified iterator to point to the LiveRange
132    /// containing the specified position, or end() if the position is past the
133    /// end of the interval.  If no LiveRange contains this position, but the
134    /// position is in a hole, this method returns an iterator pointing the the
135    /// LiveRange immediately after the hole.
136    iterator advanceTo(iterator I, unsigned Pos) {
137      if (Pos >= endNumber())
138        return end();
139      while (I->end <= Pos) ++I;
140      return I;
141    }
142
143    bool containsOneValue() const { return valnos.size() == 1; }
144
145    unsigned getNumValNums() const { return valnos.size(); }
146
147    /// getValNumInfo - Returns pointer to the specified val#.
148    ///
149    inline VNInfo *getValNumInfo(unsigned ValNo) {
150      return valnos[ValNo];
151    }
152    inline const VNInfo *getValNumInfo(unsigned ValNo) const {
153      return valnos[ValNo];
154    }
155
156    /// copyValNumInfo - Copy the value number info for one value number to
157    /// another.
158    void copyValNumInfo(VNInfo *DstValNo, VNInfo *SrcValNo) {
159      DstValNo->def = SrcValNo->def;
160      DstValNo->reg = SrcValNo->reg;
161      DstValNo->kills = SrcValNo->kills;
162    }
163
164    /// getNextValue - Create a new value number and return it.  MIIdx specifies
165    /// the instruction that defines the value number.
166    VNInfo *getNextValue(unsigned MIIdx, unsigned SrcReg) {
167#ifdef __GNUC__
168      unsigned Alignment = __alignof__(VNInfo);
169#else
170      // FIXME: ugly.
171      unsigned Alignment = 8;
172#endif
173      VNInfo *VNI= static_cast<VNInfo*>(VNInfoAllocator.Allocate(sizeof(VNInfo),
174                                                                 Alignment));
175      new (VNI) VNInfo(valnos.size(), MIIdx, SrcReg);
176      valnos.push_back(VNI);
177      return VNI;
178    }
179
180    /// addKillForValNum - Add a kill instruction index to the specified value
181    /// number.
182    static void addKill(VNInfo *VNI, unsigned KillIdx) {
183      SmallVector<unsigned, 4> &kills = VNI->kills;
184      if (kills.empty()) {
185        kills.push_back(KillIdx);
186      } else {
187        SmallVector<unsigned, 4>::iterator
188          I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
189        kills.insert(I, KillIdx);
190      }
191    }
192
193    /// addKills - Add a number of kills into the VNInfo kill vector. If this
194    /// interval is live at a kill point, then the kill is not added.
195    void addKills(VNInfo *VNI, const SmallVector<unsigned, 4> &kills) {
196      for (unsigned i = 0, e = kills.size(); i != e; ++i) {
197        unsigned KillIdx = kills[i];
198        if (!liveAt(KillIdx)) {
199          SmallVector<unsigned, 4>::iterator
200            I = std::lower_bound(VNI->kills.begin(), VNI->kills.end(), KillIdx);
201          VNI->kills.insert(I, KillIdx);
202        }
203      }
204    }
205
206    /// removeKill - Remove the specified kill from the list of kills of
207    /// the specified val#.
208    static bool removeKill(VNInfo *VNI, unsigned KillIdx) {
209      SmallVector<unsigned, 4> &kills = VNI->kills;
210      SmallVector<unsigned, 4>::iterator
211        I = std::lower_bound(kills.begin(), kills.end(), KillIdx);
212      if (I != kills.end() && *I == KillIdx) {
213        kills.erase(I);
214        return true;
215      }
216      return false;
217    }
218
219    /// removeKills - Remove all the kills in specified range
220    /// [Start, End] of the specified val#.
221    void removeKills(VNInfo *VNI, unsigned Start, unsigned End) {
222      SmallVector<unsigned, 4> &kills = VNI->kills;
223      SmallVector<unsigned, 4>::iterator
224        I = std::lower_bound(kills.begin(), kills.end(), Start);
225      SmallVector<unsigned, 4>::iterator
226        E = std::upper_bound(kills.begin(), kills.end(), End);
227      kills.erase(I, E);
228    }
229
230    /// MergeValueNumberInto - This method is called when two value nubmers
231    /// are found to be equivalent.  This eliminates V1, replacing all
232    /// LiveRanges with the V1 value number with the V2 value number.  This can
233    /// cause merging of V1/V2 values numbers and compaction of the value space.
234    void MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
235
236    /// MergeInClobberRanges - For any live ranges that are not defined in the
237    /// current interval, but are defined in the Clobbers interval, mark them
238    /// used with an unknown definition value. Caller must pass in reference to
239    /// VNInfoAllocator since it will create a new val#.
240    void MergeInClobberRanges(const LiveInterval &Clobbers,
241                              BumpPtrAllocator &VNInfoAllocator);
242
243    /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
244    /// interval as the specified value number.  The LiveRanges in RHS are
245    /// allowed to overlap with LiveRanges in the current interval, but only if
246    /// the overlapping LiveRanges have the specified value number.
247    void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
248
249    bool empty() const { return ranges.empty(); }
250
251    /// beginNumber - Return the lowest numbered slot covered by interval.
252    unsigned beginNumber() const {
253      assert(!empty() && "empty interval for register");
254      return ranges.front().start;
255    }
256
257    /// endNumber - return the maximum point of the interval of the whole,
258    /// exclusive.
259    unsigned endNumber() const {
260      assert(!empty() && "empty interval for register");
261      return ranges.back().end;
262    }
263
264    bool expiredAt(unsigned index) const {
265      return index >= endNumber();
266    }
267
268    bool liveAt(unsigned index) const;
269
270    /// getLiveRangeContaining - Return the live range that contains the
271    /// specified index, or null if there is none.
272    const LiveRange *getLiveRangeContaining(unsigned Idx) const {
273      const_iterator I = FindLiveRangeContaining(Idx);
274      return I == end() ? 0 : &*I;
275    }
276
277    /// FindLiveRangeContaining - Return an iterator to the live range that
278    /// contains the specified index, or end() if there is none.
279    const_iterator FindLiveRangeContaining(unsigned Idx) const;
280
281    /// FindLiveRangeContaining - Return an iterator to the live range that
282    /// contains the specified index, or end() if there is none.
283    iterator FindLiveRangeContaining(unsigned Idx);
284
285    /// getOverlapingRanges - Given another live interval which is defined as a
286    /// copy from this one, return a list of all of the live ranges where the
287    /// two overlap and have different value numbers.
288    void getOverlapingRanges(const LiveInterval &Other, unsigned CopyIdx,
289                             std::vector<LiveRange*> &Ranges);
290
291    /// overlaps - Return true if the intersection of the two live intervals is
292    /// not empty.
293    bool overlaps(const LiveInterval& other) const {
294      return overlapsFrom(other, other.begin());
295    }
296
297    /// overlapsFrom - Return true if the intersection of the two live intervals
298    /// is not empty.  The specified iterator is a hint that we can begin
299    /// scanning the Other interval starting at I.
300    bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
301
302    /// addRange - Add the specified LiveRange to this interval, merging
303    /// intervals as appropriate.  This returns an iterator to the inserted live
304    /// range (which may have grown since it was inserted.
305    void addRange(LiveRange LR) {
306      addRangeFrom(LR, ranges.begin());
307    }
308
309    /// join - Join two live intervals (this, and other) together.  This applies
310    /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
311    /// the intervals are not joinable, this aborts.
312    void join(LiveInterval &Other, int *ValNoAssignments,
313              int *RHSValNoAssignments, SmallVector<VNInfo*, 16> &NewVNInfo);
314
315    /// removeRange - Remove the specified range from this interval.  Note that
316    /// the range must already be in this interval in its entirety.
317    void removeRange(unsigned Start, unsigned End);
318
319    void removeRange(LiveRange LR) {
320      removeRange(LR.start, LR.end);
321    }
322
323    /// getSize - Returns the sum of sizes of all the LiveRange's.
324    ///
325    unsigned getSize() const;
326
327    bool operator<(const LiveInterval& other) const {
328      return beginNumber() < other.beginNumber();
329    }
330
331    void print(std::ostream &OS, const MRegisterInfo *MRI = 0) const;
332    void print(std::ostream *OS, const MRegisterInfo *MRI = 0) const {
333      if (OS) print(*OS, MRI);
334    }
335    void dump() const;
336
337  private:
338    Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
339    void extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd);
340    Ranges::iterator extendIntervalStartTo(Ranges::iterator I, unsigned NewStr);
341    LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
342  };
343
344  inline std::ostream &operator<<(std::ostream &OS, const LiveInterval &LI) {
345    LI.print(OS);
346    return OS;
347  }
348}
349
350#endif
351