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