1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- 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 implements the LiveInterval analysis pass. Given some numbering of
11 // each the machine instructions (in this implemention depth-first order) an
12 // interval [i, j) is said to be a live interval for register v if there is no
13 // instruction with number j' > j such that v is live at j' and there is no
14 // instruction with number i' < i such that v is live at i'. In this
15 // implementation intervals can have holes, i.e. an interval might look like
16 // [1,20), [50,65), [1000,1001).
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
23 #include "llvm/ADT/BitVector.h"
24 #include "llvm/ADT/IndexedMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/CodeGen/LiveInterval.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/SlotIndexes.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
41 class MachineDominatorTree;
42 class MachineLoopInfo;
43 class TargetRegisterInfo;
44 class MachineRegisterInfo;
45 class TargetInstrInfo;
46 class TargetRegisterClass;
49 class LiveIntervals : public MachineFunctionPass {
51 MachineRegisterInfo* MRI;
52 const TargetMachine* TM;
53 const TargetRegisterInfo* TRI;
54 const TargetInstrInfo* TII;
58 MachineDominatorTree *DomTree;
59 LiveRangeCalc *LRCalc;
61 /// Special pool allocator for VNInfo's (LiveInterval val#).
63 VNInfo::Allocator VNInfoAllocator;
65 /// Live interval pointers for all the virtual registers.
66 IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
68 /// RegMaskSlots - Sorted list of instructions with register mask operands.
69 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
71 SmallVector<SlotIndex, 8> RegMaskSlots;
73 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
74 /// pointer to the corresponding register mask. This pointer can be
77 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
78 /// unsigned OpNum = findRegMaskOperand(MI);
79 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
81 /// This is kept in a separate vector partly because some standard
82 /// libraries don't support lower_bound() with mixed objects, partly to
83 /// improve locality when searching in RegMaskSlots.
84 /// Also see the comment in LiveInterval::find().
85 SmallVector<const uint32_t*, 8> RegMaskBits;
87 /// For each basic block number, keep (begin, size) pairs indexing into the
88 /// RegMaskSlots and RegMaskBits arrays.
89 /// Note that basic block numbers may not be layout contiguous, that's why
90 /// we can't just keep track of the first register mask in each basic
92 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
94 /// RegUnitIntervals - Keep a live interval for each register unit as a way
95 /// of tracking fixed physreg interference.
96 SmallVector<LiveInterval*, 0> RegUnitIntervals;
99 static char ID; // Pass identification, replacement for typeid
101 virtual ~LiveIntervals();
103 // Calculate the spill weight to assign to a single instruction.
104 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
106 LiveInterval &getInterval(unsigned Reg) {
107 LiveInterval *LI = VirtRegIntervals[Reg];
108 assert(LI && "Interval does not exist for virtual register");
112 const LiveInterval &getInterval(unsigned Reg) const {
113 return const_cast<LiveIntervals*>(this)->getInterval(Reg);
116 bool hasInterval(unsigned Reg) const {
117 return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
120 // Interval creation.
121 LiveInterval &getOrCreateInterval(unsigned Reg) {
122 if (!hasInterval(Reg)) {
123 VirtRegIntervals.grow(Reg);
124 VirtRegIntervals[Reg] = createInterval(Reg);
126 return getInterval(Reg);
130 void removeInterval(unsigned Reg) {
131 delete VirtRegIntervals[Reg];
132 VirtRegIntervals[Reg] = 0;
135 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
136 /// adds a live range from that instruction to the end of its MBB.
137 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
138 MachineInstr* startInst);
140 /// shrinkToUses - After removing some uses of a register, shrink its live
141 /// range to just the remaining uses. This method does not compute reaching
142 /// defs for new uses, and it doesn't remove dead defs.
143 /// Dead PHIDef values are marked as unused.
144 /// New dead machine instructions are added to the dead vector.
145 /// Return true if the interval may have been separated into multiple
146 /// connected components.
147 bool shrinkToUses(LiveInterval *li,
148 SmallVectorImpl<MachineInstr*> *dead = 0);
150 /// extendToIndices - Extend the live range of LI to reach all points in
151 /// Indices. The points in the Indices array must be jointly dominated by
152 /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
154 /// If a SlotIndex in Indices is the end index of a basic block, LI will be
155 /// extended to be live out of the basic block.
157 /// See also LiveRangeCalc::extend().
158 void extendToIndices(LiveInterval *LI, ArrayRef<SlotIndex> Indices);
160 /// pruneValue - If an LI value is live at Kill, prune its live range by
161 /// removing any liveness reachable from Kill. Add live range end points to
162 /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
163 /// value's live range.
165 /// Calling pruneValue() and extendToIndices() can be used to reconstruct
166 /// SSA form after adding defs to a virtual register.
167 void pruneValue(LiveInterval *LI, SlotIndex Kill,
168 SmallVectorImpl<SlotIndex> *EndPoints);
170 SlotIndexes *getSlotIndexes() const {
174 AliasAnalysis *getAliasAnalysis() const {
178 /// isNotInMIMap - returns true if the specified machine instr has been
179 /// removed or was never entered in the map.
180 bool isNotInMIMap(const MachineInstr* Instr) const {
181 return !Indexes->hasIndex(Instr);
184 /// Returns the base index of the given instruction.
185 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
186 return Indexes->getInstructionIndex(instr);
189 /// Returns the instruction associated with the given index.
190 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
191 return Indexes->getInstructionFromIndex(index);
194 /// Return the first index in the given basic block.
195 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
196 return Indexes->getMBBStartIdx(mbb);
199 /// Return the last index in the given basic block.
200 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
201 return Indexes->getMBBEndIdx(mbb);
204 bool isLiveInToMBB(const LiveInterval &li,
205 const MachineBasicBlock *mbb) const {
206 return li.liveAt(getMBBStartIdx(mbb));
209 bool isLiveOutOfMBB(const LiveInterval &li,
210 const MachineBasicBlock *mbb) const {
211 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
214 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
215 return Indexes->getMBBFromIndex(index);
218 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
219 return Indexes->insertMachineInstrInMaps(MI);
222 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
223 Indexes->removeMachineInstrFromMaps(MI);
226 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
227 Indexes->replaceMachineInstrInMaps(MI, NewMI);
230 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
231 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
232 return Indexes->findLiveInMBBs(Start, End, MBBs);
235 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
238 virtual void releaseMemory();
240 /// runOnMachineFunction - pass entry point
241 virtual bool runOnMachineFunction(MachineFunction&);
243 /// print - Implement the dump method.
244 virtual void print(raw_ostream &O, const Module* = 0) const;
246 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
247 /// a pointer to that block. If LI is live in to or out of any block,
249 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
251 /// Returns true if VNI is killed by any PHI-def values in LI.
252 /// This may conservatively return true to avoid expensive computations.
253 bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
255 /// addKillFlags - Add kill flags to any instruction that kills a virtual
257 void addKillFlags(const VirtRegMap*);
259 /// handleMove - call this method to notify LiveIntervals that
260 /// instruction 'mi' has been moved within a basic block. This will update
261 /// the live intervals for all operands of mi. Moves between basic blocks
262 /// are not supported.
264 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
265 void handleMove(MachineInstr* MI, bool UpdateFlags = false);
267 /// moveIntoBundle - Update intervals for operands of MI so that they
268 /// begin/end on the SlotIndex for BundleStart.
270 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
272 /// Requires MI and BundleStart to have SlotIndexes, and assumes
273 /// existing liveness is accurate. BundleStart should be the first
274 /// instruction in the Bundle.
275 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
276 bool UpdateFlags = false);
278 // Register mask functions.
280 // Machine instructions may use a register mask operand to indicate that a
281 // large number of registers are clobbered by the instruction. This is
282 // typically used for calls.
284 // For compile time performance reasons, these clobbers are not recorded in
285 // the live intervals for individual physical registers. Instead,
286 // LiveIntervalAnalysis maintains a sorted list of instructions with
287 // register mask operands.
289 /// getRegMaskSlots - Returns a sorted array of slot indices of all
290 /// instructions with register mask operands.
291 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
293 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
294 /// instructions with register mask operands in the basic block numbered
296 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
297 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
298 return getRegMaskSlots().slice(P.first, P.second);
301 /// getRegMaskBits() - Returns an array of register mask pointers
302 /// corresponding to getRegMaskSlots().
303 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
305 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
306 /// to getRegMaskSlotsInBlock(MBBNum).
307 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
308 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
309 return getRegMaskBits().slice(P.first, P.second);
312 /// checkRegMaskInterference - Test if LI is live across any register mask
313 /// instructions, and compute a bit mask of physical registers that are not
314 /// clobbered by any of them.
316 /// Returns false if LI doesn't cross any register mask instructions. In
317 /// that case, the bit vector is not filled in.
318 bool checkRegMaskInterference(LiveInterval &LI,
319 BitVector &UsableRegs);
321 // Register unit functions.
323 // Fixed interference occurs when MachineInstrs use physregs directly
324 // instead of virtual registers. This typically happens when passing
325 // arguments to a function call, or when instructions require operands in
328 // Each physreg has one or more register units, see MCRegisterInfo. We
329 // track liveness per register unit to handle aliasing registers more
332 /// getRegUnit - Return the live range for Unit.
333 /// It will be computed if it doesn't exist.
334 LiveInterval &getRegUnit(unsigned Unit) {
335 LiveInterval *LI = RegUnitIntervals[Unit];
337 // Compute missing ranges on demand.
338 RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
339 computeRegUnitInterval(LI);
344 /// getCachedRegUnit - Return the live range for Unit if it has already
345 /// been computed, or NULL if it hasn't been computed yet.
346 LiveInterval *getCachedRegUnit(unsigned Unit) {
347 return RegUnitIntervals[Unit];
350 const LiveInterval *getCachedRegUnit(unsigned Unit) const {
351 return RegUnitIntervals[Unit];
355 /// computeIntervals - Compute live intervals.
356 void computeIntervals();
358 /// Compute live intervals for all virtual registers.
359 void computeVirtRegs();
361 /// Compute RegMaskSlots and RegMaskBits.
362 void computeRegMasks();
364 /// handleRegisterDef - update intervals for a register def
365 /// (calls handleVirtualRegisterDef)
366 void handleRegisterDef(MachineBasicBlock *MBB,
367 MachineBasicBlock::iterator MI,
369 MachineOperand& MO, unsigned MOIdx);
371 /// isPartialRedef - Return true if the specified def at the specific index
372 /// is partially re-defining the specified live interval. A common case of
373 /// this is a definition of the sub-register.
374 bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
375 LiveInterval &interval);
377 /// handleVirtualRegisterDef - update intervals for a virtual
379 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
380 MachineBasicBlock::iterator MI,
381 SlotIndex MIIdx, MachineOperand& MO,
383 LiveInterval& interval);
385 static LiveInterval* createInterval(unsigned Reg);
387 void printInstrs(raw_ostream &O) const;
388 void dumpInstrs() const;
390 void computeLiveInRegUnits();
391 void computeRegUnitInterval(LiveInterval*);
392 void computeVirtRegInterval(LiveInterval*);
396 } // End llvm namespace