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