Use InstrSlots::NUM rather than pre-dividing by four. Also, mark this const.
[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/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 #include <cmath>
31 #include <map>
32
33 namespace llvm {
34
35   class LiveVariables;
36   class MachineLoopInfo;
37   class TargetRegisterInfo;
38   class MachineRegisterInfo;
39   class TargetInstrInfo;
40   class TargetRegisterClass;
41   class VirtRegMap;
42   typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
43
44   inline bool operator<(unsigned V, const IdxMBBPair &IM) {
45     return V < IM.first;
46   }
47
48   inline bool operator<(const IdxMBBPair &IM, unsigned V) {
49     return IM.first < V;
50   }
51
52   struct Idx2MBBCompare {
53     bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
54       return LHS.first < RHS.first;
55     }
56   };
57
58   class LiveIntervals : public MachineFunctionPass {
59     MachineFunction* mf_;
60     MachineRegisterInfo* mri_;
61     const TargetMachine* tm_;
62     const TargetRegisterInfo* tri_;
63     const TargetInstrInfo* tii_;
64     LiveVariables* lv_;
65
66     /// Special pool allocator for VNInfo's (LiveInterval val#).
67     ///
68     BumpPtrAllocator VNInfoAllocator;
69
70     /// MBB2IdxMap - The indexes of the first and last instructions in the
71     /// specified basic block.
72     std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
73
74     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
75     /// and MBB id.
76     std::vector<IdxMBBPair> Idx2MBBMap;
77
78     typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
79     Mi2IndexMap mi2iMap_;
80
81     typedef std::vector<MachineInstr*> Index2MiMap;
82     Index2MiMap i2miMap_;
83
84     typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
85     Reg2IntervalMap r2iMap_;
86
87     BitVector allocatableRegs_;
88
89     std::vector<MachineInstr*> ClonedMIs;
90
91   public:
92     static char ID; // Pass identification, replacement for typeid
93     LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
94
95     struct InstrSlots {
96       enum {
97         LOAD  = 0,
98         USE   = 1,
99         DEF   = 2,
100         STORE = 3,
101         NUM   = 4
102       };
103     };
104
105     static unsigned getBaseIndex(unsigned index) {
106       return index - (index % InstrSlots::NUM);
107     }
108     static unsigned getBoundaryIndex(unsigned index) {
109       return getBaseIndex(index + InstrSlots::NUM - 1);
110     }
111     static unsigned getLoadIndex(unsigned index) {
112       return getBaseIndex(index) + InstrSlots::LOAD;
113     }
114     static unsigned getUseIndex(unsigned index) {
115       return getBaseIndex(index) + InstrSlots::USE;
116     }
117     static unsigned getDefIndex(unsigned index) {
118       return getBaseIndex(index) + InstrSlots::DEF;
119     }
120     static unsigned getStoreIndex(unsigned index) {
121       return getBaseIndex(index) + InstrSlots::STORE;
122     }
123
124     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
125       return (isDef + isUse) * powf(10.0F, (float)loopDepth);
126     }
127
128     typedef Reg2IntervalMap::iterator iterator;
129     typedef Reg2IntervalMap::const_iterator const_iterator;
130     const_iterator begin() const { return r2iMap_.begin(); }
131     const_iterator end() const { return r2iMap_.end(); }
132     iterator begin() { return r2iMap_.begin(); }
133     iterator end() { return r2iMap_.end(); }
134     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
135
136     LiveInterval &getInterval(unsigned reg) {
137       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
138       assert(I != r2iMap_.end() && "Interval does not exist for register");
139       return I->second;
140     }
141
142     const LiveInterval &getInterval(unsigned reg) const {
143       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
144       assert(I != r2iMap_.end() && "Interval does not exist for register");
145       return I->second;
146     }
147
148     bool hasInterval(unsigned reg) const {
149       return r2iMap_.count(reg);
150     }
151
152     /// getMBBStartIdx - Return the base index of the first instruction in the
153     /// specified MachineBasicBlock.
154     unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
155       return getMBBStartIdx(MBB->getNumber());
156     }
157     unsigned getMBBStartIdx(unsigned MBBNo) const {
158       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
159       return MBB2IdxMap[MBBNo].first;
160     }
161
162     /// getMBBEndIdx - Return the store index of the last instruction in the
163     /// specified MachineBasicBlock.
164     unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
165       return getMBBEndIdx(MBB->getNumber());
166     }
167     unsigned getMBBEndIdx(unsigned MBBNo) const {
168       assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
169       return MBB2IdxMap[MBBNo].second;
170     }
171
172     /// getIntervalSize - get the size of an interval in "units,"
173     /// where every function is composed of one thousand units.  This
174     /// measure scales properly with empty index slots in the function.
175     unsigned getScaledIntervalSize(LiveInterval& I) const {
176       // Factor of 250 comes from 1000 units per function divided
177       // by four slots per instruction.
178       return (1000 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
179     }
180
181     /// getMBBFromIndex - given an index in any instruction of an
182     /// MBB return a pointer the MBB
183     MachineBasicBlock* getMBBFromIndex(unsigned index) const {
184       std::vector<IdxMBBPair>::const_iterator I =
185         std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
186       // Take the pair containing the index
187       std::vector<IdxMBBPair>::const_iterator J =
188         ((I != Idx2MBBMap.end() && I->first > index) ||
189          (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
190
191       assert(J != Idx2MBBMap.end() && J->first < index+1 &&
192              index <= getMBBEndIdx(J->second) &&
193              "index does not correspond to an MBB");
194       return J->second;
195     }
196
197     /// getInstructionIndex - returns the base index of instr
198     unsigned getInstructionIndex(MachineInstr* instr) const {
199       Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
200       assert(it != mi2iMap_.end() && "Invalid instruction!");
201       return it->second;
202     }
203
204     /// getInstructionFromIndex - given an index in any slot of an
205     /// instruction return a pointer the instruction
206     MachineInstr* getInstructionFromIndex(unsigned index) const {
207       index /= InstrSlots::NUM; // convert index to vector index
208       assert(index < i2miMap_.size() &&
209              "index does not correspond to an instruction");
210       return i2miMap_[index];
211     }
212
213     /// conflictsWithPhysRegDef - Returns true if the specified register
214     /// is defined during the duration of the specified interval.
215     bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
216                                  unsigned reg);
217
218     /// findLiveInMBBs - Given a live range, if the value of the range
219     /// is live in any MBB returns true as well as the list of basic blocks
220     /// where the value is live in.
221     bool findLiveInMBBs(const LiveRange &LR,
222                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
223
224     // Interval creation
225
226     LiveInterval &getOrCreateInterval(unsigned reg) {
227       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
228       if (I == r2iMap_.end())
229         I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
230       return I->second;
231     }
232     
233     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
234     /// adds a live range from that instruction to the end of its MBB.
235     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
236                                         MachineInstr* startInst);
237
238     // Interval removal
239
240     void removeInterval(unsigned Reg) {
241       r2iMap_.erase(Reg);
242     }
243
244     /// isRemoved - returns true if the specified machine instr has been
245     /// removed.
246     bool isRemoved(MachineInstr* instr) const {
247       return !mi2iMap_.count(instr);
248     }
249
250     /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
251     /// deleted.
252     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
253       // remove index -> MachineInstr and
254       // MachineInstr -> index mappings
255       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
256       if (mi2i != mi2iMap_.end()) {
257         i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
258         mi2iMap_.erase(mi2i);
259       }
260     }
261
262     /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
263     /// maps used by register allocator.
264     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
265       Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
266       if (mi2i == mi2iMap_.end())
267         return;
268       i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
269       Mi2IndexMap::iterator it = mi2iMap_.find(MI);
270       assert(it != mi2iMap_.end() && "Invalid instruction!");
271       unsigned Index = it->second;
272       mi2iMap_.erase(it);
273       mi2iMap_[NewMI] = Index;
274     }
275
276     BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
277
278     /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
279     /// copy field and returns the source register that defines it.
280     unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
281
282     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
283     virtual void releaseMemory();
284
285     /// runOnMachineFunction - pass entry point
286     virtual bool runOnMachineFunction(MachineFunction&);
287
288     /// print - Implement the dump method.
289     virtual void print(std::ostream &O, const Module* = 0) const;
290     void print(std::ostream *O, const Module* M = 0) const {
291       if (O) print(*O, M);
292     }
293
294     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
295     /// the given interval. FIXME: It also returns the weight of the spill slot
296     /// (if any is created) by reference. This is temporary.
297     std::vector<LiveInterval*>
298     addIntervalsForSpills(const LiveInterval& i,
299                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
300                           float &SSWeight);
301
302     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
303     /// around all defs and uses of the specified interval.
304     void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
305                                        unsigned PhysReg, VirtRegMap &vrm);
306
307     /// isReMaterializable - Returns true if every definition of MI of every
308     /// val# of the specified interval is re-materializable. Also returns true
309     /// by reference if all of the defs are load instructions.
310     bool isReMaterializable(const LiveInterval &li, bool &isLoad);
311
312     /// getRepresentativeReg - Find the largest super register of the specified
313     /// physical register.
314     unsigned getRepresentativeReg(unsigned Reg) const;
315
316     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
317     /// specified interval that conflicts with the specified physical register.
318     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
319                                         unsigned PhysReg) const;
320
321     /// computeNumbering - Compute the index numbering.
322     void computeNumbering();
323
324   private:      
325     /// computeIntervals - Compute live intervals.
326     void computeIntervals();
327     
328     /// handleRegisterDef - update intervals for a register def
329     /// (calls handlePhysicalRegisterDef and
330     /// handleVirtualRegisterDef)
331     void handleRegisterDef(MachineBasicBlock *MBB,
332                            MachineBasicBlock::iterator MI, unsigned MIIdx,
333                            unsigned reg);
334
335     /// handleVirtualRegisterDef - update intervals for a virtual
336     /// register def
337     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
338                                   MachineBasicBlock::iterator MI,
339                                   unsigned MIIdx,
340                                   LiveInterval& interval);
341
342     /// handlePhysicalRegisterDef - update intervals for a physical register
343     /// def.
344     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
345                                    MachineBasicBlock::iterator mi,
346                                    unsigned MIIdx,
347                                    LiveInterval &interval,
348                                    MachineInstr *CopyMI);
349
350     /// handleLiveInRegister - Create interval for a livein register.
351     void handleLiveInRegister(MachineBasicBlock* mbb,
352                               unsigned MIIdx,
353                               LiveInterval &interval, bool isAlias = false);
354
355     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
356     /// only allow one) virtual register operand, then its uses are implicitly
357     /// using the register. Returns the virtual register.
358     unsigned getReMatImplicitUse(const LiveInterval &li,
359                                  MachineInstr *MI) const;
360
361     /// isValNoAvailableAt - Return true if the val# of the specified interval
362     /// which reaches the given instruction also reaches the specified use
363     /// index.
364     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
365                             unsigned UseIdx) const;
366
367     /// isReMaterializable - Returns true if the definition MI of the specified
368     /// val# of the specified interval is re-materializable. Also returns true
369     /// by reference if the def is a load.
370     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
371                             MachineInstr *MI, bool &isLoad);
372
373     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
374     /// slot / to reg or any rematerialized load into ith operand of specified
375     /// MI. If it is successul, MI is updated with the newly created MI and
376     /// returns true.
377     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
378                               MachineInstr *DefMI, unsigned InstrIdx,
379                               SmallVector<unsigned, 2> &Ops,
380                               bool isSS, int Slot, unsigned Reg);
381
382     /// canFoldMemoryOperand - Return true if the specified load / store
383     /// folding is possible.
384     bool canFoldMemoryOperand(MachineInstr *MI,
385                               SmallVector<unsigned, 2> &Ops,
386                               bool ReMatLoadSS) const;
387
388     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
389     /// VNInfo that's after the specified index but is within the basic block.
390     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
391                               MachineBasicBlock *MBB, unsigned Idx) const;
392
393     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
394     /// within a single basic block.
395     bool intervalIsInOneMBB(const LiveInterval &li) const;
396
397     /// hasAllocatableSuperReg - Return true if the specified physical register
398     /// has any super register that's allocatable.
399     bool hasAllocatableSuperReg(unsigned Reg) const;
400
401     /// SRInfo - Spill / restore info.
402     struct SRInfo {
403       int index;
404       unsigned vreg;
405       bool canFold;
406       SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
407     };
408
409     bool alsoFoldARestore(int Id, int index, unsigned vr,
410                           BitVector &RestoreMBBs,
411                           std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
412     void eraseRestoreInfo(int Id, int index, unsigned vr,
413                           BitVector &RestoreMBBs,
414                           std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
415
416     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
417     /// spilled and create empty intervals for their uses.
418     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
419                               const TargetRegisterClass* rc,
420                               std::vector<LiveInterval*> &NewLIs);
421
422     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
423     /// interval on to-be re-materialized operands of MI) with new register.
424     void rewriteImplicitOps(const LiveInterval &li,
425                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
426
427     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
428     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
429     /// live range.
430     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
431         bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
432         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
433         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
434         VirtRegMap &vrm, const TargetRegisterClass* rc,
435         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
436         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
437         std::map<unsigned,unsigned> &MBBVRegsMap,
438         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
439     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
440         LiveInterval::Ranges::const_iterator &I,
441         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
442         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
443         VirtRegMap &vrm, const TargetRegisterClass* rc,
444         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
445         BitVector &SpillMBBs,
446         std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
447         BitVector &RestoreMBBs,
448         std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
449         std::map<unsigned,unsigned> &MBBVRegsMap,
450         std::vector<LiveInterval*> &NewLIs, float &SSWeight);
451
452     static LiveInterval createInterval(unsigned Reg);
453
454     void printRegName(unsigned reg) const;
455   };
456
457 } // End llvm namespace
458
459 #endif