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