SplitKit.h revision 13ba2dab631636e525a44bb259aaea56a860d1c7
1//===-------- SplitKit.h - Toolkit for splitting live ranges ----*- 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 contains the SplitAnalysis class as well as mutator functions for
11// live range splitting.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/BitVector.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/IndexedMap.h"
18#include "llvm/ADT/IntervalMap.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/CodeGen/SlotIndexes.h"
21
22namespace llvm {
23
24class ConnectedVNInfoEqClasses;
25class LiveInterval;
26class LiveIntervals;
27class LiveRangeEdit;
28class MachineInstr;
29class MachineLoopInfo;
30class MachineRegisterInfo;
31class TargetInstrInfo;
32class TargetRegisterInfo;
33class VirtRegMap;
34class VNInfo;
35class raw_ostream;
36
37/// At some point we should just include MachineDominators.h:
38class MachineDominatorTree;
39template <class NodeT> class DomTreeNodeBase;
40typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
41
42
43/// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
44/// opportunities.
45class SplitAnalysis {
46public:
47  const MachineFunction &MF;
48  const VirtRegMap &VRM;
49  const LiveIntervals &LIS;
50  const MachineLoopInfo &Loops;
51  const TargetInstrInfo &TII;
52
53  // Instructions using the the current register.
54  typedef SmallPtrSet<const MachineInstr*, 16> InstrPtrSet;
55  InstrPtrSet UsingInstrs;
56
57  // Sorted slot indexes of using instructions.
58  SmallVector<SlotIndex, 8> UseSlots;
59
60  // The number of instructions using CurLI in each basic block.
61  typedef DenseMap<const MachineBasicBlock*, unsigned> BlockCountMap;
62  BlockCountMap UsingBlocks;
63
64  /// Additional information about basic blocks where the current variable is
65  /// live. Such a block will look like one of these templates:
66  ///
67  ///  1. |   o---x   | Internal to block. Variable is only live in this block.
68  ///  2. |---x       | Live-in, kill.
69  ///  3. |       o---| Def, live-out.
70  ///  4. |---x   o---| Live-in, kill, def, live-out.
71  ///  5. |---o---o---| Live-through with uses or defs.
72  ///  6. |-----------| Live-through without uses. Transparent.
73  ///
74  struct BlockInfo {
75    MachineBasicBlock *MBB;
76    SlotIndex Start;      ///< Beginining of block.
77    SlotIndex Stop;       ///< End of block.
78    SlotIndex FirstUse;   ///< First instr using current reg.
79    SlotIndex LastUse;    ///< Last instr using current reg.
80    SlotIndex Kill;       ///< Interval end point inside block.
81    SlotIndex Def;        ///< Interval start point inside block.
82    /// Last possible point for splitting live ranges.
83    SlotIndex LastSplitPoint;
84    bool Uses;            ///< Current reg has uses or defs in block.
85    bool LiveThrough;     ///< Live in whole block (Templ 5. or 6. above).
86    bool LiveIn;          ///< Current reg is live in.
87    bool LiveOut;         ///< Current reg is live out.
88
89    // Per-interference pattern scratch data.
90    bool OverlapEntry;    ///< Interference overlaps entering interval.
91    bool OverlapExit;     ///< Interference overlaps exiting interval.
92  };
93
94  /// Basic blocks where var is live. This array is parallel to
95  /// SpillConstraints.
96  SmallVector<BlockInfo, 8> LiveBlocks;
97
98private:
99  // Current live interval.
100  const LiveInterval *CurLI;
101
102  // Sumarize statistics by counting instructions using CurLI.
103  void analyzeUses();
104
105  /// calcLiveBlockInfo - Compute per-block information about CurLI.
106  void calcLiveBlockInfo();
107
108  /// canAnalyzeBranch - Return true if MBB ends in a branch that can be
109  /// analyzed.
110  bool canAnalyzeBranch(const MachineBasicBlock *MBB);
111
112public:
113  SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
114                const MachineLoopInfo &mli);
115
116  /// analyze - set CurLI to the specified interval, and analyze how it may be
117  /// split.
118  void analyze(const LiveInterval *li);
119
120  /// clear - clear all data structures so SplitAnalysis is ready to analyze a
121  /// new interval.
122  void clear();
123
124  /// getParent - Return the last analyzed interval.
125  const LiveInterval &getParent() const { return *CurLI; }
126
127  /// hasUses - Return true if MBB has any uses of CurLI.
128  bool hasUses(const MachineBasicBlock *MBB) const {
129    return UsingBlocks.lookup(MBB);
130  }
131
132  /// isOriginalEndpoint - Return true if the original live range was killed or
133  /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
134  /// and 'use' for an early-clobber def.
135  /// This can be used to recognize code inserted by earlier live range
136  /// splitting.
137  bool isOriginalEndpoint(SlotIndex Idx) const;
138
139  typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
140
141  // Print a set of blocks with use counts.
142  void print(const BlockPtrSet&, raw_ostream&) const;
143
144  /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
145  /// having CurLI split to a new live interval. Return true if Blocks can be
146  /// passed to SplitEditor::splitSingleBlocks.
147  bool getMultiUseBlocks(BlockPtrSet &Blocks);
148};
149
150
151/// SplitEditor - Edit machine code and LiveIntervals for live range
152/// splitting.
153///
154/// - Create a SplitEditor from a SplitAnalysis.
155/// - Start a new live interval with openIntv.
156/// - Mark the places where the new interval is entered using enterIntv*
157/// - Mark the ranges where the new interval is used with useIntv*
158/// - Mark the places where the interval is exited with exitIntv*.
159/// - Finish the current interval with closeIntv and repeat from 2.
160/// - Rewrite instructions with finish().
161///
162class SplitEditor {
163  SplitAnalysis &SA;
164  LiveIntervals &LIS;
165  VirtRegMap &VRM;
166  MachineRegisterInfo &MRI;
167  MachineDominatorTree &MDT;
168  const TargetInstrInfo &TII;
169  const TargetRegisterInfo &TRI;
170
171  /// Edit - The current parent register and new intervals created.
172  LiveRangeEdit *Edit;
173
174  /// Index into Edit of the currently open interval.
175  /// The index 0 is used for the complement, so the first interval started by
176  /// openIntv will be 1.
177  unsigned OpenIdx;
178
179  typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
180
181  /// Allocator for the interval map. This will eventually be shared with
182  /// SlotIndexes and LiveIntervals.
183  RegAssignMap::Allocator Allocator;
184
185  /// RegAssign - Map of the assigned register indexes.
186  /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
187  /// Idx.
188  RegAssignMap RegAssign;
189
190  typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
191
192  /// Values - keep track of the mapping from parent values to values in the new
193  /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
194  ///
195  /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
196  /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
197  ///    Each value is represented by a minimal live range at its def.
198  /// 3. A non-null VNInfo - the value is mapped to a single new value.
199  ///    The new value has no live ranges anywhere.
200  ValueMap Values;
201
202  typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
203  typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
204
205  // LiveOutCache - Map each basic block where a new register is live out to the
206  // live-out value and its defining block.
207  // One of these conditions shall be true:
208  //
209  //  1. !LiveOutCache.count(MBB)
210  //  2. LiveOutCache[MBB].second.getNode() == MBB
211  //  3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
212  //
213  // This is only a cache, the values can be computed as:
214  //
215  //  VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
216  //  Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
217  //
218  // The cache is also used as a visited set by extendRange(). It can be shared
219  // by all the new registers because at most one is live out of each block.
220  LiveOutMap LiveOutCache;
221
222  // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
223  // entry in LiveOutCache.
224  BitVector LiveOutSeen;
225
226  /// defValue - define a value in RegIdx from ParentVNI at Idx.
227  /// Idx does not have to be ParentVNI->def, but it must be contained within
228  /// ParentVNI's live range in ParentLI. The new value is added to the value
229  /// map.
230  /// Return the new LI value.
231  VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
232
233  /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
234  /// of the number of defs.
235  void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
236
237  /// defFromParent - Define Reg from ParentVNI at UseIdx using either
238  /// rematerialization or a COPY from parent. Return the new value.
239  VNInfo *defFromParent(unsigned RegIdx,
240                        VNInfo *ParentVNI,
241                        SlotIndex UseIdx,
242                        MachineBasicBlock &MBB,
243                        MachineBasicBlock::iterator I);
244
245  /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
246  /// Insert PHIDefs as needed to preserve SSA form.
247  void extendRange(unsigned RegIdx, SlotIndex Idx);
248
249  /// updateSSA - Insert PHIDefs as necessary and update LiveOutCache such that
250  /// Edit.get(RegIdx) is live-in to all the blocks in LiveIn.
251  /// Return the value that is eventually live-in to IdxMBB.
252  VNInfo *updateSSA(unsigned RegIdx,
253                    SmallVectorImpl<MachineDomTreeNode*> &LiveIn,
254                    SlotIndex Idx,
255                    const MachineBasicBlock *IdxMBB);
256
257  /// transferSimpleValues - Transfer simply defined values to the new ranges.
258  /// Return true if any complex ranges were skipped.
259  bool transferSimpleValues();
260
261  /// extendPHIKillRanges - Extend the ranges of all values killed by original
262  /// parent PHIDefs.
263  void extendPHIKillRanges();
264
265  /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
266  void rewriteAssigned(bool ExtendRanges);
267
268  /// rewriteComponents - Rewrite all uses of Intv[0] according to the eq
269  /// classes in ConEQ.
270  /// This must be done when Intvs[0] is styill live at all uses, before calling
271  /// ConEq.Distribute().
272  void rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs,
273                         const ConnectedVNInfoEqClasses &ConEq);
274
275public:
276  /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
277  /// Newly created intervals will be appended to newIntervals.
278  SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
279              MachineDominatorTree&);
280
281  /// reset - Prepare for a new split.
282  void reset(LiveRangeEdit&);
283
284  /// Create a new virtual register and live interval.
285  void openIntv();
286
287  /// enterIntvBefore - Enter the open interval before the instruction at Idx.
288  /// If the parent interval is not live before Idx, a COPY is not inserted.
289  /// Return the beginning of the new live range.
290  SlotIndex enterIntvBefore(SlotIndex Idx);
291
292  /// enterIntvAtEnd - Enter the open interval at the end of MBB.
293  /// Use the open interval from he inserted copy to the MBB end.
294  /// Return the beginning of the new live range.
295  SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
296
297  /// useIntv - indicate that all instructions in MBB should use OpenLI.
298  void useIntv(const MachineBasicBlock &MBB);
299
300  /// useIntv - indicate that all instructions in range should use OpenLI.
301  void useIntv(SlotIndex Start, SlotIndex End);
302
303  /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
304  /// Return the end of the live range.
305  SlotIndex leaveIntvAfter(SlotIndex Idx);
306
307  /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
308  /// Return the end of the live range.
309  SlotIndex leaveIntvBefore(SlotIndex Idx);
310
311  /// leaveIntvAtTop - Leave the interval at the top of MBB.
312  /// Add liveness from the MBB top to the copy.
313  /// Return the end of the live range.
314  SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
315
316  /// overlapIntv - Indicate that all instructions in range should use the open
317  /// interval, but also let the complement interval be live.
318  ///
319  /// This doubles the register pressure, but is sometimes required to deal with
320  /// register uses after the last valid split point.
321  ///
322  /// The Start index should be a return value from a leaveIntv* call, and End
323  /// should be in the same basic block. The parent interval must have the same
324  /// value across the range.
325  ///
326  void overlapIntv(SlotIndex Start, SlotIndex End);
327
328  /// closeIntv - Indicate that we are done editing the currently open
329  /// LiveInterval, and ranges can be trimmed.
330  void closeIntv();
331
332  /// finish - after all the new live ranges have been created, compute the
333  /// remaining live range, and rewrite instructions to use the new registers.
334  void finish();
335
336  /// dump - print the current interval maping to dbgs().
337  void dump() const;
338
339  // ===--- High level methods ---===
340
341  /// splitSingleBlocks - Split CurLI into a separate live interval inside each
342  /// basic block in Blocks.
343  void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
344};
345
346}
347