Add experimental support for register unit liveness.
[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/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"
32 #include <cmath>
33 #include <iterator>
34
35 namespace llvm {
36
37   class AliasAnalysis;
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     LiveVariables* LV;
56     SlotIndexes* Indexes;
57     MachineDominatorTree *DomTree;
58     LiveRangeCalc *LRCalc;
59
60     /// Special pool allocator for VNInfo's (LiveInterval val#).
61     ///
62     VNInfo::Allocator VNInfoAllocator;
63
64     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
65     Reg2IntervalMap R2IMap;
66
67     /// AllocatableRegs - A bit vector of allocatable registers.
68     BitVector AllocatableRegs;
69
70     /// ReservedRegs - A bit vector of reserved registers.
71     BitVector ReservedRegs;
72
73     /// RegMaskSlots - Sorted list of instructions with register mask operands.
74     /// Always use the 'r' slot, RegMasks are normal clobbers, not early
75     /// clobbers.
76     SmallVector<SlotIndex, 8> RegMaskSlots;
77
78     /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
79     /// pointer to the corresponding register mask.  This pointer can be
80     /// recomputed as:
81     ///
82     ///   MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
83     ///   unsigned OpNum = findRegMaskOperand(MI);
84     ///   RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
85     ///
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;
91
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
96     /// block.
97     SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
98
99     /// RegUnitIntervals - Keep a live interval for each register unit as a way
100     /// of tracking fixed physreg interference.
101     SmallVector<LiveInterval*, 0> RegUnitIntervals;
102
103   public:
104     static char ID; // Pass identification, replacement for typeid
105     LiveIntervals();
106     virtual ~LiveIntervals();
107
108     // Calculate the spill weight to assign to a single instruction.
109     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
110
111     typedef Reg2IntervalMap::iterator iterator;
112     typedef Reg2IntervalMap::const_iterator const_iterator;
113     const_iterator begin() const { return R2IMap.begin(); }
114     const_iterator end() const { return R2IMap.end(); }
115     iterator begin() { return R2IMap.begin(); }
116     iterator end() { return R2IMap.end(); }
117     unsigned getNumIntervals() const { return (unsigned)R2IMap.size(); }
118
119     LiveInterval &getInterval(unsigned reg) {
120       Reg2IntervalMap::iterator I = R2IMap.find(reg);
121       assert(I != R2IMap.end() && "Interval does not exist for register");
122       return *I->second;
123     }
124
125     const LiveInterval &getInterval(unsigned reg) const {
126       Reg2IntervalMap::const_iterator I = R2IMap.find(reg);
127       assert(I != R2IMap.end() && "Interval does not exist for register");
128       return *I->second;
129     }
130
131     bool hasInterval(unsigned reg) const {
132       return R2IMap.count(reg);
133     }
134
135     /// isAllocatable - is the physical register reg allocatable in the current
136     /// function?
137     bool isAllocatable(unsigned reg) const {
138       return AllocatableRegs.test(reg);
139     }
140
141     /// isReserved - is the physical register reg reserved in the current
142     /// function
143     bool isReserved(unsigned reg) const {
144       return ReservedRegs.test(reg);
145     }
146
147     // Interval creation
148     LiveInterval &getOrCreateInterval(unsigned reg) {
149       Reg2IntervalMap::iterator I = R2IMap.find(reg);
150       if (I == R2IMap.end())
151         I = R2IMap.insert(std::make_pair(reg, createInterval(reg))).first;
152       return *I->second;
153     }
154
155     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
156     /// adds a live range from that instruction to the end of its MBB.
157     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
158                                        MachineInstr* startInst);
159
160     /// shrinkToUses - After removing some uses of a register, shrink its live
161     /// range to just the remaining uses. This method does not compute reaching
162     /// defs for new uses, and it doesn't remove dead defs.
163     /// Dead PHIDef values are marked as unused.
164     /// New dead machine instructions are added to the dead vector.
165     /// Return true if the interval may have been separated into multiple
166     /// connected components.
167     bool shrinkToUses(LiveInterval *li,
168                       SmallVectorImpl<MachineInstr*> *dead = 0);
169
170     // Interval removal
171
172     void removeInterval(unsigned Reg) {
173       DenseMap<unsigned, LiveInterval*>::iterator I = R2IMap.find(Reg);
174       delete I->second;
175       R2IMap.erase(I);
176     }
177
178     SlotIndexes *getSlotIndexes() const {
179       return Indexes;
180     }
181
182     AliasAnalysis *getAliasAnalysis() const {
183       return AA;
184     }
185
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);
190     }
191
192     /// Returns the base index of the given instruction.
193     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
194       return Indexes->getInstructionIndex(instr);
195     }
196
197     /// Returns the instruction associated with the given index.
198     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
199       return Indexes->getInstructionFromIndex(index);
200     }
201
202     /// Return the first index in the given basic block.
203     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
204       return Indexes->getMBBStartIdx(mbb);
205     }
206
207     /// Return the last index in the given basic block.
208     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
209       return Indexes->getMBBEndIdx(mbb);
210     }
211
212     bool isLiveInToMBB(const LiveInterval &li,
213                        const MachineBasicBlock *mbb) const {
214       return li.liveAt(getMBBStartIdx(mbb));
215     }
216
217     bool isLiveOutOfMBB(const LiveInterval &li,
218                         const MachineBasicBlock *mbb) const {
219       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
220     }
221
222     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
223       return Indexes->getMBBFromIndex(index);
224     }
225
226     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
227       return Indexes->insertMachineInstrInMaps(MI);
228     }
229
230     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
231       Indexes->removeMachineInstrFromMaps(MI);
232     }
233
234     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
235       Indexes->replaceMachineInstrInMaps(MI, NewMI);
236     }
237
238     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
239                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
240       return Indexes->findLiveInMBBs(Start, End, MBBs);
241     }
242
243     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
244
245     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
246     virtual void releaseMemory();
247
248     /// runOnMachineFunction - pass entry point
249     virtual bool runOnMachineFunction(MachineFunction&);
250
251     /// print - Implement the dump method.
252     virtual void print(raw_ostream &O, const Module* = 0) const;
253
254     /// isReMaterializable - Returns true if every definition of MI of every
255     /// val# of the specified interval is re-materializable. Also returns true
256     /// by reference if all of the defs are load instructions.
257     bool isReMaterializable(const LiveInterval &li,
258                             const SmallVectorImpl<LiveInterval*> *SpillIs,
259                             bool &isLoad);
260
261     /// intervalIsInOneMBB - If LI is confined to a single basic block, return
262     /// a pointer to that block.  If LI is live in to or out of any block,
263     /// return NULL.
264     MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
265
266     /// addKillFlags - Add kill flags to any instruction that kills a virtual
267     /// register.
268     void addKillFlags();
269
270     /// handleMove - call this method to notify LiveIntervals that
271     /// instruction 'mi' has been moved within a basic block. This will update
272     /// the live intervals for all operands of mi. Moves between basic blocks
273     /// are not supported.
274     void handleMove(MachineInstr* MI);
275
276     /// moveIntoBundle - Update intervals for operands of MI so that they
277     /// begin/end on the SlotIndex for BundleStart.
278     ///
279     /// Requires MI and BundleStart to have SlotIndexes, and assumes
280     /// existing liveness is accurate. BundleStart should be the first
281     /// instruction in the Bundle.
282     void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
283
284     // Register mask functions.
285     //
286     // Machine instructions may use a register mask operand to indicate that a
287     // large number of registers are clobbered by the instruction.  This is
288     // typically used for calls.
289     //
290     // For compile time performance reasons, these clobbers are not recorded in
291     // the live intervals for individual physical registers.  Instead,
292     // LiveIntervalAnalysis maintains a sorted list of instructions with
293     // register mask operands.
294
295     /// getRegMaskSlots - Returns a sorted array of slot indices of all
296     /// instructions with register mask operands.
297     ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
298
299     /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
300     /// instructions with register mask operands in the basic block numbered
301     /// MBBNum.
302     ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
303       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
304       return getRegMaskSlots().slice(P.first, P.second);
305     }
306
307     /// getRegMaskBits() - Returns an array of register mask pointers
308     /// corresponding to getRegMaskSlots().
309     ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
310
311     /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
312     /// to getRegMaskSlotsInBlock(MBBNum).
313     ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
314       std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
315       return getRegMaskBits().slice(P.first, P.second);
316     }
317
318     /// checkRegMaskInterference - Test if LI is live across any register mask
319     /// instructions, and compute a bit mask of physical registers that are not
320     /// clobbered by any of them.
321     ///
322     /// Returns false if LI doesn't cross any register mask instructions. In
323     /// that case, the bit vector is not filled in.
324     bool checkRegMaskInterference(LiveInterval &LI,
325                                   BitVector &UsableRegs);
326
327     // Register unit functions.
328     //
329     // Fixed interference occurs when MachineInstrs use physregs directly
330     // instead of virtual registers. This typically happens when passing
331     // arguments to a function call, or when instructions require operands in
332     // fixed registers.
333     //
334     // Each physreg has one or more register units, see MCRegisterInfo. We
335     // track liveness per register unit to handle aliasing registers more
336     // efficiently.
337
338     /// getRegUnit - Return the live range for Unit.
339     /// It will be computed if it doesn't exist.
340     LiveInterval &getRegUnit(unsigned Unit) {
341       LiveInterval *LI = RegUnitIntervals[Unit];
342       if (!LI) {
343         // Compute missing ranges on demand.
344         RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
345         computeRegUnitInterval(LI);
346       }
347       return *LI;
348     }
349
350     /// trackingRegUnits - Does LiveIntervals curently track register units?
351     /// This function will be removed when regunit tracking is permanently
352     /// enabled.
353     bool trackingRegUnits() const { return !RegUnitIntervals.empty(); }
354
355   private:
356     /// computeIntervals - Compute live intervals.
357     void computeIntervals();
358
359     /// handleRegisterDef - update intervals for a register def
360     /// (calls handlePhysicalRegisterDef and
361     /// handleVirtualRegisterDef)
362     void handleRegisterDef(MachineBasicBlock *MBB,
363                            MachineBasicBlock::iterator MI,
364                            SlotIndex MIIdx,
365                            MachineOperand& MO, unsigned MOIdx);
366
367     /// isPartialRedef - Return true if the specified def at the specific index
368     /// is partially re-defining the specified live interval. A common case of
369     /// this is a definition of the sub-register.
370     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
371                         LiveInterval &interval);
372
373     /// handleVirtualRegisterDef - update intervals for a virtual
374     /// register def
375     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
376                                   MachineBasicBlock::iterator MI,
377                                   SlotIndex MIIdx, MachineOperand& MO,
378                                   unsigned MOIdx,
379                                   LiveInterval& interval);
380
381     /// handlePhysicalRegisterDef - update intervals for a physical register
382     /// def.
383     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
384                                    MachineBasicBlock::iterator mi,
385                                    SlotIndex MIIdx, MachineOperand& MO,
386                                    LiveInterval &interval);
387
388     /// handleLiveInRegister - Create interval for a livein register.
389     void handleLiveInRegister(MachineBasicBlock* mbb,
390                               SlotIndex MIIdx,
391                               LiveInterval &interval);
392
393     static LiveInterval* createInterval(unsigned Reg);
394
395     void printInstrs(raw_ostream &O) const;
396     void dumpInstrs() const;
397
398     void computeLiveInRegUnits();
399     void computeRegUnitInterval(LiveInterval*);
400
401     class HMEditor;
402   };
403 } // End llvm namespace
404
405 #endif