Revert r134047 while investigating a llvm-gcc-i386-linux-selfhost
[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 LiveThrough;     ///< Live in whole block (Templ 5. above).
82     bool LiveIn;          ///< Current reg is live in.
83     bool LiveOut;         ///< Current reg is live out.
84   };
85
86 private:
87   // Current live interval.
88   const LiveInterval *CurLI;
89
90   /// LastSplitPoint - Last legal split point in each basic block in the current
91   /// function. The first entry is the first terminator, the second entry is the
92   /// last valid split point for a variable that is live in to a landing pad
93   /// successor.
94   SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
95
96   /// UseBlocks - Blocks where CurLI has uses.
97   SmallVector<BlockInfo, 8> UseBlocks;
98
99   /// NumGapBlocks - Number of duplicate entries in UseBlocks for blocks where
100   /// the live range has a gap.
101   unsigned NumGapBlocks;
102
103   /// ThroughBlocks - Block numbers where CurLI is live through without uses.
104   BitVector ThroughBlocks;
105
106   /// NumThroughBlocks - Number of live-through blocks.
107   unsigned NumThroughBlocks;
108
109   /// DidRepairRange - analyze was forced to shrinkToUses().
110   bool DidRepairRange;
111
112   SlotIndex computeLastSplitPoint(unsigned Num);
113
114   // Sumarize statistics by counting instructions using CurLI.
115   void analyzeUses();
116
117   /// calcLiveBlockInfo - Compute per-block information about CurLI.
118   bool calcLiveBlockInfo();
119
120 public:
121   SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
122                 const MachineLoopInfo &mli);
123
124   /// analyze - set CurLI to the specified interval, and analyze how it may be
125   /// split.
126   void analyze(const LiveInterval *li);
127
128   /// didRepairRange() - Returns true if CurLI was invalid and has been repaired
129   /// by analyze(). This really shouldn't happen, but sometimes the coalescer
130   /// can create live ranges that end in mid-air.
131   bool didRepairRange() const { return DidRepairRange; }
132
133   /// clear - clear all data structures so SplitAnalysis is ready to analyze a
134   /// new interval.
135   void clear();
136
137   /// getParent - Return the last analyzed interval.
138   const LiveInterval &getParent() const { return *CurLI; }
139
140   /// getLastSplitPoint - Return that base index of the last valid split point
141   /// in the basic block numbered Num.
142   SlotIndex getLastSplitPoint(unsigned Num) {
143     // Inline the common simple case.
144     if (LastSplitPoint[Num].first.isValid() &&
145         !LastSplitPoint[Num].second.isValid())
146       return LastSplitPoint[Num].first;
147     return computeLastSplitPoint(Num);
148   }
149
150   /// isOriginalEndpoint - Return true if the original live range was killed or
151   /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
152   /// and 'use' for an early-clobber def.
153   /// This can be used to recognize code inserted by earlier live range
154   /// splitting.
155   bool isOriginalEndpoint(SlotIndex Idx) const;
156
157   /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
158   /// where CurLI has uses.
159   ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
160
161   /// getNumThroughBlocks - Return the number of through blocks.
162   unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
163
164   /// isThroughBlock - Return true if CurLI is live through MBB without uses.
165   bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
166
167   /// getThroughBlocks - Return the set of through blocks.
168   const BitVector &getThroughBlocks() const { return ThroughBlocks; }
169
170   /// getNumLiveBlocks - Return the number of blocks where CurLI is live.
171   unsigned getNumLiveBlocks() const {
172     return getUseBlocks().size() - NumGapBlocks + getNumThroughBlocks();
173   }
174
175   /// countLiveBlocks - Return the number of blocks where li is live. This is
176   /// guaranteed to return the same number as getNumLiveBlocks() after calling
177   /// analyze(li).
178   unsigned countLiveBlocks(const LiveInterval *li) const;
179
180   typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
181
182   /// getMultiUseBlocks - Add basic blocks to Blocks that may benefit from
183   /// having CurLI split to a new live interval. Return true if Blocks can be
184   /// passed to SplitEditor::splitSingleBlocks.
185   bool getMultiUseBlocks(BlockPtrSet &Blocks);
186 };
187
188
189 /// SplitEditor - Edit machine code and LiveIntervals for live range
190 /// splitting.
191 ///
192 /// - Create a SplitEditor from a SplitAnalysis.
193 /// - Start a new live interval with openIntv.
194 /// - Mark the places where the new interval is entered using enterIntv*
195 /// - Mark the ranges where the new interval is used with useIntv* 
196 /// - Mark the places where the interval is exited with exitIntv*.
197 /// - Finish the current interval with closeIntv and repeat from 2.
198 /// - Rewrite instructions with finish().
199 ///
200 class SplitEditor {
201   SplitAnalysis &SA;
202   LiveIntervals &LIS;
203   VirtRegMap &VRM;
204   MachineRegisterInfo &MRI;
205   MachineDominatorTree &MDT;
206   const TargetInstrInfo &TII;
207   const TargetRegisterInfo &TRI;
208
209   /// Edit - The current parent register and new intervals created.
210   LiveRangeEdit *Edit;
211
212   /// Index into Edit of the currently open interval.
213   /// The index 0 is used for the complement, so the first interval started by
214   /// openIntv will be 1.
215   unsigned OpenIdx;
216
217   typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
218
219   /// Allocator for the interval map. This will eventually be shared with
220   /// SlotIndexes and LiveIntervals.
221   RegAssignMap::Allocator Allocator;
222
223   /// RegAssign - Map of the assigned register indexes.
224   /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
225   /// Idx.
226   RegAssignMap RegAssign;
227
228   typedef DenseMap<std::pair<unsigned, unsigned>, VNInfo*> ValueMap;
229
230   /// Values - keep track of the mapping from parent values to values in the new
231   /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
232   ///
233   /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
234   /// 2. Null - the value is mapped to multiple values in Edit.get(RegIdx).
235   ///    Each value is represented by a minimal live range at its def.
236   /// 3. A non-null VNInfo - the value is mapped to a single new value.
237   ///    The new value has no live ranges anywhere.
238   ValueMap Values;
239
240   typedef std::pair<VNInfo*, MachineDomTreeNode*> LiveOutPair;
241   typedef IndexedMap<LiveOutPair, MBB2NumberFunctor> LiveOutMap;
242
243   // LiveOutCache - Map each basic block where a new register is live out to the
244   // live-out value and its defining block.
245   // One of these conditions shall be true:
246   //
247   //  1. !LiveOutCache.count(MBB)
248   //  2. LiveOutCache[MBB].second.getNode() == MBB
249   //  3. forall P in preds(MBB): LiveOutCache[P] == LiveOutCache[MBB]
250   //
251   // This is only a cache, the values can be computed as:
252   //
253   //  VNI = Edit.get(RegIdx)->getVNInfoAt(LIS.getMBBEndIdx(MBB))
254   //  Node = mbt_[LIS.getMBBFromIndex(VNI->def)]
255   //
256   // The cache is also used as a visited set by extendRange(). It can be shared
257   // by all the new registers because at most one is live out of each block.
258   LiveOutMap LiveOutCache;
259
260   // LiveOutSeen - Indexed by MBB->getNumber(), a bit is set for each valid
261   // entry in LiveOutCache.
262   BitVector LiveOutSeen;
263
264   /// LiveInBlock - Info for updateSSA() about a block where a register is
265   /// live-in.
266   /// The updateSSA caller provides DomNode and Kill inside MBB, updateSSA()
267   /// adds the computed live-in value.
268   struct LiveInBlock {
269     // Dominator tree node for the block.
270     // Cleared by updateSSA when the final value has been determined.
271     MachineDomTreeNode *DomNode;
272
273     // Live-in value filled in by updateSSA once it is known.
274     VNInfo *Value;
275
276     // Position in block where the live-in range ends, or SlotIndex() if the
277     // range passes through the block.
278     SlotIndex Kill;
279
280     LiveInBlock(MachineDomTreeNode *node) : DomNode(node), Value(0) {}
281   };
282
283   /// LiveInBlocks - List of live-in blocks used by findReachingDefs() and
284   /// updateSSA(). This list is usually empty, it exists here to avoid frequent
285   /// reallocations.
286   SmallVector<LiveInBlock, 16> LiveInBlocks;
287
288   /// defValue - define a value in RegIdx from ParentVNI at Idx.
289   /// Idx does not have to be ParentVNI->def, but it must be contained within
290   /// ParentVNI's live range in ParentLI. The new value is added to the value
291   /// map.
292   /// Return the new LI value.
293   VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
294
295   /// markComplexMapped - Mark ParentVNI as complex mapped in RegIdx regardless
296   /// of the number of defs.
297   void markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI);
298
299   /// defFromParent - Define Reg from ParentVNI at UseIdx using either
300   /// rematerialization or a COPY from parent. Return the new value.
301   VNInfo *defFromParent(unsigned RegIdx,
302                         VNInfo *ParentVNI,
303                         SlotIndex UseIdx,
304                         MachineBasicBlock &MBB,
305                         MachineBasicBlock::iterator I);
306
307   /// extendRange - Extend the live range of Edit.get(RegIdx) so it reaches Idx.
308   /// Insert PHIDefs as needed to preserve SSA form.
309   void extendRange(unsigned RegIdx, SlotIndex Idx);
310
311   /// findReachingDefs - Starting from MBB, add blocks to LiveInBlocks until all
312   /// reaching defs for LI are found.
313   /// @param LI   Live interval whose value is needed.
314   /// @param MBB  Block where LI should be live-in.
315   /// @param Kill Kill point in MBB.
316   /// @return Unique value seen, or NULL.
317   VNInfo *findReachingDefs(LiveInterval *LI, MachineBasicBlock *MBB,
318                            SlotIndex Kill);
319
320   /// updateSSA - Compute and insert PHIDefs such that all blocks in
321   // LiveInBlocks get a known live-in value. Add live ranges to the blocks.
322   void updateSSA();
323
324   /// transferValues - Transfer values to the new ranges.
325   /// Return true if any ranges were skipped.
326   bool transferValues();
327
328   /// extendPHIKillRanges - Extend the ranges of all values killed by original
329   /// parent PHIDefs.
330   void extendPHIKillRanges();
331
332   /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
333   void rewriteAssigned(bool ExtendRanges);
334
335   /// deleteRematVictims - Delete defs that are dead after rematerializing.
336   void deleteRematVictims();
337
338 public:
339   /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
340   /// Newly created intervals will be appended to newIntervals.
341   SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
342               MachineDominatorTree&);
343
344   /// reset - Prepare for a new split.
345   void reset(LiveRangeEdit&);
346
347   /// Create a new virtual register and live interval.
348   /// Return the interval index, starting from 1. Interval index 0 is the
349   /// implicit complement interval.
350   unsigned openIntv();
351
352   /// currentIntv - Return the current interval index.
353   unsigned currentIntv() const { return OpenIdx; }
354
355   /// selectIntv - Select a previously opened interval index.
356   void selectIntv(unsigned Idx);
357
358   /// enterIntvBefore - Enter the open interval before the instruction at Idx.
359   /// If the parent interval is not live before Idx, a COPY is not inserted.
360   /// Return the beginning of the new live range.
361   SlotIndex enterIntvBefore(SlotIndex Idx);
362
363   /// enterIntvAtEnd - Enter the open interval at the end of MBB.
364   /// Use the open interval from he inserted copy to the MBB end.
365   /// Return the beginning of the new live range.
366   SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
367
368   /// useIntv - indicate that all instructions in MBB should use OpenLI.
369   void useIntv(const MachineBasicBlock &MBB);
370
371   /// useIntv - indicate that all instructions in range should use OpenLI.
372   void useIntv(SlotIndex Start, SlotIndex End);
373
374   /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
375   /// Return the end of the live range.
376   SlotIndex leaveIntvAfter(SlotIndex Idx);
377
378   /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
379   /// Return the end of the live range.
380   SlotIndex leaveIntvBefore(SlotIndex Idx);
381
382   /// leaveIntvAtTop - Leave the interval at the top of MBB.
383   /// Add liveness from the MBB top to the copy.
384   /// Return the end of the live range.
385   SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
386
387   /// overlapIntv - Indicate that all instructions in range should use the open
388   /// interval, but also let the complement interval be live.
389   ///
390   /// This doubles the register pressure, but is sometimes required to deal with
391   /// register uses after the last valid split point.
392   ///
393   /// The Start index should be a return value from a leaveIntv* call, and End
394   /// should be in the same basic block. The parent interval must have the same
395   /// value across the range.
396   ///
397   void overlapIntv(SlotIndex Start, SlotIndex End);
398
399   /// finish - after all the new live ranges have been created, compute the
400   /// remaining live range, and rewrite instructions to use the new registers.
401   /// @param LRMap When not null, this vector will map each live range in Edit
402   ///              back to the indices returned by openIntv.
403   ///              There may be extra indices created by dead code elimination.
404   void finish(SmallVectorImpl<unsigned> *LRMap = 0);
405
406   /// dump - print the current interval maping to dbgs().
407   void dump() const;
408
409   // ===--- High level methods ---===
410
411   /// splitSingleBlock - Split CurLI into a separate live interval around the
412   /// uses in a single block. This is intended to be used as part of a larger
413   /// split, and doesn't call finish().
414   void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
415
416   /// splitSingleBlocks - Split CurLI into a separate live interval inside each
417   /// basic block in Blocks.
418   void splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks);
419 };
420
421 }
422
423 #endif