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 "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"
33 #include "Support/STLExtras.h"
34 #include "VirtRegMap.h"
42 RegisterAnalysis<LiveIntervals> X("liveintervals",
43 "Live Interval Analysis");
45 Statistic<> numIntervals
46 ("liveintervals", "Number of original intervals");
48 Statistic<> numIntervalsAfter
49 ("liveintervals", "Number of intervals after coalescing");
52 ("liveintervals", "Number of interval joins performed");
55 ("liveintervals", "Number of identity moves eliminated after coalescing");
58 ("liveintervals", "Number of loads/stores folded into instructions");
61 join("join-liveintervals",
62 cl::desc("Join compatible live intervals"),
66 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
68 AU.addPreserved<LiveVariables>();
69 AU.addRequired<LiveVariables>();
70 AU.addPreservedID(PHIEliminationID);
71 AU.addRequiredID(PHIEliminationID);
72 AU.addRequiredID(TwoAddressInstructionPassID);
73 AU.addRequired<LoopInfo>();
74 MachineFunctionPass::getAnalysisUsage(AU);
77 void LiveIntervals::releaseMemory()
88 /// runOnMachineFunction - Register allocate the whole function
90 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
92 tm_ = &fn.getTarget();
93 mri_ = tm_->getRegisterInfo();
94 lv_ = &getAnalysis<LiveVariables>();
96 // number MachineInstrs
98 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
99 mbb != mbbEnd; ++mbb) {
100 const std::pair<MachineBasicBlock*, unsigned>& entry =
101 lv_->getMachineBasicBlockInfo(mbb);
102 bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
103 entry.first)).second;
104 assert(inserted && "multiple index -> MachineBasicBlock");
106 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
108 inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
109 assert(inserted && "multiple MachineInstr -> index mappings");
110 i2miMap_.push_back(mi);
111 miIndex += InstrSlots::NUM;
117 numIntervals += intervals_.size();
119 // join intervals if requested
120 if (join) joinIntervals();
122 numIntervalsAfter += intervals_.size();
124 // perform a final pass over the instructions and compute spill
125 // weights, coalesce virtual registers and remove identity moves
126 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
127 const TargetInstrInfo& tii = tm_->getInstrInfo();
129 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
130 mbbi != mbbe; ++mbbi) {
131 MachineBasicBlock* mbb = mbbi;
132 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
134 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
136 // if the move will be an identity move delete it
137 unsigned srcReg, dstReg;
138 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
139 rep(srcReg) == rep(dstReg)) {
140 // remove from def list
141 Interval& interval = getOrCreateInterval(dstReg);
142 unsigned defIndex = getInstructionIndex(mii);
143 Interval::Defs::iterator d = std::lower_bound(
144 interval.defs.begin(), interval.defs.end(), defIndex);
145 assert(*d == defIndex && "Def index not found in def list!");
146 interval.defs.erase(d);
147 // remove index -> MachineInstr and
148 // MachineInstr -> index mappings
149 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
150 if (mi2i != mi2iMap_.end()) {
151 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
152 mi2iMap_.erase(mi2i);
154 mii = mbbi->erase(mii);
158 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
159 const MachineOperand& mop = mii->getOperand(i);
160 if (mop.isRegister() && mop.getReg() &&
161 MRegisterInfo::isVirtualRegister(mop.getReg())) {
162 // replace register with representative register
163 unsigned reg = rep(mop.getReg());
164 mii->SetMachineOperandReg(i, reg);
166 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
167 assert(r2iit != r2iMap_.end());
168 r2iit->second->weight +=
169 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
177 intervals_.sort(StartPointComp());
178 DEBUG(std::cerr << "********** INTERVALS **********\n");
179 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
180 std::ostream_iterator<Interval>(std::cerr, "\n")));
181 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
183 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
184 mbbi != mbbe; ++mbbi) {
185 std::cerr << mbbi->getBasicBlock()->getName() << ":\n";
186 for (MachineBasicBlock::iterator mii = mbbi->begin(),
187 mie = mbbi->end(); mii != mie; ++mii) {
188 std::cerr << getInstructionIndex(mii) << '\t';
189 mii->print(std::cerr, *tm_);
196 void LiveIntervals::updateSpilledInterval(Interval& li,
200 assert(li.weight != std::numeric_limits<float>::infinity() &&
201 "attempt to spill already spilled interval!");
202 Interval::Ranges oldRanges;
203 swap(oldRanges, li.ranges);
205 DEBUG(std::cerr << "\t\t\t\tupdating interval: " << li);
207 for (Interval::Ranges::iterator i = oldRanges.begin(), e = oldRanges.end();
209 unsigned index = getBaseIndex(i->first);
210 unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM;
211 for (; index < end; index += InstrSlots::NUM) {
212 // skip deleted instructions
213 while (!getInstructionFromIndex(index)) index += InstrSlots::NUM;
214 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
217 for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
218 MachineOperand& mop = mi->getOperand(i);
219 if (mop.isRegister() && mop.getReg() == li.reg) {
220 if (MachineInstr* fmi =
221 mri_->foldMemoryOperand(mi, i, slot)) {
222 lv_->instructionChanged(mi, fmi);
223 vrm.virtFolded(li.reg, mi, fmi);
225 i2miMap_[index/InstrSlots::NUM] = fmi;
226 mi2iMap_[fmi] = index;
227 MachineBasicBlock& mbb = *mi->getParent();
228 mi = mbb.insert(mbb.erase(mi), fmi);
233 // This is tricky. We need to add information in
234 // the interval about the spill code so we have to
235 // use our extra load/store slots.
237 // If we have a use we are going to have a load so
238 // we start the interval from the load slot
239 // onwards. Otherwise we start from the def slot.
240 unsigned start = (mop.isUse() ?
241 getLoadIndex(index) :
243 // If we have a def we are going to have a store
244 // right after it so we end the interval after the
245 // use of the next instruction. Otherwise we end
246 // after the use of this instruction.
247 unsigned end = 1 + (mop.isDef() ?
248 getUseIndex(index+InstrSlots::NUM) :
250 li.addRange(start, end);
256 // the new spill weight is now infinity as it cannot be spilled again
257 li.weight = std::numeric_limits<float>::infinity();
258 DEBUG(std::cerr << '\n');
259 DEBUG(std::cerr << "\t\t\t\tupdated interval: " << li << '\n');
262 void LiveIntervals::printRegName(unsigned reg) const
264 if (MRegisterInfo::isPhysicalRegister(reg))
265 std::cerr << mri_->getName(reg);
267 std::cerr << "%reg" << reg;
270 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
271 MachineBasicBlock::iterator mi,
274 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
275 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
277 // iterate over all of the blocks that the variable is completely
278 // live in, adding them to the live interval. obviously we only
279 // need to do this once.
280 if (interval.empty()) {
281 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
282 if (vi.AliveBlocks[i]) {
283 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
286 getInstructionIndex(&mbb->front()),
287 getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
293 unsigned baseIndex = getInstructionIndex(mi);
294 interval.defs.push_back(baseIndex);
296 bool killedInDefiningBasicBlock = false;
297 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
298 MachineBasicBlock* killerBlock = vi.Kills[i].first;
299 MachineInstr* killerInstr = vi.Kills[i].second;
300 unsigned start = (mbb == killerBlock ?
301 getDefIndex(baseIndex) :
302 getInstructionIndex(&killerBlock->front()));
303 unsigned end = (killerInstr == mi ?
307 getUseIndex(getInstructionIndex(killerInstr))+1);
308 // we do not want to add invalid ranges. these can happen when
309 // a variable has its latest use and is redefined later on in
310 // the same basic block (common with variables introduced by
313 killedInDefiningBasicBlock |= mbb == killerBlock;
314 interval.addRange(start, end);
318 if (!killedInDefiningBasicBlock) {
319 unsigned end = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
320 interval.addRange(getDefIndex(baseIndex), end);
322 DEBUG(std::cerr << '\n');
325 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
326 MachineBasicBlock::iterator mi,
329 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
330 typedef LiveVariables::killed_iterator KillIter;
332 MachineBasicBlock::iterator e = mbb->end();
333 unsigned baseIndex = getInstructionIndex(mi);
334 interval.defs.push_back(baseIndex);
335 unsigned start = getDefIndex(baseIndex);
336 unsigned end = start;
338 // a variable can be dead by the instruction defining it
339 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
341 if (interval.reg == ki->second) {
342 DEBUG(std::cerr << " dead");
343 end = getDefIndex(start) + 1;
348 // a variable can only be killed by subsequent instructions
351 baseIndex += InstrSlots::NUM;
352 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
354 if (interval.reg == ki->second) {
355 DEBUG(std::cerr << " killed");
356 end = getUseIndex(baseIndex) + 1;
363 assert(start < end && "did not find end of interval?");
364 interval.addRange(start, end);
365 DEBUG(std::cerr << '\n');
368 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
369 MachineBasicBlock::iterator mi,
372 if (MRegisterInfo::isPhysicalRegister(reg)) {
373 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
374 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
375 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
376 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
380 handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
383 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
385 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
386 return (it == mi2iMap_.end() ?
387 std::numeric_limits<unsigned>::max() :
391 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
393 index /= InstrSlots::NUM; // convert index to vector index
394 assert(index < i2miMap_.size() &&
395 "index does not correspond to an instruction");
396 return i2miMap_[index];
399 /// computeIntervals - computes the live intervals for virtual
400 /// registers. for some ordering of the machine instructions [1,N] a
401 /// live interval is an interval [i, j) where 1 <= i <= j < N for
402 /// which a variable is live
403 void LiveIntervals::computeIntervals()
405 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
406 DEBUG(std::cerr << "********** Function: "
407 << mf_->getFunction()->getName() << '\n');
409 for (MbbIndex2MbbMap::iterator
410 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
412 MachineBasicBlock* mbb = it->second;
413 DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
415 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
417 const TargetInstrDescriptor& tid =
418 tm_->getInstrInfo().get(mi->getOpcode());
419 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
420 mi->print(std::cerr, *tm_));
422 // handle implicit defs
423 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
424 handleRegisterDef(mbb, mi, *id);
426 // handle explicit defs
427 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
428 MachineOperand& mop = mi->getOperand(i);
429 // handle register defs - build intervals
430 if (mop.isRegister() && mop.getReg() && mop.isDef())
431 handleRegisterDef(mbb, mi, mop.getReg());
437 unsigned LiveIntervals::rep(unsigned reg)
439 Reg2RegMap::iterator it = r2rMap_.find(reg);
440 if (it != r2rMap_.end())
441 return it->second = rep(it->second);
445 void LiveIntervals::joinIntervals()
447 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
449 const TargetInstrInfo& tii = tm_->getInstrInfo();
451 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
452 mbbi != mbbe; ++mbbi) {
453 MachineBasicBlock* mbb = mbbi;
454 DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
456 for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
458 const TargetInstrDescriptor& tid =
459 tm_->getInstrInfo().get(mi->getOpcode());
460 DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
461 mi->print(std::cerr, *tm_););
463 // we only join virtual registers with allocatable
464 // physical registers since we do not have liveness information
465 // on not allocatable physical registers
467 if (tii.isMoveInstr(*mi, regA, regB) &&
468 (MRegisterInfo::isVirtualRegister(regA) ||
469 lv_->getAllocatablePhysicalRegisters()[regA]) &&
470 (MRegisterInfo::isVirtualRegister(regB) ||
471 lv_->getAllocatablePhysicalRegisters()[regB])) {
473 // get representative registers
477 // if they are already joined we continue
481 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
482 assert(r2iA != r2iMap_.end());
483 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
484 assert(r2iB != r2iMap_.end());
486 Intervals::iterator intA = r2iA->second;
487 Intervals::iterator intB = r2iB->second;
489 // both A and B are virtual registers
490 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
491 MRegisterInfo::isVirtualRegister(intB->reg)) {
493 const TargetRegisterClass *rcA, *rcB;
494 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
495 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
496 assert(rcA == rcB && "registers must be of the same class");
498 // if their intervals do not overlap we join them
499 if (!intB->overlaps(*intA)) {
501 r2iB->second = r2iA->second;
502 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
503 intervals_.erase(intB);
506 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
507 MRegisterInfo::isPhysicalRegister(intB->reg)) {
508 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
509 std::swap(regA, regB);
510 std::swap(intA, intB);
511 std::swap(r2iA, r2iB);
514 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
515 MRegisterInfo::isVirtualRegister(intB->reg) &&
516 "A must be physical and B must be virtual");
518 if (!intA->overlaps(*intB) &&
519 !overlapsAliases(*intA, *intB)) {
521 r2iB->second = r2iA->second;
522 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
523 intervals_.erase(intB);
531 bool LiveIntervals::overlapsAliases(const Interval& lhs,
532 const Interval& rhs) const
534 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
535 "first interval must describe a physical register");
537 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
538 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
539 assert(r2i != r2iMap_.end() && "alias does not have interval?");
540 if (rhs.overlaps(*r2i->second))
547 LiveIntervals::Interval& LiveIntervals::getOrCreateInterval(unsigned reg)
549 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
550 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
551 intervals_.push_back(Interval(reg));
552 r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
555 return *r2iit->second;
558 LiveIntervals::Interval::Interval(unsigned r)
560 weight((MRegisterInfo::isPhysicalRegister(r) ?
561 std::numeric_limits<float>::infinity() : 0.0F))
566 bool LiveIntervals::Interval::spilled() const
568 return (weight == std::numeric_limits<float>::infinity() &&
569 MRegisterInfo::isVirtualRegister(reg));
572 // An example for liveAt():
574 // this = [1,4), liveAt(0) will return false. The instruction defining
575 // this spans slots [0,3]. The interval belongs to an spilled
576 // definition of the variable it represents. This is because slot 1 is
577 // used (def slot) and spans up to slot 3 (store slot).
579 bool LiveIntervals::Interval::liveAt(unsigned index) const
581 Range dummy(index, index+1);
582 Ranges::const_iterator r = std::upper_bound(ranges.begin(),
585 if (r == ranges.begin())
589 return index >= r->first && index < r->second;
592 // An example for overlaps():
596 // 8: C = A + B ;; last use of A
598 // The live intervals should look like:
604 // A->overlaps(C) should return false since we want to be able to join
606 bool LiveIntervals::Interval::overlaps(const Interval& other) const
608 Ranges::const_iterator i = ranges.begin();
609 Ranges::const_iterator ie = ranges.end();
610 Ranges::const_iterator j = other.ranges.begin();
611 Ranges::const_iterator je = other.ranges.end();
612 if (i->first < j->first) {
613 i = std::upper_bound(i, ie, *j);
614 if (i != ranges.begin()) --i;
616 else if (j->first < i->first) {
617 j = std::upper_bound(j, je, *i);
618 if (j != other.ranges.begin()) --j;
621 while (i != ie && j != je) {
622 if (i->first == j->first) {
626 if (i->first > j->first) {
630 assert(i->first < j->first);
632 if (i->second > j->first) {
644 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
646 assert(start < end && "Invalid range to add!");
647 DEBUG(std::cerr << " +[" << start << ',' << end << ")");
648 //assert(start < end && "invalid range?");
649 Range range = std::make_pair(start, end);
650 Ranges::iterator it =
651 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
654 it = mergeRangesForward(it);
655 it = mergeRangesBackward(it);
658 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
660 DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other << '\n');
661 Ranges::iterator cur = ranges.begin();
663 for (Ranges::const_iterator i = other.ranges.begin(),
664 e = other.ranges.end(); i != e; ++i) {
665 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
666 cur = mergeRangesForward(cur);
667 cur = mergeRangesBackward(cur);
669 weight += other.weight;
671 std::set_union(defs.begin(), defs.end(),
672 other.defs.begin(), other.defs.end(),
673 std::back_inserter(u));
678 LiveIntervals::Interval::Ranges::iterator
679 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
682 while ((n = next(it)) != ranges.end()) {
683 if (n->first > it->second)
685 it->second = std::max(it->second, n->second);
691 LiveIntervals::Interval::Ranges::iterator
692 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
694 while (it != ranges.begin()) {
695 Ranges::iterator p = prior(it);
696 if (it->first > p->second)
699 it->first = std::min(it->first, p->first);
700 it->second = std::max(it->second, p->second);
701 it = ranges.erase(p);
707 std::ostream& llvm::operator<<(std::ostream& os,
708 const LiveIntervals::Interval& li)
710 os << "%reg" << li.reg << ',' << li.weight;
712 return os << "EMPTY";
714 os << " {" << li.defs.front();
715 for (LiveIntervals::Interval::Defs::const_iterator
716 i = next(li.defs.begin()), e = li.defs.end(); i != e; ++i)
721 for (LiveIntervals::Interval::Ranges::const_iterator
722 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
723 os << "[" << i->first << "," << i->second << ")";