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 intervals joined");
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());
113 for (MachineBasicBlock::const_iterator mii = mbb->begin(),
114 mie = mbb->end(); mii != mie; ++mii) {
115 MachineInstr* mi = *mii;
117 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
118 MachineOperand& mop = mi->getOperand(i);
120 if (!mop.isVirtualRegister())
123 unsigned reg = mop.getAllocatedRegNum();
124 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
125 assert(r2iit != r2iMap_.end());
126 r2iit->second->weight += pow(10.0F, loopDepth);
132 // join intervals if requested
133 if (join) joinIntervals();
135 numIntervals += intervals_.size();
137 intervals_.sort(StartPointComp());
138 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
139 std::ostream_iterator<Interval>(std::cerr, "\n")));
143 void LiveIntervals::printRegName(unsigned reg) const
145 if (MRegisterInfo::isPhysicalRegister(reg))
146 std::cerr << mri_->getName(reg);
148 std::cerr << '%' << reg;
151 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
152 MachineBasicBlock::iterator mi,
155 DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
157 unsigned instrIndex = getInstructionIndex(*mi);
159 LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
161 Interval* interval = 0;
162 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
163 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
165 intervals_.push_back(Interval(reg));
166 // update interval index for this register
167 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
168 interval = &intervals_.back();
171 interval = &*r2iit->second;
174 // iterate over all of the blocks that the variable is completely
175 // live in, adding them to the live interval
176 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
177 if (vi.AliveBlocks[i]) {
178 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
180 interval->addRange(getInstructionIndex(mbb->front()),
181 getInstructionIndex(mbb->back()) + 1);
186 bool killedInDefiningBasicBlock = false;
187 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
188 MachineBasicBlock* killerBlock = vi.Kills[i].first;
189 MachineInstr* killerInstr = vi.Kills[i].second;
190 unsigned start = (mbb == killerBlock ?
192 getInstructionIndex(killerBlock->front()));
193 unsigned end = getInstructionIndex(killerInstr) + 1;
194 // we do not want to add invalid ranges. these can happen when
195 // a variable has its latest use and is redefined later on in
196 // the same basic block (common with variables introduced by
199 killedInDefiningBasicBlock |= mbb == killerBlock;
200 interval->addRange(start, end);
204 if (!killedInDefiningBasicBlock) {
205 unsigned end = getInstructionIndex(mbb->back()) + 1;
206 interval->addRange(instrIndex, end);
210 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
211 MachineBasicBlock::iterator mi,
214 typedef LiveVariables::killed_iterator KillIter;
216 DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
218 MachineBasicBlock::iterator e = mbb->end();
219 unsigned start = getInstructionIndex(*mi);
220 unsigned end = start + 1;
222 // a variable can be dead by the instruction defining it
223 for (KillIter ki = lv_->dead_begin(*mi), ke = lv_->dead_end(*mi);
225 if (reg == ki->second) {
226 DEBUG(std::cerr << " dead\n");
231 // a variable can only be killed by subsequent instructions
235 for (KillIter ki = lv_->killed_begin(*mi), ke = lv_->killed_end(*mi);
237 if (reg == ki->second) {
238 DEBUG(std::cerr << " killed\n");
245 assert(start < end && "did not find end of interval?");
247 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
248 if (r2iit != r2iMap_.end() && r2iit->first == reg) {
249 r2iit->second->addRange(start, end);
252 intervals_.push_back(Interval(reg));
253 // update interval index for this register
254 r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
255 intervals_.back().addRange(start, end);
259 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
260 MachineBasicBlock::iterator mi,
263 if (MRegisterInfo::isPhysicalRegister(reg)) {
264 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
265 handlePhysicalRegisterDef(mbb, mi, reg);
266 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
267 handlePhysicalRegisterDef(mbb, mi, *as);
271 handleVirtualRegisterDef(mbb, mi, reg);
275 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
277 assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
278 "instruction not assigned a number");
279 return mi2iMap_.find(instr)->second;
282 /// computeIntervals - computes the live intervals for virtual
283 /// registers. for some ordering of the machine instructions [1,N] a
284 /// live interval is an interval [i, j) where 1 <= i <= j < N for
285 /// which a variable is live
286 void LiveIntervals::computeIntervals()
288 DEBUG(std::cerr << "computing live intervals:\n");
290 for (MbbIndex2MbbMap::iterator
291 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
293 MachineBasicBlock* mbb = it->second;
294 DEBUG(std::cerr << "machine basic block: "
295 << mbb->getBasicBlock()->getName() << "\n");
297 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
299 MachineInstr* instr = *mi;
300 const TargetInstrDescriptor& tid =
301 tm_->getInstrInfo().get(instr->getOpcode());
302 DEBUG(std::cerr << "\t[" << getInstructionIndex(instr) << "] ";
303 instr->print(std::cerr, *tm_););
305 // handle implicit defs
306 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
307 handleRegisterDef(mbb, mi, *id);
309 // handle explicit defs
310 for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
311 MachineOperand& mop = instr->getOperand(i);
312 // handle register defs - build intervals
313 if (mop.isRegister() && mop.isDef())
314 handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
320 unsigned LiveIntervals::rep(unsigned reg)
322 Reg2RegMap::iterator it = r2rMap_.find(reg);
323 if (it != r2rMap_.end())
324 return it->second = rep(it->second);
328 void LiveIntervals::joinIntervals()
330 DEBUG(std::cerr << "joining compatible intervals:\n");
332 const TargetInstrInfo& tii = tm_->getInstrInfo();
334 for (MachineFunction::const_iterator mbbi = mf_->begin(),
335 mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
336 const MachineBasicBlock* mbb = mbbi;
337 DEBUG(std::cerr << "machine basic block: "
338 << mbb->getBasicBlock()->getName() << "\n");
340 for (MachineBasicBlock::const_iterator mii = mbb->begin(),
341 mie = mbb->end(); mii != mie; ++mii) {
342 MachineInstr* mi = *mii;
343 const TargetInstrDescriptor& tid =
344 tm_->getInstrInfo().get(mi->getOpcode());
345 DEBUG(std::cerr << "\t\tinstruction["
346 << getInstructionIndex(mi) << "]: ";
347 mi->print(std::cerr, *tm_););
349 // we only join virtual registers with allocatable
350 // physical registers since we do not have liveness information
351 // on not allocatable physical registers
353 if (tii.isMoveInstr(*mi, regA, regB) &&
354 (MRegisterInfo::isVirtualRegister(regA) ||
355 lv_->getAllocatablePhysicalRegisters()[regA]) &&
356 (MRegisterInfo::isVirtualRegister(regB) ||
357 lv_->getAllocatablePhysicalRegisters()[regB])) {
359 // get representative registers
363 // if they are already joined we continue
367 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
368 assert(r2iA != r2iMap_.end());
369 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
370 assert(r2iB != r2iMap_.end());
372 Intervals::iterator intA = r2iA->second;
373 Intervals::iterator intB = r2iB->second;
375 // both A and B are virtual registers
376 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
377 MRegisterInfo::isVirtualRegister(intB->reg)) {
379 const TargetRegisterClass *rcA, *rcB;
380 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
381 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
382 assert(rcA == rcB && "registers must be of the same class");
384 // if their intervals do not overlap we join them
385 if (!intB->overlaps(*intA)) {
387 r2iB->second = r2iA->second;
388 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
389 intervals_.erase(intB);
393 else if (MRegisterInfo::isPhysicalRegister(intA->reg) xor
394 MRegisterInfo::isPhysicalRegister(intB->reg)) {
395 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
396 std::swap(regA, regB);
397 std::swap(intA, intB);
398 std::swap(r2iA, r2iB);
401 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
402 MRegisterInfo::isVirtualRegister(intB->reg) &&
403 "A must be physical and B must be virtual");
404 assert(intA->reg != intB->reg);
405 if (!intA->overlaps(*intB) &&
406 !overlapsAliases(*intA, *intB)) {
408 r2iB->second = r2iA->second;
409 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
410 intervals_.erase(intB);
419 bool LiveIntervals::overlapsAliases(const Interval& lhs,
420 const Interval& rhs) const
422 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
423 "first interval must describe a physical register");
425 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
426 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
427 assert(r2i != r2iMap_.end() && "alias does not have interval?");
428 if (rhs.overlaps(*r2i->second))
435 LiveIntervals::Interval::Interval(unsigned r)
437 weight((MRegisterInfo::isPhysicalRegister(r) ?
438 std::numeric_limits<float>::max() : 0.0F))
443 // This example is provided becaues liveAt() is non-obvious:
445 // this = [1,2), liveAt(1) will return false. The idea is that the
446 // variable is defined in 1 and not live after definition. So it was
447 // dead to begin with (defined but never used).
449 // this = [1,3), liveAt(2) will return false. The variable is used at
450 // 2 but 2 is the last use so the variable's allocated register is
451 // available for reuse.
452 bool LiveIntervals::Interval::liveAt(unsigned index) const
454 Range dummy(index, index+1);
455 Ranges::const_iterator r = std::upper_bound(ranges.begin(),
458 if (r == ranges.begin())
462 return index >= r->first && index < (r->second - 1);
465 // This example is provided because overlaps() is non-obvious:
469 // 2: C = A + B ;; last use of A
471 // The live intervals should look like:
477 // A->overlaps(C) should return false since we want to be able to join
479 bool LiveIntervals::Interval::overlaps(const Interval& other) const
481 Ranges::const_iterator i = ranges.begin();
482 Ranges::const_iterator ie = ranges.end();
483 Ranges::const_iterator j = other.ranges.begin();
484 Ranges::const_iterator je = other.ranges.end();
485 if (i->first < j->first) {
486 i = std::upper_bound(i, ie, *j);
487 if (i != ranges.begin()) --i;
489 else if (j->first < i->first) {
490 j = std::upper_bound(j, je, *i);
491 if (j != other.ranges.begin()) --j;
494 while (i != ie && j != je) {
495 if (i->first == j->first) {
499 if (i->first > j->first) {
503 assert(i->first < j->first);
505 if ((i->second - 1) > j->first) {
517 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
519 assert(start < end && "Invalid range to add!");
520 DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
521 //assert(start < end && "invalid range?");
522 Range range = std::make_pair(start, end);
523 Ranges::iterator it =
524 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
527 it = mergeRangesForward(it);
528 it = mergeRangesBackward(it);
529 DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
532 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
534 DEBUG(std::cerr << "\t\t\t\tjoining intervals: "
535 << other << " and " << *this << '\n');
536 Ranges::iterator cur = ranges.begin();
538 for (Ranges::const_iterator i = other.ranges.begin(),
539 e = other.ranges.end(); i != e; ++i) {
540 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
541 cur = mergeRangesForward(cur);
542 cur = mergeRangesBackward(cur);
544 if (MRegisterInfo::isVirtualRegister(reg))
545 weight += other.weight;
547 DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
550 LiveIntervals::Interval::Ranges::iterator
551 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
553 for (Ranges::iterator next = it + 1;
554 next != ranges.end() && it->second >= next->first; ) {
555 it->second = std::max(it->second, next->second);
556 next = ranges.erase(next);
561 LiveIntervals::Interval::Ranges::iterator
562 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
564 while (it != ranges.begin()) {
565 Ranges::iterator prev = it - 1;
566 if (it->first > prev->second) break;
568 it->first = std::min(it->first, prev->first);
569 it->second = std::max(it->second, prev->second);
570 it = ranges.erase(prev);
576 std::ostream& llvm::operator<<(std::ostream& os,
577 const LiveIntervals::Interval& li)
579 os << "%reg" << li.reg << ',' << li.weight << " = ";
580 for (LiveIntervals::Interval::Ranges::const_iterator
581 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
582 os << "[" << i->first << "," << i->second << ")";