Refactor some code.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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' abd 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/MachineFunctionPass.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
30
31 namespace llvm {
32
33   class LiveVariables;
34   class MRegisterInfo;
35   class SSARegMap;
36   class TargetInstrInfo;
37   class TargetRegisterClass;
38   class VirtRegMap;
39   typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
40
41   class LiveIntervals : public MachineFunctionPass {
42     MachineFunction* mf_;
43     const TargetMachine* tm_;
44     const MRegisterInfo* mri_;
45     const TargetInstrInfo* tii_;
46     LiveVariables* lv_;
47
48     /// Special pool allocator for VNInfo's (LiveInterval val#).
49     ///
50     BumpPtrAllocator VNInfoAllocator;
51
52     /// MBB2IdxMap - The indexes of the first and last instructions in the
53     /// specified basic block.
54     std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
55
56     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
57     /// and MBB id.
58     std::vector<IdxMBBPair> Idx2MBBMap;
59
60     typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
61     Mi2IndexMap mi2iMap_;
62
63     typedef std::vector<MachineInstr*> Index2MiMap;
64     Index2MiMap i2miMap_;
65
66     typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
67     Reg2IntervalMap r2iMap_;
68
69     BitVector allocatableRegs_;
70
71     std::vector<MachineInstr*> ClonedMIs;
72
73   public:
74     static char ID; // Pass identification, replacement for typeid
75     LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
76
77     struct InstrSlots {
78       enum {
79         LOAD  = 0,
80         USE   = 1,
81         DEF   = 2,
82         STORE = 3,
83         NUM   = 4
84       };
85     };
86
87     static unsigned getBaseIndex(unsigned index) {
88       return index - (index % InstrSlots::NUM);
89     }
90     static unsigned getBoundaryIndex(unsigned index) {
91       return getBaseIndex(index + InstrSlots::NUM - 1);
92     }
93     static unsigned getLoadIndex(unsigned index) {
94       return getBaseIndex(index) + InstrSlots::LOAD;
95     }
96     static unsigned getUseIndex(unsigned index) {
97       return getBaseIndex(index) + InstrSlots::USE;
98     }
99     static unsigned getDefIndex(unsigned index) {
100       return getBaseIndex(index) + InstrSlots::DEF;
101     }
102     static unsigned getStoreIndex(unsigned index) {
103       return getBaseIndex(index) + InstrSlots::STORE;
104     }
105
106     static float getSpillWeight(const MachineOperand &mop, unsigned loopDepth) {
107       return (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
108     }
109
110     typedef Reg2IntervalMap::iterator iterator;
111     typedef Reg2IntervalMap::const_iterator const_iterator;
112     const_iterator begin() const { return r2iMap_.begin(); }
113     const_iterator end() const { return r2iMap_.end(); }
114     iterator begin() { return r2iMap_.begin(); }
115     iterator end() { return r2iMap_.end(); }
116     unsigned getNumIntervals() const { return r2iMap_.size(); }
117
118     LiveInterval &getInterval(unsigned reg) {
119       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
120       assert(I != r2iMap_.end() && "Interval does not exist for register");
121       return I->second;
122     }
123
124     const LiveInterval &getInterval(unsigned reg) const {
125       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
126       assert(I != r2iMap_.end() && "Interval does not exist for register");
127       return I->second;
128     }
129
130     bool hasInterval(unsigned reg) const {
131       return r2iMap_.count(reg);
132     }
133
134     /// getMBBStartIdx - Return the base index of the first instruction in the
135     /// specified MachineBasicBlock.
136     unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
137       return getMBBStartIdx(MBB->getNumber());
138     }
139     unsigned getMBBStartIdx(unsigned MBBNo) const {
140       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
141       return MBB2IdxMap[MBBNo].first;
142     }
143
144     /// getMBBEndIdx - Return the store index of the last instruction in the
145     /// specified MachineBasicBlock.
146     unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
147       return getMBBEndIdx(MBB->getNumber());
148     }
149     unsigned getMBBEndIdx(unsigned MBBNo) const {
150       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
151       return MBB2IdxMap[MBBNo].second;
152     }
153
154     /// getInstructionIndex - returns the base index of instr
155     unsigned getInstructionIndex(MachineInstr* instr) const {
156       Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
157       assert(it != mi2iMap_.end() && "Invalid instruction!");
158       return it->second;
159     }
160
161     /// getInstructionFromIndex - given an index in any slot of an
162     /// instruction return a pointer the instruction
163     MachineInstr* getInstructionFromIndex(unsigned index) const {
164       index /= InstrSlots::NUM; // convert index to vector index
165       assert(index < i2miMap_.size() &&
166              "index does not correspond to an instruction");
167       return i2miMap_[index];
168     }
169
170     /// conflictsWithPhysRegDef - Returns true if the specified register
171     /// is defined during the duration of the specified interval.
172     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
173                                  unsigned reg);
174
175     /// findLiveInMBBs - Given a live range, if the value of the range
176     /// is live in any MBB returns true as well as the list of basic blocks
177     /// where the value is live in.
178     bool findLiveInMBBs(const LiveRange &LR,
179                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
180
181     // Interval creation
182
183     LiveInterval &getOrCreateInterval(unsigned reg) {
184       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
185       if (I == r2iMap_.end())
186         I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
187       return I->second;
188     }
189
190     // Interval removal
191
192     void removeInterval(unsigned Reg) {
193       r2iMap_.erase(Reg);
194     }
195
196     /// isRemoved - returns true if the specified machine instr has been
197     /// removed.
198     bool isRemoved(MachineInstr* instr) const {
199       return !mi2iMap_.count(instr);
200     }
201
202     /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
203     /// deleted.
204     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
205       // remove index -> MachineInstr and
206       // MachineInstr -> index mappings
207       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
208       if (mi2i != mi2iMap_.end()) {
209         i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
210         mi2iMap_.erase(mi2i);
211       }
212     }
213
214     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
215
216     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
217     virtual void releaseMemory();
218
219     /// runOnMachineFunction - pass entry point
220     virtual bool runOnMachineFunction(MachineFunction&);
221
222     /// print - Implement the dump method.
223     virtual void print(std::ostream &O, const Module* = 0) const;
224     void print(std::ostream *O, const Module* M = 0) const {
225       if (O) print(*O, M);
226     }
227
228     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
229     /// the given interval.
230     std::vector<LiveInterval*>
231       addIntervalsForSpills(const LiveInterval& i, VirtRegMap& vrm);
232
233   private:      
234     /// computeIntervals - Compute live intervals.
235     void computeIntervals();
236     
237     /// handleRegisterDef - update intervals for a register def
238     /// (calls handlePhysicalRegisterDef and
239     /// handleVirtualRegisterDef)
240     void handleRegisterDef(MachineBasicBlock *MBB,
241                            MachineBasicBlock::iterator MI, unsigned MIIdx,
242                            unsigned reg);
243
244     /// handleVirtualRegisterDef - update intervals for a virtual
245     /// register def
246     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
247                                   MachineBasicBlock::iterator MI,
248                                   unsigned MIIdx,
249                                   LiveInterval& interval);
250
251     /// handlePhysicalRegisterDef - update intervals for a physical register
252     /// def.
253     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
254                                    MachineBasicBlock::iterator mi,
255                                    unsigned MIIdx,
256                                    LiveInterval &interval,
257                                    unsigned SrcReg);
258
259     /// handleLiveInRegister - Create interval for a livein register.
260     void handleLiveInRegister(MachineBasicBlock* mbb,
261                               unsigned MIIdx,
262                               LiveInterval &interval, bool isAlias = false);
263
264     /// isReMaterializable - Returns true if the definition MI of the specified
265     /// val# of the specified interval is re-materializable.
266     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
267                             MachineInstr *MI);
268
269     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
270     /// slot / to reg or any rematerialized load into ith operand of specified
271     /// MI. If it is successul, MI is updated with the newly created MI and
272     /// returns true.
273     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
274                               MachineInstr *DefMI, unsigned index, unsigned i,
275                               bool isSS, int slot, unsigned reg);
276
277     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
278     /// for addIntervalsForSpills to rewrite uses / defs for the given live range.
279     void rewriteInstructionForSpills(const LiveInterval &li,
280         unsigned id, unsigned index, unsigned end, MachineInstr *MI,
281         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
282         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
283         VirtRegMap &vrm, SSARegMap *RegMap, const TargetRegisterClass* rc,
284         SmallVector<int, 4> &ReMatIds,
285         std::vector<LiveInterval*> &NewLIs);
286     void rewriteInstructionsForSpills(const LiveInterval &li,
287         LiveInterval::Ranges::const_iterator &I,
288         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
289         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
290         VirtRegMap &vrm, SSARegMap *RegMap, const TargetRegisterClass* rc,
291         SmallVector<int, 4> &ReMatIds,
292         std::vector<LiveInterval*> &NewLIs);
293
294     static LiveInterval createInterval(unsigned Reg);
295
296     void printRegName(unsigned reg) const;
297   };
298
299 } // End llvm namespace
300
301 #endif