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