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 typedef std::map<MachineInstr*, unsigned> Mi2IndexMap;
81 typedef std::vector<MachineInstr*> Index2MiMap;
84 typedef std::map<unsigned, LiveInterval> Reg2IntervalMap;
85 Reg2IntervalMap r2iMap_;
87 BitVector allocatableRegs_;
89 std::vector<MachineInstr*> ClonedMIs;
92 static char ID; // Pass identification, replacement for typeid
93 LiveIntervals() : MachineFunctionPass((intptr_t)&ID) {}
105 static unsigned getBaseIndex(unsigned index) {
106 return index - (index % InstrSlots::NUM);
108 static unsigned getBoundaryIndex(unsigned index) {
109 return getBaseIndex(index + InstrSlots::NUM - 1);
111 static unsigned getLoadIndex(unsigned index) {
112 return getBaseIndex(index) + InstrSlots::LOAD;
114 static unsigned getUseIndex(unsigned index) {
115 return getBaseIndex(index) + InstrSlots::USE;
117 static unsigned getDefIndex(unsigned index) {
118 return getBaseIndex(index) + InstrSlots::DEF;
120 static unsigned getStoreIndex(unsigned index) {
121 return getBaseIndex(index) + InstrSlots::STORE;
124 static float getSpillWeight(bool isDef, bool isUse, bool isMem,
125 unsigned loopDepth) {
126 float Weight = isDef;
128 Weight += isMem ? 1.2f : 1.0f;
129 return Weight * 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 /// getMBBFromIndex - given an index in any instruction of an
177 /// MBB return a pointer the MBB
178 MachineBasicBlock* getMBBFromIndex(unsigned index) const {
179 std::vector<IdxMBBPair>::const_iterator I =
180 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), index);
181 // Take the pair containing the index
182 std::vector<IdxMBBPair>::const_iterator J =
183 ((I != Idx2MBBMap.end() && I->first > index) ||
184 (I == Idx2MBBMap.end() && Idx2MBBMap.size()>0)) ? (I-1): I;
186 assert(J != Idx2MBBMap.end() && J->first < index+1 &&
187 index <= getMBBEndIdx(J->second) &&
188 "index does not correspond to an MBB");
192 /// getInstructionIndex - returns the base index of instr
193 unsigned getInstructionIndex(MachineInstr* instr) const {
194 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
195 assert(it != mi2iMap_.end() && "Invalid instruction!");
199 /// getInstructionFromIndex - given an index in any slot of an
200 /// instruction return a pointer the instruction
201 MachineInstr* getInstructionFromIndex(unsigned index) const {
202 index /= InstrSlots::NUM; // convert index to vector index
203 assert(index < i2miMap_.size() &&
204 "index does not correspond to an instruction");
205 return i2miMap_[index];
208 /// conflictsWithPhysRegDef - Returns true if the specified register
209 /// is defined during the duration of the specified interval.
210 bool conflictsWithPhysRegDef(const LiveInterval &li, VirtRegMap &vrm,
213 /// findLiveInMBBs - Given a live range, if the value of the range
214 /// is live in any MBB returns true as well as the list of basic blocks
215 /// where the value is live in.
216 bool findLiveInMBBs(const LiveRange &LR,
217 SmallVectorImpl<MachineBasicBlock*> &MBBs) const;
221 LiveInterval &getOrCreateInterval(unsigned reg) {
222 Reg2IntervalMap::iterator I = r2iMap_.find(reg);
223 if (I == r2iMap_.end())
224 I = r2iMap_.insert(I, std::make_pair(reg, createInterval(reg)));
228 /// addLiveRangeToEndOfBlock - Given a register and an instruction,
229 /// adds a live range from that instruction to the end of its MBB.
230 LiveRange addLiveRangeToEndOfBlock(unsigned reg,
231 MachineInstr* startInst);
235 void removeInterval(unsigned Reg) {
239 /// isRemoved - returns true if the specified machine instr has been
241 bool isRemoved(MachineInstr* instr) const {
242 return !mi2iMap_.count(instr);
245 /// RemoveMachineInstrFromMaps - This marks the specified machine instr as
247 void RemoveMachineInstrFromMaps(MachineInstr *MI) {
248 // remove index -> MachineInstr and
249 // MachineInstr -> index mappings
250 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
251 if (mi2i != mi2iMap_.end()) {
252 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
253 mi2iMap_.erase(mi2i);
257 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
258 /// maps used by register allocator.
259 void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
260 Mi2IndexMap::iterator mi2i = mi2iMap_.find(MI);
261 if (mi2i == mi2iMap_.end())
263 i2miMap_[mi2i->second/InstrSlots::NUM] = NewMI;
264 Mi2IndexMap::iterator it = mi2iMap_.find(MI);
265 assert(it != mi2iMap_.end() && "Invalid instruction!");
266 unsigned Index = it->second;
268 mi2iMap_[NewMI] = Index;
271 BumpPtrAllocator& getVNInfoAllocator() { return VNInfoAllocator; }
273 /// getVNInfoSourceReg - Helper function that parses the specified VNInfo
274 /// copy field and returns the source register that defines it.
275 unsigned getVNInfoSourceReg(const VNInfo *VNI) const;
277 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
278 virtual void releaseMemory();
280 /// runOnMachineFunction - pass entry point
281 virtual bool runOnMachineFunction(MachineFunction&);
283 /// print - Implement the dump method.
284 virtual void print(std::ostream &O, const Module* = 0) const;
285 void print(std::ostream *O, const Module* M = 0) const {
289 /// addIntervalsForSpills - Create new intervals for spilled defs / uses of
290 /// the given interval. FIXME: It also returns the weight of the spill slot
291 /// (if any is created) by reference. This is temporary.
292 std::vector<LiveInterval*>
293 addIntervalsForSpills(const LiveInterval& i,
294 const MachineLoopInfo *loopInfo, VirtRegMap& vrm,
297 /// spillPhysRegAroundRegDefsUses - Spill the specified physical register
298 /// around all defs and uses of the specified interval.
299 void spillPhysRegAroundRegDefsUses(const LiveInterval &li,
300 unsigned PhysReg, VirtRegMap &vrm);
302 /// isReMaterializable - Returns true if every definition of MI of every
303 /// val# of the specified interval is re-materializable. Also returns true
304 /// by reference if all of the defs are load instructions.
305 bool isReMaterializable(const LiveInterval &li, bool &isLoad);
307 /// getRepresentativeReg - Find the largest super register of the specified
308 /// physical register.
309 unsigned getRepresentativeReg(unsigned Reg) const;
311 /// getNumConflictsWithPhysReg - Return the number of uses and defs of the
312 /// specified interval that conflicts with the specified physical register.
313 unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
314 unsigned PhysReg) const;
316 /// computeNumbering - Compute the index numbering.
317 void computeNumbering();
320 /// computeIntervals - Compute live intervals.
321 void computeIntervals();
323 /// handleRegisterDef - update intervals for a register def
324 /// (calls handlePhysicalRegisterDef and
325 /// handleVirtualRegisterDef)
326 void handleRegisterDef(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator MI, unsigned MIIdx,
330 /// handleVirtualRegisterDef - update intervals for a virtual
332 void handleVirtualRegisterDef(MachineBasicBlock *MBB,
333 MachineBasicBlock::iterator MI,
335 LiveInterval& interval);
337 /// handlePhysicalRegisterDef - update intervals for a physical register
339 void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
340 MachineBasicBlock::iterator mi,
342 LiveInterval &interval,
343 MachineInstr *CopyMI);
345 /// handleLiveInRegister - Create interval for a livein register.
346 void handleLiveInRegister(MachineBasicBlock* mbb,
348 LiveInterval &interval, bool isAlias = false);
350 /// getReMatImplicitUse - If the remat definition MI has one (for now, we
351 /// only allow one) virtual register operand, then its uses are implicitly
352 /// using the register. Returns the virtual register.
353 unsigned getReMatImplicitUse(const LiveInterval &li,
354 MachineInstr *MI) const;
356 /// isValNoAvailableAt - Return true if the val# of the specified interval
357 /// which reaches the given instruction also reaches the specified use
359 bool isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
360 unsigned UseIdx) const;
362 /// isReMaterializable - Returns true if the definition MI of the specified
363 /// val# of the specified interval is re-materializable. Also returns true
364 /// by reference if the def is a load.
365 bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
366 MachineInstr *MI, bool &isLoad);
368 /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
369 /// slot / to reg or any rematerialized load into ith operand of specified
370 /// MI. If it is successul, MI is updated with the newly created MI and
372 bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
373 MachineInstr *DefMI, unsigned InstrIdx,
374 SmallVector<unsigned, 2> &Ops,
375 bool isSS, int Slot, unsigned Reg);
377 /// canFoldMemoryOperand - Return true if the specified load / store
378 /// folding is possible.
379 bool canFoldMemoryOperand(MachineInstr *MI,
380 SmallVector<unsigned, 2> &Ops,
381 bool ReMatLoadSS) const;
383 /// anyKillInMBBAfterIdx - Returns true if there is a kill of the specified
384 /// VNInfo that's after the specified index but is within the basic block.
385 bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
386 MachineBasicBlock *MBB, unsigned Idx) const;
388 /// intervalIsInOneMBB - Returns true if the specified interval is entirely
389 /// within a single basic block.
390 bool intervalIsInOneMBB(const LiveInterval &li) const;
392 /// hasAllocatableSuperReg - Return true if the specified physical register
393 /// has any super register that's allocatable.
394 bool hasAllocatableSuperReg(unsigned Reg) const;
396 /// SRInfo - Spill / restore info.
401 SRInfo(int i, unsigned vr, bool f) : index(i), vreg(vr), canFold(f) {};
404 bool alsoFoldARestore(int Id, int index, unsigned vr,
405 BitVector &RestoreMBBs,
406 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
407 void eraseRestoreInfo(int Id, int index, unsigned vr,
408 BitVector &RestoreMBBs,
409 std::map<unsigned,std::vector<SRInfo> >&RestoreIdxes);
411 /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
412 /// spilled and create empty intervals for their uses.
413 void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
414 const TargetRegisterClass* rc,
415 std::vector<LiveInterval*> &NewLIs);
417 /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
418 /// interval on to-be re-materialized operands of MI) with new register.
419 void rewriteImplicitOps(const LiveInterval &li,
420 MachineInstr *MI, unsigned NewVReg, VirtRegMap &vrm);
422 /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
423 /// functions for addIntervalsForSpills to rewrite uses / defs for the given
425 bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
426 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
427 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
428 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
429 VirtRegMap &vrm, const TargetRegisterClass* rc,
430 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
431 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
432 std::map<unsigned,unsigned> &MBBVRegsMap,
433 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
434 void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
435 LiveInterval::Ranges::const_iterator &I,
436 MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int LdSlot,
437 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
438 VirtRegMap &vrm, const TargetRegisterClass* rc,
439 SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
440 BitVector &SpillMBBs,
441 std::map<unsigned,std::vector<SRInfo> > &SpillIdxes,
442 BitVector &RestoreMBBs,
443 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes,
444 std::map<unsigned,unsigned> &MBBVRegsMap,
445 std::vector<LiveInterval*> &NewLIs, float &SSWeight);
447 static LiveInterval createInterval(unsigned Reg);
449 void printRegName(unsigned reg) const;
452 } // End llvm namespace