Move #include of BitVector from .h to .cpp file.
[oota-llvm.git] / include / llvm / CodeGen / LiveIntervalAnalysis.h
1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
22
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"
31 #include <cmath>
32 #include <iterator>
33
34 namespace llvm {
35
36   class AliasAnalysis;
37   class BitVector;
38   class LiveRangeCalc;
39   class LiveVariables;
40   class MachineDominatorTree;
41   class MachineLoopInfo;
42   class TargetRegisterInfo;
43   class MachineRegisterInfo;
44   class TargetInstrInfo;
45   class TargetRegisterClass;
46   class VirtRegMap;
47
48   class LiveIntervals : public MachineFunctionPass {
49     MachineFunction* MF;
50     MachineRegisterInfo* MRI;
51     const TargetMachine* TM;
52     const TargetRegisterInfo* TRI;
53     const TargetInstrInfo* TII;
54     AliasAnalysis *AA;
55     SlotIndexes* Indexes;
56     MachineDominatorTree *DomTree;
57     LiveRangeCalc *LRCalc;
58
59     /// Special pool allocator for VNInfo's (LiveInterval val#).
60     ///
61     VNInfo::Allocator VNInfoAllocator;
62
63     /// Live interval pointers for all the virtual registers.
64     IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
65
66     /// RegMaskSlots - Sorted list of instructions with register mask operands.
67     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
68     /// clobbers.
69     SmallVector<SlotIndex, 8> RegMaskSlots;
70
71     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
72     /// pointer to the corresponding register mask.  This pointer can be
73     /// recomputed as:
74     ///
75     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
76     ///   unsigned OpNum = findRegMaskOperand(MI);
77     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
78     ///
79     /// This is kept in a separate vector partly because some standard
80     /// libraries don't support lower_bound() with mixed objects, partly to
81     /// improve locality when searching in RegMaskSlots.
82     /// Also see the comment in LiveInterval::find().
83     SmallVector<const uint32_t*, 8> RegMaskBits;
84
85     /// For each basic block number, keep (begin, size) pairs indexing into the
86     /// RegMaskSlots and RegMaskBits arrays.
87     /// Note that basic block numbers may not be layout contiguous, that's why
88     /// we can't just keep track of the first register mask in each basic
89     /// block.
90     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
91
92     /// RegUnitIntervals - Keep a live interval for each register unit as a way
93     /// of tracking fixed physreg interference.
94     SmallVector<LiveInterval*, 0> RegUnitIntervals;
95
96   public:
97     static char ID; // Pass identification, replacement for typeid
98     LiveIntervals();
99     virtual ~LiveIntervals();
100
101     // Calculate the spill weight to assign to a single instruction.
102     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
103
104     LiveInterval &getInterval(unsigned Reg) {
105       LiveInterval *LI = VirtRegIntervals[Reg];
106       assert(LI && "Interval does not exist for virtual register");
107       return *LI;
108     }
109
110     const LiveInterval &getInterval(unsigned Reg) const {
111       return const_cast<LiveIntervals*>(this)->getInterval(Reg);
112     }
113
114     bool hasInterval(unsigned Reg) const {
115       return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
116     }
117
118     // Interval creation.
119     LiveInterval &getOrCreateInterval(unsigned Reg) {
120       if (!hasInterval(Reg)) {
121         VirtRegIntervals.grow(Reg);
122         VirtRegIntervals[Reg] = createInterval(Reg);
123       }
124       return getInterval(Reg);
125     }
126
127     // Interval removal.
128     void removeInterval(unsigned Reg) {
129       delete VirtRegIntervals[Reg];
130       VirtRegIntervals[Reg] = 0;
131     }
132
133     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
134     /// adds a live range from that instruction to the end of its MBB.
135     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
136                                        MachineInstr* startInst);
137
138     /// shrinkToUses - After removing some uses of a register, shrink its live
139     /// range to just the remaining uses. This method does not compute reaching
140     /// defs for new uses, and it doesn't remove dead defs.
141     /// Dead PHIDef values are marked as unused.
142     /// New dead machine instructions are added to the dead vector.
143     /// Return true if the interval may have been separated into multiple
144     /// connected components.
145     bool shrinkToUses(LiveInterval *li,
146                       SmallVectorImpl<MachineInstr*> *dead = 0);
147
148     /// extendToIndices - Extend the live range of LI to reach all points in
149     /// Indices. The points in the Indices array must be jointly dominated by
150     /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
151     ///
152     /// If a SlotIndex in Indices is the end index of a basic block, LI will be
153     /// extended to be live out of the basic block.
154     ///
155     /// See also LiveRangeCalc::extend().
156     void extendToIndices(LiveInterval *LI, ArrayRef<SlotIndex> Indices);
157
158     /// pruneValue - If an LI value is live at Kill, prune its live range by
159     /// removing any liveness reachable from Kill. Add live range end points to
160     /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
161     /// value's live range.
162     ///
163     /// Calling pruneValue() and extendToIndices() can be used to reconstruct
164     /// SSA form after adding defs to a virtual register.
165     void pruneValue(LiveInterval *LI, SlotIndex Kill,
166                     SmallVectorImpl<SlotIndex> *EndPoints);
167
168     SlotIndexes *getSlotIndexes() const {
169       return Indexes;
170     }
171
172     AliasAnalysis *getAliasAnalysis() const {
173       return AA;
174     }
175
176     /// isNotInMIMap - returns true if the specified machine instr has been
177     /// removed or was never entered in the map.
178     bool isNotInMIMap(const MachineInstr* Instr) const {
179       return !Indexes->hasIndex(Instr);
180     }
181
182     /// Returns the base index of the given instruction.
183     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
184       return Indexes->getInstructionIndex(instr);
185     }
186
187     /// Returns the instruction associated with the given index.
188     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
189       return Indexes->getInstructionFromIndex(index);
190     }
191
192     /// Return the first index in the given basic block.
193     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
194       return Indexes->getMBBStartIdx(mbb);
195     }
196
197     /// Return the last index in the given basic block.
198     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
199       return Indexes->getMBBEndIdx(mbb);
200     }
201
202     bool isLiveInToMBB(const LiveInterval &li,
203                        const MachineBasicBlock *mbb) const {
204       return li.liveAt(getMBBStartIdx(mbb));
205     }
206
207     bool isLiveOutOfMBB(const LiveInterval &li,
208                         const MachineBasicBlock *mbb) const {
209       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
210     }
211
212     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
213       return Indexes->getMBBFromIndex(index);
214     }
215
216     void insertMBBInMaps(MachineBasicBlock *MBB) {
217       Indexes->insertMBBInMaps(MBB);
218       assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
219              "Blocks must be added in order.");
220       RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
221     }
222
223     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
224       return Indexes->insertMachineInstrInMaps(MI);
225     }
226
227     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
228       Indexes->removeMachineInstrFromMaps(MI);
229     }
230
231     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
232       Indexes->replaceMachineInstrInMaps(MI, NewMI);
233     }
234
235     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
236                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
237       return Indexes->findLiveInMBBs(Start, End, MBBs);
238     }
239
240     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
241
242     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
243     virtual void releaseMemory();
244
245     /// runOnMachineFunction - pass entry point
246     virtual bool runOnMachineFunction(MachineFunction&);
247
248     /// print - Implement the dump method.
249     virtual void print(raw_ostream &O, const Module* = 0) const;
250
251     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
252     /// a pointer to that block.  If LI is live in to or out of any block,
253     /// return NULL.
254     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
255
256     /// Returns true if VNI is killed by any PHI-def values in LI.
257     /// This may conservatively return true to avoid expensive computations.
258     bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
259
260     /// addKillFlags - Add kill flags to any instruction that kills a virtual
261     /// register.
262     void addKillFlags(const VirtRegMap*);
263
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     ///
269     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
270     void handleMove(MachineInstr* MI, bool UpdateFlags = false);
271
272     /// moveIntoBundle - Update intervals for operands of MI so that they
273     /// begin/end on the SlotIndex for BundleStart.
274     ///
275     /// \param UpdateFlags Update live intervals for nonallocatable physregs.
276     ///
277     /// Requires MI and BundleStart to have SlotIndexes, and assumes
278     /// existing liveness is accurate. BundleStart should be the first
279     /// instruction in the Bundle.
280     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart,
281                               bool UpdateFlags = false);
282
283     /// repairIntervalsInRange - Update live intervals for instructions in a
284     /// range of iterators. It is intended for use after target hooks that may
285     /// insert or remove instructions, and is only efficient for a small number
286     /// of instructions.
287     ///
288     /// OrigRegs is a vector of registers that were originally used by the
289     /// instructions in the range between the two iterators.
290     ///
291     /// Currently, the only only changes that are supported are simple removal
292     /// and addition of uses.
293     void repairIntervalsInRange(MachineBasicBlock *MBB,
294                                 MachineBasicBlock::iterator Begin,
295                                 MachineBasicBlock::iterator End,
296                                 ArrayRef<unsigned> OrigRegs);
297
298     // Register mask functions.
299     //
300     // Machine instructions may use a register mask operand to indicate that a
301     // large number of registers are clobbered by the instruction.  This is
302     // typically used for calls.
303     //
304     // For compile time performance reasons, these clobbers are not recorded in
305     // the live intervals for individual physical registers.  Instead,
306     // LiveIntervalAnalysis maintains a sorted list of instructions with
307     // register mask operands.
308
309     /// getRegMaskSlots - Returns a sorted array of slot indices of all
310     /// instructions with register mask operands.
311     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
312
313     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
314     /// instructions with register mask operands in the basic block numbered
315     /// MBBNum.
316     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
317       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
318       return getRegMaskSlots().slice(P.first, P.second);
319     }
320
321     /// getRegMaskBits() - Returns an array of register mask pointers
322     /// corresponding to getRegMaskSlots().
323     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
324
325     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
326     /// to getRegMaskSlotsInBlock(MBBNum).
327     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
328       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
329       return getRegMaskBits().slice(P.first, P.second);
330     }
331
332     /// checkRegMaskInterference - Test if LI is live across any register mask
333     /// instructions, and compute a bit mask of physical registers that are not
334     /// clobbered by any of them.
335     ///
336     /// Returns false if LI doesn't cross any register mask instructions. In
337     /// that case, the bit vector is not filled in.
338     bool checkRegMaskInterference(LiveInterval &LI,
339                                   BitVector &UsableRegs);
340
341     // Register unit functions.
342     //
343     // Fixed interference occurs when MachineInstrs use physregs directly
344     // instead of virtual registers. This typically happens when passing
345     // arguments to a function call, or when instructions require operands in
346     // fixed registers.
347     //
348     // Each physreg has one or more register units, see MCRegisterInfo. We
349     // track liveness per register unit to handle aliasing registers more
350     // efficiently.
351
352     /// getRegUnit - Return the live range for Unit.
353     /// It will be computed if it doesn't exist.
354     LiveInterval &getRegUnit(unsigned Unit) {
355       LiveInterval *LI = RegUnitIntervals[Unit];
356       if (!LI) {
357         // Compute missing ranges on demand.
358         RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
359         computeRegUnitInterval(LI);
360       }
361       return *LI;
362     }
363
364     /// getCachedRegUnit - Return the live range for Unit if it has already
365     /// been computed, or NULL if it hasn't been computed yet.
366     LiveInterval *getCachedRegUnit(unsigned Unit) {
367       return RegUnitIntervals[Unit];
368     }
369
370     const LiveInterval *getCachedRegUnit(unsigned Unit) const {
371       return RegUnitIntervals[Unit];
372     }
373
374   private:
375     /// Compute live intervals for all virtual registers.
376     void computeVirtRegs();
377
378     /// Compute RegMaskSlots and RegMaskBits.
379     void computeRegMasks();
380
381     static LiveInterval* createInterval(unsigned Reg);
382
383     void printInstrs(raw_ostream &O) const;
384     void dumpInstrs() const;
385
386     void computeLiveInRegUnits();
387     void computeRegUnitInterval(LiveInterval*);
388     void computeVirtRegInterval(LiveInterval*);
389
390     class HMEditor;
391   };
392 } // End llvm namespace
393
394 #endif