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_LIVEINTERVALANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVALANALYSIS_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 TargetRegisterInfo* TRI;
54 const TargetInstrInfo* TII;
57 MachineDominatorTree *DomTree;
58 LiveRangeCalc *LRCalc;
60 /// Special pool allocator for VNInfo's (LiveInterval val#).
62 VNInfo::Allocator VNInfoAllocator;
64 /// Live interval pointers for all the virtual registers.
65 IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
67 /// RegMaskSlots - Sorted list of instructions with register mask operands.
68 /// Always use the 'r' slot, RegMasks are normal clobbers, not early
70 SmallVector<SlotIndex, 8> RegMaskSlots;
72 /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
73 /// pointer to the corresponding register mask. This pointer can be
76 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
77 /// unsigned OpNum = findRegMaskOperand(MI);
78 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
80 /// This is kept in a separate vector partly because some standard
81 /// libraries don't support lower_bound() with mixed objects, partly to
82 /// improve locality when searching in RegMaskSlots.
83 /// Also see the comment in LiveInterval::find().
84 SmallVector<const uint32_t*, 8> RegMaskBits;
86 /// For each basic block number, keep (begin, size) pairs indexing into the
87 /// RegMaskSlots and RegMaskBits arrays.
88 /// Note that basic block numbers may not be layout contiguous, that's why
89 /// we can't just keep track of the first register mask in each basic
91 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
93 /// Keeps a live range set for each register unit to track fixed physreg
95 SmallVector<LiveRange*, 0> RegUnitRanges;
98 static char ID; // Pass identification, replacement for typeid
100 virtual ~LiveIntervals();
102 // Calculate the spill weight to assign to a single instruction.
103 static float getSpillWeight(bool isDef, bool isUse,
104 const MachineBlockFrequencyInfo *MBFI,
105 const MachineInstr *Instr);
107 LiveInterval &getInterval(unsigned Reg) {
108 if (hasInterval(Reg))
109 return *VirtRegIntervals[Reg];
111 return createAndComputeVirtRegInterval(Reg);
114 const LiveInterval &getInterval(unsigned Reg) const {
115 return const_cast<LiveIntervals*>(this)->getInterval(Reg);
118 bool hasInterval(unsigned Reg) const {
119 return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
122 // Interval creation.
123 LiveInterval &createEmptyInterval(unsigned Reg) {
124 assert(!hasInterval(Reg) && "Interval already exists!");
125 VirtRegIntervals.grow(Reg);
126 VirtRegIntervals[Reg] = createInterval(Reg);
127 return *VirtRegIntervals[Reg];
130 LiveInterval &createAndComputeVirtRegInterval(unsigned Reg) {
131 LiveInterval &LI = createEmptyInterval(Reg);
132 computeVirtRegInterval(LI);
137 void removeInterval(unsigned Reg) {
138 delete VirtRegIntervals[Reg];
139 VirtRegIntervals[Reg] = nullptr;
142 /// Given a register and an instruction, adds a live segment from that
143 /// instruction to the end of its MBB.
144 LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg,
145 MachineInstr* startInst);
147 /// shrinkToUses - After removing some uses of a register, shrink its live
148 /// range to just the remaining uses. This method does not compute reaching
149 /// defs for new uses, and it doesn't remove dead defs.
150 /// Dead PHIDef values are marked as unused.
151 /// New dead machine instructions are added to the dead vector.
152 /// Return true if the interval may have been separated into multiple
153 /// connected components.
154 bool shrinkToUses(LiveInterval *li,
155 SmallVectorImpl<MachineInstr*> *dead = nullptr);
157 /// \brief Walk the values in the given interval and compute which ones
158 /// are dead. Dead values are not deleted, however:
159 /// - Dead PHIDef values are marked as unused.
160 /// - New dead machine instructions are added to the dead vector.
161 /// - CanSeparate is set to true if the interval may have been separated
162 /// into multiple connected components.
163 void computeDeadValues(LiveInterval *li,
166 SmallVectorImpl<MachineInstr*> *dead);
168 /// extendToIndices - Extend the live range of LI to reach all points in
169 /// Indices. The points in the Indices array must be jointly dominated by
170 /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
172 /// If a SlotIndex in Indices is the end index of a basic block, LI will be
173 /// extended to be live out of the basic block.
175 /// See also LiveRangeCalc::extend().
176 void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices);
178 /// pruneValue - If an LI value is live at Kill, prune its live range by
179 /// removing any liveness reachable from Kill. Add live range end points to
180 /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
181 /// value's live range.
183 /// Calling pruneValue() and extendToIndices() can be used to reconstruct
184 /// SSA form after adding defs to a virtual register.
185 void pruneValue(LiveInterval *LI, SlotIndex Kill,
186 SmallVectorImpl<SlotIndex> *EndPoints);
188 SlotIndexes *getSlotIndexes() const {
192 AliasAnalysis *getAliasAnalysis() const {
196 /// isNotInMIMap - returns true if the specified machine instr has been
197 /// removed or was never entered in the map.
198 bool isNotInMIMap(const MachineInstr* Instr) const {
199 return !Indexes->hasIndex(Instr);
202 /// Returns the base index of the given instruction.
203 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
204 return Indexes->getInstructionIndex(instr);
207 /// Returns the instruction associated with the given index.
208 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
209 return Indexes->getInstructionFromIndex(index);
212 /// Return the first index in the given basic block.
213 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
214 return Indexes->getMBBStartIdx(mbb);
217 /// Return the last index in the given basic block.
218 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
219 return Indexes->getMBBEndIdx(mbb);
222 bool isLiveInToMBB(const LiveRange &LR,
223 const MachineBasicBlock *mbb) const {
224 return LR.liveAt(getMBBStartIdx(mbb));
227 bool isLiveOutOfMBB(const LiveRange &LR,
228 const MachineBasicBlock *mbb) const {
229 return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
232 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
233 return Indexes->getMBBFromIndex(index);
236 void insertMBBInMaps(MachineBasicBlock *MBB) {
237 Indexes->insertMBBInMaps(MBB);
238 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
239 "Blocks must be added in order.");
240 RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
243 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
244 return Indexes->insertMachineInstrInMaps(MI);
247 void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,
248 MachineBasicBlock::iterator E) {
249 for (MachineBasicBlock::iterator I = B; I != E; ++I)
250 Indexes->insertMachineInstrInMaps(I);
253 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
254 Indexes->removeMachineInstrFromMaps(MI);
257 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
258 Indexes->replaceMachineInstrInMaps(MI, NewMI);
261 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
262 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
263 return Indexes->findLiveInMBBs(Start, End, MBBs);
266 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
268 void getAnalysisUsage(AnalysisUsage &AU) const override;
269 void releaseMemory() override;
271 /// runOnMachineFunction - pass entry point
272 bool runOnMachineFunction(MachineFunction&) override;
274 /// print - Implement the dump method.
275 void print(raw_ostream &O, const Module* = nullptr) const override;
277 /// intervalIsInOneMBB - If LI is confined to a single basic block, return
278 /// a pointer to that block. If LI is live in to or out of any block,
280 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
282 /// Returns true if VNI is killed by any PHI-def values in LI.
283 /// This may conservatively return true to avoid expensive computations.
284 bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
286 /// addKillFlags - Add kill flags to any instruction that kills a virtual
288 void addKillFlags(const VirtRegMap*);
290 /// handleMove - call this method to notify LiveIntervals that
291 /// instruction 'mi' has been moved within a basic block. This will update
292 /// the live intervals for all operands of mi. Moves between basic blocks
293 /// are not supported.
295 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
296 void handleMove(MachineInstr* MI, bool UpdateFlags = false);
298 /// moveIntoBundle - Update intervals for operands of MI so that they
299 /// begin/end on the SlotIndex for BundleStart.
301 /// \param UpdateFlags Update live intervals for nonallocatable physregs.
303 /// Requires MI and BundleStart to have SlotIndexes, and assumes
304 /// existing liveness is accurate. BundleStart should be the first
305 /// instruction in the Bundle.
306 void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
307 bool UpdateFlags = false);
309 /// repairIntervalsInRange - Update live intervals for instructions in a
310 /// range of iterators. It is intended for use after target hooks that may
311 /// insert or remove instructions, and is only efficient for a small number
314 /// OrigRegs is a vector of registers that were originally used by the
315 /// instructions in the range between the two iterators.
317 /// Currently, the only only changes that are supported are simple removal
318 /// and addition of uses.
319 void repairIntervalsInRange(MachineBasicBlock *MBB,
320 MachineBasicBlock::iterator Begin,
321 MachineBasicBlock::iterator End,
322 ArrayRef<unsigned> OrigRegs);
324 // Register mask functions.
326 // Machine instructions may use a register mask operand to indicate that a
327 // large number of registers are clobbered by the instruction. This is
328 // typically used for calls.
330 // For compile time performance reasons, these clobbers are not recorded in
331 // the live intervals for individual physical registers. Instead,
332 // LiveIntervalAnalysis maintains a sorted list of instructions with
333 // register mask operands.
335 /// getRegMaskSlots - Returns a sorted array of slot indices of all
336 /// instructions with register mask operands.
337 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
339 /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
340 /// instructions with register mask operands in the basic block numbered
342 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
343 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
344 return getRegMaskSlots().slice(P.first, P.second);
347 /// getRegMaskBits() - Returns an array of register mask pointers
348 /// corresponding to getRegMaskSlots().
349 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
351 /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
352 /// to getRegMaskSlotsInBlock(MBBNum).
353 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
354 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
355 return getRegMaskBits().slice(P.first, P.second);
358 /// checkRegMaskInterference - Test if LI is live across any register mask
359 /// instructions, and compute a bit mask of physical registers that are not
360 /// clobbered by any of them.
362 /// Returns false if LI doesn't cross any register mask instructions. In
363 /// that case, the bit vector is not filled in.
364 bool checkRegMaskInterference(LiveInterval &LI,
365 BitVector &UsableRegs);
367 // Register unit functions.
369 // Fixed interference occurs when MachineInstrs use physregs directly
370 // instead of virtual registers. This typically happens when passing
371 // arguments to a function call, or when instructions require operands in
374 // Each physreg has one or more register units, see MCRegisterInfo. We
375 // track liveness per register unit to handle aliasing registers more
378 /// getRegUnit - Return the live range for Unit.
379 /// It will be computed if it doesn't exist.
380 LiveRange &getRegUnit(unsigned Unit) {
381 LiveRange *LR = RegUnitRanges[Unit];
383 // Compute missing ranges on demand.
384 RegUnitRanges[Unit] = LR = new LiveRange();
385 computeRegUnitRange(*LR, Unit);
390 /// getCachedRegUnit - Return the live range for Unit if it has already
391 /// been computed, or NULL if it hasn't been computed yet.
392 LiveRange *getCachedRegUnit(unsigned Unit) {
393 return RegUnitRanges[Unit];
396 const LiveRange *getCachedRegUnit(unsigned Unit) const {
397 return RegUnitRanges[Unit];
401 /// Compute live intervals for all virtual registers.
402 void computeVirtRegs();
404 /// Compute RegMaskSlots and RegMaskBits.
405 void computeRegMasks();
407 static LiveInterval* createInterval(unsigned Reg);
409 void printInstrs(raw_ostream &O) const;
410 void dumpInstrs() const;
412 void computeLiveInRegUnits();
413 void computeRegUnitRange(LiveRange&, unsigned Unit);
414 void computeVirtRegInterval(LiveInterval&);
418 } // End llvm namespace