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/MachineFunctionPass.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Allocator.h"
36 class MachineLoopInfo;
37 class TargetRegisterInfo;
38 class MachineRegisterInfo;
39 class TargetInstrInfo;
40 class TargetRegisterClass;
42 typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
44 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
48 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
52 struct Idx2MBBCompare {
53 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
54 return LHS.first < RHS.first;
58 // Provide DenseMapInfo for unsigned.
60 struct DenseMapInfo<unsigned> {
61 static inline unsigned getEmptyKey() { return (unsigned)-1; }
62 static inline unsigned getTombstoneKey() { return (unsigned)-2; }
63 static unsigned getHashValue(const unsigned Val) {
66 static bool isEqual(const unsigned LHS, const unsigned RHS) {
69 static bool isPod() { return true; }
72 class LiveIntervals : public MachineFunctionPass {
74 MachineRegisterInfo* mri_;
75 const TargetMachine* tm_;
76 const TargetRegisterInfo* tri_;
77 const TargetInstrInfo* tii_;
81 /// Special pool allocator for VNInfo's (LiveInterval val#).
83 BumpPtrAllocator VNInfoAllocator;
85 /// MBB2IdxMap - The indexes of the first and last instructions in the
86 /// specified basic block.
87 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
89 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
91 std::vector<IdxMBBPair> Idx2MBBMap;
93 /// FunctionSize - The number of instructions present in the function
94 uint64_t FunctionSize;
96 typedef DenseMap<MachineInstr*, unsigned> Mi2IndexMap;
99 typedef std::vector<MachineInstr*> Index2MiMap;
100 Index2MiMap i2miMap_;
102 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
103 Reg2IntervalMap r2iMap_;
105 BitVector allocatableRegs_;
107 std::vector<MachineInstr*> ClonedMIs;
110 static char ID; // Pass identification, replacement for typeid
111 LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
123 static unsigned getBaseIndex(unsigned index) {
124 return index - (index % InstrSlots::NUM);
126 static unsigned getBoundaryIndex(unsigned index) {
127 return getBaseIndex(index + InstrSlots::NUM - 1);
129 static unsigned getLoadIndex(unsigned index) {
130 return getBaseIndex(index) + InstrSlots::LOAD;
132 static unsigned getUseIndex(unsigned index) {
133 return getBaseIndex(index) + InstrSlots::USE;
135 static unsigned getDefIndex(unsigned index) {
136 return getBaseIndex(index) + InstrSlots::DEF;
138 static unsigned getStoreIndex(unsigned index) {
139 return getBaseIndex(index) + InstrSlots::STORE;
142 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
143 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
146 typedef Reg2IntervalMap::iterator iterator;
147 typedef Reg2IntervalMap::const_iterator const_iterator;
148 const_iterator begin() const { return r2iMap_.begin(); }
149 const_iterator end() const { return r2iMap_.end(); }
150 iterator begin() { return r2iMap_.begin(); }
151 iterator end() { return r2iMap_.end(); }
152 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
154 LiveInterval &getInterval(unsigned reg) {
155 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
156 assert(I != r2iMap_.end() && "Interval does not exist for register");
160 const LiveInterval &getInterval(unsigned reg) const {
161 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
162 assert(I != r2iMap_.end() && "Interval does not exist for register");
166 bool hasInterval(unsigned reg) const {
167 return r2iMap_.count(reg);
170 /// getMBBStartIdx - Return the base index of the first instruction in the
171 /// specified MachineBasicBlock.
172 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
173 return getMBBStartIdx(MBB->getNumber());
175 unsigned getMBBStartIdx(unsigned MBBNo) const {
176 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
177 return MBB2IdxMap[MBBNo].first;
180 /// getMBBEndIdx - Return the store index of the last instruction in the
181 /// specified MachineBasicBlock.
182 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
183 return getMBBEndIdx(MBB->getNumber());
185 unsigned getMBBEndIdx(unsigned MBBNo) const {
186 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
187 return MBB2IdxMap[MBBNo].second;
190 /// getScaledIntervalSize - get the size of an interval in "units,"
191 /// where every function is composed of one thousand units. This
192 /// measure scales properly with empty index slots in the function.
193 double getScaledIntervalSize(LiveInterval& I) {
194 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
197 /// getApproximateInstructionCount - computes an estimate of the number
198 /// of instructions in a given LiveInterval.
199 unsigned getApproximateInstructionCount(LiveInterval& I) {
200 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
201 return (unsigned)(IntervalPercentage * FunctionSize);
204 /// getMBBFromIndex - given an index in any instruction of an
205 /// MBB return a pointer the MBB
206 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
207 std::vector<IdxMBBPair>::const_iterator I =
208 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
209 // Take the pair containing the index
210 std::vector<IdxMBBPair>::const_iterator J =
211 ((I != Idx2MBBMap.end() && I->first > index) ||
212 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
214 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
215 index <= getMBBEndIdx(J->second) &&
216 "index does not correspond to an MBB");
220 /// getInstructionIndex - returns the base index of instr
221 unsigned getInstructionIndex(MachineInstr* instr) const {
222 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
223 assert(it != mi2iMap_.end() && "Invalid instruction!");
227 /// getInstructionFromIndex - given an index in any slot of an
228 /// instruction return a pointer the instruction
229 MachineInstr* getInstructionFromIndex(unsigned index) const {
230 index /= InstrSlots::NUM; // convert index to vector index
231 assert(index < i2miMap_.size() &&
232 "index does not correspond to an instruction");
233 return i2miMap_[index];
236 /// conflictsWithPhysRegDef - Returns true if the specified register
237 /// is defined during the duration of the specified interval.
238 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
241 /// findLiveInMBBs - Given a live range, if the value of the range
242 /// is live in any MBB returns true as well as the list of basic blocks
243 /// in which the value is live.
244 bool findLiveInMBBs(const LiveRange &LR,
245 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
249 LiveInterval &getOrCreateInterval(unsigned reg) {
250 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
251 if (I == r2iMap_.end())
252 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
256 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
257 /// adds a live range from that instruction to the end of its MBB.
258 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
259 MachineInstr* startInst);
263 void removeInterval(unsigned Reg) {
264 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
269 /// isRemoved - returns true if the specified machine instr has been
271 bool isRemoved(MachineInstr* instr) const {
272 return !mi2iMap_.count(instr);
275 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
277 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
278 // remove index -> MachineInstr and
279 // MachineInstr -> index mappings
280 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
281 if (mi2i != mi2iMap_.end()) {
282 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
283 mi2iMap_.erase(mi2i);
287 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
288 /// maps used by register allocator.
289 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
290 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
291 if (mi2i == mi2iMap_.end())
293 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
294 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
295 assert(it != mi2iMap_.end() && "Invalid instruction!");
296 unsigned Index = it->second;
298 mi2iMap_[NewMI] = Index;
301 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
303 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
304 /// copy field and returns the source register that defines it.
305 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
307 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
308 virtual void releaseMemory();
310 /// runOnMachineFunction - pass entry point
311 virtual bool runOnMachineFunction(MachineFunction&);
313 /// print - Implement the dump method.
314 virtual void print(std::ostream &O, const Module* = 0) const;
315 void print(std::ostream *O, const Module* M = 0) const {
319 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
320 /// the given interval. FIXME: It also returns the weight of the spill slot
321 /// (if any is created) by reference. This is temporary.
322 std::vector<LiveInterval*>
323 addIntervalsForSpills(const LiveInterval& i,
324 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
327 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
328 /// around all defs and uses of the specified interval.
329 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
330 unsigned PhysReg, VirtRegMap &vrm);
332 /// isReMaterializable - Returns true if every definition of MI of every
333 /// val# of the specified interval is re-materializable. Also returns true
334 /// by reference if all of the defs are load instructions.
335 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
337 /// getRepresentativeReg - Find the largest super register of the specified
338 /// physical register.
339 unsigned getRepresentativeReg(unsigned Reg) const;
341 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
342 /// specified interval that conflicts with the specified physical register.
343 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
344 unsigned PhysReg) const;
346 /// computeNumbering - Compute the index numbering.
347 void computeNumbering();
350 /// computeIntervals - Compute live intervals.
351 void computeIntervals();
353 /// handleRegisterDef - update intervals for a register def
354 /// (calls handlePhysicalRegisterDef and
355 /// handleVirtualRegisterDef)
356 void handleRegisterDef(MachineBasicBlock *MBB,
357 MachineBasicBlock::iterator MI, unsigned MIIdx,
358 MachineOperand& MO, unsigned MOIdx);
360 /// handleVirtualRegisterDef - update intervals for a virtual
362 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
363 MachineBasicBlock::iterator MI,
364 unsigned MIIdx, MachineOperand& MO,
365 unsigned MOIdx, LiveInterval& interval);
367 /// handlePhysicalRegisterDef - update intervals for a physical register
369 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
370 MachineBasicBlock::iterator mi,
371 unsigned MIIdx, MachineOperand& MO,
372 LiveInterval &interval,
373 MachineInstr *CopyMI);
375 /// handleLiveInRegister - Create interval for a livein register.
376 void handleLiveInRegister(MachineBasicBlock* mbb,
378 LiveInterval &interval, bool isAlias = false);
380 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
381 /// only allow one) virtual register operand, then its uses are implicitly
382 /// using the register. Returns the virtual register.
383 unsigned getReMatImplicitUse(const LiveInterval &li,
384 MachineInstr *MI) const;
386 /// isValNoAvailableAt - Return true if the val# of the specified interval
387 /// which reaches the given instruction also reaches the specified use
389 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
390 unsigned UseIdx) const;
392 /// isReMaterializable - Returns true if the definition MI of the specified
393 /// val# of the specified interval is re-materializable. Also returns true
394 /// by reference if the def is a load.
395 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
396 MachineInstr *MI, bool &isLoad);
398 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
399 /// slot / to reg or any rematerialized load into ith operand of specified
400 /// MI. If it is successul, MI is updated with the newly created MI and
402 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
403 MachineInstr *DefMI, unsigned InstrIdx,
404 SmallVector<unsigned, 2> &Ops,
405 bool isSS, int Slot, unsigned Reg);
407 /// canFoldMemoryOperand - Return true if the specified load / store
408 /// folding is possible.
409 bool canFoldMemoryOperand(MachineInstr *MI,
410 SmallVector<unsigned, 2> &Ops,
411 bool ReMatLoadSS) const;
413 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
414 /// VNInfo that's after the specified index but is within the basic block.
415 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
416 MachineBasicBlock *MBB, unsigned Idx) const;
418 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
419 /// within a single basic block.
420 bool intervalIsInOneMBB(const LiveInterval &li) const;
422 /// hasAllocatableSuperReg - Return true if the specified physical register
423 /// has any super register that's allocatable.
424 bool hasAllocatableSuperReg(unsigned Reg) const;
426 /// SRInfo - Spill / restore info.
431 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
434 bool alsoFoldARestore(int Id, int index, unsigned vr,
435 BitVector &RestoreMBBs,
436 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
437 void eraseRestoreInfo(int Id, int index, unsigned vr,
438 BitVector &RestoreMBBs,
439 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
441 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
442 /// spilled and create empty intervals for their uses.
443 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
444 const TargetRegisterClass* rc,
445 std::vector<LiveInterval*> &NewLIs);
447 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
448 /// interval on to-be re-materialized operands of MI) with new register.
449 void rewriteImplicitOps(const LiveInterval &li,
450 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
452 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
453 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
455 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
456 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
457 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
458 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
459 VirtRegMap &vrm, const TargetRegisterClass* rc,
460 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
461 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
462 DenseMap<unsigned,unsigned> &MBBVRegsMap,
463 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
464 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
465 LiveInterval::Ranges::const_iterator &I,
466 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
467 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
468 VirtRegMap &vrm, const TargetRegisterClass* rc,
469 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
470 BitVector &SpillMBBs,
471 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
472 BitVector &RestoreMBBs,
473 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
474 DenseMap<unsigned,unsigned> &MBBVRegsMap,
475 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
477 static LiveInterval* createInterval(unsigned Reg);
479 void printRegName(unsigned reg) const;
482 } // End llvm namespace