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/Value.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.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"
40 RegisterAnalysis<LiveIntervals> X("liveintervals",
41 "Live Interval Analysis");
43 Statistic<> numIntervals
44 ("liveintervals", "Number of original intervals");
46 Statistic<> numIntervalsAfter
47 ("liveintervals", "Number of intervals after coalescing");
50 ("liveintervals", "Number of interval joins performed");
53 ("liveintervals", "Number of identity moves eliminated after coalescing");
56 ("liveintervals", "Number of loads/stores folded into instructions");
59 EnableJoining("join-liveintervals",
60 cl::desc("Join compatible live intervals"),
64 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
66 AU.addPreserved<LiveVariables>();
67 AU.addRequired<LiveVariables>();
68 AU.addPreservedID(PHIEliminationID);
69 AU.addRequiredID(PHIEliminationID);
70 AU.addRequiredID(TwoAddressInstructionPassID);
71 AU.addRequired<LoopInfo>();
72 MachineFunctionPass::getAnalysisUsage(AU);
75 void LiveIntervals::releaseMemory()
85 /// runOnMachineFunction - Register allocate the whole function
87 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
89 tm_ = &fn.getTarget();
90 mri_ = tm_->getRegisterInfo();
91 lv_ = &getAnalysis<LiveVariables>();
93 // number MachineInstrs
95 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
97 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
99 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
100 assert(inserted && "multiple MachineInstr -> index mappings");
101 i2miMap_.push_back(mi);
102 miIndex += InstrSlots::NUM;
107 numIntervals += intervals_.size();
109 // join intervals if requested
110 if (EnableJoining) joinIntervals();
112 numIntervalsAfter += intervals_.size();
114 // perform a final pass over the instructions and compute spill
115 // weights, coalesce virtual registers and remove identity moves
116 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
117 const TargetInstrInfo& tii = *tm_->getInstrInfo();
119 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
120 mbbi != mbbe; ++mbbi) {
121 MachineBasicBlock* mbb = mbbi;
122 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
124 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
126 // if the move will be an identity move delete it
127 unsigned srcReg, dstReg;
128 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
129 rep(srcReg) == rep(dstReg)) {
130 // remove from def list
131 LiveInterval& interval = getOrCreateInterval(rep(dstReg));
132 // remove index -> MachineInstr and
133 // MachineInstr -> index mappings
134 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
135 if (mi2i != mi2iMap_.end()) {
136 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
137 mi2iMap_.erase(mi2i);
139 mii = mbbi->erase(mii);
143 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
144 const MachineOperand& mop = mii->getOperand(i);
145 if (mop.isRegister() && mop.getReg() &&
146 MRegisterInfo::isVirtualRegister(mop.getReg())) {
147 // replace register with representative register
148 unsigned reg = rep(mop.getReg());
149 mii->SetMachineOperandReg(i, reg);
151 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
152 assert(r2iit != r2iMap_.end());
153 r2iit->second->weight +=
154 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
162 DEBUG(std::cerr << "********** INTERVALS **********\n");
163 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
164 std::ostream_iterator<LiveInterval>(std::cerr, "\n")));
165 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
167 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
168 mbbi != mbbe; ++mbbi) {
169 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
170 for (MachineBasicBlock::iterator mii = mbbi->begin(),
171 mie = mbbi->end(); mii != mie; ++mii) {
172 std::cerr << getInstructionIndex(mii) << '\t';
173 mii->print(std::cerr, tm_);
180 std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
181 const LiveInterval& li,
185 std::vector<LiveInterval*> added;
187 assert(li.weight != HUGE_VAL &&
188 "attempt to spill already spilled interval!");
190 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
193 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
195 for (LiveInterval::Ranges::const_iterator
196 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
197 unsigned index = getBaseIndex(i->start);
198 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
199 for (; index != end; index += InstrSlots::NUM) {
200 // skip deleted instructions
201 while (index != end && !getInstructionFromIndex(index))
202 index += InstrSlots::NUM;
203 if (index == end) break;
205 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
208 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
209 MachineOperand& mop = mi->getOperand(i);
210 if (mop.isRegister() && mop.getReg() == li.reg) {
211 if (MachineInstr* fmi =
212 mri_->foldMemoryOperand(mi, i, slot)) {
213 lv_->instructionChanged(mi, fmi);
214 vrm.virtFolded(li.reg, mi, fmi);
216 i2miMap_[index/InstrSlots::NUM] = fmi;
217 mi2iMap_[fmi] = index;
218 MachineBasicBlock& mbb = *mi->getParent();
219 mi = mbb.insert(mbb.erase(mi), fmi);
224 // This is tricky. We need to add information in
225 // the interval about the spill code so we have to
226 // use our extra load/store slots.
228 // If we have a use we are going to have a load so
229 // we start the interval from the load slot
230 // onwards. Otherwise we start from the def slot.
231 unsigned start = (mop.isUse() ?
232 getLoadIndex(index) :
234 // If we have a def we are going to have a store
235 // right after it so we end the interval after the
236 // use of the next instruction. Otherwise we end
237 // after the use of this instruction.
238 unsigned end = 1 + (mop.isDef() ?
239 getStoreIndex(index) :
242 // create a new register for this spill
244 mf_->getSSARegMap()->createVirtualRegister(rc);
245 mi->SetMachineOperandReg(i, nReg);
247 vrm.assignVirt2StackSlot(nReg, slot);
248 LiveInterval& nI = getOrCreateInterval(nReg);
250 // the spill weight is now infinity as it
251 // cannot be spilled again
252 nI.weight = HUGE_VAL;
253 DEBUG(std::cerr << " +" << LiveRange(start, end));
254 nI.addRange(LiveRange(start, end));
255 added.push_back(&nI);
256 // update live variables
257 lv_->addVirtualRegisterKilled(nReg, mi);
258 DEBUG(std::cerr << "\t\t\t\tadded new interval: "
269 void LiveIntervals::printRegName(unsigned reg) const
271 if (MRegisterInfo::isPhysicalRegister(reg))
272 std::cerr << mri_->getName(reg);
274 std::cerr << "%reg" << reg;
277 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
278 MachineBasicBlock::iterator mi,
279 LiveInterval& interval)
281 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
282 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
284 // Virtual registers may be defined multiple times (due to phi
285 // elimination and 2-addr elimination). Much of what we do only has to be
286 // done once for the vreg. We use an empty interval to detect the first
287 // time we see a vreg.
288 if (interval.empty()) {
289 // Assume this interval is singly defined until we find otherwise.
290 interval.isDefinedOnce = true;
292 // Get the Idx of the defining instructions.
293 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
295 // Loop over all of the blocks that the vreg is defined in. There are
296 // two cases we have to handle here. The most common case is a vreg
297 // whose lifetime is contained within a basic block. In this case there
298 // will be a single kill, in MBB, which comes after the definition.
299 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
300 // FIXME: what about dead vars?
302 if (vi.Kills[0] != mi)
303 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
305 killIdx = defIndex+1;
307 // If the kill happens after the definition, we have an intra-block
309 if (killIdx > defIndex) {
310 assert(vi.AliveBlocks.empty() &&
311 "Shouldn't be alive across any blocks!");
312 interval.addRange(LiveRange(defIndex, killIdx));
313 DEBUG(std::cerr << " +" << LiveRange(defIndex, killIdx) << "\n");
318 // The other case we handle is when a virtual register lives to the end
319 // of the defining block, potentially live across some blocks, then is
320 // live into some number of blocks, but gets killed. Start by adding a
321 // range that goes from this definition to the end of the defining block.
322 LiveRange NewLR(defIndex, getInstructionIndex(&mbb->back()) +
324 DEBUG(std::cerr << " +" << NewLR);
325 interval.addRange(NewLR);
327 // Iterate over all of the blocks that the variable is completely
328 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
330 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
331 if (vi.AliveBlocks[i]) {
332 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
334 LiveRange LR(getInstructionIndex(&mbb->front()),
335 getInstructionIndex(&mbb->back())+InstrSlots::NUM);
336 interval.addRange(LR);
337 DEBUG(std::cerr << " +" << LR);
342 // Finally, this virtual register is live from the start of any killing
343 // block to the 'use' slot of the killing instruction.
344 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
345 MachineInstr *Kill = vi.Kills[i];
346 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
347 getUseIndex(getInstructionIndex(Kill))+1);
348 interval.addRange(LR);
349 DEBUG(std::cerr << " +" << LR);
353 // If this is the second time we see a virtual register definition, it
354 // must be due to phi elimination or two addr elimination. If this is
355 // the result of two address elimination, then the vreg is the first
356 // operand, and is a def-and-use.
357 if (mi->getOperand(0).isRegister() &&
358 mi->getOperand(0).getReg() == interval.reg &&
359 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
360 // If this is a two-address definition, just ignore it.
362 // Otherwise, this must be because of phi elimination. In this case,
363 // the defined value will be live until the end of the basic block it
365 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
366 LiveRange LR(defIndex,
367 getInstructionIndex(&mbb->back()) +InstrSlots::NUM);
368 interval.addRange(LR);
369 DEBUG(std::cerr << " +" << LR);
371 interval.isDefinedOnce = false;
374 DEBUG(std::cerr << '\n');
377 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
378 MachineBasicBlock::iterator mi,
379 LiveInterval& interval)
381 // A physical register cannot be live across basic block, so its
382 // lifetime must end somewhere in its defining basic block.
383 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
384 typedef LiveVariables::killed_iterator KillIter;
386 MachineBasicBlock::iterator e = mbb->end();
387 unsigned baseIndex = getInstructionIndex(mi);
388 unsigned start = getDefIndex(baseIndex);
389 unsigned end = start;
391 // If it is not used after definition, it is considered dead at
392 // the instruction defining it. Hence its interval is:
393 // [defSlot(def), defSlot(def)+1)
394 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
396 if (interval.reg == ki->second) {
397 DEBUG(std::cerr << " dead");
398 end = getDefIndex(start) + 1;
403 // If it is not dead on definition, it must be killed by a
404 // subsequent instruction. Hence its interval is:
405 // [defSlot(def), useSlot(kill)+1)
408 baseIndex += InstrSlots::NUM;
409 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
411 if (interval.reg == ki->second) {
412 DEBUG(std::cerr << " killed");
413 end = getUseIndex(baseIndex) + 1;
420 assert(start < end && "did not find end of interval?");
421 interval.addRange(LiveRange(start, end));
422 DEBUG(std::cerr << " +" << LiveRange(start, end) << '\n');
425 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
426 MachineBasicBlock::iterator mi,
429 if (MRegisterInfo::isPhysicalRegister(reg)) {
430 if (lv_->getAllocatablePhysicalRegisters()[reg]) {
431 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
432 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
433 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
437 handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
440 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
442 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
443 return (it == mi2iMap_.end() ?
444 std::numeric_limits<unsigned>::max() :
448 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
450 index /= InstrSlots::NUM; // convert index to vector index
451 assert(index < i2miMap_.size() &&
452 "index does not correspond to an instruction");
453 return i2miMap_[index];
456 /// computeIntervals - computes the live intervals for virtual
457 /// registers. for some ordering of the machine instructions [1,N] a
458 /// live interval is an interval [i, j) where 1 <= i <= j < N for
459 /// which a variable is live
460 void LiveIntervals::computeIntervals()
462 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
463 DEBUG(std::cerr << "********** Function: "
464 << ((Value*)mf_->getFunction())->getName() << '\n');
466 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
468 MachineBasicBlock* mbb = I;
469 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
471 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
473 const TargetInstrDescriptor& tid =
474 tm_->getInstrInfo()->get(mi->getOpcode());
475 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
476 mi->print(std::cerr, tm_));
478 // handle implicit defs
479 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
480 handleRegisterDef(mbb, mi, *id);
482 // handle explicit defs
483 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
484 MachineOperand& mop = mi->getOperand(i);
485 // handle register defs - build intervals
486 if (mop.isRegister() && mop.getReg() && mop.isDef())
487 handleRegisterDef(mbb, mi, mop.getReg());
493 unsigned LiveIntervals::rep(unsigned reg)
495 Reg2RegMap::iterator it = r2rMap_.find(reg);
496 if (it != r2rMap_.end())
497 return it->second = rep(it->second);
501 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
502 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
503 const TargetInstrInfo& tii = *tm_->getInstrInfo();
505 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
507 const TargetInstrDescriptor& tid = tii.get(mi->getOpcode());
508 DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
509 mi->print(std::cerr, tm_););
511 // we only join virtual registers with allocatable
512 // physical registers since we do not have liveness information
513 // on not allocatable physical registers
515 if (tii.isMoveInstr(*mi, regA, regB) &&
516 (MRegisterInfo::isVirtualRegister(regA) ||
517 lv_->getAllocatablePhysicalRegisters()[regA]) &&
518 (MRegisterInfo::isVirtualRegister(regB) ||
519 lv_->getAllocatablePhysicalRegisters()[regB])) {
521 // get representative registers
525 // if they are already joined we continue
529 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
530 assert(r2iA != r2iMap_.end() &&
531 "Found unknown vreg in 'isMoveInstr' instruction");
532 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
533 assert(r2iB != r2iMap_.end() &&
534 "Found unknown vreg in 'isMoveInstr' instruction");
536 Intervals::iterator intA = r2iA->second;
537 Intervals::iterator intB = r2iB->second;
539 DEBUG(std::cerr << "\t\tInspecting " << *intA << " and " << *intB
542 // both A and B are virtual registers
543 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
544 MRegisterInfo::isVirtualRegister(intB->reg)) {
546 const TargetRegisterClass *rcA, *rcB;
547 rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
548 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
550 // if they are not of the same register class we continue
552 DEBUG(std::cerr << "Differing reg classes.\n");
556 // if their intervals do not overlap we join them.
557 if ((intA->containsOneValue() && intB->containsOneValue()) ||
558 !intB->overlaps(*intA)) {
561 DEBUG(std::cerr << "Joined. Result = " << *intA << "\n");
562 r2iB->second = r2iA->second;
563 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
564 intervals_.erase(intB);
566 DEBUG(std::cerr << "Interference!\n");
568 } else if (!MRegisterInfo::isPhysicalRegister(intA->reg) ||
569 !MRegisterInfo::isPhysicalRegister(intB->reg)) {
570 if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
571 std::swap(regA, regB);
572 std::swap(intA, intB);
573 std::swap(r2iA, r2iB);
576 assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
577 MRegisterInfo::isVirtualRegister(intB->reg) &&
578 "A must be physical and B must be virtual");
580 const TargetRegisterClass *rcA, *rcB;
581 rcA = mri_->getRegClass(intA->reg);
582 rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
583 // if they are not of the same register class we continue
585 DEBUG(std::cerr << "Differing reg classes.\n");
589 if (!intA->overlaps(*intB) &&
590 !overlapsAliases(*intA, *intB)) {
593 DEBUG(std::cerr << "Joined. Result = " << *intA << "\n");
594 r2iB->second = r2iA->second;
595 r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
596 intervals_.erase(intB);
598 DEBUG(std::cerr << "Interference!\n");
601 DEBUG(std::cerr << "Cannot join physregs.\n");
608 // DepthMBBCompare - Comparison predicate that sort first based on the loop
609 // depth of the basic block (the unsigned), and then on the MBB number.
610 struct DepthMBBCompare {
611 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
612 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
613 if (LHS.first > RHS.first) return true; // Deeper loops first
614 return LHS.first == RHS.first &&
615 LHS.second->getNumber() < RHS.second->getNumber();
620 void LiveIntervals::joinIntervals() {
621 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
623 const LoopInfo &LI = getAnalysis<LoopInfo>();
624 if (LI.begin() == LI.end()) {
625 // If there are no loops in the function, join intervals in function order.
626 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
628 joinIntervalsInMachineBB(I);
630 // Otherwise, join intervals in inner loops before other intervals.
631 // Unfortunately we can't just iterate over loop hierarchy here because
632 // there may be more MBB's than BB's. Collect MBB's for sorting.
633 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
634 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
636 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
638 // Sort by loop depth.
639 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
641 // Finally, join intervals in loop nest order.
642 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
643 joinIntervalsInMachineBB(MBBs[i].second);
647 bool LiveIntervals::overlapsAliases(const LiveInterval& lhs,
648 const LiveInterval& rhs) const
650 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
651 "first interval must describe a physical register");
653 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
654 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
655 assert(r2i != r2iMap_.end() && "alias does not have interval?");
656 if (rhs.overlaps(*r2i->second))
663 LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg)
665 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
666 if (r2iit == r2iMap_.end() || r2iit->first != reg) {
667 float Weight = MRegisterInfo::isPhysicalRegister(reg) ? HUGE_VAL :0.0F;
668 intervals_.push_back(LiveInterval(reg, Weight));
669 r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
672 return *r2iit->second;