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/ADT/BitVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Support/Allocator.h"
37 class MachineLoopInfo;
38 class TargetRegisterInfo;
39 class MachineRegisterInfo;
40 class TargetInstrInfo;
41 class TargetRegisterClass;
43 typedef std::pair<MachineInstrIndex, MachineBasicBlock*> IdxMBBPair;
45 inline bool operator<(MachineInstrIndex V, const IdxMBBPair &IM) {
49 inline bool operator<(const IdxMBBPair &IM, MachineInstrIndex 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_;
71 /// Special pool allocator for VNInfo's (LiveInterval val#).
73 BumpPtrAllocator VNInfoAllocator;
75 /// MBB2IdxMap - The indexes of the first and last instructions in the
76 /// specified basic block.
77 std::vector<std::pair<MachineInstrIndex, MachineInstrIndex> > MBB2IdxMap;
79 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
81 std::vector<IdxMBBPair> Idx2MBBMap;
83 /// FunctionSize - The number of instructions present in the function
84 uint64_t FunctionSize;
86 typedef DenseMap<const MachineInstr*, MachineInstrIndex> Mi2IndexMap;
89 typedef std::vector<MachineInstr*> Index2MiMap;
92 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
93 Reg2IntervalMap r2iMap_;
95 DenseMap<MachineBasicBlock*, MachineInstrIndex> terminatorGaps;
97 BitVector allocatableRegs_;
99 std::vector<MachineInstr*> ClonedMIs;
101 typedef LiveInterval::InstrSlots InstrSlots;
104 static char ID; // Pass identification, replacement for typeid
105 LiveIntervals() : MachineFunctionPass(&ID) {}
107 MachineInstrIndex getBaseIndex(MachineInstrIndex index) {
108 return MachineInstrIndex(index, MachineInstrIndex::LOAD);
110 MachineInstrIndex getBoundaryIndex(MachineInstrIndex index) {
111 return MachineInstrIndex(index,
112 (MachineInstrIndex::Slot)(MachineInstrIndex::NUM - 1));
114 MachineInstrIndex getLoadIndex(MachineInstrIndex index) {
115 return MachineInstrIndex(index, MachineInstrIndex::LOAD);
117 MachineInstrIndex getUseIndex(MachineInstrIndex index) {
118 return MachineInstrIndex(index, MachineInstrIndex::USE);
120 MachineInstrIndex getDefIndex(MachineInstrIndex index) {
121 return MachineInstrIndex(index, MachineInstrIndex::DEF);
123 MachineInstrIndex getStoreIndex(MachineInstrIndex index) {
124 return MachineInstrIndex(index, MachineInstrIndex::STORE);
127 MachineInstrIndex getNextSlot(MachineInstrIndex m) const {
128 return m.nextSlot_();
131 MachineInstrIndex getNextIndex(MachineInstrIndex m) const {
132 return m.nextIndex_();
135 MachineInstrIndex getPrevSlot(MachineInstrIndex m) const {
136 return m.prevSlot_();
139 MachineInstrIndex getPrevIndex(MachineInstrIndex m) const {
140 return m.prevIndex_();
143 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
144 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
147 typedef Reg2IntervalMap::iterator iterator;
148 typedef Reg2IntervalMap::const_iterator const_iterator;
149 const_iterator begin() const { return r2iMap_.begin(); }
150 const_iterator end() const { return r2iMap_.end(); }
151 iterator begin() { return r2iMap_.begin(); }
152 iterator end() { return r2iMap_.end(); }
153 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
155 LiveInterval &getInterval(unsigned reg) {
156 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
157 assert(I != r2iMap_.end() && "Interval does not exist for register");
161 const LiveInterval &getInterval(unsigned reg) const {
162 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
163 assert(I != r2iMap_.end() && "Interval does not exist for register");
167 bool hasInterval(unsigned reg) const {
168 return r2iMap_.count(reg);
171 /// getMBBStartIdx - Return the base index of the first instruction in the
172 /// specified MachineBasicBlock.
173 MachineInstrIndex getMBBStartIdx(MachineBasicBlock *MBB) const {
174 return getMBBStartIdx(MBB->getNumber());
176 MachineInstrIndex getMBBStartIdx(unsigned MBBNo) const {
177 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
178 return MBB2IdxMap[MBBNo].first;
181 /// getMBBEndIdx - Return the store index of the last instruction in the
182 /// specified MachineBasicBlock.
183 MachineInstrIndex getMBBEndIdx(MachineBasicBlock *MBB) const {
184 return getMBBEndIdx(MBB->getNumber());
186 MachineInstrIndex getMBBEndIdx(unsigned MBBNo) const {
187 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
188 return MBB2IdxMap[MBBNo].second;
191 /// getScaledIntervalSize - get the size of an interval in "units,"
192 /// where every function is composed of one thousand units. This
193 /// measure scales properly with empty index slots in the function.
194 double getScaledIntervalSize(LiveInterval& I) {
195 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
198 /// getApproximateInstructionCount - computes an estimate of the number
199 /// of instructions in a given LiveInterval.
200 unsigned getApproximateInstructionCount(LiveInterval& I) {
201 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
202 return (unsigned)(IntervalPercentage * FunctionSize);
205 /// getMBBFromIndex - given an index in any instruction of an
206 /// MBB return a pointer the MBB
207 MachineBasicBlock* getMBBFromIndex(MachineInstrIndex index) const {
208 std::vector<IdxMBBPair>::const_iterator I =
209 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
210 // Take the pair containing the index
211 std::vector<IdxMBBPair>::const_iterator J =
212 ((I != Idx2MBBMap.end() && I->first > index) ||
213 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
215 assert(J != Idx2MBBMap.end() && J->first <= index &&
216 index <= getMBBEndIdx(J->second) &&
217 "index does not correspond to an MBB");
221 /// getInstructionIndex - returns the base index of instr
222 MachineInstrIndex getInstructionIndex(const MachineInstr* instr) const {
223 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
224 assert(it != mi2iMap_.end() && "Invalid instruction!");
228 /// getInstructionFromIndex - given an index in any slot of an
229 /// instruction return a pointer the instruction
230 MachineInstr* getInstructionFromIndex(MachineInstrIndex index) const {
231 // convert index to vector index
232 unsigned i = index.getVecIndex();
233 assert(i < i2miMap_.size() &&
234 "index does not correspond to an instruction");
238 /// hasGapBeforeInstr - Return true if the previous instruction slot,
239 /// i.e. Index - InstrSlots::NUM, is not occupied.
240 bool hasGapBeforeInstr(MachineInstrIndex Index) {
241 Index = getBaseIndex(getPrevIndex(Index));
242 return getInstructionFromIndex(Index) == 0;
245 /// hasGapAfterInstr - Return true if the successive instruction slot,
246 /// i.e. Index + InstrSlots::Num, is not occupied.
247 bool hasGapAfterInstr(MachineInstrIndex Index) {
248 Index = getBaseIndex(getNextIndex(Index));
249 return getInstructionFromIndex(Index) == 0;
252 /// findGapBeforeInstr - Find an empty instruction slot before the
253 /// specified index. If "Furthest" is true, find one that's furthest
254 /// away from the index (but before any index that's occupied).
255 MachineInstrIndex findGapBeforeInstr(MachineInstrIndex Index,
256 bool Furthest = false) {
257 Index = getBaseIndex(getPrevIndex(Index));
258 if (getInstructionFromIndex(Index))
259 return MachineInstrIndex(); // No gap!
262 MachineInstrIndex PrevIndex = getBaseIndex(getPrevIndex(Index));
263 while (getInstructionFromIndex(Index)) {
265 PrevIndex = getBaseIndex(getPrevIndex(Index));
270 /// InsertMachineInstrInMaps - Insert the specified machine instruction
271 /// into the instruction index map at the given index.
272 void InsertMachineInstrInMaps(MachineInstr *MI, MachineInstrIndex Index) {
273 i2miMap_[Index.getVecIndex()] = MI;
274 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
275 assert(it == mi2iMap_.end() && "Already in map!");
276 mi2iMap_[MI] = Index;
279 /// conflictsWithPhysRegDef - Returns true if the specified register
280 /// is defined during the duration of the specified interval.
281 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
284 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
285 /// it can check use as well.
286 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
288 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
290 /// findLiveInMBBs - Given a live range, if the value of the range
291 /// is live in any MBB returns true as well as the list of basic blocks
292 /// in which the value is live.
293 bool findLiveInMBBs(MachineInstrIndex Start, MachineInstrIndex End,
294 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
296 /// findReachableMBBs - Return a list MBB that can be reached via any
297 /// branch or fallthroughs. Return true if the list is not empty.
298 bool findReachableMBBs(MachineInstrIndex Start, MachineInstrIndex End,
299 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
303 LiveInterval &getOrCreateInterval(unsigned reg) {
304 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
305 if (I == r2iMap_.end())
306 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
310 /// dupInterval - Duplicate a live interval. The caller is responsible for
311 /// managing the allocated memory.
312 LiveInterval *dupInterval(LiveInterval *li);
314 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
315 /// adds a live range from that instruction to the end of its MBB.
316 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
317 MachineInstr* startInst);
321 void removeInterval(unsigned Reg) {
322 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
327 /// isNotInMIMap - returns true if the specified machine instr has been
328 /// removed or was never entered in the map.
329 bool isNotInMIMap(MachineInstr* instr) const {
330 return !mi2iMap_.count(instr);
333 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
335 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
336 // remove index -> MachineInstr and
337 // MachineInstr -> index mappings
338 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
339 if (mi2i != mi2iMap_.end()) {
340 i2miMap_[mi2i->second.index/InstrSlots::NUM] = 0;
341 mi2iMap_.erase(mi2i);
345 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
346 /// maps used by register allocator.
347 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
348 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
349 if (mi2i == mi2iMap_.end())
351 i2miMap_[mi2i->second.index/InstrSlots::NUM] = NewMI;
352 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
353 assert(it != mi2iMap_.end() && "Invalid instruction!");
354 MachineInstrIndex Index = it->second;
356 mi2iMap_[NewMI] = Index;
359 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
361 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
362 /// copy field and returns the source register that defines it.
363 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
365 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
366 virtual void releaseMemory();
368 /// runOnMachineFunction - pass entry point
369 virtual bool runOnMachineFunction(MachineFunction&);
371 /// print - Implement the dump method.
372 virtual void print(raw_ostream &O, const Module* = 0) const;
374 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
375 /// the given interval. FIXME: It also returns the weight of the spill slot
376 /// (if any is created) by reference. This is temporary.
377 std::vector<LiveInterval*>
378 addIntervalsForSpills(const LiveInterval& i,
379 SmallVectorImpl<LiveInterval*> &SpillIs,
380 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
382 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
383 /// defs / uses without remat or splitting.
384 std::vector<LiveInterval*>
385 addIntervalsForSpillsFast(const LiveInterval &li,
386 const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
388 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
389 /// around all defs and uses of the specified interval. Return true if it
390 /// was able to cut its interval.
391 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
392 unsigned PhysReg, VirtRegMap &vrm);
394 /// isReMaterializable - Returns true if every definition of MI of every
395 /// val# of the specified interval is re-materializable. Also returns true
396 /// by reference if all of the defs are load instructions.
397 bool isReMaterializable(const LiveInterval &li,
398 SmallVectorImpl<LiveInterval*> &SpillIs,
401 /// isReMaterializable - Returns true if the definition MI of the specified
402 /// val# of the specified interval is re-materializable.
403 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
406 /// getRepresentativeReg - Find the largest super register of the specified
407 /// physical register.
408 unsigned getRepresentativeReg(unsigned Reg) const;
410 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
411 /// specified interval that conflicts with the specified physical register.
412 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
413 unsigned PhysReg) const;
415 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
416 /// marker to implicit_def defs and their uses.
417 void processImplicitDefs();
419 /// computeNumbering - Compute the index numbering.
420 void computeNumbering();
422 /// scaleNumbering - Rescale interval numbers to introduce gaps for new
424 void scaleNumbering(int factor);
426 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
427 /// within a single basic block.
428 bool intervalIsInOneMBB(const LiveInterval &li) const;
431 /// computeIntervals - Compute live intervals.
432 void computeIntervals();
434 /// handleRegisterDef - update intervals for a register def
435 /// (calls handlePhysicalRegisterDef and
436 /// handleVirtualRegisterDef)
437 void handleRegisterDef(MachineBasicBlock *MBB,
438 MachineBasicBlock::iterator MI,
439 MachineInstrIndex MIIdx,
440 MachineOperand& MO, unsigned MOIdx);
442 /// handleVirtualRegisterDef - update intervals for a virtual
444 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
445 MachineBasicBlock::iterator MI,
446 MachineInstrIndex MIIdx, MachineOperand& MO,
448 LiveInterval& interval);
450 /// handlePhysicalRegisterDef - update intervals for a physical register
452 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
453 MachineBasicBlock::iterator mi,
454 MachineInstrIndex MIIdx, MachineOperand& MO,
455 LiveInterval &interval,
456 MachineInstr *CopyMI);
458 /// handleLiveInRegister - Create interval for a livein register.
459 void handleLiveInRegister(MachineBasicBlock* mbb,
460 MachineInstrIndex MIIdx,
461 LiveInterval &interval, bool isAlias = false);
463 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
464 /// only allow one) virtual register operand, then its uses are implicitly
465 /// using the register. Returns the virtual register.
466 unsigned getReMatImplicitUse(const LiveInterval &li,
467 MachineInstr *MI) const;
469 /// isValNoAvailableAt - Return true if the val# of the specified interval
470 /// which reaches the given instruction also reaches the specified use
472 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
473 MachineInstrIndex UseIdx) const;
475 /// isReMaterializable - Returns true if the definition MI of the specified
476 /// val# of the specified interval is re-materializable. Also returns true
477 /// by reference if the def is a load.
478 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
480 SmallVectorImpl<LiveInterval*> &SpillIs,
483 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
484 /// slot / to reg or any rematerialized load into ith operand of specified
485 /// MI. If it is successul, MI is updated with the newly created MI and
487 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
488 MachineInstr *DefMI, MachineInstrIndex InstrIdx,
489 SmallVector<unsigned, 2> &Ops,
490 bool isSS, int FrameIndex, unsigned Reg);
492 /// canFoldMemoryOperand - Return true if the specified load / store
493 /// folding is possible.
494 bool canFoldMemoryOperand(MachineInstr *MI,
495 SmallVector<unsigned, 2> &Ops,
496 bool ReMatLoadSS) const;
498 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
499 /// VNInfo that's after the specified index but is within the basic block.
500 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
501 MachineBasicBlock *MBB,
502 MachineInstrIndex Idx) const;
504 /// hasAllocatableSuperReg - Return true if the specified physical register
505 /// has any super register that's allocatable.
506 bool hasAllocatableSuperReg(unsigned Reg) const;
508 /// SRInfo - Spill / restore info.
510 MachineInstrIndex index;
513 SRInfo(MachineInstrIndex i, unsigned vr, bool f)
514 : index(i), vreg(vr), canFold(f) {}
517 bool alsoFoldARestore(int Id, MachineInstrIndex index, unsigned vr,
518 BitVector &RestoreMBBs,
519 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
520 void eraseRestoreInfo(int Id, MachineInstrIndex index, unsigned vr,
521 BitVector &RestoreMBBs,
522 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
524 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
525 /// spilled and create empty intervals for their uses.
526 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
527 const TargetRegisterClass* rc,
528 std::vector<LiveInterval*> &NewLIs);
530 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
531 /// interval on to-be re-materialized operands of MI) with new register.
532 void rewriteImplicitOps(const LiveInterval &li,
533 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
535 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
536 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
538 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
539 bool TrySplit, MachineInstrIndex index, MachineInstrIndex end,
540 MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
541 unsigned Slot, int LdSlot,
542 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
543 VirtRegMap &vrm, const TargetRegisterClass* rc,
544 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
545 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
546 DenseMap<unsigned,unsigned> &MBBVRegsMap,
547 std::vector<LiveInterval*> &NewLIs);
548 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
549 LiveInterval::Ranges::const_iterator &I,
550 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
551 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
552 VirtRegMap &vrm, const TargetRegisterClass* rc,
553 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
554 BitVector &SpillMBBs,
555 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
556 BitVector &RestoreMBBs,
557 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
558 DenseMap<unsigned,unsigned> &MBBVRegsMap,
559 std::vector<LiveInterval*> &NewLIs);
561 static LiveInterval* createInterval(unsigned Reg);
563 void printRegName(unsigned reg) const;
565 } // End llvm namespace