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/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/SlotIndexes.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/Allocator.h"
40 class MachineDominatorTree;
41 class MachineLoopInfo;
42 class TargetRegisterInfo;
43 class MachineRegisterInfo;
44 class TargetInstrInfo;
45 class TargetRegisterClass;
48 class LiveIntervals : public MachineFunctionPass {
50 MachineRegisterInfo* MRI;
51 const TargetMachine* TM;
52 const TargetRegisterInfo* TRI;
53 const TargetInstrInfo* TII;
57 MachineDominatorTree *DomTree;
58 LiveRangeCalc *LRCalc;
60 /// Special pool allocator for VNInfo's (LiveInterval val#).
62 VNInfo::Allocator VNInfoAllocator;
64 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
65 Reg2IntervalMap R2IMap;
67 /// AllocatableRegs - A bit vector of allocatable registers.
68 BitVector AllocatableRegs;
70 /// ReservedRegs - A bit vector of reserved registers.
71 BitVector ReservedRegs;
73 /// RegMaskSlots - Sorted list of instructions with register mask operands.
74 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
76 SmallVector<SlotIndex, 8> RegMaskSlots;
78 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
79 /// pointer to the corresponding register mask. This pointer can be
82 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
83 /// unsigned OpNum = findRegMaskOperand(MI);
84 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
86 /// This is kept in a separate vector partly because some standard
87 /// libraries don't support lower_bound() with mixed objects, partly to
88 /// improve locality when searching in RegMaskSlots.
89 /// Also see the comment in LiveInterval::find().
90 SmallVector<const uint32_t*, 8> RegMaskBits;
92 /// For each basic block number, keep (begin, size) pairs indexing into the
93 /// RegMaskSlots and RegMaskBits arrays.
94 /// Note that basic block numbers may not be layout contiguous, that's why
95 /// we can't just keep track of the first register mask in each basic
97 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
99 /// RegUnitIntervals - Keep a live interval for each register unit as a way
100 /// of tracking fixed physreg interference.
101 SmallVector<LiveInterval*, 0> RegUnitIntervals;
104 static char ID; // Pass identification, replacement for typeid
106 virtual ~LiveIntervals();
108 // Calculate the spill weight to assign to a single instruction.
109 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
111 unsigned getNumIntervals() const { return (unsigned)R2IMap.size(); }
113 LiveInterval &getInterval(unsigned reg) {
114 Reg2IntervalMap::iterator I = R2IMap.find(reg);
115 assert(I != R2IMap.end() && "Interval does not exist for register");
119 const LiveInterval &getInterval(unsigned reg) const {
120 Reg2IntervalMap::const_iterator I = R2IMap.find(reg);
121 assert(I != R2IMap.end() && "Interval does not exist for register");
125 bool hasInterval(unsigned reg) const {
126 return R2IMap.count(reg);
129 /// isAllocatable - is the physical register reg allocatable in the current
131 bool isAllocatable(unsigned reg) const {
132 return AllocatableRegs.test(reg);
135 /// isReserved - is the physical register reg reserved in the current
137 bool isReserved(unsigned reg) const {
138 return ReservedRegs.test(reg);
142 LiveInterval &getOrCreateInterval(unsigned reg) {
143 Reg2IntervalMap::iterator I = R2IMap.find(reg);
144 if (I == R2IMap.end())
145 I = R2IMap.insert(std::make_pair(reg, createInterval(reg))).first;
149 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
150 /// adds a live range from that instruction to the end of its MBB.
151 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
152 MachineInstr* startInst);
154 /// shrinkToUses - After removing some uses of a register, shrink its live
155 /// range to just the remaining uses. This method does not compute reaching
156 /// defs for new uses, and it doesn't remove dead defs.
157 /// Dead PHIDef values are marked as unused.
158 /// New dead machine instructions are added to the dead vector.
159 /// Return true if the interval may have been separated into multiple
160 /// connected components.
161 bool shrinkToUses(LiveInterval *li,
162 SmallVectorImpl<MachineInstr*> *dead = 0);
166 void removeInterval(unsigned Reg) {
167 DenseMap<unsigned, LiveInterval*>::iterator I = R2IMap.find(Reg);
172 SlotIndexes *getSlotIndexes() const {
176 AliasAnalysis *getAliasAnalysis() const {
180 /// isNotInMIMap - returns true if the specified machine instr has been
181 /// removed or was never entered in the map.
182 bool isNotInMIMap(const MachineInstr* Instr) const {
183 return !Indexes->hasIndex(Instr);
186 /// Returns the base index of the given instruction.
187 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
188 return Indexes->getInstructionIndex(instr);
191 /// Returns the instruction associated with the given index.
192 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
193 return Indexes->getInstructionFromIndex(index);
196 /// Return the first index in the given basic block.
197 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
198 return Indexes->getMBBStartIdx(mbb);
201 /// Return the last index in the given basic block.
202 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
203 return Indexes->getMBBEndIdx(mbb);
206 bool isLiveInToMBB(const LiveInterval &li,
207 const MachineBasicBlock *mbb) const {
208 return li.liveAt(getMBBStartIdx(mbb));
211 bool isLiveOutOfMBB(const LiveInterval &li,
212 const MachineBasicBlock *mbb) const {
213 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
216 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
217 return Indexes->getMBBFromIndex(index);
220 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
221 return Indexes->insertMachineInstrInMaps(MI);
224 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
225 Indexes->removeMachineInstrFromMaps(MI);
228 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
229 Indexes->replaceMachineInstrInMaps(MI, NewMI);
232 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
233 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
234 return Indexes->findLiveInMBBs(Start, End, MBBs);
237 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
239 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
240 virtual void releaseMemory();
242 /// runOnMachineFunction - pass entry point
243 virtual bool runOnMachineFunction(MachineFunction&);
245 /// print - Implement the dump method.
246 virtual void print(raw_ostream &O, const Module* = 0) const;
248 /// isReMaterializable - Returns true if every definition of MI of every
249 /// val# of the specified interval is re-materializable. Also returns true
250 /// by reference if all of the defs are load instructions.
251 bool isReMaterializable(const LiveInterval &li,
252 const SmallVectorImpl<LiveInterval*> *SpillIs,
255 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
256 /// a pointer to that block. If LI is live in to or out of any block,
258 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
260 /// addKillFlags - Add kill flags to any instruction that kills a virtual
264 /// handleMove - call this method to notify LiveIntervals that
265 /// instruction 'mi' has been moved within a basic block. This will update
266 /// the live intervals for all operands of mi. Moves between basic blocks
267 /// are not supported.
268 void handleMove(MachineInstr* MI);
270 /// moveIntoBundle - Update intervals for operands of MI so that they
271 /// begin/end on the SlotIndex for BundleStart.
273 /// Requires MI and BundleStart to have SlotIndexes, and assumes
274 /// existing liveness is accurate. BundleStart should be the first
275 /// instruction in the Bundle.
276 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
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];
351 /// computeIntervals - Compute live intervals.
352 void computeIntervals();
354 /// handleRegisterDef - update intervals for a register def
355 /// (calls handlePhysicalRegisterDef and
356 /// handleVirtualRegisterDef)
357 void handleRegisterDef(MachineBasicBlock *MBB,
358 MachineBasicBlock::iterator MI,
360 MachineOperand& MO, unsigned MOIdx);
362 /// isPartialRedef - Return true if the specified def at the specific index
363 /// is partially re-defining the specified live interval. A common case of
364 /// this is a definition of the sub-register.
365 bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
366 LiveInterval &interval);
368 /// handleVirtualRegisterDef - update intervals for a virtual
370 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
371 MachineBasicBlock::iterator MI,
372 SlotIndex MIIdx, MachineOperand& MO,
374 LiveInterval& interval);
376 /// handlePhysicalRegisterDef - update intervals for a physical register
378 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
379 MachineBasicBlock::iterator mi,
380 SlotIndex MIIdx, MachineOperand& MO,
381 LiveInterval &interval);
383 /// handleLiveInRegister - Create interval for a livein register.
384 void handleLiveInRegister(MachineBasicBlock* mbb,
386 LiveInterval &interval);
388 static LiveInterval* createInterval(unsigned Reg);
390 void printInstrs(raw_ostream &O) const;
391 void dumpInstrs() const;
393 void computeLiveInRegUnits();
394 void computeRegUnitInterval(LiveInterval*);
398 } // End llvm namespace