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"
37 class MachineLoopInfo;
38 class TargetRegisterInfo;
39 class MachineRegisterInfo;
40 class TargetInstrInfo;
41 class TargetRegisterClass;
43 typedef std::pair<unsigned, MachineBasicBlock*> IdxMBBPair;
45 inline bool operator<(unsigned V, const IdxMBBPair &IM) {
49 inline bool operator<(const IdxMBBPair &IM, unsigned V) {
53 struct Idx2MBBCompare {
54 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
55 return LHS.first < RHS.first;
59 class LiveIntervals : public MachineFunctionPass {
61 MachineRegisterInfo* mri_;
62 const TargetMachine* tm_;
63 const TargetRegisterInfo* tri_;
64 const TargetInstrInfo* tii_;
68 /// Special pool allocator for VNInfo's (LiveInterval val#).
70 BumpPtrAllocator VNInfoAllocator;
72 /// MBB2IdxMap - The indexes of the first and last instructions in the
73 /// specified basic block.
74 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
76 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
78 std::vector<IdxMBBPair> Idx2MBBMap;
80 /// FunctionSize - The number of instructions present in the function
81 uint64_t FunctionSize;
83 typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
86 typedef std::vector<MachineInstr*> Index2MiMap;
89 typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
90 Reg2IntervalMap r2iMap_;
92 BitVector allocatableRegs_;
94 std::vector<MachineInstr*> ClonedMIs;
97 static char ID; // Pass identification, replacement for typeid
98 LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
110 static unsigned getBaseIndex(unsigned index) {
111 return index - (index % InstrSlots::NUM);
113 static unsigned getBoundaryIndex(unsigned index) {
114 return getBaseIndex(index + InstrSlots::NUM - 1);
116 static unsigned getLoadIndex(unsigned index) {
117 return getBaseIndex(index) + InstrSlots::LOAD;
119 static unsigned getUseIndex(unsigned index) {
120 return getBaseIndex(index) + InstrSlots::USE;
122 static unsigned getDefIndex(unsigned index) {
123 return getBaseIndex(index) + InstrSlots::DEF;
125 static unsigned getStoreIndex(unsigned index) {
126 return getBaseIndex(index) + InstrSlots::STORE;
129 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
130 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
133 typedef Reg2IntervalMap::iterator iterator;
134 typedef Reg2IntervalMap::const_iterator const_iterator;
135 const_iterator begin() const { return r2iMap_.begin(); }
136 const_iterator end() const { return r2iMap_.end(); }
137 iterator begin() { return r2iMap_.begin(); }
138 iterator end() { return r2iMap_.end(); }
139 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
141 LiveInterval &getInterval(unsigned reg) {
142 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
143 assert(I != r2iMap_.end() && "Interval does not exist for register");
147 const LiveInterval &getInterval(unsigned reg) const {
148 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
149 assert(I != r2iMap_.end() && "Interval does not exist for register");
153 bool hasInterval(unsigned reg) const {
154 return r2iMap_.count(reg);
157 /// getMBBStartIdx - Return the base index of the first instruction in the
158 /// specified MachineBasicBlock.
159 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
160 return getMBBStartIdx(MBB->getNumber());
162 unsigned getMBBStartIdx(unsigned MBBNo) const {
163 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
164 return MBB2IdxMap[MBBNo].first;
167 /// getMBBEndIdx - Return the store index of the last instruction in the
168 /// specified MachineBasicBlock.
169 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
170 return getMBBEndIdx(MBB->getNumber());
172 unsigned getMBBEndIdx(unsigned MBBNo) const {
173 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
174 return MBB2IdxMap[MBBNo].second;
177 /// getScaledIntervalSize - get the size of an interval in "units,"
178 /// where every function is composed of one thousand units. This
179 /// measure scales properly with empty index slots in the function.
180 double getScaledIntervalSize(LiveInterval& I) {
181 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
184 /// getApproximateInstructionCount - computes an estimate of the number
185 /// of instructions in a given LiveInterval.
186 unsigned getApproximateInstructionCount(LiveInterval& I) {
187 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
188 return IntervalPercentage * FunctionSize;
191 /// getMBBFromIndex - given an index in any instruction of an
192 /// MBB return a pointer the MBB
193 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
194 std::vector<IdxMBBPair>::const_iterator I =
195 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
196 // Take the pair containing the index
197 std::vector<IdxMBBPair>::const_iterator J =
198 ((I != Idx2MBBMap.end() && I->first > index) ||
199 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
201 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
202 index <= getMBBEndIdx(J->second) &&
203 "index does not correspond to an MBB");
207 /// getInstructionIndex - returns the base index of instr
208 unsigned getInstructionIndex(MachineInstr* instr) const {
209 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
210 assert(it != mi2iMap_.end() && "Invalid instruction!");
214 /// getInstructionFromIndex - given an index in any slot of an
215 /// instruction return a pointer the instruction
216 MachineInstr* getInstructionFromIndex(unsigned index) const {
217 index /= InstrSlots::NUM; // convert index to vector index
218 assert(index < i2miMap_.size() &&
219 "index does not correspond to an instruction");
220 return i2miMap_[index];
223 /// conflictsWithPhysRegDef - Returns true if the specified register
224 /// is defined during the duration of the specified interval.
225 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
228 /// findLiveInMBBs - Given a live range, if the value of the range
229 /// is live in any MBB returns true as well as the list of basic blocks
230 /// where the value is live in.
231 bool findLiveInMBBs(const LiveRange &LR,
232 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
236 LiveInterval &getOrCreateInterval(unsigned reg) {
237 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
238 if (I == r2iMap_.end())
239 I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
243 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
244 /// adds a live range from that instruction to the end of its MBB.
245 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
246 MachineInstr* startInst);
250 void removeInterval(unsigned Reg) {
254 /// isRemoved - returns true if the specified machine instr has been
256 bool isRemoved(MachineInstr* instr) const {
257 return !mi2iMap_.count(instr);
260 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
262 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
263 // remove index -> MachineInstr and
264 // MachineInstr -> index mappings
265 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
266 if (mi2i != mi2iMap_.end()) {
267 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
268 mi2iMap_.erase(mi2i);
272 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
273 /// maps used by register allocator.
274 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
275 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
276 if (mi2i == mi2iMap_.end())
278 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
279 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
280 assert(it != mi2iMap_.end() && "Invalid instruction!");
281 unsigned Index = it->second;
283 mi2iMap_[NewMI] = Index;
286 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
288 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
289 /// copy field and returns the source register that defines it.
290 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
292 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
293 virtual void releaseMemory();
295 /// runOnMachineFunction - pass entry point
296 virtual bool runOnMachineFunction(MachineFunction&);
298 /// print - Implement the dump method.
299 virtual void print(std::ostream &O, const Module* = 0) const;
300 void print(std::ostream *O, const Module* M = 0) const {
304 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
305 /// the given interval. FIXME: It also returns the weight of the spill slot
306 /// (if any is created) by reference. This is temporary.
307 std::vector<LiveInterval*>
308 addIntervalsForSpills(const LiveInterval& i,
309 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
312 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
313 /// around all defs and uses of the specified interval.
314 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
315 unsigned PhysReg, VirtRegMap &vrm);
317 /// isReMaterializable - Returns true if every definition of MI of every
318 /// val# of the specified interval is re-materializable. Also returns true
319 /// by reference if all of the defs are load instructions.
320 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
322 /// getRepresentativeReg - Find the largest super register of the specified
323 /// physical register.
324 unsigned getRepresentativeReg(unsigned Reg) const;
326 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
327 /// specified interval that conflicts with the specified physical register.
328 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
329 unsigned PhysReg) const;
331 /// computeNumbering - Compute the index numbering.
332 void computeNumbering();
335 /// computeIntervals - Compute live intervals.
336 void computeIntervals();
338 /// handleRegisterDef - update intervals for a register def
339 /// (calls handlePhysicalRegisterDef and
340 /// handleVirtualRegisterDef)
341 void handleRegisterDef(MachineBasicBlock *MBB,
342 MachineBasicBlock::iterator MI, unsigned MIIdx,
343 MachineOperand& MO, unsigned MOIdx);
345 /// handleVirtualRegisterDef - update intervals for a virtual
347 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
348 MachineBasicBlock::iterator MI,
349 unsigned MIIdx, MachineOperand& MO,
350 unsigned MOIdx, LiveInterval& interval);
352 /// handlePhysicalRegisterDef - update intervals for a physical register
354 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
355 MachineBasicBlock::iterator mi,
356 unsigned MIIdx, MachineOperand& MO,
357 LiveInterval &interval,
358 MachineInstr *CopyMI);
360 /// handleLiveInRegister - Create interval for a livein register.
361 void handleLiveInRegister(MachineBasicBlock* mbb,
363 LiveInterval &interval, bool isAlias = false);
365 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
366 /// only allow one) virtual register operand, then its uses are implicitly
367 /// using the register. Returns the virtual register.
368 unsigned getReMatImplicitUse(const LiveInterval &li,
369 MachineInstr *MI) const;
371 /// isValNoAvailableAt - Return true if the val# of the specified interval
372 /// which reaches the given instruction also reaches the specified use
374 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
375 unsigned UseIdx) const;
377 /// isReMaterializable - Returns true if the definition MI of the specified
378 /// val# of the specified interval is re-materializable. Also returns true
379 /// by reference if the def is a load.
380 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
381 MachineInstr *MI, bool &isLoad);
383 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
384 /// slot / to reg or any rematerialized load into ith operand of specified
385 /// MI. If it is successul, MI is updated with the newly created MI and
387 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
388 MachineInstr *DefMI, unsigned InstrIdx,
389 SmallVector<unsigned, 2> &Ops,
390 bool isSS, int Slot, unsigned Reg);
392 /// canFoldMemoryOperand - Return true if the specified load / store
393 /// folding is possible.
394 bool canFoldMemoryOperand(MachineInstr *MI,
395 SmallVector<unsigned, 2> &Ops,
396 bool ReMatLoadSS) const;
398 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
399 /// VNInfo that's after the specified index but is within the basic block.
400 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
401 MachineBasicBlock *MBB, unsigned Idx) const;
403 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
404 /// within a single basic block.
405 bool intervalIsInOneMBB(const LiveInterval &li) const;
407 /// hasAllocatableSuperReg - Return true if the specified physical register
408 /// has any super register that's allocatable.
409 bool hasAllocatableSuperReg(unsigned Reg) const;
411 /// SRInfo - Spill / restore info.
416 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
419 bool alsoFoldARestore(int Id, int index, unsigned vr,
420 BitVector &RestoreMBBs,
421 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
422 void eraseRestoreInfo(int Id, int index, unsigned vr,
423 BitVector &RestoreMBBs,
424 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
426 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
427 /// spilled and create empty intervals for their uses.
428 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
429 const TargetRegisterClass* rc,
430 std::vector<LiveInterval*> &NewLIs);
432 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
433 /// interval on to-be re-materialized operands of MI) with new register.
434 void rewriteImplicitOps(const LiveInterval &li,
435 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
437 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
438 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
440 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
441 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
442 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
443 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
444 VirtRegMap &vrm, const TargetRegisterClass* rc,
445 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
446 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
447 std::map<unsigned,unsigned> &MBBVRegsMap,
448 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
449 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
450 LiveInterval::Ranges::const_iterator &I,
451 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
452 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
453 VirtRegMap &vrm, const TargetRegisterClass* rc,
454 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
455 BitVector &SpillMBBs,
456 std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
457 BitVector &RestoreMBBs,
458 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
459 std::map<unsigned,unsigned> &MBBVRegsMap,
460 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
462 static LiveInterval createInterval(unsigned Reg);
464 void printRegName(unsigned reg) const;
467 } // End llvm namespace