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/IndexedMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/SlotIndexes.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
41 class MachineDominatorTree;
42 class MachineLoopInfo;
43 class TargetRegisterInfo;
44 class MachineRegisterInfo;
45 class TargetInstrInfo;
46 class TargetRegisterClass;
48 class MachineBlockFrequencyInfo;
50 class LiveIntervals : public MachineFunctionPass {
52 MachineRegisterInfo* MRI;
53 const TargetMachine* TM;
54 const TargetRegisterInfo* TRI;
55 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 /// Keeps a live range set for each register unit to track fixed physreg
96 SmallVector<LiveRange*, 0> RegUnitRanges;
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,
105 const MachineBlockFrequencyInfo *MBFI,
106 const MachineInstr *Instr);
108 LiveInterval &getInterval(unsigned Reg) {
109 if (hasInterval(Reg))
110 return *VirtRegIntervals[Reg];
112 return createAndComputeVirtRegInterval(Reg);
115 const LiveInterval &getInterval(unsigned Reg) const {
116 return const_cast<LiveIntervals*>(this)->getInterval(Reg);
119 bool hasInterval(unsigned Reg) const {
120 return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
123 // Interval creation.
124 LiveInterval &createEmptyInterval(unsigned Reg) {
125 assert(!hasInterval(Reg) && "Interval already exists!");
126 VirtRegIntervals.grow(Reg);
127 VirtRegIntervals[Reg] = createInterval(Reg);
128 return *VirtRegIntervals[Reg];
131 LiveInterval &createAndComputeVirtRegInterval(unsigned Reg) {
132 LiveInterval &LI = createEmptyInterval(Reg);
133 computeVirtRegInterval(LI);
138 void removeInterval(unsigned Reg) {
139 delete VirtRegIntervals[Reg];
140 VirtRegIntervals[Reg] = nullptr;
143 /// Given a register and an instruction, adds a live segment from that
144 /// instruction to the end of its MBB.
145 LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg,
146 MachineInstr* startInst);
148 /// shrinkToUses - After removing some uses of a register, shrink its live
149 /// range to just the remaining uses. This method does not compute reaching
150 /// defs for new uses, and it doesn't remove dead defs.
151 /// Dead PHIDef values are marked as unused.
152 /// New dead machine instructions are added to the dead vector.
153 /// Return true if the interval may have been separated into multiple
154 /// connected components.
155 bool shrinkToUses(LiveInterval *li,
156 SmallVectorImpl<MachineInstr*> *dead = nullptr);
158 /// extendToIndices - Extend the live range of LI to reach all points in
159 /// Indices. The points in the Indices array must be jointly dominated by
160 /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
162 /// If a SlotIndex in Indices is the end index of a basic block, LI will be
163 /// extended to be live out of the basic block.
165 /// See also LiveRangeCalc::extend().
166 void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices);
168 /// pruneValue - If an LI value is live at Kill, prune its live range by
169 /// removing any liveness reachable from Kill. Add live range end points to
170 /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
171 /// value's live range.
173 /// Calling pruneValue() and extendToIndices() can be used to reconstruct
174 /// SSA form after adding defs to a virtual register.
175 void pruneValue(LiveInterval *LI, SlotIndex Kill,
176 SmallVectorImpl<SlotIndex> *EndPoints);
178 SlotIndexes *getSlotIndexes() const {
182 AliasAnalysis *getAliasAnalysis() const {
186 /// isNotInMIMap - returns true if the specified machine instr has been
187 /// removed or was never entered in the map.
188 bool isNotInMIMap(const MachineInstr* Instr) const {
189 return !Indexes->hasIndex(Instr);
192 /// Returns the base index of the given instruction.
193 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
194 return Indexes->getInstructionIndex(instr);
197 /// Returns the instruction associated with the given index.
198 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
199 return Indexes->getInstructionFromIndex(index);
202 /// Return the first index in the given basic block.
203 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
204 return Indexes->getMBBStartIdx(mbb);
207 /// Return the last index in the given basic block.
208 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
209 return Indexes->getMBBEndIdx(mbb);
212 bool isLiveInToMBB(const LiveRange &LR,
213 const MachineBasicBlock *mbb) const {
214 return LR.liveAt(getMBBStartIdx(mbb));
217 bool isLiveOutOfMBB(const LiveRange &LR,
218 const MachineBasicBlock *mbb) const {
219 return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
222 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
223 return Indexes->getMBBFromIndex(index);
226 void insertMBBInMaps(MachineBasicBlock *MBB) {
227 Indexes->insertMBBInMaps(MBB);
228 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
229 "Blocks must be added in order.");
230 RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
233 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
234 return Indexes->insertMachineInstrInMaps(MI);
237 void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,
238 MachineBasicBlock::iterator E) {
239 for (MachineBasicBlock::iterator I = B; I != E; ++I)
240 Indexes->insertMachineInstrInMaps(I);
243 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
244 Indexes->removeMachineInstrFromMaps(MI);
247 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
248 Indexes->replaceMachineInstrInMaps(MI, NewMI);
251 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
252 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
253 return Indexes->findLiveInMBBs(Start, End, MBBs);
256 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
258 void getAnalysisUsage(AnalysisUsage &AU) const override;
259 void releaseMemory() override;
261 /// runOnMachineFunction - pass entry point
262 bool runOnMachineFunction(MachineFunction&) override;
264 /// print - Implement the dump method.
265 void print(raw_ostream &O, const Module* = nullptr) const override;
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 /// Returns true if VNI is killed by any PHI-def values in LI.
273 /// This may conservatively return true to avoid expensive computations.
274 bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
276 /// addKillFlags - Add kill flags to any instruction that kills a virtual
278 void addKillFlags(const VirtRegMap*);
280 /// handleMove - call this method to notify LiveIntervals that
281 /// instruction 'mi' has been moved within a basic block. This will update
282 /// the live intervals for all operands of mi. Moves between basic blocks
283 /// are not supported.
285 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
286 void handleMove(MachineInstr* MI, bool UpdateFlags = false);
288 /// moveIntoBundle - Update intervals for operands of MI so that they
289 /// begin/end on the SlotIndex for BundleStart.
291 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
293 /// Requires MI and BundleStart to have SlotIndexes, and assumes
294 /// existing liveness is accurate. BundleStart should be the first
295 /// instruction in the Bundle.
296 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
297 bool UpdateFlags = false);
299 /// repairIntervalsInRange - Update live intervals for instructions in a
300 /// range of iterators. It is intended for use after target hooks that may
301 /// insert or remove instructions, and is only efficient for a small number
304 /// OrigRegs is a vector of registers that were originally used by the
305 /// instructions in the range between the two iterators.
307 /// Currently, the only only changes that are supported are simple removal
308 /// and addition of uses.
309 void repairIntervalsInRange(MachineBasicBlock *MBB,
310 MachineBasicBlock::iterator Begin,
311 MachineBasicBlock::iterator End,
312 ArrayRef<unsigned> OrigRegs);
314 // Register mask functions.
316 // Machine instructions may use a register mask operand to indicate that a
317 // large number of registers are clobbered by the instruction. This is
318 // typically used for calls.
320 // For compile time performance reasons, these clobbers are not recorded in
321 // the live intervals for individual physical registers. Instead,
322 // LiveIntervalAnalysis maintains a sorted list of instructions with
323 // register mask operands.
325 /// getRegMaskSlots - Returns a sorted array of slot indices of all
326 /// instructions with register mask operands.
327 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
329 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
330 /// instructions with register mask operands in the basic block numbered
332 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
333 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
334 return getRegMaskSlots().slice(P.first, P.second);
337 /// getRegMaskBits() - Returns an array of register mask pointers
338 /// corresponding to getRegMaskSlots().
339 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
341 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
342 /// to getRegMaskSlotsInBlock(MBBNum).
343 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
344 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
345 return getRegMaskBits().slice(P.first, P.second);
348 /// checkRegMaskInterference - Test if LI is live across any register mask
349 /// instructions, and compute a bit mask of physical registers that are not
350 /// clobbered by any of them.
352 /// Returns false if LI doesn't cross any register mask instructions. In
353 /// that case, the bit vector is not filled in.
354 bool checkRegMaskInterference(LiveInterval &LI,
355 BitVector &UsableRegs);
357 // Register unit functions.
359 // Fixed interference occurs when MachineInstrs use physregs directly
360 // instead of virtual registers. This typically happens when passing
361 // arguments to a function call, or when instructions require operands in
364 // Each physreg has one or more register units, see MCRegisterInfo. We
365 // track liveness per register unit to handle aliasing registers more
368 /// getRegUnit - Return the live range for Unit.
369 /// It will be computed if it doesn't exist.
370 LiveRange &getRegUnit(unsigned Unit) {
371 LiveRange *LR = RegUnitRanges[Unit];
373 // Compute missing ranges on demand.
374 RegUnitRanges[Unit] = LR = new LiveRange();
375 computeRegUnitRange(*LR, Unit);
380 /// getCachedRegUnit - Return the live range for Unit if it has already
381 /// been computed, or NULL if it hasn't been computed yet.
382 LiveRange *getCachedRegUnit(unsigned Unit) {
383 return RegUnitRanges[Unit];
386 const LiveRange *getCachedRegUnit(unsigned Unit) const {
387 return RegUnitRanges[Unit];
391 /// Compute live intervals for all virtual registers.
392 void computeVirtRegs();
394 /// Compute RegMaskSlots and RegMaskBits.
395 void computeRegMasks();
397 static LiveInterval* createInterval(unsigned Reg);
399 void printInstrs(raw_ostream &O) const;
400 void dumpInstrs() const;
402 void computeLiveInRegUnits();
403 void computeRegUnitRange(LiveRange&, unsigned Unit);
404 void computeVirtRegInterval(LiveInterval&);
408 } // End llvm namespace