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.addPreserved<LiveVariables>();
66 AU.addRequired<LiveVariables>();
67 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
69 AU.addRequiredID(TwoAddressInstructionPassID);
70 AU.addRequired<LoopInfo>();
71 MachineFunctionPass::getAnalysisUsage(AU);
74 void LiveIntervals::releaseMemory()
83 /// runOnMachineFunction - Register allocate the whole function
85 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
87 tm_ = &fn.getTarget();
88 mri_ = tm_->getRegisterInfo();
89 tii_ = tm_->getInstrInfo();
90 lv_ = &getAnalysis<LiveVariables>();
91 allocatableRegs_ = mri_->getAllocatableSet(fn);
92 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
94 // If this function has any live ins, insert a dummy instruction at the
95 // beginning of the function that we will pretend "defines" the values. This
96 // is to make the interval analysis simpler by providing a number.
97 if (fn.livein_begin() != fn.livein_end()) {
98 unsigned FirstLiveIn = fn.livein_begin()->first;
100 // Find a reg class that contains this live in.
101 const TargetRegisterClass *RC = 0;
102 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
103 E = mri_->regclass_end(); RCI != E; ++RCI)
104 if ((*RCI)->contains(FirstLiveIn)) {
109 MachineInstr *OldFirstMI = fn.begin()->begin();
110 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
111 FirstLiveIn, FirstLiveIn, RC);
112 assert(OldFirstMI != fn.begin()->begin() &&
113 "copyRetToReg didn't insert anything!");
116 // number MachineInstrs
117 unsigned miIndex = 0;
118 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
119 mbb != mbbEnd; ++mbb)
120 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
122 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
123 assert(inserted && "multiple MachineInstr -> index mappings");
124 i2miMap_.push_back(mi);
125 miIndex += InstrSlots::NUM;
128 // Note intervals due to live-in values.
129 if (fn.livein_begin() != fn.livein_end()) {
130 MachineBasicBlock *Entry = fn.begin();
131 for (MachineFunction::livein_iterator I = fn.livein_begin(),
132 E = fn.livein_end(); I != E; ++I) {
133 handlePhysicalRegisterDef(Entry, Entry->begin(),
134 getOrCreateInterval(I->first), 0, 0);
135 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
136 handlePhysicalRegisterDef(Entry, Entry->begin(),
137 getOrCreateInterval(*AS), 0, 0);
143 numIntervals += getNumIntervals();
145 DEBUG(std::cerr << "********** INTERVALS **********\n";
146 for (iterator I = begin(), E = end(); I != E; ++I) {
147 I->second.print(std::cerr, mri_);
151 // join intervals if requested
152 if (EnableJoining) joinIntervals();
154 numIntervalsAfter += getNumIntervals();
156 // perform a final pass over the instructions and compute spill
157 // weights, coalesce virtual registers and remove identity moves
158 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
160 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
161 mbbi != mbbe; ++mbbi) {
162 MachineBasicBlock* mbb = mbbi;
163 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
165 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
167 // if the move will be an identity move delete it
168 unsigned srcReg, dstReg, RegRep;
169 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
170 (RegRep = rep(srcReg)) == rep(dstReg)) {
171 // remove from def list
172 LiveInterval &interval = getOrCreateInterval(RegRep);
173 // remove index -> MachineInstr and
174 // MachineInstr -> index mappings
175 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
176 if (mi2i != mi2iMap_.end()) {
177 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
178 mi2iMap_.erase(mi2i);
180 mii = mbbi->erase(mii);
184 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
185 const MachineOperand& mop = mii->getOperand(i);
186 if (mop.isRegister() && mop.getReg() &&
187 MRegisterInfo::isVirtualRegister(mop.getReg())) {
188 // replace register with representative register
189 unsigned reg = rep(mop.getReg());
190 mii->SetMachineOperandReg(i, reg);
192 LiveInterval &RegInt = getInterval(reg);
194 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
206 /// print - Implement the dump method.
207 void LiveIntervals::print(std::ostream &O, const Module* ) const {
208 O << "********** INTERVALS **********\n";
209 for (const_iterator I = begin(), E = end(); I != E; ++I) {
210 I->second.print(std::cerr, mri_);
214 O << "********** MACHINEINSTRS **********\n";
215 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
216 mbbi != mbbe; ++mbbi) {
217 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
218 for (MachineBasicBlock::iterator mii = mbbi->begin(),
219 mie = mbbi->end(); mii != mie; ++mii) {
220 O << getInstructionIndex(mii) << '\t' << *mii;
225 std::vector<LiveInterval*> LiveIntervals::
226 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
227 // since this is called after the analysis is done we don't know if
228 // LiveVariables is available
229 lv_ = getAnalysisToUpdate<LiveVariables>();
231 std::vector<LiveInterval*> added;
233 assert(li.weight != HUGE_VAL &&
234 "attempt to spill already spilled interval!");
236 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
239 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
241 for (LiveInterval::Ranges::const_iterator
242 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
243 unsigned index = getBaseIndex(i->start);
244 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
245 for (; index != end; index += InstrSlots::NUM) {
246 // skip deleted instructions
247 while (index != end && !getInstructionFromIndex(index))
248 index += InstrSlots::NUM;
249 if (index == end) break;
251 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
254 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
255 MachineOperand& mop = mi->getOperand(i);
256 if (mop.isRegister() && mop.getReg() == li.reg) {
257 // First thing, attempt to fold the memory reference into the
258 // instruction. If we can do this, we don't need to insert spill
260 if (MachineInstr* fmi = mri_->foldMemoryOperand(mi, i, slot)) {
262 lv_->instructionChanged(mi, fmi);
263 vrm.virtFolded(li.reg, mi, i, fmi);
265 i2miMap_[index/InstrSlots::NUM] = fmi;
266 mi2iMap_[fmi] = index;
267 MachineBasicBlock &MBB = *mi->getParent();
268 mi = MBB.insert(MBB.erase(mi), fmi);
271 // Folding the load/store can completely change the instruction in
272 // unpredictable ways, rescan it from the beginning.
275 // This is tricky. We need to add information in the interval about
276 // the spill code so we have to use our extra load/store slots.
278 // If we have a use we are going to have a load so we start the
279 // interval from the load slot onwards. Otherwise we start from the
281 unsigned start = (mop.isUse() ?
282 getLoadIndex(index) :
284 // If we have a def we are going to have a store right after it so
285 // we end the interval after the use of the next
286 // instruction. Otherwise we end after the use of this instruction.
287 unsigned end = 1 + (mop.isDef() ?
288 getStoreIndex(index) :
291 // create a new register for this spill
292 unsigned nReg = mf_->getSSARegMap()->createVirtualRegister(rc);
293 mi->SetMachineOperandReg(i, nReg);
295 vrm.assignVirt2StackSlot(nReg, slot);
296 LiveInterval& nI = getOrCreateInterval(nReg);
299 // the spill weight is now infinity as it
300 // cannot be spilled again
301 nI.weight = float(HUGE_VAL);
302 LiveRange LR(start, end, nI.getNextValue());
303 DEBUG(std::cerr << " +" << LR);
305 added.push_back(&nI);
307 // update live variables if it is available
309 lv_->addVirtualRegisterKilled(nReg, mi);
310 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
320 void LiveIntervals::printRegName(unsigned reg) const
322 if (MRegisterInfo::isPhysicalRegister(reg))
323 std::cerr << mri_->getName(reg);
325 std::cerr << "%reg" << reg;
328 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
329 MachineBasicBlock::iterator mi,
330 LiveInterval& interval)
332 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
333 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
335 // Virtual registers may be defined multiple times (due to phi
336 // elimination and 2-addr elimination). Much of what we do only has to be
337 // done once for the vreg. We use an empty interval to detect the first
338 // time we see a vreg.
339 if (interval.empty()) {
340 // Get the Idx of the defining instructions.
341 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
343 unsigned ValNum = interval.getNextValue();
344 assert(ValNum == 0 && "First value in interval is not 0?");
345 ValNum = 0; // Clue in the optimizer.
347 // Loop over all of the blocks that the vreg is defined in. There are
348 // two cases we have to handle here. The most common case is a vreg
349 // whose lifetime is contained within a basic block. In this case there
350 // will be a single kill, in MBB, which comes after the definition.
351 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
352 // FIXME: what about dead vars?
354 if (vi.Kills[0] != mi)
355 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
357 killIdx = defIndex+1;
359 // If the kill happens after the definition, we have an intra-block
361 if (killIdx > defIndex) {
362 assert(vi.AliveBlocks.empty() &&
363 "Shouldn't be alive across any blocks!");
364 LiveRange LR(defIndex, killIdx, ValNum);
365 interval.addRange(LR);
366 DEBUG(std::cerr << " +" << LR << "\n");
371 // The other case we handle is when a virtual register lives to the end
372 // of the defining block, potentially live across some blocks, then is
373 // live into some number of blocks, but gets killed. Start by adding a
374 // range that goes from this definition to the end of the defining block.
375 LiveRange NewLR(defIndex,
376 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
378 DEBUG(std::cerr << " +" << NewLR);
379 interval.addRange(NewLR);
381 // Iterate over all of the blocks that the variable is completely
382 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
384 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
385 if (vi.AliveBlocks[i]) {
386 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
388 LiveRange LR(getInstructionIndex(&mbb->front()),
389 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
391 interval.addRange(LR);
392 DEBUG(std::cerr << " +" << LR);
397 // Finally, this virtual register is live from the start of any killing
398 // block to the 'use' slot of the killing instruction.
399 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
400 MachineInstr *Kill = vi.Kills[i];
401 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
402 getUseIndex(getInstructionIndex(Kill))+1,
404 interval.addRange(LR);
405 DEBUG(std::cerr << " +" << LR);
409 // If this is the second time we see a virtual register definition, it
410 // must be due to phi elimination or two addr elimination. If this is
411 // the result of two address elimination, then the vreg is the first
412 // operand, and is a def-and-use.
413 if (mi->getOperand(0).isRegister() &&
414 mi->getOperand(0).getReg() == interval.reg &&
415 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
416 // If this is a two-address definition, then we have already processed
417 // the live range. The only problem is that we didn't realize there
418 // are actually two values in the live interval. Because of this we
419 // need to take the LiveRegion that defines this register and split it
421 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
422 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
424 // Delete the initial value, which should be short and continuous,
425 // becuase the 2-addr copy must be in the same MBB as the redef.
426 interval.removeRange(DefIndex, RedefIndex);
428 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
429 DEBUG(std::cerr << " replace range with " << LR);
430 interval.addRange(LR);
432 // If this redefinition is dead, we need to add a dummy unit live
433 // range covering the def slot.
434 if (lv_->RegisterDefIsDead(mi, interval.reg))
435 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
437 DEBUG(std::cerr << "RESULT: " << interval);
440 // Otherwise, this must be because of phi elimination. If this is the
441 // first redefinition of the vreg that we have seen, go back and change
442 // the live range in the PHI block to be a different value number.
443 if (interval.containsOneValue()) {
444 assert(vi.Kills.size() == 1 &&
445 "PHI elimination vreg should have one kill, the PHI itself!");
447 // Remove the old range that we now know has an incorrect number.
448 MachineInstr *Killer = vi.Kills[0];
449 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
450 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
451 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
452 << interval << "\n");
453 interval.removeRange(Start, End);
454 DEBUG(std::cerr << "RESULT: " << interval);
456 // Replace the interval with one of a NEW value number.
457 LiveRange LR(Start, End, interval.getNextValue());
458 DEBUG(std::cerr << " replace range with " << LR);
459 interval.addRange(LR);
460 DEBUG(std::cerr << "RESULT: " << interval);
463 // In the case of PHI elimination, each variable definition is only
464 // live until the end of the block. We've already taken care of the
465 // rest of the live range.
466 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
467 LiveRange LR(defIndex,
468 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
469 interval.getNextValue());
470 interval.addRange(LR);
471 DEBUG(std::cerr << " +" << LR);
475 DEBUG(std::cerr << '\n');
478 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
479 MachineBasicBlock::iterator mi,
480 LiveInterval& interval,
481 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)
506 assert(mi != MBB->end() && "physreg was not killed in defining block!");
507 baseIndex += InstrSlots::NUM;
508 if (lv_->KillsRegister(mi, interval.reg)) {
509 DEBUG(std::cerr << " killed");
510 end = getUseIndex(baseIndex) + 1;
516 assert(start < end && "did not find end of interval?");
518 // Finally, if this is defining a new range for the physical register, and if
519 // that physreg is just a copy from a vreg, and if THAT vreg was a copy from
520 // the physreg, then the new fragment has the same value as the one copied
522 if (interval.reg == DestReg && !interval.empty() &&
523 MRegisterInfo::isVirtualRegister(SrcReg)) {
525 // Get the live interval for the vreg, see if it is defined by a copy.
526 LiveInterval &SrcInterval = getOrCreateInterval(SrcReg);
528 if (SrcInterval.containsOneValue()) {
529 assert(!SrcInterval.empty() && "Can't contain a value and be empty!");
531 // Get the first index of the first range. Though the interval may have
532 // multiple liveranges in it, we only check the first.
533 unsigned StartIdx = SrcInterval.begin()->start;
534 MachineInstr *SrcDefMI = getInstructionFromIndex(StartIdx);
536 // Check to see if the vreg was defined by a copy instruction, and that
537 // the source was this physreg.
538 unsigned VRegSrcSrc, VRegSrcDest;
539 if (tii_->isMoveInstr(*SrcDefMI, VRegSrcSrc, VRegSrcDest) &&
540 SrcReg == VRegSrcDest && VRegSrcSrc == DestReg) {
541 // Okay, now we know that the vreg was defined by a copy from this
542 // physreg. Find the value number being copied and use it as the value
544 const LiveRange *DefRange = interval.getLiveRangeContaining(StartIdx-1);
546 LiveRange LR(start, end, DefRange->ValId);
547 interval.addRange(LR);
548 DEBUG(std::cerr << " +" << LR << '\n');
556 LiveRange LR(start, end, interval.getNextValue());
557 interval.addRange(LR);
558 DEBUG(std::cerr << " +" << LR << '\n');
561 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
562 MachineBasicBlock::iterator MI,
564 if (MRegisterInfo::isVirtualRegister(reg))
565 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
566 else if (allocatableRegs_[reg]) {
567 unsigned SrcReg = 0, DestReg = 0;
568 bool IsMove = tii_->isMoveInstr(*MI, SrcReg, DestReg);
570 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg),
572 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
573 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS),
578 /// computeIntervals - computes the live intervals for virtual
579 /// registers. for some ordering of the machine instructions [1,N] a
580 /// live interval is an interval [i, j) where 1 <= i <= j < N for
581 /// which a variable is live
582 void LiveIntervals::computeIntervals()
584 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
585 DEBUG(std::cerr << "********** Function: "
586 << ((Value*)mf_->getFunction())->getName() << '\n');
587 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
589 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
591 MachineBasicBlock* mbb = I;
592 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
594 MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
595 if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
596 for (; mi != miEnd; ++mi) {
597 const TargetInstrDescriptor& tid =
598 tm_->getInstrInfo()->get(mi->getOpcode());
599 DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
601 // handle implicit defs
602 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
603 handleRegisterDef(mbb, mi, *id);
605 // handle explicit defs
606 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
607 MachineOperand& mop = mi->getOperand(i);
608 // handle register defs - build intervals
609 if (mop.isRegister() && mop.getReg() && mop.isDef())
610 handleRegisterDef(mbb, mi, mop.getReg());
616 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
617 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
619 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
621 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
623 // we only join virtual registers with allocatable
624 // physical registers since we do not have liveness information
625 // on not allocatable physical registers
627 if (tii_->isMoveInstr(*mi, regA, regB) &&
628 (MRegisterInfo::isVirtualRegister(regA) || allocatableRegs_[regA]) &&
629 (MRegisterInfo::isVirtualRegister(regB) || allocatableRegs_[regB])) {
631 // Get representative registers.
635 // If they are already joined we continue.
639 // If they are both physical registers, we cannot join them.
640 if (MRegisterInfo::isPhysicalRegister(regA) &&
641 MRegisterInfo::isPhysicalRegister(regB))
644 // If they are not of the same register class, we cannot join them.
645 if (differingRegisterClasses(regA, regB))
648 LiveInterval &IntA = getInterval(regA);
649 LiveInterval &IntB = getInterval(regB);
650 assert(IntA.reg == regA && IntB.reg == regB &&
651 "Register mapping is horribly broken!");
653 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
655 // If two intervals contain a single value and are joined by a copy, it
656 // does not matter if the intervals overlap, they can always be joined.
657 bool TriviallyJoinable =
658 IntA.containsOneValue() && IntB.containsOneValue();
660 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
661 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
662 !overlapsAliases(&IntA, &IntB)) {
663 IntB.join(IntA, MIDefIdx);
664 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
666 if (!MRegisterInfo::isPhysicalRegister(regA)) {
668 r2rMap_[regA] = regB;
670 // Otherwise merge the data structures the other way so we don't lose
671 // the physreg information.
672 r2rMap_[regB] = regA;
679 DEBUG(std::cerr << "Interference!\n");
686 // DepthMBBCompare - Comparison predicate that sort first based on the loop
687 // depth of the basic block (the unsigned), and then on the MBB number.
688 struct DepthMBBCompare {
689 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
690 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
691 if (LHS.first > RHS.first) return true; // Deeper loops first
692 return LHS.first == RHS.first &&
693 LHS.second->getNumber() < RHS.second->getNumber();
698 void LiveIntervals::joinIntervals() {
699 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
701 const LoopInfo &LI = getAnalysis<LoopInfo>();
702 if (LI.begin() == LI.end()) {
703 // If there are no loops in the function, join intervals in function order.
704 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
706 joinIntervalsInMachineBB(I);
708 // Otherwise, join intervals in inner loops before other intervals.
709 // Unfortunately we can't just iterate over loop hierarchy here because
710 // there may be more MBB's than BB's. Collect MBB's for sorting.
711 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
712 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
714 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
716 // Sort by loop depth.
717 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
719 // Finally, join intervals in loop nest order.
720 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
721 joinIntervalsInMachineBB(MBBs[i].second);
724 DEBUG(std::cerr << "*** Register mapping ***\n");
725 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
727 std::cerr << " reg " << i << " -> reg " << r2rMap_[i] << "\n");
730 /// Return true if the two specified registers belong to different register
731 /// classes. The registers may be either phys or virt regs.
732 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
733 unsigned RegB) const {
735 // Get the register classes for the first reg.
736 if (MRegisterInfo::isPhysicalRegister(RegA)) {
737 assert(MRegisterInfo::isVirtualRegister(RegB) &&
738 "Shouldn't consider two physregs!");
739 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
742 // Compare against the regclass for the second reg.
743 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
744 if (MRegisterInfo::isVirtualRegister(RegB))
745 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
747 return !RegClass->contains(RegB);
750 bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
751 const LiveInterval *RHS) const {
752 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
753 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
754 return false; // vreg-vreg merge has no aliases!
758 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
759 MRegisterInfo::isVirtualRegister(RHS->reg) &&
760 "first interval must describe a physical register");
762 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
763 if (RHS->overlaps(getInterval(*AS)))
769 LiveInterval LiveIntervals::createInterval(unsigned reg) {
770 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
771 (float)HUGE_VAL :0.0F;
772 return LiveInterval(reg, Weight);