1 //===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "liveintervals"
19 #include "llvm/CodeGen/LiveIntervals.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CFG.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
40 RegisterAnalysis<LiveIntervals> X("liveintervals",
41 "Live Interval Analysis");
43 Statistic<> numIntervals("liveintervals", "Number of intervals");
44 Statistic<> numJoined ("liveintervals", "Number of joined intervals");
47 join("join-liveintervals",
48 cl::desc("Join compatible live intervals"),
52 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
54 AU.addPreserved<LiveVariables>();
55 AU.addRequired<LiveVariables>();
56 AU.addPreservedID(PHIEliminationID);
57 AU.addRequiredID(PHIEliminationID);
58 AU.addRequiredID(TwoAddressInstructionPassID);
59 AU.addRequired<LoopInfo>();
60 MachineFunctionPass::getAnalysisUsage(AU);
63 void LiveIntervals::releaseMemory()
74 /// runOnMachineFunction - Register allocate the whole function
76 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
77 DEBUG(std::cerr << "Machine Function\n");
79 tm_ = &fn.getTarget();
80 mri_ = tm_->getRegisterInfo();
81 lv_ = &getAnalysis<LiveVariables>();
83 // number MachineInstrs
85 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
86 mbb != mbbEnd; ++mbb) {
87 const std::pair<MachineBasicBlock*, unsigned>& entry =
88 lv_->getMachineBasicBlockInfo(mbb);
89 bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
91 assert(inserted && "multiple index -> MachineBasicBlock");
93 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
95 inserted = mi2iMap_.insert(std::make_pair(*mi, miIndex)).second;
96 assert(inserted && "multiple MachineInstr -> index mappings");
103 // compute spill weights
104 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
105 const TargetInstrInfo& tii = tm_->getInstrInfo();
107 for (MachineFunction::const_iterator mbbi = mf_->begin(),
108 mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
109 const MachineBasicBlock* mbb = mbbi;
110 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
112 for (MachineBasicBlock::const_iterator mii = mbb->begin(),
113 mie = mbb->end(); mii != mie; ++mii) {
114 MachineInstr* mi = *mii;
116 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
117 MachineOperand& mop = mi->getOperand(i);
118 if (mop.isVirtualRegister()) {
119 unsigned reg = mop.getAllocatedRegNum();
120 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
121 assert(r2iit != r2iMap_.end());
122 r2iit->second->weight += pow(10.0F, loopDepth);
128 // join intervals if requested
129 if (join) joinIntervals();
131 numIntervals += intervals_.size();
133 intervals_.sort(StartPointComp());
134 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
135 std::ostream_iterator<Interval>(std::cerr, "\n")));
139 void LiveIntervals::printRegName(unsigned reg) const
141 if (MRegisterInfo::isPhysicalRegister(reg))
142 std::cerr << mri_->getName(reg);
144 std::cerr << '%' << reg;
147 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
148 MachineBasicBlock::iterator mi,
151 DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
153 unsigned instrIndex = getInstructionIndex(*mi);
155 LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
157 Interval* interval = 0;
158 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
159 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
161 intervals_.push_back(Interval(reg));
162 // update interval index for this register
163 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
164 interval = &intervals_.back();
167 interval = &*r2iit->second;
170 // iterate over all of the blocks that the variable is completely
171 // live in, adding them to the live interval
172 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
173 if (vi.AliveBlocks[i]) {
174 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
176 interval->addRange(getInstructionIndex(mbb->front()),
177 getInstructionIndex(mbb->back()) + 1);
182 bool killedInDefiningBasicBlock = false;
183 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
184 MachineBasicBlock* killerBlock = vi.Kills[i].first;
185 MachineInstr* killerInstr = vi.Kills[i].second;
186 unsigned start = (mbb == killerBlock ?
188 getInstructionIndex(killerBlock->front()));
189 unsigned end = getInstructionIndex(killerInstr) + 1;
190 // we do not want to add invalid ranges. these can happen when
191 // a variable has its latest use and is redefined later on in
192 // the same basic block (common with variables introduced by
195 killedInDefiningBasicBlock |= mbb == killerBlock;
196 interval->addRange(start, end);
200 if (!killedInDefiningBasicBlock) {
201 unsigned end = getInstructionIndex(mbb->back()) + 1;
202 interval->addRange(instrIndex, end);
206 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
207 MachineBasicBlock::iterator mi,
210 typedef LiveVariables::killed_iterator KillIter;
212 DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
214 MachineBasicBlock::iterator e = mbb->end();
215 unsigned start = getInstructionIndex(*mi);
216 unsigned end = start + 1;
218 // a variable can be dead by the instruction defining it
219 for (KillIter ki = lv_->dead_begin(*mi), ke = lv_->dead_end(*mi);
221 if (reg == ki->second) {
222 DEBUG(std::cerr << " dead\n");
227 // a variable can only be killed by subsequent instructions
231 for (KillIter ki = lv_->killed_begin(*mi), ke = lv_->killed_end(*mi);
233 if (reg == ki->second) {
234 DEBUG(std::cerr << " killed\n");
241 assert(start < end && "did not find end of interval?");
243 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
244 if (r2iit != r2iMap_.end() && r2iit->first == reg) {
245 r2iit->second->addRange(start, end);
248 intervals_.push_back(Interval(reg));
249 // update interval index for this register
250 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
251 intervals_.back().addRange(start, end);
255 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
256 MachineBasicBlock::iterator mi,
259 if (MRegisterInfo::isPhysicalRegister(reg)) {
260 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
261 handlePhysicalRegisterDef(mbb, mi, reg);
262 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
263 handlePhysicalRegisterDef(mbb, mi, *as);
267 handleVirtualRegisterDef(mbb, mi, reg);
271 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
273 assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
274 "instruction not assigned a number");
275 return mi2iMap_.find(instr)->second;
278 /// computeIntervals - computes the live intervals for virtual
279 /// registers. for some ordering of the machine instructions [1,N] a
280 /// live interval is an interval [i, j) where 1 <= i <= j < N for
281 /// which a variable is live
282 void LiveIntervals::computeIntervals()
284 DEBUG(std::cerr << "computing live intervals:\n");
286 for (MbbIndex2MbbMap::iterator
287 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
289 MachineBasicBlock* mbb = it->second;
290 DEBUG(std::cerr << "machine basic block: "
291 << mbb->getBasicBlock()->getName() << "\n");
293 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
295 MachineInstr* instr = *mi;
296 const TargetInstrDescriptor& tid =
297 tm_->getInstrInfo().get(instr->getOpcode());
298 DEBUG(std::cerr << "\t[" << getInstructionIndex(instr) << "] ";
299 instr->print(std::cerr, *tm_););
301 // handle implicit defs
302 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
303 handleRegisterDef(mbb, mi, *id);
305 // handle explicit defs
306 for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
307 MachineOperand& mop = instr->getOperand(i);
308 // handle register defs - build intervals
309 if (mop.isRegister() && mop.isDef())
310 handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
316 unsigned LiveIntervals::rep(unsigned reg)
318 Reg2RegMap::iterator it = r2rMap_.find(reg);
319 if (it != r2rMap_.end())
320 return it->second = rep(it->second);
324 void LiveIntervals::joinIntervals()
326 DEBUG(std::cerr << "joining compatible intervals:\n");
328 const TargetInstrInfo& tii = tm_->getInstrInfo();
330 for (MachineFunction::const_iterator mbbi = mf_->begin(),
331 mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
332 const MachineBasicBlock* mbb = mbbi;
333 DEBUG(std::cerr << "machine basic block: "
334 << mbb->getBasicBlock()->getName() << "\n");
336 for (MachineBasicBlock::const_iterator mii = mbb->begin(),
337 mie = mbb->end(); mii != mie; ++mii) {
338 MachineInstr* mi = *mii;
339 const TargetInstrDescriptor& tid =
340 tm_->getInstrInfo().get(mi->getOpcode());
341 DEBUG(std::cerr << "\t\tinstruction["
342 << getInstructionIndex(mi) << "]: ";
343 mi->print(std::cerr, *tm_););
345 // we only join virtual registers with allocatable
346 // physical registers since we do not have liveness information
347 // on not allocatable physical registers
349 if (tii.isMoveInstr(*mi, regA, regB) &&
350 (MRegisterInfo::isVirtualRegister(regA) ||
351 lv_->getAllocatablePhysicalRegisters()[regA]) &&
352 (MRegisterInfo::isVirtualRegister(regB) ||
353 lv_->getAllocatablePhysicalRegisters()[regB])) {
355 // get representative registers
359 // if they are already joined we continue
363 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
364 assert(r2iA != r2iMap_.end());
365 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
366 assert(r2iB != r2iMap_.end());
368 Intervals::iterator intA = r2iA->second;
369 Intervals::iterator intB = r2iB->second;
371 // both A and B are virtual registers
372 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
373 MRegisterInfo::isVirtualRegister(intB->reg)) {
375 const TargetRegisterClass *rcA, *rcB;
376 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
377 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
378 assert(rcA == rcB && "registers must be of the same class");
380 // if their intervals do not overlap we join them
381 if (!intB->overlaps(*intA)) {
383 r2iB->second = r2iA->second;
384 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
385 intervals_.erase(intB);
389 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
390 MRegisterInfo::isPhysicalRegister(intB->reg)) {
391 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
392 std::swap(regA, regB);
393 std::swap(intA, intB);
394 std::swap(r2iA, r2iB);
397 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
398 MRegisterInfo::isVirtualRegister(intB->reg) &&
399 "A must be physical and B must be virtual");
401 if (!intA->overlaps(*intB) &&
402 !overlapsAliases(*intA, *intB)) {
404 r2iB->second = r2iA->second;
405 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
406 intervals_.erase(intB);
415 bool LiveIntervals::overlapsAliases(const Interval& lhs,
416 const Interval& rhs) const
418 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
419 "first interval must describe a physical register");
421 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
422 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
423 assert(r2i != r2iMap_.end() && "alias does not have interval?");
424 if (rhs.overlaps(*r2i->second))
431 LiveIntervals::Interval::Interval(unsigned r)
433 weight((MRegisterInfo::isPhysicalRegister(r) ?
434 std::numeric_limits<float>::max() : 0.0F))
439 // This example is provided becaues liveAt() is non-obvious:
441 // this = [1,2), liveAt(1) will return false. The idea is that the
442 // variable is defined in 1 and not live after definition. So it was
443 // dead to begin with (defined but never used).
445 // this = [1,3), liveAt(2) will return false. The variable is used at
446 // 2 but 2 is the last use so the variable's allocated register is
447 // available for reuse.
448 bool LiveIntervals::Interval::liveAt(unsigned index) const
450 Range dummy(index, index+1);
451 Ranges::const_iterator r = std::upper_bound(ranges.begin(),
454 if (r == ranges.begin())
458 return index >= r->first && index < (r->second - 1);
461 // This example is provided because overlaps() is non-obvious:
465 // 2: C = A + B ;; last use of A
467 // The live intervals should look like:
473 // A->overlaps(C) should return false since we want to be able to join
475 bool LiveIntervals::Interval::overlaps(const Interval& other) const
477 Ranges::const_iterator i = ranges.begin();
478 Ranges::const_iterator ie = ranges.end();
479 Ranges::const_iterator j = other.ranges.begin();
480 Ranges::const_iterator je = other.ranges.end();
481 if (i->first < j->first) {
482 i = std::upper_bound(i, ie, *j);
483 if (i != ranges.begin()) --i;
485 else if (j->first < i->first) {
486 j = std::upper_bound(j, je, *i);
487 if (j != other.ranges.begin()) --j;
490 while (i != ie && j != je) {
491 if (i->first == j->first) {
495 if (i->first > j->first) {
499 assert(i->first < j->first);
501 if ((i->second - 1) > j->first) {
513 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
515 assert(start < end && "Invalid range to add!");
516 DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
517 //assert(start < end && "invalid range?");
518 Range range = std::make_pair(start, end);
519 Ranges::iterator it =
520 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
523 it = mergeRangesForward(it);
524 it = mergeRangesBackward(it);
525 DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
528 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
530 DEBUG(std::cerr << "\t\t\t\tjoining intervals: "
531 << other << " and " << *this << '\n');
532 Ranges::iterator cur = ranges.begin();
534 for (Ranges::const_iterator i = other.ranges.begin(),
535 e = other.ranges.end(); i != e; ++i) {
536 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
537 cur = mergeRangesForward(cur);
538 cur = mergeRangesBackward(cur);
540 if (MRegisterInfo::isVirtualRegister(reg))
541 weight += other.weight;
543 DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
546 LiveIntervals::Interval::Ranges::iterator
547 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
549 for (Ranges::iterator next = it + 1;
550 next != ranges.end() && it->second >= next->first; ) {
551 it->second = std::max(it->second, next->second);
552 next = ranges.erase(next);
557 LiveIntervals::Interval::Ranges::iterator
558 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
560 while (it != ranges.begin()) {
561 Ranges::iterator prev = it - 1;
562 if (it->first > prev->second) break;
564 it->first = std::min(it->first, prev->first);
565 it->second = std::max(it->second, prev->second);
566 it = ranges.erase(prev);
572 std::ostream& llvm::operator<<(std::ostream& os,
573 const LiveIntervals::Interval& li)
575 os << "%reg" << li.reg << ',' << li.weight << " = ";
576 for (LiveIntervals::Interval::Ranges::const_iterator
577 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
578 os << "[" << i->first << "," << i->second << ")";