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_;
66 /// Special pool allocator for VNInfo's (LiveInterval val#).
68 BumpPtrAllocator VNInfoAllocator;
70 /// MBB2IdxMap - The indexes of the first and last instructions in the
71 /// specified basic block.
72 std::vector<std::pair<unsigned, unsigned> > MBB2IdxMap;
74 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
76 std::vector<IdxMBBPair> Idx2MBBMap;
78 /// FunctionSize - The number of instructions present in the function
79 uint64_t FunctionSize;
81 typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
84 typedef std::vector<MachineInstr*> Index2MiMap;
87 typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
88 Reg2IntervalMap r2iMap_;
90 BitVector allocatableRegs_;
92 std::vector<MachineInstr*> ClonedMIs;
95 static char ID; // Pass identification, replacement for typeid
96 LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
108 static unsigned getBaseIndex(unsigned index) {
109 return index - (index % InstrSlots::NUM);
111 static unsigned getBoundaryIndex(unsigned index) {
112 return getBaseIndex(index + InstrSlots::NUM - 1);
114 static unsigned getLoadIndex(unsigned index) {
115 return getBaseIndex(index) + InstrSlots::LOAD;
117 static unsigned getUseIndex(unsigned index) {
118 return getBaseIndex(index) + InstrSlots::USE;
120 static unsigned getDefIndex(unsigned index) {
121 return getBaseIndex(index) + InstrSlots::DEF;
123 static unsigned getStoreIndex(unsigned index) {
124 return getBaseIndex(index) + InstrSlots::STORE;
127 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
128 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
131 typedef Reg2IntervalMap::iterator iterator;
132 typedef Reg2IntervalMap::const_iterator const_iterator;
133 const_iterator begin() const { return r2iMap_.begin(); }
134 const_iterator end() const { return r2iMap_.end(); }
135 iterator begin() { return r2iMap_.begin(); }
136 iterator end() { return r2iMap_.end(); }
137 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
139 LiveInterval &getInterval(unsigned reg) {
140 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
141 assert(I != r2iMap_.end() && "Interval does not exist for register");
145 const LiveInterval &getInterval(unsigned reg) const {
146 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
147 assert(I != r2iMap_.end() && "Interval does not exist for register");
151 bool hasInterval(unsigned reg) const {
152 return r2iMap_.count(reg);
155 /// getMBBStartIdx - Return the base index of the first instruction in the
156 /// specified MachineBasicBlock.
157 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
158 return getMBBStartIdx(MBB->getNumber());
160 unsigned getMBBStartIdx(unsigned MBBNo) const {
161 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
162 return MBB2IdxMap[MBBNo].first;
165 /// getMBBEndIdx - Return the store index of the last instruction in the
166 /// specified MachineBasicBlock.
167 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
168 return getMBBEndIdx(MBB->getNumber());
170 unsigned getMBBEndIdx(unsigned MBBNo) const {
171 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
172 return MBB2IdxMap[MBBNo].second;
175 /// getScaledIntervalSize - get the size of an interval in "units,"
176 /// where every function is composed of one thousand units. This
177 /// measure scales properly with empty index slots in the function.
178 double getScaledIntervalSize(LiveInterval& I) {
179 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
182 /// getApproximateInstructionCount - computes an estimate of the number
183 /// of instructions in a given LiveInterval.
184 unsigned getApproximateInstructionCount(LiveInterval& I) {
185 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
186 return IntervalPercentage * FunctionSize;
189 /// getMBBFromIndex - given an index in any instruction of an
190 /// MBB return a pointer the MBB
191 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
192 std::vector<IdxMBBPair>::const_iterator I =
193 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
194 // Take the pair containing the index
195 std::vector<IdxMBBPair>::const_iterator J =
196 ((I != Idx2MBBMap.end() && I->first > index) ||
197 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
199 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
200 index <= getMBBEndIdx(J->second) &&
201 "index does not correspond to an MBB");
205 /// getInstructionIndex - returns the base index of instr
206 unsigned getInstructionIndex(MachineInstr* instr) const {
207 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
208 assert(it != mi2iMap_.end() && "Invalid instruction!");
212 /// getInstructionFromIndex - given an index in any slot of an
213 /// instruction return a pointer the instruction
214 MachineInstr* getInstructionFromIndex(unsigned index) const {
215 index /= InstrSlots::NUM; // convert index to vector index
216 assert(index < i2miMap_.size() &&
217 "index does not correspond to an instruction");
218 return i2miMap_[index];
221 /// conflictsWithPhysRegDef - Returns true if the specified register
222 /// is defined during the duration of the specified interval.
223 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
226 /// findLiveInMBBs - Given a live range, if the value of the range
227 /// is live in any MBB returns true as well as the list of basic blocks
228 /// where the value is live in.
229 bool findLiveInMBBs(const LiveRange &LR,
230 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
234 LiveInterval &getOrCreateInterval(unsigned reg) {
235 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
236 if (I == r2iMap_.end())
237 I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
241 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
242 /// adds a live range from that instruction to the end of its MBB.
243 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
244 MachineInstr* startInst);
248 void removeInterval(unsigned Reg) {
252 /// isRemoved - returns true if the specified machine instr has been
254 bool isRemoved(MachineInstr* instr) const {
255 return !mi2iMap_.count(instr);
258 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
260 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
261 // remove index -> MachineInstr and
262 // MachineInstr -> index mappings
263 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
264 if (mi2i != mi2iMap_.end()) {
265 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
266 mi2iMap_.erase(mi2i);
270 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
271 /// maps used by register allocator.
272 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
273 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
274 if (mi2i == mi2iMap_.end())
276 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
277 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
278 assert(it != mi2iMap_.end() && "Invalid instruction!");
279 unsigned Index = it->second;
281 mi2iMap_[NewMI] = Index;
284 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
286 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
287 /// copy field and returns the source register that defines it.
288 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
290 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
291 virtual void releaseMemory();
293 /// runOnMachineFunction - pass entry point
294 virtual bool runOnMachineFunction(MachineFunction&);
296 /// print - Implement the dump method.
297 virtual void print(std::ostream &O, const Module* = 0) const;
298 void print(std::ostream *O, const Module* M = 0) const {
302 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
303 /// the given interval. FIXME: It also returns the weight of the spill slot
304 /// (if any is created) by reference. This is temporary.
305 std::vector<LiveInterval*>
306 addIntervalsForSpills(const LiveInterval& i,
307 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
310 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
311 /// around all defs and uses of the specified interval.
312 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
313 unsigned PhysReg, VirtRegMap &vrm);
315 /// isReMaterializable - Returns true if every definition of MI of every
316 /// val# of the specified interval is re-materializable. Also returns true
317 /// by reference if all of the defs are load instructions.
318 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
320 /// getRepresentativeReg - Find the largest super register of the specified
321 /// physical register.
322 unsigned getRepresentativeReg(unsigned Reg) const;
324 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
325 /// specified interval that conflicts with the specified physical register.
326 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
327 unsigned PhysReg) const;
329 /// computeNumbering - Compute the index numbering.
330 void computeNumbering();
333 /// computeIntervals - Compute live intervals.
334 void computeIntervals();
336 /// handleRegisterDef - update intervals for a register def
337 /// (calls handlePhysicalRegisterDef and
338 /// handleVirtualRegisterDef)
339 void handleRegisterDef(MachineBasicBlock *MBB,
340 MachineBasicBlock::iterator MI, unsigned MIIdx,
341 MachineOperand& MO, unsigned MOIdx);
343 /// handleVirtualRegisterDef - update intervals for a virtual
345 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
346 MachineBasicBlock::iterator MI,
347 unsigned MIIdx, MachineOperand& MO,
348 unsigned MOIdx, LiveInterval& interval);
350 /// handlePhysicalRegisterDef - update intervals for a physical register
352 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
353 MachineBasicBlock::iterator mi,
354 unsigned MIIdx, MachineOperand& MO,
355 LiveInterval &interval,
356 MachineInstr *CopyMI);
358 /// handleLiveInRegister - Create interval for a livein register.
359 void handleLiveInRegister(MachineBasicBlock* mbb,
361 LiveInterval &interval, bool isAlias = false);
363 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
364 /// only allow one) virtual register operand, then its uses are implicitly
365 /// using the register. Returns the virtual register.
366 unsigned getReMatImplicitUse(const LiveInterval &li,
367 MachineInstr *MI) const;
369 /// isValNoAvailableAt - Return true if the val# of the specified interval
370 /// which reaches the given instruction also reaches the specified use
372 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
373 unsigned UseIdx) const;
375 /// isReMaterializable - Returns true if the definition MI of the specified
376 /// val# of the specified interval is re-materializable. Also returns true
377 /// by reference if the def is a load.
378 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
379 MachineInstr *MI, bool &isLoad);
381 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
382 /// slot / to reg or any rematerialized load into ith operand of specified
383 /// MI. If it is successul, MI is updated with the newly created MI and
385 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
386 MachineInstr *DefMI, unsigned InstrIdx,
387 SmallVector<unsigned, 2> &Ops,
388 bool isSS, int Slot, unsigned Reg);
390 /// canFoldMemoryOperand - Return true if the specified load / store
391 /// folding is possible.
392 bool canFoldMemoryOperand(MachineInstr *MI,
393 SmallVector<unsigned, 2> &Ops,
394 bool ReMatLoadSS) const;
396 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
397 /// VNInfo that's after the specified index but is within the basic block.
398 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
399 MachineBasicBlock *MBB, unsigned Idx) const;
401 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
402 /// within a single basic block.
403 bool intervalIsInOneMBB(const LiveInterval &li) const;
405 /// hasAllocatableSuperReg - Return true if the specified physical register
406 /// has any super register that's allocatable.
407 bool hasAllocatableSuperReg(unsigned Reg) const;
409 /// SRInfo - Spill / restore info.
414 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
417 bool alsoFoldARestore(int Id, int index, unsigned vr,
418 BitVector &RestoreMBBs,
419 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
420 void eraseRestoreInfo(int Id, int index, unsigned vr,
421 BitVector &RestoreMBBs,
422 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
424 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
425 /// spilled and create empty intervals for their uses.
426 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
427 const TargetRegisterClass* rc,
428 std::vector<LiveInterval*> &NewLIs);
430 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
431 /// interval on to-be re-materialized operands of MI) with new register.
432 void rewriteImplicitOps(const LiveInterval &li,
433 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
435 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
436 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
438 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
439 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
440 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
441 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
442 VirtRegMap &vrm, const TargetRegisterClass* rc,
443 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
444 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
445 std::map<unsigned,unsigned> &MBBVRegsMap,
446 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
447 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
448 LiveInterval::Ranges::const_iterator &I,
449 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
450 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
451 VirtRegMap &vrm, const TargetRegisterClass* rc,
452 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
453 BitVector &SpillMBBs,
454 std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
455 BitVector &RestoreMBBs,
456 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
457 std::map<unsigned,unsigned> &MBBVRegsMap,
458 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
460 static LiveInterval createInterval(unsigned Reg);
462 void printRegName(unsigned reg) const;
465 } // End llvm namespace