1 //===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
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"
39 class MachineLoopInfo;
40 class TargetRegisterInfo;
41 class MachineRegisterInfo;
42 class TargetInstrInfo;
43 class TargetRegisterClass;
46 class LiveIntervals : public MachineFunctionPass {
48 MachineRegisterInfo* mri_;
49 const TargetMachine* tm_;
50 const TargetRegisterInfo* tri_;
51 const TargetInstrInfo* tii_;
54 SlotIndexes* indexes_;
56 /// Special pool allocator for VNInfo's (LiveInterval val#).
58 BumpPtrAllocator VNInfoAllocator;
60 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
61 Reg2IntervalMap r2iMap_;
63 /// phiJoinCopies - Copy instructions which are PHI joins.
64 SmallVector<MachineInstr*, 16> phiJoinCopies;
66 /// allocatableRegs_ - A bit vector of allocatable registers.
67 BitVector allocatableRegs_;
69 /// CloneMIs - A list of clones as result of re-materialization.
70 std::vector<MachineInstr*> CloneMIs;
73 static char ID; // Pass identification, replacement for typeid
74 LiveIntervals() : MachineFunctionPass(&ID) {}
76 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
77 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
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(); }
88 LiveInterval &getInterval(unsigned reg) {
89 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
90 assert(I != r2iMap_.end() && "Interval does not exist for register");
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");
100 bool hasInterval(unsigned reg) const {
101 return r2iMap_.count(reg);
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();
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());
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,
123 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
124 /// it can check use as well.
125 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
127 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
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;
137 /// dupInterval - Duplicate a live interval. The caller is responsible for
138 /// managing the allocated memory.
139 LiveInterval *dupInterval(LiveInterval *li);
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);
148 void removeInterval(unsigned Reg) {
149 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
154 SlotIndex getZeroIndex() const {
155 return indexes_->getZeroIndex();
158 SlotIndex getInvalidIndex() const {
159 return indexes_->getInvalidIndex();
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);
168 /// Returns the base index of the given instruction.
169 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
170 return indexes_->getInstructionIndex(instr);
173 /// Returns the instruction associated with the given index.
174 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
175 return indexes_->getInstructionFromIndex(index);
178 /// Return the first index in the given basic block.
179 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
180 return indexes_->getMBBStartIdx(mbb);
183 /// Return the last index in the given basic block.
184 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
185 return indexes_->getMBBEndIdx(mbb);
188 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
189 return indexes_->getMBBFromIndex(index);
192 SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
193 return indexes_->insertMachineInstrInMaps(MI);
196 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
197 indexes_->removeMachineInstrFromMaps(MI);
200 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
201 indexes_->replaceMachineInstrInMaps(MI, NewMI);
204 bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
205 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
206 return indexes_->findLiveInMBBs(Start, End, MBBs);
210 indexes_->renumberIndexes();
213 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
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;
219 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
220 virtual void releaseMemory();
222 /// runOnMachineFunction - pass entry point
223 virtual bool runOnMachineFunction(MachineFunction&);
225 /// print - Implement the dump method.
226 virtual void print(raw_ostream &O, const Module* = 0) const;
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);
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);
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);
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,
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,
260 /// getRepresentativeReg - Find the largest super register of the specified
261 /// physical register.
262 unsigned getRepresentativeReg(unsigned Reg) const;
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;
269 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
270 /// marker to implicit_def defs and their uses.
271 void processImplicitDefs();
273 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
274 /// within a single basic block.
275 bool intervalIsInOneMBB(const LiveInterval &li) const;
278 /// computeIntervals - Compute live intervals.
279 void computeIntervals();
281 bool isSafeAndProfitableToCoalesce(LiveInterval &DstInt,
282 LiveInterval &SrcInt,
283 SmallVector<MachineInstr*,16> &IdentCopies,
284 SmallVector<MachineInstr*,16> &OtherCopies);
286 void performEarlyCoalescing();
288 /// handleRegisterDef - update intervals for a register def
289 /// (calls handlePhysicalRegisterDef and
290 /// handleVirtualRegisterDef)
291 void handleRegisterDef(MachineBasicBlock *MBB,
292 MachineBasicBlock::iterator MI,
294 MachineOperand& MO, unsigned MOIdx);
296 /// handleVirtualRegisterDef - update intervals for a virtual
298 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
299 MachineBasicBlock::iterator MI,
300 SlotIndex MIIdx, MachineOperand& MO,
302 LiveInterval& interval);
304 /// handlePhysicalRegisterDef - update intervals for a physical register
306 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
307 MachineBasicBlock::iterator mi,
308 SlotIndex MIIdx, MachineOperand& MO,
309 LiveInterval &interval,
310 MachineInstr *CopyMI);
312 /// handleLiveInRegister - Create interval for a livein register.
313 void handleLiveInRegister(MachineBasicBlock* mbb,
315 LiveInterval &interval, bool isAlias = false);
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;
323 /// isValNoAvailableAt - Return true if the val# of the specified interval
324 /// which reaches the given instruction also reaches the specified use
326 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
327 SlotIndex UseIdx) const;
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,
334 SmallVectorImpl<LiveInterval*> &SpillIs,
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
341 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
342 MachineInstr *DefMI, SlotIndex InstrIdx,
343 SmallVector<unsigned, 2> &Ops,
344 bool isSS, int FrameIndex, unsigned Reg);
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;
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;
358 /// hasAllocatableSuperReg - Return true if the specified physical register
359 /// has any super register that's allocatable.
360 bool hasAllocatableSuperReg(unsigned Reg) const;
362 /// SRInfo - Spill / restore info.
367 SRInfo(SlotIndex i, unsigned vr, bool f)
368 : index(i), vreg(vr), canFold(f) {}
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);
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);
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);
389 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
390 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
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);
415 static LiveInterval* createInterval(unsigned Reg);
417 void printInstrs(raw_ostream &O) const;
418 void dumpInstrs() const;
420 } // End llvm namespace