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<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 DenseMap<const MachineInstr*, unsigned> Mi2IndexMap;
86 typedef std::vector<MachineInstr*> Index2MiMap;
89 typedef DenseMap<unsigned, LiveInterval*> Reg2IntervalMap;
90 Reg2IntervalMap r2iMap_;
92 DenseMap<MachineBasicBlock*, unsigned> terminatorGaps;
94 BitVector allocatableRegs_;
96 std::vector<MachineInstr*> ClonedMIs;
98 typedef LiveInterval::InstrSlots InstrSlots;
101 static char ID; // Pass identification, replacement for typeid
102 LiveIntervals() : MachineFunctionPass(&ID) {}
104 static unsigned getBaseIndex(unsigned index) {
105 return index - (index % InstrSlots::NUM);
107 static unsigned getBoundaryIndex(unsigned index) {
108 return getBaseIndex(index + InstrSlots::NUM - 1);
110 static unsigned getLoadIndex(unsigned index) {
111 return getBaseIndex(index) + InstrSlots::LOAD;
113 static unsigned getUseIndex(unsigned index) {
114 return getBaseIndex(index) + InstrSlots::USE;
116 static unsigned getDefIndex(unsigned index) {
117 return getBaseIndex(index) + InstrSlots::DEF;
119 static unsigned getStoreIndex(unsigned index) {
120 return getBaseIndex(index) + InstrSlots::STORE;
123 static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
124 return (isDef + isUse) * powf(10.0F, (float)loopDepth);
127 typedef Reg2IntervalMap::iterator iterator;
128 typedef Reg2IntervalMap::const_iterator const_iterator;
129 const_iterator begin() const { return r2iMap_.begin(); }
130 const_iterator end() const { return r2iMap_.end(); }
131 iterator begin() { return r2iMap_.begin(); }
132 iterator end() { return r2iMap_.end(); }
133 unsigned getNumIntervals() const { return (unsigned)r2iMap_.size(); }
135 LiveInterval &getInterval(unsigned reg) {
136 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
137 assert(I != r2iMap_.end() && "Interval does not exist for register");
141 const LiveInterval &getInterval(unsigned reg) const {
142 Reg2IntervalMap::const_iterator I = r2iMap_.find(reg);
143 assert(I != r2iMap_.end() && "Interval does not exist for register");
147 bool hasInterval(unsigned reg) const {
148 return r2iMap_.count(reg);
151 /// getMBBStartIdx - Return the base index of the first instruction in the
152 /// specified MachineBasicBlock.
153 unsigned getMBBStartIdx(MachineBasicBlock *MBB) const {
154 return getMBBStartIdx(MBB->getNumber());
156 unsigned getMBBStartIdx(unsigned MBBNo) const {
157 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
158 return MBB2IdxMap[MBBNo].first;
161 /// getMBBEndIdx - Return the store index of the last instruction in the
162 /// specified MachineBasicBlock.
163 unsigned getMBBEndIdx(MachineBasicBlock *MBB) const {
164 return getMBBEndIdx(MBB->getNumber());
166 unsigned getMBBEndIdx(unsigned MBBNo) const {
167 assert(MBBNo < MBB2IdxMap.size() && "Invalid MBB number!");
168 return MBB2IdxMap[MBBNo].second;
171 /// getScaledIntervalSize - get the size of an interval in "units,"
172 /// where every function is composed of one thousand units. This
173 /// measure scales properly with empty index slots in the function.
174 double getScaledIntervalSize(LiveInterval& I) {
175 return (1000.0 / InstrSlots::NUM * I.getSize()) / i2miMap_.size();
178 /// getApproximateInstructionCount - computes an estimate of the number
179 /// of instructions in a given LiveInterval.
180 unsigned getApproximateInstructionCount(LiveInterval& I) {
181 double IntervalPercentage = getScaledIntervalSize(I) / 1000.0;
182 return (unsigned)(IntervalPercentage * FunctionSize);
185 /// getMBBFromIndex - given an index in any instruction of an
186 /// MBB return a pointer the MBB
187 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
188 std::vector<IdxMBBPair>::const_iterator I =
189 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
190 // Take the pair containing the index
191 std::vector<IdxMBBPair>::const_iterator J =
192 ((I != Idx2MBBMap.end() && I->first > index) ||
193 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
195 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
196 index <= getMBBEndIdx(J->second) &&
197 "index does not correspond to an MBB");
201 /// getInstructionIndex - returns the base index of instr
202 unsigned getInstructionIndex(const MachineInstr* instr) const {
203 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
204 assert(it != mi2iMap_.end() && "Invalid instruction!");
208 /// getInstructionFromIndex - given an index in any slot of an
209 /// instruction return a pointer the instruction
210 MachineInstr* getInstructionFromIndex(unsigned index) const {
211 index /= InstrSlots::NUM; // convert index to vector index
212 assert(index < i2miMap_.size() &&
213 "index does not correspond to an instruction");
214 return i2miMap_[index];
217 /// hasGapBeforeInstr - Return true if the previous instruction slot,
218 /// i.e. Index - InstrSlots::NUM, is not occupied.
219 bool hasGapBeforeInstr(unsigned Index) {
220 Index = getBaseIndex(Index - InstrSlots::NUM);
221 return getInstructionFromIndex(Index) == 0;
224 /// hasGapAfterInstr - Return true if the successive instruction slot,
225 /// i.e. Index + InstrSlots::Num, is not occupied.
226 bool hasGapAfterInstr(unsigned Index) {
227 Index = getBaseIndex(Index + InstrSlots::NUM);
228 return getInstructionFromIndex(Index) == 0;
231 /// findGapBeforeInstr - Find an empty instruction slot before the
232 /// specified index. If "Furthest" is true, find one that's furthest
233 /// away from the index (but before any index that's occupied).
234 unsigned findGapBeforeInstr(unsigned Index, bool Furthest = false) {
235 Index = getBaseIndex(Index - InstrSlots::NUM);
236 if (getInstructionFromIndex(Index))
240 unsigned PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
241 while (getInstructionFromIndex(Index)) {
243 PrevIndex = getBaseIndex(Index - InstrSlots::NUM);
248 /// InsertMachineInstrInMaps - Insert the specified machine instruction
249 /// into the instruction index map at the given index.
250 void InsertMachineInstrInMaps(MachineInstr *MI, unsigned Index) {
251 i2miMap_[Index / InstrSlots::NUM] = MI;
252 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
253 assert(it == mi2iMap_.end() && "Already in map!");
254 mi2iMap_[MI] = Index;
257 /// conflictsWithPhysRegDef - Returns true if the specified register
258 /// is defined during the duration of the specified interval.
259 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
262 /// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
263 /// it can check use as well.
264 bool conflictsWithPhysRegRef(LiveInterval &li, unsigned Reg,
266 SmallPtrSet<MachineInstr*,32> &JoinedCopies);
268 /// findLiveInMBBs - Given a live range, if the value of the range
269 /// is live in any MBB returns true as well as the list of basic blocks
270 /// in which the value is live.
271 bool findLiveInMBBs(unsigned Start, unsigned End,
272 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
274 /// findReachableMBBs - Return a list MBB that can be reached via any
275 /// branch or fallthroughs. Return true if the list is not empty.
276 bool findReachableMBBs(unsigned Start, unsigned End,
277 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
281 LiveInterval &getOrCreateInterval(unsigned reg) {
282 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
283 if (I == r2iMap_.end())
284 I = r2iMap_.insert(std::make_pair(reg, createInterval(reg))).first;
288 /// dupInterval - Duplicate a live interval. The caller is responsible for
289 /// managing the allocated memory.
290 LiveInterval *dupInterval(LiveInterval *li);
292 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
293 /// adds a live range from that instruction to the end of its MBB.
294 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
295 MachineInstr* startInst);
299 void removeInterval(unsigned Reg) {
300 DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.find(Reg);
305 /// isNotInMIMap - returns true if the specified machine instr has been
306 /// removed or was never entered in the map.
307 bool isNotInMIMap(MachineInstr* instr) const {
308 return !mi2iMap_.count(instr);
311 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
313 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
314 // remove index -> MachineInstr and
315 // MachineInstr -> index mappings
316 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
317 if (mi2i != mi2iMap_.end()) {
318 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
319 mi2iMap_.erase(mi2i);
323 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
324 /// maps used by register allocator.
325 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
326 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
327 if (mi2i == mi2iMap_.end())
329 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
330 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
331 assert(it != mi2iMap_.end() && "Invalid instruction!");
332 unsigned Index = it->second;
334 mi2iMap_[NewMI] = Index;
337 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
339 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
340 /// copy field and returns the source register that defines it.
341 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
343 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
344 virtual void releaseMemory();
346 /// runOnMachineFunction - pass entry point
347 virtual bool runOnMachineFunction(MachineFunction&);
349 /// print - Implement the dump method.
350 virtual void print(std::ostream &O, const Module* = 0) const;
351 void print(std::ostream *O, const Module* M = 0) const {
355 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
356 /// the given interval. FIXME: It also returns the weight of the spill slot
357 /// (if any is created) by reference. This is temporary.
358 std::vector<LiveInterval*>
359 addIntervalsForSpills(const LiveInterval& i,
360 SmallVectorImpl<LiveInterval*> &SpillIs,
361 const MachineLoopInfo *loopInfo, VirtRegMap& vrm);
363 /// addIntervalsForSpillsFast - Quickly create new intervals for spilled
364 /// defs / uses without remat or splitting.
365 std::vector<LiveInterval*>
366 addIntervalsForSpillsFast(const LiveInterval &li,
367 const MachineLoopInfo *loopInfo, VirtRegMap &vrm);
369 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
370 /// around all defs and uses of the specified interval. Return true if it
371 /// was able to cut its interval.
372 bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
373 unsigned PhysReg, VirtRegMap &vrm);
375 /// isReMaterializable - Returns true if every definition of MI of every
376 /// val# of the specified interval is re-materializable. Also returns true
377 /// by reference if all of the defs are load instructions.
378 bool isReMaterializable(const LiveInterval &li,
379 SmallVectorImpl<LiveInterval*> &SpillIs,
382 /// isReMaterializable - Returns true if the definition MI of the specified
383 /// val# of the specified interval is re-materializable.
384 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
387 /// getRepresentativeReg - Find the largest super register of the specified
388 /// physical register.
389 unsigned getRepresentativeReg(unsigned Reg) const;
391 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
392 /// specified interval that conflicts with the specified physical register.
393 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
394 unsigned PhysReg) const;
396 /// processImplicitDefs - Process IMPLICIT_DEF instructions. Add isUndef
397 /// marker to implicit_def defs and their uses.
398 void processImplicitDefs();
400 /// computeNumbering - Compute the index numbering.
401 void computeNumbering();
403 /// scaleNumbering - Rescale interval numbers to introduce gaps for new
405 void scaleNumbering(int factor);
407 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
408 /// within a single basic block.
409 bool intervalIsInOneMBB(const LiveInterval &li) const;
412 /// computeIntervals - Compute live intervals.
413 void computeIntervals();
415 /// handleRegisterDef - update intervals for a register def
416 /// (calls handlePhysicalRegisterDef and
417 /// handleVirtualRegisterDef)
418 void handleRegisterDef(MachineBasicBlock *MBB,
419 MachineBasicBlock::iterator MI, unsigned MIIdx,
420 MachineOperand& MO, unsigned MOIdx);
422 /// handleVirtualRegisterDef - update intervals for a virtual
424 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
425 MachineBasicBlock::iterator MI,
426 unsigned MIIdx, MachineOperand& MO,
427 unsigned MOIdx, LiveInterval& interval);
429 /// handlePhysicalRegisterDef - update intervals for a physical register
431 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
432 MachineBasicBlock::iterator mi,
433 unsigned MIIdx, MachineOperand& MO,
434 LiveInterval &interval,
435 MachineInstr *CopyMI);
437 /// handleLiveInRegister - Create interval for a livein register.
438 void handleLiveInRegister(MachineBasicBlock* mbb,
440 LiveInterval &interval, bool isAlias = false);
442 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
443 /// only allow one) virtual register operand, then its uses are implicitly
444 /// using the register. Returns the virtual register.
445 unsigned getReMatImplicitUse(const LiveInterval &li,
446 MachineInstr *MI) const;
448 /// isValNoAvailableAt - Return true if the val# of the specified interval
449 /// which reaches the given instruction also reaches the specified use
451 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
452 unsigned UseIdx) const;
454 /// isReMaterializable - Returns true if the definition MI of the specified
455 /// val# of the specified interval is re-materializable. Also returns true
456 /// by reference if the def is a load.
457 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
459 SmallVectorImpl<LiveInterval*> &SpillIs,
462 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
463 /// slot / to reg or any rematerialized load into ith operand of specified
464 /// MI. If it is successul, MI is updated with the newly created MI and
466 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
467 MachineInstr *DefMI, unsigned InstrIdx,
468 SmallVector<unsigned, 2> &Ops,
469 bool isSS, int Slot, unsigned Reg);
471 /// canFoldMemoryOperand - Return true if the specified load / store
472 /// folding is possible.
473 bool canFoldMemoryOperand(MachineInstr *MI,
474 SmallVector<unsigned, 2> &Ops,
475 bool ReMatLoadSS) const;
477 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
478 /// VNInfo that's after the specified index but is within the basic block.
479 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
480 MachineBasicBlock *MBB, unsigned Idx) const;
482 /// hasAllocatableSuperReg - Return true if the specified physical register
483 /// has any super register that's allocatable.
484 bool hasAllocatableSuperReg(unsigned Reg) const;
486 /// SRInfo - Spill / restore info.
491 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
494 bool alsoFoldARestore(int Id, int index, unsigned vr,
495 BitVector &RestoreMBBs,
496 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
497 void eraseRestoreInfo(int Id, int index, unsigned vr,
498 BitVector &RestoreMBBs,
499 DenseMap<unsigned,std::vector<SRInfo> >&RestoreIdxes);
501 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
502 /// spilled and create empty intervals for their uses.
503 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
504 const TargetRegisterClass* rc,
505 std::vector<LiveInterval*> &NewLIs);
507 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
508 /// interval on to-be re-materialized operands of MI) with new register.
509 void rewriteImplicitOps(const LiveInterval &li,
510 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
512 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
513 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
515 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
516 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
517 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
518 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
519 VirtRegMap &vrm, const TargetRegisterClass* rc,
520 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
521 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
522 DenseMap<unsigned,unsigned> &MBBVRegsMap,
523 std::vector<LiveInterval*> &NewLIs);
524 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
525 LiveInterval::Ranges::const_iterator &I,
526 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
527 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
528 VirtRegMap &vrm, const TargetRegisterClass* rc,
529 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
530 BitVector &SpillMBBs,
531 DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
532 BitVector &RestoreMBBs,
533 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
534 DenseMap<unsigned,unsigned> &MBBVRegsMap,
535 std::vector<LiveInterval*> &NewLIs);
537 static LiveInterval* createInterval(unsigned Reg);
539 void printRegName(unsigned reg) const;
542 /// IntervalPrefixPrinter - Print live interval indices before each
544 class IntervalPrefixPrinter : public PrefixPrinter {
546 const LiveIntervals &liinfo;
549 IntervalPrefixPrinter(const LiveIntervals &lii)
552 // We need null implementations of the other virtual functions to
553 // avoid warnings about hidden virtual functions.
555 raw_ostream &operator()(raw_ostream &out,
556 const MachineBasicBlock &instr) const {
560 raw_ostream &operator()(raw_ostream &out,
561 const MachineInstr &instr) const;
563 std::ostream &operator()(std::ostream &out,
564 const MachineBasicBlock &instr) const {
568 std::ostream &operator()(std::ostream &out,
569 const MachineInstr &instr) const {
573 } // End llvm namespace