1 //===-- LiveIntervalAnalysis.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 "LiveIntervalAnalysis.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
40 RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
42 Statistic<> numIntervals
43 ("liveintervals", "Number of original intervals");
45 Statistic<> numIntervalsAfter
46 ("liveintervals", "Number of intervals after coalescing");
49 ("liveintervals", "Number of interval joins performed");
52 ("liveintervals", "Number of identity moves eliminated after coalescing");
55 ("liveintervals", "Number of loads/stores folded into instructions");
58 EnableJoining("join-liveintervals",
59 cl::desc("Join compatible live intervals"),
63 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
65 AU.addRequired<LiveVariables>();
66 AU.addPreservedID(PHIEliminationID);
67 AU.addRequiredID(PHIEliminationID);
68 AU.addRequiredID(TwoAddressInstructionPassID);
69 AU.addRequired<LoopInfo>();
70 MachineFunctionPass::getAnalysisUsage(AU);
73 void LiveIntervals::releaseMemory()
82 /// runOnMachineFunction - Register allocate the whole function
84 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
86 tm_ = &fn.getTarget();
87 mri_ = tm_->getRegisterInfo();
88 tii_ = tm_->getInstrInfo();
89 lv_ = &getAnalysis<LiveVariables>();
90 allocatableRegs_ = mri_->getAllocatableSet(fn);
91 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
93 // If this function has any live ins, insert a dummy instruction at the
94 // beginning of the function that we will pretend "defines" the values. This
95 // is to make the interval analysis simpler by providing a number.
96 if (fn.livein_begin() != fn.livein_end()) {
97 unsigned FirstLiveIn = fn.livein_begin()->first;
99 // Find a reg class that contains this live in.
100 const TargetRegisterClass *RC = 0;
101 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
102 E = mri_->regclass_end(); RCI != E; ++RCI)
103 if ((*RCI)->contains(FirstLiveIn)) {
108 MachineInstr *OldFirstMI = fn.begin()->begin();
109 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
110 FirstLiveIn, FirstLiveIn, RC);
111 assert(OldFirstMI != fn.begin()->begin() &&
112 "copyRetToReg didn't insert anything!");
115 // number MachineInstrs
116 unsigned miIndex = 0;
117 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
118 mbb != mbbEnd; ++mbb)
119 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
121 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
122 assert(inserted && "multiple MachineInstr -> index mappings");
123 i2miMap_.push_back(mi);
124 miIndex += InstrSlots::NUM;
127 // Note intervals due to live-in values.
128 if (fn.livein_begin() != fn.livein_end()) {
129 MachineBasicBlock *Entry = fn.begin();
130 for (MachineFunction::livein_iterator I = fn.livein_begin(),
131 E = fn.livein_end(); I != E; ++I) {
132 handlePhysicalRegisterDef(Entry, Entry->begin(),
133 getOrCreateInterval(I->first), 0, 0, true);
134 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
135 handlePhysicalRegisterDef(Entry, Entry->begin(),
136 getOrCreateInterval(*AS), 0, 0, true);
142 numIntervals += getNumIntervals();
144 DEBUG(std::cerr << "********** INTERVALS **********\n";
145 for (iterator I = begin(), E = end(); I != E; ++I) {
146 I->second.print(std::cerr, mri_);
150 // join intervals if requested
151 if (EnableJoining) joinIntervals();
153 numIntervalsAfter += getNumIntervals();
155 // perform a final pass over the instructions and compute spill
156 // weights, coalesce virtual registers and remove identity moves
157 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
159 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
160 mbbi != mbbe; ++mbbi) {
161 MachineBasicBlock* mbb = mbbi;
162 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
164 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
166 // if the move will be an identity move delete it
167 unsigned srcReg, dstReg, RegRep;
168 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
169 (RegRep = rep(srcReg)) == rep(dstReg)) {
170 // remove from def list
171 LiveInterval &interval = getOrCreateInterval(RegRep);
172 // remove index -> MachineInstr and
173 // MachineInstr -> index mappings
174 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
175 if (mi2i != mi2iMap_.end()) {
176 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
177 mi2iMap_.erase(mi2i);
179 mii = mbbi->erase(mii);
183 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
184 const MachineOperand& mop = mii->getOperand(i);
185 if (mop.isRegister() && mop.getReg() &&
186 MRegisterInfo::isVirtualRegister(mop.getReg())) {
187 // replace register with representative register
188 unsigned reg = rep(mop.getReg());
189 mii->SetMachineOperandReg(i, reg);
191 LiveInterval &RegInt = getInterval(reg);
193 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
205 /// print - Implement the dump method.
206 void LiveIntervals::print(std::ostream &O, const Module* ) const {
207 O << "********** INTERVALS **********\n";
208 for (const_iterator I = begin(), E = end(); I != E; ++I) {
209 I->second.print(std::cerr, mri_);
213 O << "********** MACHINEINSTRS **********\n";
214 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
215 mbbi != mbbe; ++mbbi) {
216 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
217 for (MachineBasicBlock::iterator mii = mbbi->begin(),
218 mie = mbbi->end(); mii != mie; ++mii) {
219 O << getInstructionIndex(mii) << '\t' << *mii;
224 std::vector<LiveInterval*> LiveIntervals::
225 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
226 // since this is called after the analysis is done we don't know if
227 // LiveVariables is available
228 lv_ = getAnalysisToUpdate<LiveVariables>();
230 std::vector<LiveInterval*> added;
232 assert(li.weight != HUGE_VAL &&
233 "attempt to spill already spilled interval!");
235 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
238 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
240 for (LiveInterval::Ranges::const_iterator
241 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
242 unsigned index = getBaseIndex(i->start);
243 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
244 for (; index != end; index += InstrSlots::NUM) {
245 // skip deleted instructions
246 while (index != end && !getInstructionFromIndex(index))
247 index += InstrSlots::NUM;
248 if (index == end) break;
250 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
253 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
254 MachineOperand& mop = mi->getOperand(i);
255 if (mop.isRegister() && mop.getReg() == li.reg) {
256 // First thing, attempt to fold the memory reference into the
257 // instruction. If we can do this, we don't need to insert spill
259 if (MachineInstr* fmi = mri_->foldMemoryOperand(mi, i, slot)) {
261 lv_->instructionChanged(mi, fmi);
262 vrm.virtFolded(li.reg, mi, i, fmi);
264 i2miMap_[index/InstrSlots::NUM] = fmi;
265 mi2iMap_[fmi] = index;
266 MachineBasicBlock &MBB = *mi->getParent();
267 mi = MBB.insert(MBB.erase(mi), fmi);
270 // Folding the load/store can completely change the instruction in
271 // unpredictable ways, rescan it from the beginning.
274 // This is tricky. We need to add information in the interval about
275 // the spill code so we have to use our extra load/store slots.
277 // If we have a use we are going to have a load so we start the
278 // interval from the load slot onwards. Otherwise we start from the
280 unsigned start = (mop.isUse() ?
281 getLoadIndex(index) :
283 // If we have a def we are going to have a store right after it so
284 // we end the interval after the use of the next
285 // instruction. Otherwise we end after the use of this instruction.
286 unsigned end = 1 + (mop.isDef() ?
287 getStoreIndex(index) :
290 // create a new register for this spill
291 unsigned nReg = mf_->getSSARegMap()->createVirtualRegister(rc);
292 mi->SetMachineOperandReg(i, nReg);
294 vrm.assignVirt2StackSlot(nReg, slot);
295 LiveInterval& nI = getOrCreateInterval(nReg);
298 // the spill weight is now infinity as it
299 // cannot be spilled again
300 nI.weight = float(HUGE_VAL);
301 LiveRange LR(start, end, nI.getNextValue());
302 DEBUG(std::cerr << " +" << LR);
304 added.push_back(&nI);
306 // update live variables if it is available
308 lv_->addVirtualRegisterKilled(nReg, mi);
309 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
319 void LiveIntervals::printRegName(unsigned reg) const
321 if (MRegisterInfo::isPhysicalRegister(reg))
322 std::cerr << mri_->getName(reg);
324 std::cerr << "%reg" << reg;
327 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
328 MachineBasicBlock::iterator mi,
329 LiveInterval& interval)
331 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
332 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
334 // Virtual registers may be defined multiple times (due to phi
335 // elimination and 2-addr elimination). Much of what we do only has to be
336 // done once for the vreg. We use an empty interval to detect the first
337 // time we see a vreg.
338 if (interval.empty()) {
339 // Get the Idx of the defining instructions.
340 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
342 unsigned ValNum = interval.getNextValue();
343 assert(ValNum == 0 && "First value in interval is not 0?");
344 ValNum = 0; // Clue in the optimizer.
346 // Loop over all of the blocks that the vreg is defined in. There are
347 // two cases we have to handle here. The most common case is a vreg
348 // whose lifetime is contained within a basic block. In this case there
349 // will be a single kill, in MBB, which comes after the definition.
350 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
351 // FIXME: what about dead vars?
353 if (vi.Kills[0] != mi)
354 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
356 killIdx = defIndex+1;
358 // If the kill happens after the definition, we have an intra-block
360 if (killIdx > defIndex) {
361 assert(vi.AliveBlocks.empty() &&
362 "Shouldn't be alive across any blocks!");
363 LiveRange LR(defIndex, killIdx, ValNum);
364 interval.addRange(LR);
365 DEBUG(std::cerr << " +" << LR << "\n");
370 // The other case we handle is when a virtual register lives to the end
371 // of the defining block, potentially live across some blocks, then is
372 // live into some number of blocks, but gets killed. Start by adding a
373 // range that goes from this definition to the end of the defining block.
374 LiveRange NewLR(defIndex,
375 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
377 DEBUG(std::cerr << " +" << NewLR);
378 interval.addRange(NewLR);
380 // Iterate over all of the blocks that the variable is completely
381 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
383 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
384 if (vi.AliveBlocks[i]) {
385 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
387 LiveRange LR(getInstructionIndex(&mbb->front()),
388 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
390 interval.addRange(LR);
391 DEBUG(std::cerr << " +" << LR);
396 // Finally, this virtual register is live from the start of any killing
397 // block to the 'use' slot of the killing instruction.
398 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
399 MachineInstr *Kill = vi.Kills[i];
400 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
401 getUseIndex(getInstructionIndex(Kill))+1,
403 interval.addRange(LR);
404 DEBUG(std::cerr << " +" << LR);
408 // If this is the second time we see a virtual register definition, it
409 // must be due to phi elimination or two addr elimination. If this is
410 // the result of two address elimination, then the vreg is the first
411 // operand, and is a def-and-use.
412 if (mi->getOperand(0).isRegister() &&
413 mi->getOperand(0).getReg() == interval.reg &&
414 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
415 // If this is a two-address definition, then we have already processed
416 // the live range. The only problem is that we didn't realize there
417 // are actually two values in the live interval. Because of this we
418 // need to take the LiveRegion that defines this register and split it
420 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
421 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
423 // Delete the initial value, which should be short and continuous,
424 // becuase the 2-addr copy must be in the same MBB as the redef.
425 interval.removeRange(DefIndex, RedefIndex);
427 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
428 DEBUG(std::cerr << " replace range with " << LR);
429 interval.addRange(LR);
431 // If this redefinition is dead, we need to add a dummy unit live
432 // range covering the def slot.
433 if (lv_->RegisterDefIsDead(mi, interval.reg))
434 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
436 DEBUG(std::cerr << "RESULT: " << interval);
439 // Otherwise, this must be because of phi elimination. If this is the
440 // first redefinition of the vreg that we have seen, go back and change
441 // the live range in the PHI block to be a different value number.
442 if (interval.containsOneValue()) {
443 assert(vi.Kills.size() == 1 &&
444 "PHI elimination vreg should have one kill, the PHI itself!");
446 // Remove the old range that we now know has an incorrect number.
447 MachineInstr *Killer = vi.Kills[0];
448 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
449 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
450 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
451 << interval << "\n");
452 interval.removeRange(Start, End);
453 DEBUG(std::cerr << "RESULT: " << interval);
455 // Replace the interval with one of a NEW value number.
456 LiveRange LR(Start, End, interval.getNextValue());
457 DEBUG(std::cerr << " replace range with " << LR);
458 interval.addRange(LR);
459 DEBUG(std::cerr << "RESULT: " << interval);
462 // In the case of PHI elimination, each variable definition is only
463 // live until the end of the block. We've already taken care of the
464 // rest of the live range.
465 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
466 LiveRange LR(defIndex,
467 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
468 interval.getNextValue());
469 interval.addRange(LR);
470 DEBUG(std::cerr << " +" << LR);
474 DEBUG(std::cerr << '\n');
477 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
478 MachineBasicBlock::iterator mi,
479 LiveInterval& interval,
480 unsigned SrcReg, unsigned DestReg,
483 // A physical register cannot be live across basic block, so its
484 // lifetime must end somewhere in its defining basic block.
485 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
486 typedef LiveVariables::killed_iterator KillIter;
488 unsigned baseIndex = getInstructionIndex(mi);
489 unsigned start = getDefIndex(baseIndex);
490 unsigned end = start;
492 // If it is not used after definition, it is considered dead at
493 // the instruction defining it. Hence its interval is:
494 // [defSlot(def), defSlot(def)+1)
495 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
496 DEBUG(std::cerr << " dead");
497 end = getDefIndex(start) + 1;
501 // If it is not dead on definition, it must be killed by a
502 // subsequent instruction. Hence its interval is:
503 // [defSlot(def), useSlot(kill)+1)
504 while (++mi != MBB->end()) {
505 baseIndex += InstrSlots::NUM;
506 if (lv_->KillsRegister(mi, interval.reg)) {
507 DEBUG(std::cerr << " killed");
508 end = getUseIndex(baseIndex) + 1;
513 // The only case we should have a dead physreg here without a killing or
514 // instruction where we know it's dead is if it is live-in to the function
516 assert(isLiveIn && "physreg was not killed in defining block!");
517 end = getDefIndex(start) + 1; // It's dead.
520 assert(start < end && "did not find end of interval?");
522 // Finally, if this is defining a new range for the physical register, and if
523 // that physreg is just a copy from a vreg, and if THAT vreg was a copy from
524 // the physreg, then the new fragment has the same value as the one copied
526 if (interval.reg == DestReg && !interval.empty() &&
527 MRegisterInfo::isVirtualRegister(SrcReg)) {
529 // Get the live interval for the vreg, see if it is defined by a copy.
530 LiveInterval &SrcInterval = getOrCreateInterval(SrcReg);
532 if (SrcInterval.containsOneValue()) {
533 assert(!SrcInterval.empty() && "Can't contain a value and be empty!");
535 // Get the first index of the first range. Though the interval may have
536 // multiple liveranges in it, we only check the first.
537 unsigned StartIdx = SrcInterval.begin()->start;
538 MachineInstr *SrcDefMI = getInstructionFromIndex(StartIdx);
540 // Check to see if the vreg was defined by a copy instruction, and that
541 // the source was this physreg.
542 unsigned VRegSrcSrc, VRegSrcDest;
543 if (tii_->isMoveInstr(*SrcDefMI, VRegSrcSrc, VRegSrcDest) &&
544 SrcReg == VRegSrcDest && VRegSrcSrc == DestReg) {
545 // Okay, now we know that the vreg was defined by a copy from this
546 // physreg. Find the value number being copied and use it as the value
548 const LiveRange *DefRange = interval.getLiveRangeContaining(StartIdx-1);
550 LiveRange LR(start, end, DefRange->ValId);
551 interval.addRange(LR);
552 DEBUG(std::cerr << " +" << LR << '\n');
560 LiveRange LR(start, end, interval.getNextValue());
561 interval.addRange(LR);
562 DEBUG(std::cerr << " +" << LR << '\n');
565 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
566 MachineBasicBlock::iterator MI,
568 if (MRegisterInfo::isVirtualRegister(reg))
569 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
570 else if (allocatableRegs_[reg]) {
571 unsigned SrcReg = 0, DestReg = 0;
572 bool IsMove = tii_->isMoveInstr(*MI, SrcReg, DestReg);
574 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg),
576 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
577 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS),
582 /// computeIntervals - computes the live intervals for virtual
583 /// registers. for some ordering of the machine instructions [1,N] a
584 /// live interval is an interval [i, j) where 1 <= i <= j < N for
585 /// which a variable is live
586 void LiveIntervals::computeIntervals()
588 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
589 DEBUG(std::cerr << "********** Function: "
590 << ((Value*)mf_->getFunction())->getName() << '\n');
591 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
593 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
595 MachineBasicBlock* mbb = I;
596 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
598 MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
599 if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
600 for (; mi != miEnd; ++mi) {
601 const TargetInstrDescriptor& tid =
602 tm_->getInstrInfo()->get(mi->getOpcode());
603 DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
605 // handle implicit defs
606 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
607 handleRegisterDef(mbb, mi, *id);
609 // handle explicit defs
610 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
611 MachineOperand& mop = mi->getOperand(i);
612 // handle register defs - build intervals
613 if (mop.isRegister() && mop.getReg() && mop.isDef())
614 handleRegisterDef(mbb, mi, mop.getReg());
620 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
621 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
623 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
625 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
627 // we only join virtual registers with allocatable
628 // physical registers since we do not have liveness information
629 // on not allocatable physical registers
631 if (tii_->isMoveInstr(*mi, regA, regB) &&
632 (MRegisterInfo::isVirtualRegister(regA) || allocatableRegs_[regA]) &&
633 (MRegisterInfo::isVirtualRegister(regB) || allocatableRegs_[regB])) {
635 // Get representative registers.
639 // If they are already joined we continue.
643 // If they are both physical registers, we cannot join them.
644 if (MRegisterInfo::isPhysicalRegister(regA) &&
645 MRegisterInfo::isPhysicalRegister(regB))
648 // If they are not of the same register class, we cannot join them.
649 if (differingRegisterClasses(regA, regB))
652 LiveInterval &IntA = getInterval(regA);
653 LiveInterval &IntB = getInterval(regB);
654 assert(IntA.reg == regA && IntB.reg == regB &&
655 "Register mapping is horribly broken!");
657 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
659 // If two intervals contain a single value and are joined by a copy, it
660 // does not matter if the intervals overlap, they can always be joined.
661 bool TriviallyJoinable =
662 IntA.containsOneValue() && IntB.containsOneValue();
664 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
665 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
666 !overlapsAliases(&IntA, &IntB)) {
667 IntB.join(IntA, MIDefIdx);
668 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
670 if (!MRegisterInfo::isPhysicalRegister(regA)) {
672 r2rMap_[regA] = regB;
674 // Otherwise merge the data structures the other way so we don't lose
675 // the physreg information.
676 r2rMap_[regB] = regA;
683 DEBUG(std::cerr << "Interference!\n");
690 // DepthMBBCompare - Comparison predicate that sort first based on the loop
691 // depth of the basic block (the unsigned), and then on the MBB number.
692 struct DepthMBBCompare {
693 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
694 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
695 if (LHS.first > RHS.first) return true; // Deeper loops first
696 return LHS.first == RHS.first &&
697 LHS.second->getNumber() < RHS.second->getNumber();
702 void LiveIntervals::joinIntervals() {
703 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
705 const LoopInfo &LI = getAnalysis<LoopInfo>();
706 if (LI.begin() == LI.end()) {
707 // If there are no loops in the function, join intervals in function order.
708 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
710 joinIntervalsInMachineBB(I);
712 // Otherwise, join intervals in inner loops before other intervals.
713 // Unfortunately we can't just iterate over loop hierarchy here because
714 // there may be more MBB's than BB's. Collect MBB's for sorting.
715 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
716 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
718 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
720 // Sort by loop depth.
721 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
723 // Finally, join intervals in loop nest order.
724 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
725 joinIntervalsInMachineBB(MBBs[i].second);
728 DEBUG(std::cerr << "*** Register mapping ***\n");
729 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
731 std::cerr << " reg " << i << " -> reg " << r2rMap_[i] << "\n");
734 /// Return true if the two specified registers belong to different register
735 /// classes. The registers may be either phys or virt regs.
736 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
737 unsigned RegB) const {
739 // Get the register classes for the first reg.
740 if (MRegisterInfo::isPhysicalRegister(RegA)) {
741 assert(MRegisterInfo::isVirtualRegister(RegB) &&
742 "Shouldn't consider two physregs!");
743 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
746 // Compare against the regclass for the second reg.
747 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
748 if (MRegisterInfo::isVirtualRegister(RegB))
749 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
751 return !RegClass->contains(RegB);
754 bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
755 const LiveInterval *RHS) const {
756 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
757 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
758 return false; // vreg-vreg merge has no aliases!
762 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
763 MRegisterInfo::isVirtualRegister(RHS->reg) &&
764 "first interval must describe a physical register");
766 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
767 if (RHS->overlaps(getInterval(*AS)))
773 LiveInterval LiveIntervals::createInterval(unsigned reg) {
774 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
775 (float)HUGE_VAL :0.0F;
776 return LiveInterval(reg, Weight);