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 class LiveIntervals : public MachineFunctionPass {
60 MachineRegisterInfo* mri_;
61 const TargetMachine* tm_;
62 const TargetRegisterInfo* tri_;
63 const TargetInstrInfo* tii_;
67 /// Special pool allocator for VNInfo's (LiveInterval val#).
69 BumpPtrAllocator VNInfoAllocator;
71 /// MBB2IdxMap - The indexes of the first and last instructions in the
72 /// specified basic block.
73 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
75 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
77 std::vector<IdxMBBPair> Idx2MBBMap;
79 /// FunctionSize - The number of instructions present in the function
80 uint64_t FunctionSize;
82 typedef DenseMap<MachineInstr*, unsigned> Mi2IndexMap;
85 typedef std::vector<MachineInstr*> Index2MiMap;
88 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
89 Reg2IntervalMap r2iMap_;
91 BitVector allocatableRegs_;
93 std::vector<MachineInstr*> ClonedMIs;
96 static char ID; // Pass identification, replacement for typeid
97 LiveIntervals() : MachineFunctionPass(&ID) {}
109 static unsigned getBaseIndex(unsigned index) {
110 return index - (index % InstrSlots::NUM);
112 static unsigned getBoundaryIndex(unsigned index) {
113 return getBaseIndex(index + InstrSlots::NUM - 1);
115 static unsigned getLoadIndex(unsigned index) {
116 return getBaseIndex(index) + InstrSlots::LOAD;
118 static unsigned getUseIndex(unsigned index) {
119 return getBaseIndex(index) + InstrSlots::USE;
121 static unsigned getDefIndex(unsigned index) {
122 return getBaseIndex(index) + InstrSlots::DEF;
124 static unsigned getStoreIndex(unsigned index) {
125 return getBaseIndex(index) + InstrSlots::STORE;
128 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
129 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
132 typedef Reg2IntervalMap::iterator iterator;
133 typedef Reg2IntervalMap::const_iterator const_iterator;
134 const_iterator begin() const { return r2iMap_.begin(); }
135 const_iterator end() const { return r2iMap_.end(); }
136 iterator begin() { return r2iMap_.begin(); }
137 iterator end() { return r2iMap_.end(); }
138 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
140 LiveInterval &getInterval(unsigned reg) {
141 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
142 assert(I != r2iMap_.end() && "Interval does not exist for register");
146 const LiveInterval &getInterval(unsigned reg) const {
147 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
148 assert(I != r2iMap_.end() && "Interval does not exist for register");
152 bool hasInterval(unsigned reg) const {
153 return r2iMap_.count(reg);
156 /// getMBBStartIdx - Return the base index of the first instruction in the
157 /// specified MachineBasicBlock.
158 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
159 return getMBBStartIdx(MBB->getNumber());
161 unsigned getMBBStartIdx(unsigned MBBNo) const {
162 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
163 return MBB2IdxMap[MBBNo].first;
166 /// getMBBEndIdx - Return the store index of the last instruction in the
167 /// specified MachineBasicBlock.
168 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
169 return getMBBEndIdx(MBB->getNumber());
171 unsigned getMBBEndIdx(unsigned MBBNo) const {
172 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
173 return MBB2IdxMap[MBBNo].second;
176 /// getScaledIntervalSize - get the size of an interval in "units,"
177 /// where every function is composed of one thousand units. This
178 /// measure scales properly with empty index slots in the function.
179 double getScaledIntervalSize(LiveInterval& I) {
180 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
183 /// getApproximateInstructionCount - computes an estimate of the number
184 /// of instructions in a given LiveInterval.
185 unsigned getApproximateInstructionCount(LiveInterval& I) {
186 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
187 return (unsigned)(IntervalPercentage * FunctionSize);
190 /// getMBBFromIndex - given an index in any instruction of an
191 /// MBB return a pointer the MBB
192 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
193 std::vector<IdxMBBPair>::const_iterator I =
194 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
195 // Take the pair containing the index
196 std::vector<IdxMBBPair>::const_iterator J =
197 ((I != Idx2MBBMap.end() && I->first > index) ||
198 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
200 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
201 index <= getMBBEndIdx(J->second) &&
202 "index does not correspond to an MBB");
206 /// getInstructionIndex - returns the base index of instr
207 unsigned getInstructionIndex(MachineInstr* instr) const {
208 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
209 assert(it != mi2iMap_.end() && "Invalid instruction!");
213 /// getInstructionFromIndex - given an index in any slot of an
214 /// instruction return a pointer the instruction
215 MachineInstr* getInstructionFromIndex(unsigned index) const {
216 index /= InstrSlots::NUM; // convert index to vector index
217 assert(index < i2miMap_.size() &&
218 "index does not correspond to an instruction");
219 return i2miMap_[index];
222 /// conflictsWithPhysRegDef - Returns true if the specified register
223 /// is defined during the duration of the specified interval.
224 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
227 /// findLiveInMBBs - Given a live range, if the value of the range
228 /// is live in any MBB returns true as well as the list of basic blocks
229 /// in which the value is live.
230 bool findLiveInMBBs(const LiveRange &LR,
231 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
235 LiveInterval &getOrCreateInterval(unsigned reg) {
236 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
237 if (I == r2iMap_.end())
238 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
242 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
243 /// adds a live range from that instruction to the end of its MBB.
244 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
245 MachineInstr* startInst);
249 void removeInterval(unsigned Reg) {
250 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
255 /// isRemoved - returns true if the specified machine instr has been
257 bool isRemoved(MachineInstr* instr) const {
258 return !mi2iMap_.count(instr);
261 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
263 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
264 // remove index -> MachineInstr and
265 // MachineInstr -> index mappings
266 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
267 if (mi2i != mi2iMap_.end()) {
268 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
269 mi2iMap_.erase(mi2i);
273 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
274 /// maps used by register allocator.
275 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
276 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
277 if (mi2i == mi2iMap_.end())
279 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
280 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
281 assert(it != mi2iMap_.end() && "Invalid instruction!");
282 unsigned Index = it->second;
284 mi2iMap_[NewMI] = Index;
287 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
289 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
290 /// copy field and returns the source register that defines it.
291 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
293 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
294 virtual void releaseMemory();
296 /// runOnMachineFunction - pass entry point
297 virtual bool runOnMachineFunction(MachineFunction&);
299 /// print - Implement the dump method.
300 virtual void print(std::ostream &O, const Module* = 0) const;
301 void print(std::ostream *O, const Module* M = 0) const {
305 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
306 /// the given interval. FIXME: It also returns the weight of the spill slot
307 /// (if any is created) by reference. This is temporary.
308 std::vector<LiveInterval*>
309 addIntervalsForSpills(const LiveInterval& i,
310 SmallVectorImpl<LiveInterval*> &SpillIs,
311 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
314 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
315 /// defs / uses without remat or splitting.
316 std::vector<LiveInterval*>
317 addIntervalsForSpillsFast(const LiveInterval &li,
318 const MachineLoopInfo *loopInfo,
319 VirtRegMap &vrm, float& SSWeight);
321 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
322 /// around all defs and uses of the specified interval.
323 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
324 unsigned PhysReg, VirtRegMap &vrm);
326 /// isReMaterializable - Returns true if every definition of MI of every
327 /// val# of the specified interval is re-materializable. Also returns true
328 /// by reference if all of the defs are load instructions.
329 bool isReMaterializable(const LiveInterval &li,
330 SmallVectorImpl<LiveInterval*> &SpillIs,
333 /// getRepresentativeReg - Find the largest super register of the specified
334 /// physical register.
335 unsigned getRepresentativeReg(unsigned Reg) const;
337 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
338 /// specified interval that conflicts with the specified physical register.
339 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
340 unsigned PhysReg) const;
342 /// computeNumbering - Compute the index numbering.
343 void computeNumbering();
346 /// computeIntervals - Compute live intervals.
347 void computeIntervals();
349 /// handleRegisterDef - update intervals for a register def
350 /// (calls handlePhysicalRegisterDef and
351 /// handleVirtualRegisterDef)
352 void handleRegisterDef(MachineBasicBlock *MBB,
353 MachineBasicBlock::iterator MI, unsigned MIIdx,
354 MachineOperand& MO, unsigned MOIdx);
356 /// handleVirtualRegisterDef - update intervals for a virtual
358 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
359 MachineBasicBlock::iterator MI,
360 unsigned MIIdx, MachineOperand& MO,
361 unsigned MOIdx, LiveInterval& interval);
363 /// handlePhysicalRegisterDef - update intervals for a physical register
365 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
366 MachineBasicBlock::iterator mi,
367 unsigned MIIdx, MachineOperand& MO,
368 LiveInterval &interval,
369 MachineInstr *CopyMI);
371 /// handleLiveInRegister - Create interval for a livein register.
372 void handleLiveInRegister(MachineBasicBlock* mbb,
374 LiveInterval &interval, bool isAlias = false);
376 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
377 /// only allow one) virtual register operand, then its uses are implicitly
378 /// using the register. Returns the virtual register.
379 unsigned getReMatImplicitUse(const LiveInterval &li,
380 MachineInstr *MI) const;
382 /// isValNoAvailableAt - Return true if the val# of the specified interval
383 /// which reaches the given instruction also reaches the specified use
385 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
386 unsigned UseIdx) const;
388 /// isReMaterializable - Returns true if the definition MI of the specified
389 /// val# of the specified interval is re-materializable. Also returns true
390 /// by reference if the def is a load.
391 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
393 SmallVectorImpl<LiveInterval*> &SpillIs,
396 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
397 /// slot / to reg or any rematerialized load into ith operand of specified
398 /// MI. If it is successul, MI is updated with the newly created MI and
400 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
401 MachineInstr *DefMI, unsigned InstrIdx,
402 SmallVector<unsigned, 2> &Ops,
403 bool isSS, int Slot, unsigned Reg);
405 /// canFoldMemoryOperand - Return true if the specified load / store
406 /// folding is possible.
407 bool canFoldMemoryOperand(MachineInstr *MI,
408 SmallVector<unsigned, 2> &Ops,
409 bool ReMatLoadSS) const;
411 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
412 /// VNInfo that's after the specified index but is within the basic block.
413 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
414 MachineBasicBlock *MBB, unsigned Idx) const;
416 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
417 /// within a single basic block.
418 bool intervalIsInOneMBB(const LiveInterval &li) const;
420 /// hasAllocatableSuperReg - Return true if the specified physical register
421 /// has any super register that's allocatable.
422 bool hasAllocatableSuperReg(unsigned Reg) const;
424 /// SRInfo - Spill / restore info.
429 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
432 bool alsoFoldARestore(int Id, int index, unsigned vr,
433 BitVector &RestoreMBBs,
434 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
435 void eraseRestoreInfo(int Id, int index, unsigned vr,
436 BitVector &RestoreMBBs,
437 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
439 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
440 /// spilled and create empty intervals for their uses.
441 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
442 const TargetRegisterClass* rc,
443 std::vector<LiveInterval*> &NewLIs);
445 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
446 /// interval on to-be re-materialized operands of MI) with new register.
447 void rewriteImplicitOps(const LiveInterval &li,
448 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
450 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
451 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
453 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
454 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
455 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
456 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
457 VirtRegMap &vrm, const TargetRegisterClass* rc,
458 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
459 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
460 DenseMap<unsigned,unsigned> &MBBVRegsMap,
461 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
462 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
463 LiveInterval::Ranges::const_iterator &I,
464 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
465 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
466 VirtRegMap &vrm, const TargetRegisterClass* rc,
467 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
468 BitVector &SpillMBBs,
469 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
470 BitVector &RestoreMBBs,
471 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
472 DenseMap<unsigned,unsigned> &MBBVRegsMap,
473 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
475 static LiveInterval* createInterval(unsigned Reg);
477 void printRegName(unsigned reg) const;
480 } // End llvm namespace