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