Delete BlockInfo::LiveThrough. It wasn't used any more.
[oota-llvm.git] / lib / CodeGen / SplitKit.h
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 #ifndef LLVM_CODEGEN_SPLITKIT_H
16 #define LLVM_CODEGEN_SPLITKIT_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IndexedMap.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25
26 namespace llvm {
27
28 class ConnectedVNInfoEqClasses;
29 class LiveInterval;
30 class LiveIntervals;
31 class LiveRangeEdit;
32 class MachineInstr;
33 class MachineLoopInfo;
34 class MachineRegisterInfo;
35 class TargetInstrInfo;
36 class TargetRegisterInfo;
37 class VirtRegMap;
38 class VNInfo;
39 class raw_ostream;
40
41 /// At some point we should just include MachineDominators.h:
42 class MachineDominatorTree;
43 template <class NodeT> class DomTreeNodeBase;
44 typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
45
46
47 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
48 /// opportunities.
49 class SplitAnalysis {
50 public:
51   const MachineFunction &MF;
52   const VirtRegMap &VRM;
53   const LiveIntervals &LIS;
54   const MachineLoopInfo &Loops;
55   const TargetInstrInfo &TII;
56
57   // Sorted slot indexes of using instructions.
58   SmallVector<SlotIndex, 8> UseSlots;
59
60   /// Additional information about basic blocks where the current variable is
61   /// live. Such a block will look like one of these templates:
62   ///
63   ///  1. |   o---x   | Internal to block. Variable is only live in this block.
64   ///  2. |---x       | Live-in, kill.
65   ///  3. |       o---| Def, live-out.
66   ///  4. |---x   o---| Live-in, kill, def, live-out. Counted by NumGapBlocks.
67   ///  5. |---o---o---| Live-through with uses or defs.
68   ///  6. |-----------| Live-through without uses. Counted by NumThroughBlocks.
69   ///
70   /// Two BlockInfo entries are created for template 4. One for the live-in
71   /// segment, and one for the live-out segment. These entries look as if the
72   /// block were split in the middle where the live range isn't live.
73   ///
74   /// Live-through blocks without any uses don't get BlockInfo entries. They
75   /// are simply listed in ThroughBlocks instead.
76   ///
77   struct BlockInfo {
78     MachineBasicBlock *MBB;
79     SlotIndex FirstUse;   ///< First instr using current reg.
80     SlotIndex LastUse;    ///< Last instr using current reg.
81     bool LiveIn;          ///< Current reg is live in.
82     bool LiveOut;         ///< Current reg is live out.
83
84     /// isOneInstr - Returns true when this BlockInfo describes a single
85     /// instruction.
86     bool isOneInstr() const {
87       return SlotIndex::isSameInstr(FirstUse, LastUse);
88     }
89   };
90
91 private:
92   // Current live interval.
93   const LiveInterval *CurLI;
94
95   /// LastSplitPoint - Last legal split point in each basic block in the current
96   /// function. The first entry is the first terminator, the second entry is the
97   /// last valid split point for a variable that is live in to a landing pad
98   /// successor.
99   SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
100
101   /// UseBlocks - Blocks where CurLI has uses.
102   SmallVector<BlockInfo, 8> UseBlocks;
103
104   /// NumGapBlocks - Number of duplicate entries in UseBlocks for blocks where
105   /// the live range has a gap.
106   unsigned NumGapBlocks;
107
108   /// ThroughBlocks - Block numbers where CurLI is live through without uses.
109   BitVector ThroughBlocks;
110
111   /// NumThroughBlocks - Number of live-through blocks.
112   unsigned NumThroughBlocks;
113
114   /// DidRepairRange - analyze was forced to shrinkToUses().
115   bool DidRepairRange;
116
117   SlotIndex computeLastSplitPoint(unsigned Num);
118
119   // Sumarize statistics by counting instructions using CurLI.
120   void analyzeUses();
121
122   /// calcLiveBlockInfo - Compute per-block information about CurLI.
123   bool calcLiveBlockInfo();
124
125 public:
126   SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
127                 const MachineLoopInfo &mli);
128
129   /// analyze - set CurLI to the specified interval, and analyze how it may be
130   /// split.
131   void analyze(const LiveInterval *li);
132
133   /// didRepairRange() - Returns true if CurLI was invalid and has been repaired
134   /// by analyze(). This really shouldn't happen, but sometimes the coalescer
135   /// can create live ranges that end in mid-air.
136   bool didRepairRange() const { return DidRepairRange; }
137
138   /// clear - clear all data structures so SplitAnalysis is ready to analyze a
139   /// new interval.
140   void clear();
141
142   /// getParent - Return the last analyzed interval.
143   const LiveInterval &getParent() const { return *CurLI; }
144
145   /// getLastSplitPoint - Return that base index of the last valid split point
146   /// in the basic block numbered Num.
147   SlotIndex getLastSplitPoint(unsigned Num) {
148     // Inline the common simple case.
149     if (LastSplitPoint[Num].first.isValid() &&
150         !LastSplitPoint[Num].second.isValid())
151       return LastSplitPoint[Num].first;
152     return computeLastSplitPoint(Num);
153   }
154
155   /// isOriginalEndpoint - Return true if the original live range was killed or
156   /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
157   /// and 'use' for an early-clobber def.
158   /// This can be used to recognize code inserted by earlier live range
159   /// splitting.
160   bool isOriginalEndpoint(SlotIndex Idx) const;
161
162   /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
163   /// where CurLI has uses.
164   ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
165
166   /// getNumThroughBlocks - Return the number of through blocks.
167   unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
168
169   /// isThroughBlock - Return true if CurLI is live through MBB without uses.
170   bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
171
172   /// getThroughBlocks - Return the set of through blocks.
173   const BitVector &getThroughBlocks() const { return ThroughBlocks; }
174
175   /// getNumLiveBlocks - Return the number of blocks where CurLI is live.
176   unsigned getNumLiveBlocks() const {
177     return getUseBlocks().size() - NumGapBlocks + getNumThroughBlocks();
178   }
179
180   /// countLiveBlocks - Return the number of blocks where li is live. This is
181   /// guaranteed to return the same number as getNumLiveBlocks() after calling
182   /// analyze(li).
183   unsigned countLiveBlocks(const LiveInterval *li) const;
184
185   typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
186
187   /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
188   /// having CurLI split to a new live interval. Return true if Blocks can be
189   /// passed to SplitEditor::splitSingleBlocks.
190   bool getMultiUseBlocks(BlockPtrSet &Blocks);
191 };
192
193
194 /// SplitEditor - Edit machine code and LiveIntervals for live range
195 /// splitting.
196 ///
197 /// - Create a SplitEditor from a SplitAnalysis.
198 /// - Start a new live interval with openIntv.
199 /// - Mark the places where the new interval is entered using enterIntv*
200 /// - Mark the ranges where the new interval is used with useIntv* 
201 /// - Mark the places where the interval is exited with exitIntv*.
202 /// - Finish the current interval with closeIntv and repeat from 2.
203 /// - Rewrite instructions with finish().
204 ///
205 class SplitEditor {
206   SplitAnalysis &SA;
207   LiveIntervals &LIS;
208   VirtRegMap &VRM;
209   MachineRegisterInfo &MRI;
210   MachineDominatorTree &MDT;
211   const TargetInstrInfo &TII;
212   const TargetRegisterInfo &TRI;
213
214   /// Edit - The current parent register and new intervals created.
215   LiveRangeEdit *Edit;
216
217   /// Index into Edit of the currently open interval.
218   /// The index 0 is used for the complement, so the first interval started by
219   /// openIntv will be 1.
220   unsigned OpenIdx;
221
222   typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
223
224   /// Allocator for the interval map. This will eventually be shared with
225   /// SlotIndexes and LiveIntervals.
226   RegAssignMap::Allocator Allocator;
227
228   /// RegAssign - Map of the assigned register indexes.
229   /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
230   /// Idx.
231   RegAssignMap RegAssign;
232
233   typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
234
235   /// Values - keep track of the mapping from parent values to values in the new
236   /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
237   ///
238   /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
239   /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
240   ///    Each value is represented by a minimal live range at its def.
241   /// 3. A non-null VNInfo - the value is mapped to a single new value.
242   ///    The new value has no live ranges anywhere.
243   ValueMap Values;
244
245   typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
246   typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
247
248   // LiveOutCache - Map each basic block where a new register is live out to the
249   // live-out value and its defining block.
250   // One of these conditions shall be true:
251   //
252   //  1. !LiveOutCache.count(MBB)
253   //  2. LiveOutCache[MBB].second.getNode() == MBB
254   //  3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
255   //
256   // This is only a cache, the values can be computed as:
257   //
258   //  VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
259   //  Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
260   //
261   // The cache is also used as a visited set by extendRange(). It can be shared
262   // by all the new registers because at most one is live out of each block.
263   LiveOutMap LiveOutCache;
264
265   // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
266   // entry in LiveOutCache.
267   BitVector LiveOutSeen;
268
269   /// LiveInBlock - Info for updateSSA() about a block where a register is
270   /// live-in.
271   /// The updateSSA caller provides DomNode and Kill inside MBB, updateSSA()
272   /// adds the computed live-in value.
273   struct LiveInBlock {
274     // Dominator tree node for the block.
275     // Cleared by updateSSA when the final value has been determined.
276     MachineDomTreeNode *DomNode;
277
278     // Live-in value filled in by updateSSA once it is known.
279     VNInfo *Value;
280
281     // Position in block where the live-in range ends, or SlotIndex() if the
282     // range passes through the block.
283     SlotIndex Kill;
284
285     LiveInBlock(MachineDomTreeNode *node) : DomNode(node), Value(0) {}
286   };
287
288   /// LiveInBlocks - List of live-in blocks used by findReachingDefs() and
289   /// updateSSA(). This list is usually empty, it exists here to avoid frequent
290   /// reallocations.
291   SmallVector<LiveInBlock, 16> LiveInBlocks;
292
293   /// defValue - define a value in RegIdx from ParentVNI at Idx.
294   /// Idx does not have to be ParentVNI->def, but it must be contained within
295   /// ParentVNI's live range in ParentLI. The new value is added to the value
296   /// map.
297   /// Return the new LI value.
298   VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
299
300   /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
301   /// of the number of defs.
302   void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
303
304   /// defFromParent - Define Reg from ParentVNI at UseIdx using either
305   /// rematerialization or a COPY from parent. Return the new value.
306   VNInfo *defFromParent(unsigned RegIdx,
307                         VNInfo *ParentVNI,
308                         SlotIndex UseIdx,
309                         MachineBasicBlock &MBB,
310                         MachineBasicBlock::iterator I);
311
312   /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
313   /// Insert PHIDefs as needed to preserve SSA form.
314   void extendRange(unsigned RegIdx, SlotIndex Idx);
315
316   /// findReachingDefs - Starting from MBB, add blocks to LiveInBlocks until all
317   /// reaching defs for LI are found.
318   /// @param LI   Live interval whose value is needed.
319   /// @param MBB  Block where LI should be live-in.
320   /// @param Kill Kill point in MBB.
321   /// @return Unique value seen, or NULL.
322   VNInfo *findReachingDefs(LiveInterval *LI, MachineBasicBlock *MBB,
323                            SlotIndex Kill);
324
325   /// updateSSA - Compute and insert PHIDefs such that all blocks in
326   // LiveInBlocks get a known live-in value. Add live ranges to the blocks.
327   void updateSSA();
328
329   /// transferValues - Transfer values to the new ranges.
330   /// Return true if any ranges were skipped.
331   bool transferValues();
332
333   /// extendPHIKillRanges - Extend the ranges of all values killed by original
334   /// parent PHIDefs.
335   void extendPHIKillRanges();
336
337   /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
338   void rewriteAssigned(bool ExtendRanges);
339
340   /// deleteRematVictims - Delete defs that are dead after rematerializing.
341   void deleteRematVictims();
342
343 public:
344   /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
345   /// Newly created intervals will be appended to newIntervals.
346   SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
347               MachineDominatorTree&);
348
349   /// reset - Prepare for a new split.
350   void reset(LiveRangeEdit&);
351
352   /// Create a new virtual register and live interval.
353   /// Return the interval index, starting from 1. Interval index 0 is the
354   /// implicit complement interval.
355   unsigned openIntv();
356
357   /// currentIntv - Return the current interval index.
358   unsigned currentIntv() const { return OpenIdx; }
359
360   /// selectIntv - Select a previously opened interval index.
361   void selectIntv(unsigned Idx);
362
363   /// enterIntvBefore - Enter the open interval before the instruction at Idx.
364   /// If the parent interval is not live before Idx, a COPY is not inserted.
365   /// Return the beginning of the new live range.
366   SlotIndex enterIntvBefore(SlotIndex Idx);
367
368   /// enterIntvAfter - Enter the open interval after the instruction at Idx.
369   /// Return the beginning of the new live range.
370   SlotIndex enterIntvAfter(SlotIndex Idx);
371
372   /// enterIntvAtEnd - Enter the open interval at the end of MBB.
373   /// Use the open interval from he inserted copy to the MBB end.
374   /// Return the beginning of the new live range.
375   SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
376
377   /// useIntv - indicate that all instructions in MBB should use OpenLI.
378   void useIntv(const MachineBasicBlock &MBB);
379
380   /// useIntv - indicate that all instructions in range should use OpenLI.
381   void useIntv(SlotIndex Start, SlotIndex End);
382
383   /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
384   /// Return the end of the live range.
385   SlotIndex leaveIntvAfter(SlotIndex Idx);
386
387   /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
388   /// Return the end of the live range.
389   SlotIndex leaveIntvBefore(SlotIndex Idx);
390
391   /// leaveIntvAtTop - Leave the interval at the top of MBB.
392   /// Add liveness from the MBB top to the copy.
393   /// Return the end of the live range.
394   SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
395
396   /// overlapIntv - Indicate that all instructions in range should use the open
397   /// interval, but also let the complement interval be live.
398   ///
399   /// This doubles the register pressure, but is sometimes required to deal with
400   /// register uses after the last valid split point.
401   ///
402   /// The Start index should be a return value from a leaveIntv* call, and End
403   /// should be in the same basic block. The parent interval must have the same
404   /// value across the range.
405   ///
406   void overlapIntv(SlotIndex Start, SlotIndex End);
407
408   /// finish - after all the new live ranges have been created, compute the
409   /// remaining live range, and rewrite instructions to use the new registers.
410   /// @param LRMap When not null, this vector will map each live range in Edit
411   ///              back to the indices returned by openIntv.
412   ///              There may be extra indices created by dead code elimination.
413   void finish(SmallVectorImpl<unsigned> *LRMap = 0);
414
415   /// dump - print the current interval maping to dbgs().
416   void dump() const;
417
418   // ===--- High level methods ---===
419
420   /// splitSingleBlock - Split CurLI into a separate live interval around the
421   /// uses in a single block. This is intended to be used as part of a larger
422   /// split, and doesn't call finish().
423   void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
424
425   /// splitSingleBlocks - Split CurLI into a separate live interval inside each
426   /// basic block in Blocks.
427   void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
428
429   /// splitLiveThroughBlock - Split CurLI in the given block such that it
430   /// enters the block in IntvIn and leaves it in IntvOut. There may be uses in
431   /// the block, but they will be ignored when placing split points.
432   ///
433   /// @param MBBNum      Block number.
434   /// @param IntvIn      Interval index entering the block.
435   /// @param LeaveBefore When set, leave IntvIn before this point.
436   /// @param IntvOut     Interval index leaving the block.
437   /// @param EnterAfter  When set, enter IntvOut after this point.
438   void splitLiveThroughBlock(unsigned MBBNum,
439                              unsigned IntvIn, SlotIndex LeaveBefore,
440                              unsigned IntvOut, SlotIndex EnterAfter);
441
442   /// splitRegInBlock - Split CurLI in the given block such that it enters the
443   /// block in IntvIn and leaves it on the stack (or not at all). Split points
444   /// are placed in a way that avoids putting uses in the stack interval. This
445   /// may require creating a local interval when there is interference.
446   ///
447   /// @param BI          Block descriptor.
448   /// @param IntvIn      Interval index entering the block. Not 0.
449   /// @param LeaveBefore When set, leave IntvIn before this point.
450   void splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
451                        unsigned IntvIn, SlotIndex LeaveBefore);
452
453   /// splitRegOutBlock - Split CurLI in the given block such that it enters the
454   /// block on the stack (or isn't live-in at all) and leaves it in IntvOut.
455   /// Split points are placed to avoid interference and such that the uses are
456   /// not in the stack interval. This may require creating a local interval
457   /// when there is interference.
458   ///
459   /// @param BI          Block descriptor.
460   /// @param IntvOut     Interval index leaving the block.
461   /// @param EnterAfter  When set, enter IntvOut after this point.
462   void splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
463                         unsigned IntvOut, SlotIndex EnterAfter);
464 };
465
466 }
467
468 #endif