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"
39 class MachineLoopInfo;
40 class TargetRegisterInfo;
41 class MachineRegisterInfo;
42 class TargetInstrInfo;
43 class TargetRegisterClass;
46 class LiveIntervals : public MachineFunctionPass {
48 MachineRegisterInfo* mri_;
49 const TargetMachine* tm_;
50 const TargetRegisterInfo* tri_;
51 const TargetInstrInfo* tii_;
54 SlotIndexes* indexes_;
56 /// Special pool allocator for VNInfo's (LiveInterval val#).
58 VNInfo::Allocator VNInfoAllocator;
60 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61 Reg2IntervalMap r2iMap_;
63 /// allocatableRegs_ - A bit vector of allocatable registers.
64 BitVector allocatableRegs_;
66 /// reservedRegs_ - A bit vector of reserved registers.
67 BitVector reservedRegs_;
69 /// RegMaskSlots - Sorted list of instructions with register mask operands.
70 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
72 SmallVector<SlotIndex, 8> RegMaskSlots;
74 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
75 /// pointer to the corresponding register mask. This pointer can be
78 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
79 /// unsigned OpNum = findRegMaskOperand(MI);
80 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
82 /// This is kept in a separate vector partly because some standard
83 /// libraries don't support lower_bound() with mixed objects, partly to
84 /// improve locality when searching in RegMaskSlots.
85 /// Also see the comment in LiveInterval::find().
86 SmallVector<const uint32_t*, 8> RegMaskBits;
88 /// For each basic block number, keep (begin, size) pairs indexing into the
89 /// RegMaskSlots and RegMaskBits arrays.
90 /// Note that basic block numbers may not be layout contiguous, that's why
91 /// we can't just keep track of the first register mask in each basic
93 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
96 static char ID; // Pass identification, replacement for typeid
97 LiveIntervals() : MachineFunctionPass(ID) {
98 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
101 // Calculate the spill weight to assign to a single instruction.
102 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
104 typedef Reg2IntervalMap::iterator iterator;
105 typedef Reg2IntervalMap::const_iterator const_iterator;
106 const_iterator begin() const { return r2iMap_.begin(); }
107 const_iterator end() const { return r2iMap_.end(); }
108 iterator begin() { return r2iMap_.begin(); }
109 iterator end() { return r2iMap_.end(); }
110 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
112 LiveInterval &getInterval(unsigned reg) {
113 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
114 assert(I != r2iMap_.end() && "Interval does not exist for register");
118 const LiveInterval &getInterval(unsigned reg) const {
119 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
120 assert(I != r2iMap_.end() && "Interval does not exist for register");
124 bool hasInterval(unsigned reg) const {
125 return r2iMap_.count(reg);
128 /// isAllocatable - is the physical register reg allocatable in the current
130 bool isAllocatable(unsigned reg) const {
131 return allocatableRegs_.test(reg);
134 /// isReserved - is the physical register reg reserved in the current
136 bool isReserved(unsigned reg) const {
137 return reservedRegs_.test(reg);
140 /// getScaledIntervalSize - get the size of an interval in "units,"
141 /// where every function is composed of one thousand units. This
142 /// measure scales properly with empty index slots in the function.
143 double getScaledIntervalSize(LiveInterval& I) {
144 return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
147 /// getApproximateInstructionCount - computes an estimate of the number
148 /// of instructions in a given LiveInterval.
149 unsigned getApproximateInstructionCount(LiveInterval& I) {
150 return I.getSize()/SlotIndex::InstrDist;
154 LiveInterval &getOrCreateInterval(unsigned reg) {
155 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
156 if (I == r2iMap_.end())
157 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
161 /// dupInterval - Duplicate a live interval. The caller is responsible for
162 /// managing the allocated memory.
163 LiveInterval *dupInterval(LiveInterval *li);
165 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
166 /// adds a live range from that instruction to the end of its MBB.
167 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
168 MachineInstr* startInst);
170 /// shrinkToUses - After removing some uses of a register, shrink its live
171 /// range to just the remaining uses. This method does not compute reaching
172 /// defs for new uses, and it doesn't remove dead defs.
173 /// Dead PHIDef values are marked as unused.
174 /// New dead machine instructions are added to the dead vector.
175 /// Return true if the interval may have been separated into multiple
176 /// connected components.
177 bool shrinkToUses(LiveInterval *li,
178 SmallVectorImpl<MachineInstr*> *dead = 0);
182 void removeInterval(unsigned Reg) {
183 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
188 SlotIndexes *getSlotIndexes() const {
192 /// isNotInMIMap - returns true if the specified machine instr has been
193 /// removed or was never entered in the map.
194 bool isNotInMIMap(const MachineInstr* Instr) const {
195 return !indexes_->hasIndex(Instr);
198 /// Returns the base index of the given instruction.
199 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
200 return indexes_->getInstructionIndex(instr);
203 /// Returns the instruction associated with the given index.
204 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
205 return indexes_->getInstructionFromIndex(index);
208 /// Return the first index in the given basic block.
209 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
210 return indexes_->getMBBStartIdx(mbb);
213 /// Return the last index in the given basic block.
214 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
215 return indexes_->getMBBEndIdx(mbb);
218 bool isLiveInToMBB(const LiveInterval &li,
219 const MachineBasicBlock *mbb) const {
220 return li.liveAt(getMBBStartIdx(mbb));
223 bool isLiveOutOfMBB(const LiveInterval &li,
224 const MachineBasicBlock *mbb) const {
225 return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
228 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
229 return indexes_->getMBBFromIndex(index);
232 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
233 return indexes_->insertMachineInstrInMaps(MI);
236 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
237 indexes_->removeMachineInstrFromMaps(MI);
240 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
241 indexes_->replaceMachineInstrInMaps(MI, NewMI);
244 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
245 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
246 return indexes_->findLiveInMBBs(Start, End, MBBs);
249 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
251 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
252 virtual void releaseMemory();
254 /// runOnMachineFunction - pass entry point
255 virtual bool runOnMachineFunction(MachineFunction&);
257 /// print - Implement the dump method.
258 virtual void print(raw_ostream &O, const Module* = 0) const;
260 /// isReMaterializable - Returns true if every definition of MI of every
261 /// val# of the specified interval is re-materializable. Also returns true
262 /// by reference if all of the defs are load instructions.
263 bool isReMaterializable(const LiveInterval &li,
264 const SmallVectorImpl<LiveInterval*> *SpillIs,
267 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
268 /// a pointer to that block. If LI is live in to or out of any block,
270 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
272 /// addKillFlags - Add kill flags to any instruction that kills a virtual
276 /// handleMove - call this method to notify LiveIntervals that
277 /// instruction 'mi' has been moved within a basic block. This will update
278 /// the live intervals for all operands of mi. Moves between basic blocks
279 /// are not supported.
280 void handleMove(MachineInstr* MI);
282 /// moveIntoBundle - Update intervals for operands of MI so that they
283 /// begin/end on the SlotIndex for BundleStart.
285 /// Requires MI and BundleStart to have SlotIndexes, and assumes
286 /// existing liveness is accurate. BundleStart should be the first
287 /// instruction in the Bundle.
288 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
290 // Register mask functions.
292 // Machine instructions may use a register mask operand to indicate that a
293 // large number of registers are clobbered by the instruction. This is
294 // typically used for calls.
296 // For compile time performance reasons, these clobbers are not recorded in
297 // the live intervals for individual physical registers. Instead,
298 // LiveIntervalAnalysis maintains a sorted list of instructions with
299 // register mask operands.
301 /// getRegMaskSlots - Returns a sorted array of slot indices of all
302 /// instructions with register mask operands.
303 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
305 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
306 /// instructions with register mask operands in the basic block numbered
308 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
309 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
310 return getRegMaskSlots().slice(P.first, P.second);
313 /// getRegMaskBits() - Returns an array of register mask pointers
314 /// corresponding to getRegMaskSlots().
315 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
317 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
318 /// to getRegMaskSlotsInBlock(MBBNum).
319 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
320 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
321 return getRegMaskBits().slice(P.first, P.second);
324 /// checkRegMaskInterference - Test if LI is live across any register mask
325 /// instructions, and compute a bit mask of physical registers that are not
326 /// clobbered by any of them.
328 /// Returns false if LI doesn't cross any register mask instructions. In
329 /// that case, the bit vector is not filled in.
330 bool checkRegMaskInterference(LiveInterval &LI,
331 BitVector &UsableRegs);
334 /// computeIntervals - Compute live intervals.
335 void computeIntervals();
337 /// handleRegisterDef - update intervals for a register def
338 /// (calls handlePhysicalRegisterDef and
339 /// handleVirtualRegisterDef)
340 void handleRegisterDef(MachineBasicBlock *MBB,
341 MachineBasicBlock::iterator MI,
343 MachineOperand& MO, unsigned MOIdx);
345 /// isPartialRedef - Return true if the specified def at the specific index
346 /// is partially re-defining the specified live interval. A common case of
347 /// this is a definition of the sub-register.
348 bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
349 LiveInterval &interval);
351 /// handleVirtualRegisterDef - update intervals for a virtual
353 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
354 MachineBasicBlock::iterator MI,
355 SlotIndex MIIdx, MachineOperand& MO,
357 LiveInterval& interval);
359 /// handlePhysicalRegisterDef - update intervals for a physical register
361 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
362 MachineBasicBlock::iterator mi,
363 SlotIndex MIIdx, MachineOperand& MO,
364 LiveInterval &interval);
366 /// handleLiveInRegister - Create interval for a livein register.
367 void handleLiveInRegister(MachineBasicBlock* mbb,
369 LiveInterval &interval);
371 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
372 /// only allow one) virtual register operand, then its uses are implicitly
373 /// using the register. Returns the virtual register.
374 unsigned getReMatImplicitUse(const LiveInterval &li,
375 MachineInstr *MI) const;
377 /// isValNoAvailableAt - Return true if the val# of the specified interval
378 /// which reaches the given instruction also reaches the specified use
380 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
381 SlotIndex UseIdx) const;
383 /// isReMaterializable - Returns true if the definition MI of the specified
384 /// val# of the specified interval is re-materializable. Also returns true
385 /// by reference if the def is a load.
386 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
388 const SmallVectorImpl<LiveInterval*> *SpillIs,
391 static LiveInterval* createInterval(unsigned Reg);
393 void printInstrs(raw_ostream &O) const;
394 void dumpInstrs() const;
398 } // End llvm namespace