8a59bf1428a0f9f6962b5334206847555a10dc12
[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 LiveVariables;
39   class MachineLoopInfo;
40   class TargetRegisterInfo;
41   class MachineRegisterInfo;
42   class TargetInstrInfo;
43   class TargetRegisterClass;
44   class VirtRegMap;
45   
46   class LiveIntervals : public MachineFunctionPass {
47     MachineFunction* mf_;
48     MachineRegisterInfo* mri_;
49     const TargetMachine* tm_;
50     const TargetRegisterInfo* tri_;
51     const TargetInstrInfo* tii_;
52     AliasAnalysis *aa_;
53     LiveVariables* lv_;
54     SlotIndexes* indexes_;
55
56     /// Special pool allocator for VNInfo's (LiveInterval val#).
57     ///
58     VNInfo::Allocator VNInfoAllocator;
59
60     typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61     Reg2IntervalMap r2iMap_;
62
63     /// allocatableRegs_ - A bit vector of allocatable registers.
64     BitVector allocatableRegs_;
65
66     /// CloneMIs - A list of clones as result of re-materialization.
67     std::vector<MachineInstr*> CloneMIs;
68
69   public:
70     static char ID; // Pass identification, replacement for typeid
71     LiveIntervals() : MachineFunctionPass(&ID) {}
72
73     // Calculate the spill weight to assign to a single instruction.
74     static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
75
76     // After summing the spill weights of all defs and uses, the final weight
77     // should be normalized, dividing the weight of the interval by its size.
78     // This encourages spilling of intervals that are large and have few uses,
79     // and discourages spilling of small intervals with many uses.
80     void normalizeSpillWeight(LiveInterval &li) {
81       li.weight /= getApproximateInstructionCount(li) + 25;
82     }
83
84     typedef Reg2IntervalMap::iterator iterator;
85     typedef Reg2IntervalMap::const_iterator const_iterator;
86     const_iterator begin() const { return r2iMap_.begin(); }
87     const_iterator end() const { return r2iMap_.end(); }
88     iterator begin() { return r2iMap_.begin(); }
89     iterator end() { return r2iMap_.end(); }
90     unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
91
92     LiveInterval &getInterval(unsigned reg) {
93       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
94       assert(I != r2iMap_.end() && "Interval does not exist for register");
95       return *I->second;
96     }
97
98     const LiveInterval &getInterval(unsigned reg) const {
99       Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
100       assert(I != r2iMap_.end() && "Interval does not exist for register");
101       return *I->second;
102     }
103
104     bool hasInterval(unsigned reg) const {
105       return r2iMap_.count(reg);
106     }
107
108     /// getScaledIntervalSize - get the size of an interval in "units,"
109     /// where every function is composed of one thousand units.  This
110     /// measure scales properly with empty index slots in the function.
111     double getScaledIntervalSize(LiveInterval& I) {
112       return (1000.0 * I.getSize()) / indexes_->getIndexesLength();
113     }
114
115     /// getFuncInstructionCount - Return the number of instructions in the
116     /// current function.
117     unsigned getFuncInstructionCount() {
118       return indexes_->getFunctionSize();
119     }
120     
121     /// getApproximateInstructionCount - computes an estimate of the number
122     /// of instructions in a given LiveInterval.
123     unsigned getApproximateInstructionCount(LiveInterval& I) {
124       double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
125       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
126     }
127
128     /// conflictsWithPhysReg - Returns true if the specified register is used or
129     /// defined during the duration of the specified interval. Copies to and
130     /// from li.reg are allowed. This method is only able to analyze simple
131     /// ranges that stay within a single basic block. Anything else is
132     /// considered a conflict.
133     bool conflictsWithPhysReg(const LiveInterval &li, VirtRegMap &vrm,
134                               unsigned reg);
135
136     /// conflictsWithAliasRef - Similar to conflictsWithPhysRegRef except
137     /// it checks for alias uses and defs.
138     bool conflictsWithAliasRef(LiveInterval &li, unsigned Reg,
139                                    SmallPtrSet<MachineInstr*,32> &JoinedCopies);
140
141     // Interval creation
142     LiveInterval &getOrCreateInterval(unsigned reg) {
143       Reg2IntervalMap::iterator I = r2iMap_.find(reg);
144       if (I == r2iMap_.end())
145         I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
146       return *I->second;
147     }
148
149     /// dupInterval - Duplicate a live interval. The caller is responsible for
150     /// managing the allocated memory.
151     LiveInterval *dupInterval(LiveInterval *li);
152     
153     /// addLiveRangeToEndOfBlock - Given a register and an instruction,
154     /// adds a live range from that instruction to the end of its MBB.
155     LiveRange addLiveRangeToEndOfBlock(unsigned reg,
156                                        MachineInstr* startInst);
157
158     // Interval removal
159
160     void removeInterval(unsigned Reg) {
161       DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
162       delete I->second;
163       r2iMap_.erase(I);
164     }
165
166     SlotIndex getZeroIndex() const {
167       return indexes_->getZeroIndex();
168     }
169
170     SlotIndex getInvalidIndex() const {
171       return indexes_->getInvalidIndex();
172     }
173
174     /// isNotInMIMap - returns true if the specified machine instr has been
175     /// removed or was never entered in the map.
176     bool isNotInMIMap(const MachineInstr* Instr) const {
177       return !indexes_->hasIndex(Instr);
178     }
179
180     /// Returns the base index of the given instruction.
181     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
182       return indexes_->getInstructionIndex(instr);
183     }
184     
185     /// Returns the instruction associated with the given index.
186     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
187       return indexes_->getInstructionFromIndex(index);
188     }
189
190     /// Return the first index in the given basic block.
191     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
192       return indexes_->getMBBStartIdx(mbb);
193     } 
194
195     /// Return the last index in the given basic block.
196     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
197       return indexes_->getMBBEndIdx(mbb);
198     } 
199
200     bool isLiveInToMBB(const LiveInterval &li,
201                        const MachineBasicBlock *mbb) const {
202       return li.liveAt(getMBBStartIdx(mbb));
203     }
204
205     LiveRange* findEnteringRange(LiveInterval &li,
206                                  const MachineBasicBlock *mbb) {
207       return li.getLiveRangeContaining(getMBBStartIdx(mbb));
208     }
209
210     bool isLiveOutOfMBB(const LiveInterval &li,
211                         const MachineBasicBlock *mbb) const {
212       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
213     }
214
215     LiveRange* findExitingRange(LiveInterval &li,
216                                 const MachineBasicBlock *mbb) {
217       return li.getLiveRangeContaining(getMBBEndIdx(mbb).getPrevSlot());
218     }
219
220     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
221       return indexes_->getMBBFromIndex(index);
222     }
223
224     SlotIndex getMBBTerminatorGap(const MachineBasicBlock *mbb) {
225       return indexes_->getTerminatorGap(mbb);
226     }
227
228     SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
229       return indexes_->insertMachineInstrInMaps(MI);
230     }
231
232     void RemoveMachineInstrFromMaps(MachineInstr *MI) {
233       indexes_->removeMachineInstrFromMaps(MI);
234     }
235
236     void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
237       indexes_->replaceMachineInstrInMaps(MI, NewMI);
238     }
239
240     void InsertMBBInMaps(MachineBasicBlock *MBB) {
241       indexes_->insertMBBInMaps(MBB);
242     }
243
244     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
245                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
246       return indexes_->findLiveInMBBs(Start, End, MBBs);
247     }
248
249     void renumber() {
250       indexes_->renumberIndexes();
251     }
252
253     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
254
255     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
256     virtual void releaseMemory();
257
258     /// runOnMachineFunction - pass entry point
259     virtual bool runOnMachineFunction(MachineFunction&);
260
261     /// print - Implement the dump method.
262     virtual void print(raw_ostream &O, const Module* = 0) const;
263
264     /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
265     /// the given interval. FIXME: It also returns the weight of the spill slot
266     /// (if any is created) by reference. This is temporary.
267     std::vector<LiveInterval*>
268     addIntervalsForSpills(const LiveInterval& i,
269                           SmallVectorImpl<LiveInterval*> &SpillIs,
270                           const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
271
272     /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
273     /// around all defs and uses of the specified interval. Return true if it
274     /// was able to cut its interval.
275     bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
276                                        unsigned PhysReg, VirtRegMap &vrm);
277
278     /// isReMaterializable - Returns true if every definition of MI of every
279     /// val# of the specified interval is re-materializable. Also returns true
280     /// by reference if all of the defs are load instructions.
281     bool isReMaterializable(const LiveInterval &li,
282                             SmallVectorImpl<LiveInterval*> &SpillIs,
283                             bool &isLoad);
284
285     /// isReMaterializable - Returns true if the definition MI of the specified
286     /// val# of the specified interval is re-materializable.
287     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
288                             MachineInstr *MI);
289
290     /// getRepresentativeReg - Find the largest super register of the specified
291     /// physical register.
292     unsigned getRepresentativeReg(unsigned Reg) const;
293
294     /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
295     /// specified interval that conflicts with the specified physical register.
296     unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
297                                         unsigned PhysReg) const;
298
299     /// intervalIsInOneMBB - Returns true if the specified interval is entirely
300     /// within a single basic block.
301     bool intervalIsInOneMBB(const LiveInterval &li) const;
302
303   private:      
304     /// computeIntervals - Compute live intervals.
305     void computeIntervals();
306
307     /// handleRegisterDef - update intervals for a register def
308     /// (calls handlePhysicalRegisterDef and
309     /// handleVirtualRegisterDef)
310     void handleRegisterDef(MachineBasicBlock *MBB,
311                            MachineBasicBlock::iterator MI,
312                            SlotIndex MIIdx,
313                            MachineOperand& MO, unsigned MOIdx);
314
315     /// isPartialRedef - Return true if the specified def at the specific index
316     /// is partially re-defining the specified live interval. A common case of
317     /// this is a definition of the sub-register. 
318     bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
319                         LiveInterval &interval);
320
321     /// handleVirtualRegisterDef - update intervals for a virtual
322     /// register def
323     void handleVirtualRegisterDef(MachineBasicBlock *MBB,
324                                   MachineBasicBlock::iterator MI,
325                                   SlotIndex MIIdx, MachineOperand& MO,
326                                   unsigned MOIdx,
327                                   LiveInterval& interval);
328
329     /// handlePhysicalRegisterDef - update intervals for a physical register
330     /// def.
331     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
332                                    MachineBasicBlock::iterator mi,
333                                    SlotIndex MIIdx, MachineOperand& MO,
334                                    LiveInterval &interval,
335                                    MachineInstr *CopyMI);
336
337     /// handleLiveInRegister - Create interval for a livein register.
338     void handleLiveInRegister(MachineBasicBlock* mbb,
339                               SlotIndex MIIdx,
340                               LiveInterval &interval, bool isAlias = false);
341
342     /// getReMatImplicitUse - If the remat definition MI has one (for now, we
343     /// only allow one) virtual register operand, then its uses are implicitly
344     /// using the register. Returns the virtual register.
345     unsigned getReMatImplicitUse(const LiveInterval &li,
346                                  MachineInstr *MI) const;
347
348     /// isValNoAvailableAt - Return true if the val# of the specified interval
349     /// which reaches the given instruction also reaches the specified use
350     /// index.
351     bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
352                             SlotIndex UseIdx) const;
353
354     /// isReMaterializable - Returns true if the definition MI of the specified
355     /// val# of the specified interval is re-materializable. Also returns true
356     /// by reference if the def is a load.
357     bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
358                             MachineInstr *MI,
359                             SmallVectorImpl<LiveInterval*> &SpillIs,
360                             bool &isLoad);
361
362     /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
363     /// slot / to reg or any rematerialized load into ith operand of specified
364     /// MI. If it is successul, MI is updated with the newly created MI and
365     /// returns true.
366     bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
367                               MachineInstr *DefMI, SlotIndex InstrIdx,
368                               SmallVector<unsigned, 2> &Ops,
369                               bool isSS, int FrameIndex, unsigned Reg);
370
371     /// canFoldMemoryOperand - Return true if the specified load / store
372     /// folding is possible.
373     bool canFoldMemoryOperand(MachineInstr *MI,
374                               SmallVector<unsigned, 2> &Ops,
375                               bool ReMatLoadSS) const;
376
377     /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
378     /// VNInfo that's after the specified index but is within the basic block.
379     bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
380                               MachineBasicBlock *MBB,
381                               SlotIndex Idx) const;
382
383     /// hasAllocatableSuperReg - Return true if the specified physical register
384     /// has any super register that's allocatable.
385     bool hasAllocatableSuperReg(unsigned Reg) const;
386
387     /// SRInfo - Spill / restore info.
388     struct SRInfo {
389       SlotIndex index;
390       unsigned vreg;
391       bool canFold;
392       SRInfo(SlotIndex i, unsigned vr, bool f)
393         : index(i), vreg(vr), canFold(f) {}
394     };
395
396     bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
397                           BitVector &RestoreMBBs,
398                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
399     void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
400                           BitVector &RestoreMBBs,
401                           DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
402
403     /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
404     /// spilled and create empty intervals for their uses.
405     void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
406                               const TargetRegisterClass* rc,
407                               std::vector<LiveInterval*> &NewLIs);
408
409     /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
410     /// interval on to-be re-materialized operands of MI) with new register.
411     void rewriteImplicitOps(const LiveInterval &li,
412                            MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
413
414     /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
415     /// functions for addIntervalsForSpills to rewrite uses / defs for the given
416     /// live range.
417     bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
418         bool TrySplit, SlotIndex index, SlotIndex end,
419         MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
420         unsigned Slot, int LdSlot,
421         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
422         VirtRegMap &vrm, const TargetRegisterClass* rc,
423         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
424         unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
425         DenseMap<unsigned,unsigned> &MBBVRegsMap,
426         std::vector<LiveInterval*> &NewLIs);
427     void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
428         LiveInterval::Ranges::const_iterator &I,
429         MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
430         bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
431         VirtRegMap &vrm, const TargetRegisterClass* rc,
432         SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
433         BitVector &SpillMBBs,
434         DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
435         BitVector &RestoreMBBs,
436         DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
437         DenseMap<unsigned,unsigned> &MBBVRegsMap,
438         std::vector<LiveInterval*> &NewLIs);
439
440     // Normalize the spill weight of all the intervals in NewLIs.
441     void normalizeSpillWeights(std::vector<LiveInterval*> &NewLIs);
442
443     static LiveInterval* createInterval(unsigned Reg);
444
445     void printInstrs(raw_ostream &O) const;
446     void dumpInstrs() const;
447   };
448 } // End llvm namespace
449
450 #endif