1 //===-------- SplitKit.h - Toolkit for splitting live ranges ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SPLITKIT_H
16 #define LLVM_CODEGEN_SPLITKIT_H
18 #include "LiveRangeCalc.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IntervalMap.h"
22 #include "llvm/ADT/SmallPtrSet.h"
26 class ConnectedVNInfoEqClasses;
31 class MachineLoopInfo;
32 class MachineRegisterInfo;
33 class TargetInstrInfo;
34 class TargetRegisterInfo;
39 /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
43 const MachineFunction &MF;
44 const VirtRegMap &VRM;
45 const LiveIntervals &LIS;
46 const MachineLoopInfo &Loops;
47 const TargetInstrInfo &TII;
49 // Sorted slot indexes of using instructions.
50 SmallVector<SlotIndex, 8> UseSlots;
52 /// Additional information about basic blocks where the current variable is
53 /// live. Such a block will look like one of these templates:
55 /// 1. | o---x | Internal to block. Variable is only live in this block.
56 /// 2. |---x | Live-in, kill.
57 /// 3. | o---| Def, live-out.
58 /// 4. |---x o---| Live-in, kill, def, live-out. Counted by NumGapBlocks.
59 /// 5. |---o---o---| Live-through with uses or defs.
60 /// 6. |-----------| Live-through without uses. Counted by NumThroughBlocks.
62 /// Two BlockInfo entries are created for template 4. One for the live-in
63 /// segment, and one for the live-out segment. These entries look as if the
64 /// block were split in the middle where the live range isn't live.
66 /// Live-through blocks without any uses don't get BlockInfo entries. They
67 /// are simply listed in ThroughBlocks instead.
70 MachineBasicBlock *MBB;
71 SlotIndex FirstInstr; ///< First instr accessing current reg.
72 SlotIndex LastInstr; ///< Last instr accessing current reg.
73 SlotIndex FirstDef; ///< First non-phi valno->def, or SlotIndex().
74 bool LiveIn; ///< Current reg is live in.
75 bool LiveOut; ///< Current reg is live out.
77 /// isOneInstr - Returns true when this BlockInfo describes a single
79 bool isOneInstr() const {
80 return SlotIndex::isSameInstr(FirstInstr, LastInstr);
85 // Current live interval.
86 const LiveInterval *CurLI;
88 /// LastSplitPoint - Last legal split point in each basic block in the current
89 /// function. The first entry is the first terminator, the second entry is the
90 /// last valid split point for a variable that is live in to a landing pad
92 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
94 /// UseBlocks - Blocks where CurLI has uses.
95 SmallVector<BlockInfo, 8> UseBlocks;
97 /// NumGapBlocks - Number of duplicate entries in UseBlocks for blocks where
98 /// the live range has a gap.
99 unsigned NumGapBlocks;
101 /// ThroughBlocks - Block numbers where CurLI is live through without uses.
102 BitVector ThroughBlocks;
104 /// NumThroughBlocks - Number of live-through blocks.
105 unsigned NumThroughBlocks;
107 /// DidRepairRange - analyze was forced to shrinkToUses().
110 SlotIndex computeLastSplitPoint(unsigned Num);
112 // Sumarize statistics by counting instructions using CurLI.
115 /// calcLiveBlockInfo - Compute per-block information about CurLI.
116 bool calcLiveBlockInfo();
119 SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
120 const MachineLoopInfo &mli);
122 /// analyze - set CurLI to the specified interval, and analyze how it may be
124 void analyze(const LiveInterval *li);
126 /// didRepairRange() - Returns true if CurLI was invalid and has been repaired
127 /// by analyze(). This really shouldn't happen, but sometimes the coalescer
128 /// can create live ranges that end in mid-air.
129 bool didRepairRange() const { return DidRepairRange; }
131 /// clear - clear all data structures so SplitAnalysis is ready to analyze a
135 /// getParent - Return the last analyzed interval.
136 const LiveInterval &getParent() const { return *CurLI; }
138 /// getLastSplitPoint - Return the base index of the last valid split point
139 /// in the basic block numbered Num.
140 SlotIndex getLastSplitPoint(unsigned Num) {
141 // Inline the common simple case.
142 if (LastSplitPoint[Num].first.isValid() &&
143 !LastSplitPoint[Num].second.isValid())
144 return LastSplitPoint[Num].first;
145 return computeLastSplitPoint(Num);
148 /// getLastSplitPointIter - Returns the last split point as an iterator.
149 MachineBasicBlock::iterator getLastSplitPointIter(MachineBasicBlock*);
151 /// isOriginalEndpoint - Return true if the original live range was killed or
152 /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
153 /// and 'use' for an early-clobber def.
154 /// This can be used to recognize code inserted by earlier live range
156 bool isOriginalEndpoint(SlotIndex Idx) const;
158 /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
159 /// where CurLI has uses.
160 ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
162 /// getNumThroughBlocks - Return the number of through blocks.
163 unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
165 /// isThroughBlock - Return true if CurLI is live through MBB without uses.
166 bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
168 /// getThroughBlocks - Return the set of through blocks.
169 const BitVector &getThroughBlocks() const { return ThroughBlocks; }
171 /// getNumLiveBlocks - Return the number of blocks where CurLI is live.
172 unsigned getNumLiveBlocks() const {
173 return getUseBlocks().size() - NumGapBlocks + getNumThroughBlocks();
176 /// countLiveBlocks - Return the number of blocks where li is live. This is
177 /// guaranteed to return the same number as getNumLiveBlocks() after calling
179 unsigned countLiveBlocks(const LiveInterval *li) const;
181 typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
183 /// shouldSplitSingleBlock - Returns true if it would help to create a local
184 /// live range for the instructions in BI. There is normally no benefit to
185 /// creating a live range for a single instruction, but it does enable
186 /// register class inflation if the instruction has a restricted register
189 /// @param BI The block to be isolated.
190 /// @param SingleInstrs True when single instructions should be isolated.
191 bool shouldSplitSingleBlock(const BlockInfo &BI, bool SingleInstrs) const;
195 /// SplitEditor - Edit machine code and LiveIntervals for live range
198 /// - Create a SplitEditor from a SplitAnalysis.
199 /// - Start a new live interval with openIntv.
200 /// - Mark the places where the new interval is entered using enterIntv*
201 /// - Mark the ranges where the new interval is used with useIntv*
202 /// - Mark the places where the interval is exited with exitIntv*.
203 /// - Finish the current interval with closeIntv and repeat from 2.
204 /// - Rewrite instructions with finish().
210 MachineRegisterInfo &MRI;
211 MachineDominatorTree &MDT;
212 const TargetInstrInfo &TII;
213 const TargetRegisterInfo &TRI;
217 /// ComplementSpillMode - Select how the complement live range should be
218 /// created. SplitEditor automatically creates interval 0 to contain
219 /// anything that isn't added to another interval. This complement interval
220 /// can get quite complicated, and it can sometimes be an advantage to allow
221 /// it to overlap the other intervals. If it is going to spill anyway, no
222 /// registers are wasted by keeping a value in two places at the same time.
223 enum ComplementSpillMode {
224 /// SM_Partition(Default) - Try to create the complement interval so it
225 /// doesn't overlap any other intervals, and the original interval is
226 /// partitioned. This may require a large number of back copies and extra
227 /// PHI-defs. Only segments marked with overlapIntv will be overlapping.
230 /// SM_Size - Overlap intervals to minimize the number of inserted COPY
231 /// instructions. Copies to the complement interval are hoisted to their
232 /// common dominator, so only one COPY is required per value in the
233 /// complement interval. This also means that no extra PHI-defs need to be
234 /// inserted in the complement interval.
237 /// SM_Speed - Overlap intervals to minimize the expected execution
238 /// frequency of the inserted copies. This is very similar to SM_Size, but
239 /// the complement interval may get some extra PHI-defs.
245 /// Edit - The current parent register and new intervals created.
248 /// Index into Edit of the currently open interval.
249 /// The index 0 is used for the complement, so the first interval started by
250 /// openIntv will be 1.
253 /// The current spill mode, selected by reset().
254 ComplementSpillMode SpillMode;
256 typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
258 /// Allocator for the interval map. This will eventually be shared with
259 /// SlotIndexes and LiveIntervals.
260 RegAssignMap::Allocator Allocator;
262 /// RegAssign - Map of the assigned register indexes.
263 /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
265 RegAssignMap RegAssign;
267 typedef PointerIntPair<VNInfo*, 1> ValueForcePair;
268 typedef DenseMap<std::pair<unsigned, unsigned>, ValueForcePair> ValueMap;
270 /// Values - keep track of the mapping from parent values to values in the new
271 /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
273 /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
274 /// 2. (Null, false) - the value is mapped to multiple values in
275 /// Edit.get(RegIdx). Each value is represented by a minimal live range at
276 /// its def. The full live range can be inferred exactly from the range
277 /// of RegIdx in RegAssign.
278 /// 3. (Null, true). As above, but the ranges in RegAssign are too large, and
279 /// the live range must be recomputed using LiveRangeCalc::extend().
280 /// 4. (VNI, false) The value is mapped to a single new value.
281 /// The new value has no live ranges anywhere.
284 /// LRCalc - Cache for computing live ranges and SSA update. Each instance
285 /// can only handle non-overlapping live ranges, so use a separate
286 /// LiveRangeCalc instance for the complement interval when in spill mode.
287 LiveRangeCalc LRCalc[2];
289 /// getLRCalc - Return the LRCalc to use for RegIdx. In spill mode, the
290 /// complement interval can overlap the other intervals, so it gets its own
291 /// LRCalc instance. When not in spill mode, all intervals can share one.
292 LiveRangeCalc &getLRCalc(unsigned RegIdx) {
293 return LRCalc[SpillMode != SM_Partition && RegIdx != 0];
296 /// defValue - define a value in RegIdx from ParentVNI at Idx.
297 /// Idx does not have to be ParentVNI->def, but it must be contained within
298 /// ParentVNI's live range in ParentLI. The new value is added to the value
300 /// Return the new LI value.
301 VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
303 /// forceRecompute - Force the live range of ParentVNI in RegIdx to be
304 /// recomputed by LiveRangeCalc::extend regardless of the number of defs.
305 /// This is used for values whose live range doesn't match RegAssign exactly.
306 /// They could have rematerialized, or back-copies may have been moved.
307 void forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI);
309 /// defFromParent - Define Reg from ParentVNI at UseIdx using either
310 /// rematerialization or a COPY from parent. Return the new value.
311 VNInfo *defFromParent(unsigned RegIdx,
314 MachineBasicBlock &MBB,
315 MachineBasicBlock::iterator I);
317 /// removeBackCopies - Remove the copy instructions that defines the values
318 /// in the vector in the complement interval.
319 void removeBackCopies(SmallVectorImpl<VNInfo*> &Copies);
321 /// getShallowDominator - Returns the least busy dominator of MBB that is
322 /// also dominated by DefMBB. Busy is measured by loop depth.
323 MachineBasicBlock *findShallowDominator(MachineBasicBlock *MBB,
324 MachineBasicBlock *DefMBB);
326 /// hoistCopiesForSize - Hoist back-copies to the complement interval in a
327 /// way that minimizes code size. This implements the SM_Size spill mode.
328 void hoistCopiesForSize();
330 /// transferValues - Transfer values to the new ranges.
331 /// Return true if any ranges were skipped.
332 bool transferValues();
334 /// extendPHIKillRanges - Extend the ranges of all values killed by original
336 void extendPHIKillRanges();
338 /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
339 void rewriteAssigned(bool ExtendRanges);
341 /// deleteRematVictims - Delete defs that are dead after rematerializing.
342 void deleteRematVictims();
345 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
346 /// Newly created intervals will be appended to newIntervals.
347 SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
348 MachineDominatorTree&);
350 /// reset - Prepare for a new split.
351 void reset(LiveRangeEdit&, ComplementSpillMode = SM_Partition);
353 /// Create a new virtual register and live interval.
354 /// Return the interval index, starting from 1. Interval index 0 is the
355 /// implicit complement interval.
358 /// currentIntv - Return the current interval index.
359 unsigned currentIntv() const { return OpenIdx; }
361 /// selectIntv - Select a previously opened interval index.
362 void selectIntv(unsigned Idx);
364 /// enterIntvBefore - Enter the open interval before the instruction at Idx.
365 /// If the parent interval is not live before Idx, a COPY is not inserted.
366 /// Return the beginning of the new live range.
367 SlotIndex enterIntvBefore(SlotIndex Idx);
369 /// enterIntvAfter - Enter the open interval after the instruction at Idx.
370 /// Return the beginning of the new live range.
371 SlotIndex enterIntvAfter(SlotIndex Idx);
373 /// enterIntvAtEnd - Enter the open interval at the end of MBB.
374 /// Use the open interval from he inserted copy to the MBB end.
375 /// Return the beginning of the new live range.
376 SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
378 /// useIntv - indicate that all instructions in MBB should use OpenLI.
379 void useIntv(const MachineBasicBlock &MBB);
381 /// useIntv - indicate that all instructions in range should use OpenLI.
382 void useIntv(SlotIndex Start, SlotIndex End);
384 /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
385 /// Return the end of the live range.
386 SlotIndex leaveIntvAfter(SlotIndex Idx);
388 /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
389 /// Return the end of the live range.
390 SlotIndex leaveIntvBefore(SlotIndex Idx);
392 /// leaveIntvAtTop - Leave the interval at the top of MBB.
393 /// Add liveness from the MBB top to the copy.
394 /// Return the end of the live range.
395 SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
397 /// overlapIntv - Indicate that all instructions in range should use the open
398 /// interval, but also let the complement interval be live.
400 /// This doubles the register pressure, but is sometimes required to deal with
401 /// register uses after the last valid split point.
403 /// The Start index should be a return value from a leaveIntv* call, and End
404 /// should be in the same basic block. The parent interval must have the same
405 /// value across the range.
407 void overlapIntv(SlotIndex Start, SlotIndex End);
409 /// finish - after all the new live ranges have been created, compute the
410 /// remaining live range, and rewrite instructions to use the new registers.
411 /// @param LRMap When not null, this vector will map each live range in Edit
412 /// back to the indices returned by openIntv.
413 /// There may be extra indices created by dead code elimination.
414 void finish(SmallVectorImpl<unsigned> *LRMap = 0);
416 /// dump - print the current interval maping to dbgs().
419 // ===--- High level methods ---===
421 /// splitSingleBlock - Split CurLI into a separate live interval around the
422 /// uses in a single block. This is intended to be used as part of a larger
423 /// split, and doesn't call finish().
424 void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
426 /// splitLiveThroughBlock - Split CurLI in the given block such that it
427 /// enters the block in IntvIn and leaves it in IntvOut. There may be uses in
428 /// the block, but they will be ignored when placing split points.
430 /// @param MBBNum Block number.
431 /// @param IntvIn Interval index entering the block.
432 /// @param LeaveBefore When set, leave IntvIn before this point.
433 /// @param IntvOut Interval index leaving the block.
434 /// @param EnterAfter When set, enter IntvOut after this point.
435 void splitLiveThroughBlock(unsigned MBBNum,
436 unsigned IntvIn, SlotIndex LeaveBefore,
437 unsigned IntvOut, SlotIndex EnterAfter);
439 /// splitRegInBlock - Split CurLI in the given block such that it enters the
440 /// block in IntvIn and leaves it on the stack (or not at all). Split points
441 /// are placed in a way that avoids putting uses in the stack interval. This
442 /// may require creating a local interval when there is interference.
444 /// @param BI Block descriptor.
445 /// @param IntvIn Interval index entering the block. Not 0.
446 /// @param LeaveBefore When set, leave IntvIn before this point.
447 void splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
448 unsigned IntvIn, SlotIndex LeaveBefore);
450 /// splitRegOutBlock - Split CurLI in the given block such that it enters the
451 /// block on the stack (or isn't live-in at all) and leaves it in IntvOut.
452 /// Split points are placed to avoid interference and such that the uses are
453 /// not in the stack interval. This may require creating a local interval
454 /// when there is interference.
456 /// @param BI Block descriptor.
457 /// @param IntvOut Interval index leaving the block.
458 /// @param EnterAfter When set, enter IntvOut after this point.
459 void splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
460 unsigned IntvOut, SlotIndex EnterAfter);