9ba7cbeb1001616326a2d7fcaf54dd25c4f7f5dc
[oota-llvm.git] / lib / CodeGen / SplitKit.h
1 //===-------- SplitKit.cpp - 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/SmallPtrSet.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/CodeGen/SlotIndexes.h"
18
19 namespace llvm {
20
21 class LiveInterval;
22 class LiveIntervals;
23 class LiveRangeEdit;
24 class MachineInstr;
25 class MachineDominatorTree;
26 class MachineLoop;
27 class MachineLoopInfo;
28 class MachineRegisterInfo;
29 class TargetInstrInfo;
30 class VirtRegMap;
31 class VNInfo;
32 class raw_ostream;
33
34 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
35 /// opportunities.
36 class SplitAnalysis {
37 public:
38   const MachineFunction &mf_;
39   const LiveIntervals &lis_;
40   const MachineLoopInfo &loops_;
41   const TargetInstrInfo &tii_;
42
43   // Instructions using the the current register.
44   typedef SmallPtrSet<const MachineInstr*, 16> InstrPtrSet;
45   InstrPtrSet usingInstrs_;
46
47   // The number of instructions using curli in each basic block.
48   typedef DenseMap<const MachineBasicBlock*, unsigned> BlockCountMap;
49   BlockCountMap usingBlocks_;
50
51   // The number of basic block using curli in each loop.
52   typedef DenseMap<const MachineLoop*, unsigned> LoopCountMap;
53   LoopCountMap usingLoops_;
54
55 private:
56   // Current live interval.
57   const LiveInterval *curli_;
58
59   // Sumarize statistics by counting instructions using curli_.
60   void analyzeUses();
61
62   /// canAnalyzeBranch - Return true if MBB ends in a branch that can be
63   /// analyzed.
64   bool canAnalyzeBranch(const MachineBasicBlock *MBB);
65
66 public:
67   SplitAnalysis(const MachineFunction &mf, const LiveIntervals &lis,
68                 const MachineLoopInfo &mli);
69
70   /// analyze - set curli to the specified interval, and analyze how it may be
71   /// split.
72   void analyze(const LiveInterval *li);
73
74   /// clear - clear all data structures so SplitAnalysis is ready to analyze a
75   /// new interval.
76   void clear();
77
78   typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
79   typedef SmallPtrSet<const MachineLoop*, 16> LoopPtrSet;
80
81   // Print a set of blocks with use counts.
82   void print(const BlockPtrSet&, raw_ostream&) const;
83
84   // Sets of basic blocks surrounding a machine loop.
85   struct LoopBlocks {
86     BlockPtrSet Loop;  // Blocks in the loop.
87     BlockPtrSet Preds; // Loop predecessor blocks.
88     BlockPtrSet Exits; // Loop exit blocks.
89
90     void clear() {
91       Loop.clear();
92       Preds.clear();
93       Exits.clear();
94     }
95   };
96
97   // Print loop blocks with use counts.
98   void print(const LoopBlocks&, raw_ostream&) const;
99
100   // Calculate the block sets surrounding the loop.
101   void getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks);
102
103   /// LoopPeripheralUse - how is a variable used in and around a loop?
104   /// Peripheral blocks are the loop predecessors and exit blocks.
105   enum LoopPeripheralUse {
106     ContainedInLoop,  // All uses are inside the loop.
107     SinglePeripheral, // At most one instruction per peripheral block.
108     MultiPeripheral,  // Multiple instructions in some peripheral blocks.
109     OutsideLoop       // Uses outside loop periphery.
110   };
111
112   /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
113   /// and around the Loop.
114   LoopPeripheralUse analyzeLoopPeripheralUse(const LoopBlocks&);
115
116   /// getCriticalExits - It may be necessary to partially break critical edges
117   /// leaving the loop if an exit block has phi uses of curli. Collect the exit
118   /// blocks that need special treatment into CriticalExits.
119   void getCriticalExits(const LoopBlocks &Blocks, BlockPtrSet &CriticalExits);
120
121   /// canSplitCriticalExits - Return true if it is possible to insert new exit
122   /// blocks before the blocks in CriticalExits.
123   bool canSplitCriticalExits(const LoopBlocks &Blocks,
124                              BlockPtrSet &CriticalExits);
125
126   /// getCriticalPreds - Get the set of loop predecessors with critical edges to
127   /// blocks outside the loop that have curli live in. We don't have to break
128   /// these edges, but they do require special treatment.
129   void getCriticalPreds(const LoopBlocks &Blocks, BlockPtrSet &CriticalPreds);
130
131   /// getBestSplitLoop - Return the loop where curli may best be split to a
132   /// separate register, or NULL.
133   const MachineLoop *getBestSplitLoop();
134
135   /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
136   /// having curli split to a new live interval. Return true if Blocks can be
137   /// passed to SplitEditor::splitSingleBlocks.
138   bool getMultiUseBlocks(BlockPtrSet &Blocks);
139
140   /// getBlockForInsideSplit - If curli is contained inside a single basic block,
141   /// and it wou pay to subdivide the interval inside that block, return it.
142   /// Otherwise return NULL. The returned block can be passed to
143   /// SplitEditor::splitInsideBlock.
144   const MachineBasicBlock *getBlockForInsideSplit();
145 };
146
147
148 /// LiveIntervalMap - Map values from a large LiveInterval into a small
149 /// interval that is a subset. Insert phi-def values as needed. This class is
150 /// used by SplitEditor to create new smaller LiveIntervals.
151 ///
152 /// parentli_ is the larger interval, li_ is the subset interval. Every value
153 /// in li_ corresponds to exactly one value in parentli_, and the live range
154 /// of the value is contained within the live range of the parentli_ value.
155 /// Values in parentli_ may map to any number of openli_ values, including 0.
156 class LiveIntervalMap {
157   LiveIntervals &lis_;
158   MachineDominatorTree &mdt_;
159
160   // The parent interval is never changed.
161   const LiveInterval &parentli_;
162
163   // The child interval's values are fully contained inside parentli_ values.
164   LiveInterval *li_;
165
166   typedef DenseMap<const VNInfo*, VNInfo*> ValueMap;
167
168   // Map parentli_ values to simple values in li_ that are defined at the same
169   // SlotIndex, or NULL for parentli_ values that have complex li_ defs.
170   // Note there is a difference between values mapping to NULL (complex), and
171   // values not present (unknown/unmapped).
172   ValueMap valueMap_;
173
174 public:
175   LiveIntervalMap(LiveIntervals &lis,
176                   MachineDominatorTree &mdt,
177                   const LiveInterval &parentli)
178     : lis_(lis), mdt_(mdt), parentli_(parentli), li_(0) {}
179
180   /// reset - clear all data structures and start a new live interval.
181   void reset(LiveInterval *);
182
183   /// getLI - return the current live interval.
184   LiveInterval *getLI() const { return li_; }
185
186   /// defValue - define a value in li_ from the parentli_ value VNI and Idx.
187   /// Idx does not have to be ParentVNI->def, but it must be contained within
188   /// ParentVNI's live range in parentli_.
189   /// Return the new li_ value.
190   VNInfo *defValue(const VNInfo *ParentVNI, SlotIndex Idx);
191
192   /// mapValue - map ParentVNI to the corresponding li_ value at Idx. It is
193   /// assumed that ParentVNI is live at Idx.
194   /// If ParentVNI has not been defined by defValue, it is assumed that
195   /// ParentVNI->def dominates Idx.
196   /// If ParentVNI has been defined by defValue one or more times, a value that
197   /// dominates Idx will be returned. This may require creating extra phi-def
198   /// values and adding live ranges to li_.
199   /// If simple is not NULL, *simple will indicate if ParentVNI is a simply
200   /// mapped value.
201   VNInfo *mapValue(const VNInfo *ParentVNI, SlotIndex Idx, bool *simple = 0);
202
203   // extendTo - Find the last li_ value defined in MBB at or before Idx. The
204   // parentli is assumed to be live at Idx. Extend the live range to include
205   // Idx. Return the found VNInfo, or NULL.
206   VNInfo *extendTo(const MachineBasicBlock *MBB, SlotIndex Idx);
207
208   /// isMapped - Return true is ParentVNI is a known mapped value. It may be a
209   /// simple 1-1 mapping or a complex mapping to later defs.
210   bool isMapped(const VNInfo *ParentVNI) const {
211     return valueMap_.count(ParentVNI);
212   }
213
214   /// isComplexMapped - Return true if ParentVNI has received new definitions
215   /// with defValue.
216   bool isComplexMapped(const VNInfo *ParentVNI) const;
217
218   // addSimpleRange - Add a simple range from parentli_ to li_.
219   // ParentVNI must be live in the [Start;End) interval.
220   void addSimpleRange(SlotIndex Start, SlotIndex End, const VNInfo *ParentVNI);
221
222   /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
223   /// All needed values whose def is not inside [Start;End) must be defined
224   /// beforehand so mapValue will work.
225   void addRange(SlotIndex Start, SlotIndex End);
226
227   /// defByCopyFrom - Insert a copy from Reg to li, assuming that Reg carries
228   /// ParentVNI. Add a minimal live range for the new value and return it.
229   VNInfo *defByCopyFrom(unsigned Reg,
230                         const VNInfo *ParentVNI,
231                         MachineBasicBlock &MBB,
232                         MachineBasicBlock::iterator I);
233
234 };
235
236
237 /// SplitEditor - Edit machine code and LiveIntervals for live range
238 /// splitting.
239 ///
240 /// - Create a SplitEditor from a SplitAnalysis.
241 /// - Start a new live interval with openIntv.
242 /// - Mark the places where the new interval is entered using enterIntv*
243 /// - Mark the ranges where the new interval is used with useIntv* 
244 /// - Mark the places where the interval is exited with exitIntv*.
245 /// - Finish the current interval with closeIntv and repeat from 2.
246 /// - Rewrite instructions with finish().
247 ///
248 class SplitEditor {
249   SplitAnalysis &sa_;
250   LiveIntervals &lis_;
251   VirtRegMap &vrm_;
252   MachineRegisterInfo &mri_;
253   const TargetInstrInfo &tii_;
254
255   /// edit_ - The current parent register and new intervals created.
256   LiveRangeEdit &edit_;
257
258   /// dupli_ - Created as a copy of curli_, ranges are carved out as new
259   /// intervals get added through openIntv / closeIntv. This is used to avoid
260   /// editing curli_.
261   LiveIntervalMap dupli_;
262
263   /// Currently open LiveInterval.
264   LiveIntervalMap openli_;
265
266   /// intervalsLiveAt - Return true if any member of intervals_ is live at Idx.
267   bool intervalsLiveAt(SlotIndex Idx) const;
268
269   /// Values in curli whose live range has been truncated when entering an open
270   /// li.
271   SmallPtrSet<const VNInfo*, 8> truncatedValues;
272
273   /// addTruncSimpleRange - Add the given simple range to dupli_ after
274   /// truncating any overlap with intervals_.
275   void addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI);
276
277   /// criticalPreds_ - Set of basic blocks where both dupli and openli should be
278   /// live out because of a critical edge.
279   SplitAnalysis::BlockPtrSet criticalPreds_;
280
281   /// computeRemainder - Compute the dupli liveness as the complement of all the
282   /// new intervals.
283   void computeRemainder();
284
285   /// rewrite - Rewrite all uses of reg to use the new registers.
286   void rewrite(unsigned reg);
287
288 public:
289   /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
290   /// Newly created intervals will be appended to newIntervals.
291   SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
292               MachineDominatorTree&, LiveRangeEdit&);
293
294   /// getAnalysis - Get the corresponding analysis.
295   SplitAnalysis &getAnalysis() { return sa_; }
296
297   /// Create a new virtual register and live interval.
298   void openIntv();
299
300   /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
301   /// not live before Idx, a COPY is not inserted.
302   void enterIntvBefore(SlotIndex Idx);
303
304   /// enterIntvAtEnd - Enter openli at the end of MBB.
305   void enterIntvAtEnd(MachineBasicBlock &MBB);
306
307   /// useIntv - indicate that all instructions in MBB should use openli.
308   void useIntv(const MachineBasicBlock &MBB);
309
310   /// useIntv - indicate that all instructions in range should use openli.
311   void useIntv(SlotIndex Start, SlotIndex End);
312
313   /// leaveIntvAfter - Leave openli after the instruction at Idx.
314   void leaveIntvAfter(SlotIndex Idx);
315
316   /// leaveIntvAtTop - Leave the interval at the top of MBB.
317   /// Currently, only one value can leave the interval.
318   void leaveIntvAtTop(MachineBasicBlock &MBB);
319
320   /// closeIntv - Indicate that we are done editing the currently open
321   /// LiveInterval, and ranges can be trimmed.
322   void closeIntv();
323
324   /// finish - after all the new live ranges have been created, compute the
325   /// remaining live range, and rewrite instructions to use the new registers.
326   void finish();
327
328   // ===--- High level methods ---===
329
330   /// splitAroundLoop - Split curli into a separate live interval inside
331   /// the loop.
332   void splitAroundLoop(const MachineLoop*);
333
334   /// splitSingleBlocks - Split curli into a separate live interval inside each
335   /// basic block in Blocks.
336   void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
337
338   /// splitInsideBlock - Split curli into multiple intervals inside MBB.
339   void splitInsideBlock(const MachineBasicBlock *);
340 };
341
342 }