LiveIntervalAnalysis.cpp revision 2926869b4a083fc951484de03a9867eabf81e880
1//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
19#include "llvm/CodeGen/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"
35#include <algorithm>
36#include <cmath>
37#include <iostream>
38using namespace llvm;
39
40namespace {
41  RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
42
43  static Statistic<> numIntervals
44  ("liveintervals", "Number of original intervals");
45
46  static Statistic<> numIntervalsAfter
47  ("liveintervals", "Number of intervals after coalescing");
48
49  static Statistic<> numJoins
50  ("liveintervals", "Number of interval joins performed");
51
52  static Statistic<> numPeep
53  ("liveintervals", "Number of identity moves eliminated after coalescing");
54
55  static Statistic<> numFolded
56  ("liveintervals", "Number of loads/stores folded into instructions");
57
58  static cl::opt<bool>
59  EnableJoining("join-liveintervals",
60                cl::desc("Join compatible live intervals"),
61                cl::init(true));
62}
63
64void 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);
71}
72
73void LiveIntervals::releaseMemory() {
74  mi2iMap_.clear();
75  i2miMap_.clear();
76  r2iMap_.clear();
77  r2rMap_.clear();
78}
79
80
81static bool isZeroLengthInterval(LiveInterval *li) {
82  for (LiveInterval::Ranges::const_iterator
83         i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
84    if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
85      return false;
86  return true;
87}
88
89
90/// runOnMachineFunction - Register allocate the whole function
91///
92bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
93  mf_ = &fn;
94  tm_ = &fn.getTarget();
95  mri_ = tm_->getRegisterInfo();
96  tii_ = tm_->getInstrInfo();
97  lv_ = &getAnalysis<LiveVariables>();
98  allocatableRegs_ = mri_->getAllocatableSet(fn);
99  r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
100
101  // If this function has any live ins, insert a dummy instruction at the
102  // beginning of the function that we will pretend "defines" the values.  This
103  // is to make the interval analysis simpler by providing a number.
104  if (fn.livein_begin() != fn.livein_end()) {
105    unsigned FirstLiveIn = fn.livein_begin()->first;
106
107    // Find a reg class that contains this live in.
108    const TargetRegisterClass *RC = 0;
109    for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
110           E = mri_->regclass_end(); RCI != E; ++RCI)
111      if ((*RCI)->contains(FirstLiveIn)) {
112        RC = *RCI;
113        break;
114      }
115
116    MachineInstr *OldFirstMI = fn.begin()->begin();
117    mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
118                       FirstLiveIn, FirstLiveIn, RC);
119    assert(OldFirstMI != fn.begin()->begin() &&
120           "copyRetToReg didn't insert anything!");
121  }
122
123  // number MachineInstrs
124  unsigned miIndex = 0;
125  for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
126       mbb != mbbEnd; ++mbb)
127    for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
128         mi != miEnd; ++mi) {
129      bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
130      assert(inserted && "multiple MachineInstr -> index mappings");
131      i2miMap_.push_back(mi);
132      miIndex += InstrSlots::NUM;
133    }
134
135  // Note intervals due to live-in values.
136  if (fn.livein_begin() != fn.livein_end()) {
137    MachineBasicBlock *Entry = fn.begin();
138    for (MachineFunction::livein_iterator I = fn.livein_begin(),
139           E = fn.livein_end(); I != E; ++I) {
140      handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
141                                getOrCreateInterval(I->first), 0);
142      for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
143        handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
144                                  getOrCreateInterval(*AS), 0);
145    }
146  }
147
148  computeIntervals();
149
150  numIntervals += getNumIntervals();
151
152  DEBUG(std::cerr << "********** INTERVALS **********\n";
153        for (iterator I = begin(), E = end(); I != E; ++I) {
154          I->second.print(std::cerr, mri_);
155          std::cerr << "\n";
156        });
157
158  // join intervals if requested
159  if (EnableJoining) joinIntervals();
160
161  numIntervalsAfter += getNumIntervals();
162
163  // perform a final pass over the instructions and compute spill
164  // weights, coalesce virtual registers and remove identity moves.
165  const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
166
167  for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
168       mbbi != mbbe; ++mbbi) {
169    MachineBasicBlock* mbb = mbbi;
170    unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
171
172    for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
173         mii != mie; ) {
174      // if the move will be an identity move delete it
175      unsigned srcReg, dstReg, RegRep;
176      if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
177          (RegRep = rep(srcReg)) == rep(dstReg)) {
178        // remove from def list
179        LiveInterval &interval = getOrCreateInterval(RegRep);
180        RemoveMachineInstrFromMaps(mii);
181        mii = mbbi->erase(mii);
182        ++numPeep;
183      }
184      else {
185        for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
186          const MachineOperand &mop = mii->getOperand(i);
187          if (mop.isRegister() && mop.getReg() &&
188              MRegisterInfo::isVirtualRegister(mop.getReg())) {
189            // replace register with representative register
190            unsigned reg = rep(mop.getReg());
191            mii->getOperand(i).setReg(reg);
192
193            LiveInterval &RegInt = getInterval(reg);
194            RegInt.weight +=
195              (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
196          }
197        }
198        ++mii;
199      }
200    }
201  }
202
203  for (iterator I = begin(), E = end(); I != E; ++I) {
204    LiveInterval &li = I->second;
205    if (MRegisterInfo::isVirtualRegister(li.reg)) {
206      // If the live interval length is essentially zero, i.e. in every live
207      // range the use follows def immediately, it doesn't make sense to spill
208      // it and hope it will be easier to allocate for this li.
209      if (isZeroLengthInterval(&li))
210        li.weight = float(HUGE_VAL);
211    }
212  }
213
214  DEBUG(dump());
215  return true;
216}
217
218/// print - Implement the dump method.
219void LiveIntervals::print(std::ostream &O, const Module* ) const {
220  O << "********** INTERVALS **********\n";
221  for (const_iterator I = begin(), E = end(); I != E; ++I) {
222    I->second.print(std::cerr, mri_);
223    std::cerr << "\n";
224  }
225
226  O << "********** MACHINEINSTRS **********\n";
227  for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
228       mbbi != mbbe; ++mbbi) {
229    O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
230    for (MachineBasicBlock::iterator mii = mbbi->begin(),
231           mie = mbbi->end(); mii != mie; ++mii) {
232      O << getInstructionIndex(mii) << '\t' << *mii;
233    }
234  }
235}
236
237std::vector<LiveInterval*> LiveIntervals::
238addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
239  // since this is called after the analysis is done we don't know if
240  // LiveVariables is available
241  lv_ = getAnalysisToUpdate<LiveVariables>();
242
243  std::vector<LiveInterval*> added;
244
245  assert(li.weight != HUGE_VAL &&
246         "attempt to spill already spilled interval!");
247
248  DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: ";
249        li.print(std::cerr, mri_); std::cerr << '\n');
250
251  const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
252
253  for (LiveInterval::Ranges::const_iterator
254         i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
255    unsigned index = getBaseIndex(i->start);
256    unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
257    for (; index != end; index += InstrSlots::NUM) {
258      // skip deleted instructions
259      while (index != end && !getInstructionFromIndex(index))
260        index += InstrSlots::NUM;
261      if (index == end) break;
262
263      MachineInstr *MI = getInstructionFromIndex(index);
264
265    RestartInstruction:
266      for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
267        MachineOperand& mop = MI->getOperand(i);
268        if (mop.isRegister() && mop.getReg() == li.reg) {
269          if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
270            // Attempt to fold the memory reference into the instruction.  If we
271            // can do this, we don't need to insert spill code.
272            if (lv_)
273              lv_->instructionChanged(MI, fmi);
274            MachineBasicBlock &MBB = *MI->getParent();
275            vrm.virtFolded(li.reg, MI, i, fmi);
276            mi2iMap_.erase(MI);
277            i2miMap_[index/InstrSlots::NUM] = fmi;
278            mi2iMap_[fmi] = index;
279            MI = MBB.insert(MBB.erase(MI), fmi);
280            ++numFolded;
281            // Folding the load/store can completely change the instruction in
282            // unpredictable ways, rescan it from the beginning.
283            goto RestartInstruction;
284          } else {
285            // Create a new virtual register for the spill interval.
286            unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
287
288            // Scan all of the operands of this instruction rewriting operands
289            // to use NewVReg instead of li.reg as appropriate.  We do this for
290            // two reasons:
291            //
292            //   1. If the instr reads the same spilled vreg multiple times, we
293            //      want to reuse the NewVReg.
294            //   2. If the instr is a two-addr instruction, we are required to
295            //      keep the src/dst regs pinned.
296            //
297            // Keep track of whether we replace a use and/or def so that we can
298            // create the spill interval with the appropriate range.
299            mop.setReg(NewVReg);
300
301            bool HasUse = mop.isUse();
302            bool HasDef = mop.isDef();
303            for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
304              if (MI->getOperand(j).isReg() &&
305                  MI->getOperand(j).getReg() == li.reg) {
306                MI->getOperand(j).setReg(NewVReg);
307                HasUse |= MI->getOperand(j).isUse();
308                HasDef |= MI->getOperand(j).isDef();
309              }
310            }
311
312            // create a new register for this spill
313            vrm.grow();
314            vrm.assignVirt2StackSlot(NewVReg, slot);
315            LiveInterval &nI = getOrCreateInterval(NewVReg);
316            assert(nI.empty());
317
318            // the spill weight is now infinity as it
319            // cannot be spilled again
320            nI.weight = float(HUGE_VAL);
321
322            if (HasUse) {
323              LiveRange LR(getLoadIndex(index), getUseIndex(index),
324                           nI.getNextValue(~0U, 0));
325              DEBUG(std::cerr << " +" << LR);
326              nI.addRange(LR);
327            }
328            if (HasDef) {
329              LiveRange LR(getDefIndex(index), getStoreIndex(index),
330                           nI.getNextValue(~0U, 0));
331              DEBUG(std::cerr << " +" << LR);
332              nI.addRange(LR);
333            }
334
335            added.push_back(&nI);
336
337            // update live variables if it is available
338            if (lv_)
339              lv_->addVirtualRegisterKilled(NewVReg, MI);
340
341            DEBUG(std::cerr << "\t\t\t\tadded new interval: ";
342                  nI.print(std::cerr, mri_); std::cerr << '\n');
343          }
344        }
345      }
346    }
347  }
348
349  return added;
350}
351
352void LiveIntervals::printRegName(unsigned reg) const {
353  if (MRegisterInfo::isPhysicalRegister(reg))
354    std::cerr << mri_->getName(reg);
355  else
356    std::cerr << "%reg" << reg;
357}
358
359void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
360                                             MachineBasicBlock::iterator mi,
361                                             unsigned MIIdx,
362                                             LiveInterval &interval) {
363  DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
364  LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
365
366  // Virtual registers may be defined multiple times (due to phi
367  // elimination and 2-addr elimination).  Much of what we do only has to be
368  // done once for the vreg.  We use an empty interval to detect the first
369  // time we see a vreg.
370  if (interval.empty()) {
371    // Get the Idx of the defining instructions.
372    unsigned defIndex = getDefIndex(MIIdx);
373
374    unsigned ValNum;
375    unsigned SrcReg, DstReg;
376    if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
377      ValNum = interval.getNextValue(~0U, 0);
378    else
379      ValNum = interval.getNextValue(defIndex, SrcReg);
380
381    assert(ValNum == 0 && "First value in interval is not 0?");
382    ValNum = 0;  // Clue in the optimizer.
383
384    // Loop over all of the blocks that the vreg is defined in.  There are
385    // two cases we have to handle here.  The most common case is a vreg
386    // whose lifetime is contained within a basic block.  In this case there
387    // will be a single kill, in MBB, which comes after the definition.
388    if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
389      // FIXME: what about dead vars?
390      unsigned killIdx;
391      if (vi.Kills[0] != mi)
392        killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
393      else
394        killIdx = defIndex+1;
395
396      // If the kill happens after the definition, we have an intra-block
397      // live range.
398      if (killIdx > defIndex) {
399        assert(vi.AliveBlocks.empty() &&
400               "Shouldn't be alive across any blocks!");
401        LiveRange LR(defIndex, killIdx, ValNum);
402        interval.addRange(LR);
403        DEBUG(std::cerr << " +" << LR << "\n");
404        return;
405      }
406    }
407
408    // The other case we handle is when a virtual register lives to the end
409    // of the defining block, potentially live across some blocks, then is
410    // live into some number of blocks, but gets killed.  Start by adding a
411    // range that goes from this definition to the end of the defining block.
412    LiveRange NewLR(defIndex,
413                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
414                    ValNum);
415    DEBUG(std::cerr << " +" << NewLR);
416    interval.addRange(NewLR);
417
418    // Iterate over all of the blocks that the variable is completely
419    // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
420    // live interval.
421    for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
422      if (vi.AliveBlocks[i]) {
423        MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
424        if (!mbb->empty()) {
425          LiveRange LR(getInstructionIndex(&mbb->front()),
426                       getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
427                       ValNum);
428          interval.addRange(LR);
429          DEBUG(std::cerr << " +" << LR);
430        }
431      }
432    }
433
434    // Finally, this virtual register is live from the start of any killing
435    // block to the 'use' slot of the killing instruction.
436    for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
437      MachineInstr *Kill = vi.Kills[i];
438      LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
439                   getUseIndex(getInstructionIndex(Kill))+1,
440                   ValNum);
441      interval.addRange(LR);
442      DEBUG(std::cerr << " +" << LR);
443    }
444
445  } else {
446    // If this is the second time we see a virtual register definition, it
447    // must be due to phi elimination or two addr elimination.  If this is
448    // the result of two address elimination, then the vreg is the first
449    // operand, and is a def-and-use.
450    if (mi->getOperand(0).isRegister() &&
451        mi->getOperand(0).getReg() == interval.reg &&
452        mi->getNumOperands() > 1 && mi->getOperand(1).isRegister() &&
453        mi->getOperand(1).getReg() == interval.reg &&
454        mi->getOperand(0).isDef() && mi->getOperand(1).isUse()) {
455      // If this is a two-address definition, then we have already processed
456      // the live range.  The only problem is that we didn't realize there
457      // are actually two values in the live interval.  Because of this we
458      // need to take the LiveRegion that defines this register and split it
459      // into two values.
460      unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
461      unsigned RedefIndex = getDefIndex(MIIdx);
462
463      // Delete the initial value, which should be short and continuous,
464      // because the 2-addr copy must be in the same MBB as the redef.
465      interval.removeRange(DefIndex, RedefIndex);
466
467      // Two-address vregs should always only be redefined once.  This means
468      // that at this point, there should be exactly one value number in it.
469      assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
470
471      // The new value number (#1) is defined by the instruction we claimed
472      // defined value #0.
473      unsigned ValNo = interval.getNextValue(0, 0);
474      interval.setValueNumberInfo(1, interval.getValNumInfo(0));
475
476      // Value#0 is now defined by the 2-addr instruction.
477      interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
478
479      // Add the new live interval which replaces the range for the input copy.
480      LiveRange LR(DefIndex, RedefIndex, ValNo);
481      DEBUG(std::cerr << " replace range with " << LR);
482      interval.addRange(LR);
483
484      // If this redefinition is dead, we need to add a dummy unit live
485      // range covering the def slot.
486      if (lv_->RegisterDefIsDead(mi, interval.reg))
487        interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
488
489      DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
490
491    } else {
492      // Otherwise, this must be because of phi elimination.  If this is the
493      // first redefinition of the vreg that we have seen, go back and change
494      // the live range in the PHI block to be a different value number.
495      if (interval.containsOneValue()) {
496        assert(vi.Kills.size() == 1 &&
497               "PHI elimination vreg should have one kill, the PHI itself!");
498
499        // Remove the old range that we now know has an incorrect number.
500        MachineInstr *Killer = vi.Kills[0];
501        unsigned Start = getInstructionIndex(Killer->getParent()->begin());
502        unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
503        DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: ";
504              interval.print(std::cerr, mri_); std::cerr << "\n");
505        interval.removeRange(Start, End);
506        DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
507
508        // Replace the interval with one of a NEW value number.  Note that this
509        // value number isn't actually defined by an instruction, weird huh? :)
510        LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
511        DEBUG(std::cerr << " replace range with " << LR);
512        interval.addRange(LR);
513        DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
514      }
515
516      // In the case of PHI elimination, each variable definition is only
517      // live until the end of the block.  We've already taken care of the
518      // rest of the live range.
519      unsigned defIndex = getDefIndex(MIIdx);
520
521      unsigned ValNum;
522      unsigned SrcReg, DstReg;
523      if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
524        ValNum = interval.getNextValue(~0U, 0);
525      else
526        ValNum = interval.getNextValue(defIndex, SrcReg);
527
528      LiveRange LR(defIndex,
529                   getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
530      interval.addRange(LR);
531      DEBUG(std::cerr << " +" << LR);
532    }
533  }
534
535  DEBUG(std::cerr << '\n');
536}
537
538void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
539                                              MachineBasicBlock::iterator mi,
540                                              unsigned MIIdx,
541                                              LiveInterval &interval,
542                                              unsigned SrcReg) {
543  // A physical register cannot be live across basic block, so its
544  // lifetime must end somewhere in its defining basic block.
545  DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
546  typedef LiveVariables::killed_iterator KillIter;
547
548  unsigned baseIndex = MIIdx;
549  unsigned start = getDefIndex(baseIndex);
550  unsigned end = start;
551
552  // If it is not used after definition, it is considered dead at
553  // the instruction defining it. Hence its interval is:
554  // [defSlot(def), defSlot(def)+1)
555  if (lv_->RegisterDefIsDead(mi, interval.reg)) {
556    DEBUG(std::cerr << " dead");
557    end = getDefIndex(start) + 1;
558    goto exit;
559  }
560
561  // If it is not dead on definition, it must be killed by a
562  // subsequent instruction. Hence its interval is:
563  // [defSlot(def), useSlot(kill)+1)
564  while (++mi != MBB->end()) {
565    baseIndex += InstrSlots::NUM;
566    if (lv_->KillsRegister(mi, interval.reg)) {
567      DEBUG(std::cerr << " killed");
568      end = getUseIndex(baseIndex) + 1;
569      goto exit;
570    }
571  }
572
573  // The only case we should have a dead physreg here without a killing or
574  // instruction where we know it's dead is if it is live-in to the function
575  // and never used.
576  assert(!SrcReg && "physreg was not killed in defining block!");
577  end = getDefIndex(start) + 1;  // It's dead.
578
579exit:
580  assert(start < end && "did not find end of interval?");
581
582  LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
583                                                 SrcReg));
584  interval.addRange(LR);
585  DEBUG(std::cerr << " +" << LR << '\n');
586}
587
588void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
589                                      MachineBasicBlock::iterator MI,
590                                      unsigned MIIdx,
591                                      unsigned reg) {
592  if (MRegisterInfo::isVirtualRegister(reg))
593    handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
594  else if (allocatableRegs_[reg]) {
595    unsigned SrcReg, DstReg;
596    if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
597      SrcReg = 0;
598    handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
599    for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
600      handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
601  }
602}
603
604/// computeIntervals - computes the live intervals for virtual
605/// registers. for some ordering of the machine instructions [1,N] a
606/// live interval is an interval [i, j) where 1 <= i <= j < N for
607/// which a variable is live
608void LiveIntervals::computeIntervals() {
609  DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
610  DEBUG(std::cerr << "********** Function: "
611        << ((Value*)mf_->getFunction())->getName() << '\n');
612  bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
613
614  // Track the index of the current machine instr.
615  unsigned MIIndex = 0;
616  for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
617       I != E; ++I) {
618    MachineBasicBlock* mbb = I;
619    DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
620
621    MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
622    if (IgnoreFirstInstr) {
623      ++mi;
624      IgnoreFirstInstr = false;
625      MIIndex += InstrSlots::NUM;
626    }
627
628    for (; mi != miEnd; ++mi) {
629      const TargetInstrDescriptor& tid =
630        tm_->getInstrInfo()->get(mi->getOpcode());
631      DEBUG(std::cerr << MIIndex << "\t" << *mi);
632
633      // handle implicit defs
634      if (tid.ImplicitDefs) {
635        for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
636          handleRegisterDef(mbb, mi, MIIndex, *id);
637      }
638
639      // handle explicit defs
640      for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
641        MachineOperand& mop = mi->getOperand(i);
642        // handle register defs - build intervals
643        if (mop.isRegister() && mop.getReg() && mop.isDef())
644          handleRegisterDef(mbb, mi, MIIndex, mop.getReg());
645      }
646
647      MIIndex += InstrSlots::NUM;
648    }
649  }
650}
651
652/// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
653/// being the source and IntB being the dest, thus this defines a value number
654/// in IntB.  If the source value number (in IntA) is defined by a copy from B,
655/// see if we can merge these two pieces of B into a single value number,
656/// eliminating a copy.  For example:
657///
658///  A3 = B0
659///    ...
660///  B1 = A3      <- this copy
661///
662/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
663/// value number to be replaced with B0 (which simplifies the B liveinterval).
664///
665/// This returns true if an interval was modified.
666///
667bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
668                                         MachineInstr *CopyMI) {
669  unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
670
671  // BValNo is a value number in B that is defined by a copy from A.  'B3' in
672  // the example above.
673  LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
674  unsigned BValNo = BLR->ValId;
675
676  // Get the location that B is defined at.  Two options: either this value has
677  // an unknown definition point or it is defined at CopyIdx.  If unknown, we
678  // can't process it.
679  unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
680  if (BValNoDefIdx == ~0U) return false;
681  assert(BValNoDefIdx == CopyIdx &&
682         "Copy doesn't define the value?");
683
684  // AValNo is the value number in A that defines the copy, A0 in the example.
685  LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
686  unsigned AValNo = AValLR->ValId;
687
688  // If AValNo is defined as a copy from IntB, we can potentially process this.
689
690  // Get the instruction that defines this value number.
691  unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
692  if (!SrcReg) return false;  // Not defined by a copy.
693
694  // If the value number is not defined by a copy instruction, ignore it.
695
696  // If the source register comes from an interval other than IntB, we can't
697  // handle this.
698  if (rep(SrcReg) != IntB.reg) return false;
699
700  // Get the LiveRange in IntB that this value number starts with.
701  unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
702  LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
703
704  // Make sure that the end of the live range is inside the same block as
705  // CopyMI.
706  MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
707  if (!ValLREndInst ||
708      ValLREndInst->getParent() != CopyMI->getParent()) return false;
709
710  // Okay, we now know that ValLR ends in the same block that the CopyMI
711  // live-range starts.  If there are no intervening live ranges between them in
712  // IntB, we can merge them.
713  if (ValLR+1 != BLR) return false;
714
715  DEBUG(std::cerr << "\nExtending: "; IntB.print(std::cerr, mri_));
716
717  // We are about to delete CopyMI, so need to remove it as the 'instruction
718  // that defines this value #'.
719  IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
720
721  // Okay, we can merge them.  We need to insert a new liverange:
722  // [ValLR.end, BLR.begin) of either value number, then we merge the
723  // two value numbers.
724  unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
725  IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
726
727  // If the IntB live range is assigned to a physical register, and if that
728  // physreg has aliases,
729  if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
730    for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
731      LiveInterval &AliasLI = getInterval(*AS);
732      AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
733                                 AliasLI.getNextValue(~0U, 0)));
734    }
735  }
736
737  // Okay, merge "B1" into the same value number as "B0".
738  if (BValNo != ValLR->ValId)
739    IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
740  DEBUG(std::cerr << "   result = "; IntB.print(std::cerr, mri_);
741        std::cerr << "\n");
742
743  // Finally, delete the copy instruction.
744  RemoveMachineInstrFromMaps(CopyMI);
745  CopyMI->eraseFromParent();
746  ++numPeep;
747  return true;
748}
749
750
751/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
752/// which are the src/dst of the copy instruction CopyMI.  This returns true
753/// if the copy was successfully coallesced away, or if it is never possible
754/// to coallesce these this copy, due to register constraints.  It returns
755/// false if it is not currently possible to coallesce this interval, but
756/// it may be possible if other things get coallesced.
757bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
758                             unsigned SrcReg, unsigned DstReg) {
759
760
761  DEBUG(std::cerr << getInstructionIndex(CopyMI) << '\t' << *CopyMI);
762
763  // Get representative registers.
764  SrcReg = rep(SrcReg);
765  DstReg = rep(DstReg);
766
767  // If they are already joined we continue.
768  if (SrcReg == DstReg) {
769    DEBUG(std::cerr << "\tCopy already coallesced.\n");
770    return true;  // Not coallescable.
771  }
772
773  // If they are both physical registers, we cannot join them.
774  if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
775      MRegisterInfo::isPhysicalRegister(DstReg)) {
776    DEBUG(std::cerr << "\tCan not coallesce physregs.\n");
777    return true;  // Not coallescable.
778  }
779
780  // We only join virtual registers with allocatable physical registers.
781  if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
782    DEBUG(std::cerr << "\tSrc reg is unallocatable physreg.\n");
783    return true;  // Not coallescable.
784  }
785  if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
786    DEBUG(std::cerr << "\tDst reg is unallocatable physreg.\n");
787    return true;  // Not coallescable.
788  }
789
790  // If they are not of the same register class, we cannot join them.
791  if (differingRegisterClasses(SrcReg, DstReg)) {
792    DEBUG(std::cerr << "\tSrc/Dest are different register classes.\n");
793    return true;  // Not coallescable.
794  }
795
796  LiveInterval &SrcInt = getInterval(SrcReg);
797  LiveInterval &DestInt = getInterval(DstReg);
798  assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
799         "Register mapping is horribly broken!");
800
801  DEBUG(std::cerr << "\t\tInspecting "; SrcInt.print(std::cerr, mri_);
802        std::cerr << " and "; DestInt.print(std::cerr, mri_);
803        std::cerr << ": ");
804
805  // Okay, attempt to join these two intervals.  On failure, this returns false.
806  // Otherwise, if one of the intervals being joined is a physreg, this method
807  // always canonicalizes DestInt to be it.  The output "SrcInt" will not have
808  // been modified, so we can use this information below to update aliases.
809  if (!JoinIntervals(DestInt, SrcInt)) {
810    // Coallescing failed.
811
812    // If we can eliminate the copy without merging the live ranges, do so now.
813    if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
814      return true;
815
816    // Otherwise, we are unable to join the intervals.
817    DEBUG(std::cerr << "Interference!\n");
818    return false;
819  }
820
821  bool Swapped = SrcReg == DestInt.reg;
822  if (Swapped)
823    std::swap(SrcReg, DstReg);
824  assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
825         "LiveInterval::join didn't work right!");
826
827  // If we're about to merge live ranges into a physical register live range,
828  // we have to update any aliased register's live ranges to indicate that they
829  // have clobbered values for this range.
830  if (MRegisterInfo::isPhysicalRegister(DstReg)) {
831    for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
832      getInterval(*AS).MergeInClobberRanges(SrcInt);
833  }
834
835  DEBUG(std::cerr << "\n\t\tJoined.  Result = "; DestInt.print(std::cerr, mri_);
836        std::cerr << "\n");
837
838  // If the intervals were swapped by Join, swap them back so that the register
839  // mapping (in the r2i map) is correct.
840  if (Swapped) SrcInt.swap(DestInt);
841  r2iMap_.erase(SrcReg);
842  r2rMap_[SrcReg] = DstReg;
843
844  // Finally, delete the copy instruction.
845  RemoveMachineInstrFromMaps(CopyMI);
846  CopyMI->eraseFromParent();
847  ++numPeep;
848  ++numJoins;
849  return true;
850}
851
852/// ComputeUltimateVN - Assuming we are going to join two live intervals,
853/// compute what the resultant value numbers for each value in the input two
854/// ranges will be.  This is complicated by copies between the two which can
855/// and will commonly cause multiple value numbers to be merged into one.
856///
857/// VN is the value number that we're trying to resolve.  InstDefiningValue
858/// keeps track of the new InstDefiningValue assignment for the result
859/// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
860/// whether a value in this or other is a copy from the opposite set.
861/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
862/// already been assigned.
863///
864/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
865/// contains the value number the copy is from.
866///
867static unsigned ComputeUltimateVN(unsigned VN,
868                                  SmallVector<std::pair<unsigned,
869                                                unsigned>, 16> &ValueNumberInfo,
870                                  SmallVector<int, 16> &ThisFromOther,
871                                  SmallVector<int, 16> &OtherFromThis,
872                                  SmallVector<int, 16> &ThisValNoAssignments,
873                                  SmallVector<int, 16> &OtherValNoAssignments,
874                                  LiveInterval &ThisLI, LiveInterval &OtherLI) {
875  // If the VN has already been computed, just return it.
876  if (ThisValNoAssignments[VN] >= 0)
877    return ThisValNoAssignments[VN];
878//  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
879
880  // If this val is not a copy from the other val, then it must be a new value
881  // number in the destination.
882  int OtherValNo = ThisFromOther[VN];
883  if (OtherValNo == -1) {
884    ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
885    return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
886  }
887
888  // Otherwise, this *is* a copy from the RHS.  If the other side has already
889  // been computed, return it.
890  if (OtherValNoAssignments[OtherValNo] >= 0)
891    return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
892
893  // Mark this value number as currently being computed, then ask what the
894  // ultimate value # of the other value is.
895  ThisValNoAssignments[VN] = -2;
896  unsigned UltimateVN =
897    ComputeUltimateVN(OtherValNo, ValueNumberInfo,
898                      OtherFromThis, ThisFromOther,
899                      OtherValNoAssignments, ThisValNoAssignments,
900                      OtherLI, ThisLI);
901  return ThisValNoAssignments[VN] = UltimateVN;
902}
903
904static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
905  return std::find(V.begin(), V.end(), Val) != V.end();
906}
907
908/// SimpleJoin - Attempt to joint the specified interval into this one. The
909/// caller of this method must guarantee that the RHS only contains a single
910/// value number and that the RHS is not defined by a copy from this
911/// interval.  This returns false if the intervals are not joinable, or it
912/// joins them and returns true.
913bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
914  assert(RHS.containsOneValue());
915
916  // Some number (potentially more than one) value numbers in the current
917  // interval may be defined as copies from the RHS.  Scan the overlapping
918  // portions of the LHS and RHS, keeping track of this and looking for
919  // overlapping live ranges that are NOT defined as copies.  If these exist, we
920  // cannot coallesce.
921
922  LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
923  LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
924
925  if (LHSIt->start < RHSIt->start) {
926    LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
927    if (LHSIt != LHS.begin()) --LHSIt;
928  } else if (RHSIt->start < LHSIt->start) {
929    RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
930    if (RHSIt != RHS.begin()) --RHSIt;
931  }
932
933  SmallVector<unsigned, 8> EliminatedLHSVals;
934
935  while (1) {
936    // Determine if these live intervals overlap.
937    bool Overlaps = false;
938    if (LHSIt->start <= RHSIt->start)
939      Overlaps = LHSIt->end > RHSIt->start;
940    else
941      Overlaps = RHSIt->end > LHSIt->start;
942
943    // If the live intervals overlap, there are two interesting cases: if the
944    // LHS interval is defined by a copy from the RHS, it's ok and we record
945    // that the LHS value # is the same as the RHS.  If it's not, then we cannot
946    // coallesce these live ranges and we bail out.
947    if (Overlaps) {
948      // If we haven't already recorded that this value # is safe, check it.
949      if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
950        // Copy from the RHS?
951        unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
952        if (rep(SrcReg) != RHS.reg)
953          return false;    // Nope, bail out.
954
955        EliminatedLHSVals.push_back(LHSIt->ValId);
956      }
957
958      // We know this entire LHS live range is okay, so skip it now.
959      if (++LHSIt == LHSEnd) break;
960      continue;
961    }
962
963    if (LHSIt->end < RHSIt->end) {
964      if (++LHSIt == LHSEnd) break;
965    } else {
966      // One interesting case to check here.  It's possible that we have
967      // something like "X3 = Y" which defines a new value number in the LHS,
968      // and is the last use of this liverange of the RHS.  In this case, we
969      // want to notice this copy (so that it gets coallesced away) even though
970      // the live ranges don't actually overlap.
971      if (LHSIt->start == RHSIt->end) {
972        if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
973          // We already know that this value number is going to be merged in
974          // if coallescing succeeds.  Just skip the liverange.
975          if (++LHSIt == LHSEnd) break;
976        } else {
977          // Otherwise, if this is a copy from the RHS, mark it as being merged
978          // in.
979          if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
980            EliminatedLHSVals.push_back(LHSIt->ValId);
981
982            // We know this entire LHS live range is okay, so skip it now.
983            if (++LHSIt == LHSEnd) break;
984          }
985        }
986      }
987
988      if (++RHSIt == RHSEnd) break;
989    }
990  }
991
992  // If we got here, we know that the coallescing will be successful and that
993  // the value numbers in EliminatedLHSVals will all be merged together.  Since
994  // the most common case is that EliminatedLHSVals has a single number, we
995  // optimize for it: if there is more than one value, we merge them all into
996  // the lowest numbered one, then handle the interval as if we were merging
997  // with one value number.
998  unsigned LHSValNo;
999  if (EliminatedLHSVals.size() > 1) {
1000    // Loop through all the equal value numbers merging them into the smallest
1001    // one.
1002    unsigned Smallest = EliminatedLHSVals[0];
1003    for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1004      if (EliminatedLHSVals[i] < Smallest) {
1005        // Merge the current notion of the smallest into the smaller one.
1006        LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1007        Smallest = EliminatedLHSVals[i];
1008      } else {
1009        // Merge into the smallest.
1010        LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1011      }
1012    }
1013    LHSValNo = Smallest;
1014  } else {
1015    assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1016    LHSValNo = EliminatedLHSVals[0];
1017  }
1018
1019  // Okay, now that there is a single LHS value number that we're merging the
1020  // RHS into, update the value number info for the LHS to indicate that the
1021  // value number is defined where the RHS value number was.
1022  LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1023
1024  // Okay, the final step is to loop over the RHS live intervals, adding them to
1025  // the LHS.
1026  LHS.MergeRangesInAsValue(RHS, LHSValNo);
1027  LHS.weight += RHS.weight;
1028
1029  return true;
1030}
1031
1032/// JoinIntervals - Attempt to join these two intervals.  On failure, this
1033/// returns false.  Otherwise, if one of the intervals being joined is a
1034/// physreg, this method always canonicalizes LHS to be it.  The output
1035/// "RHS" will not have been modified, so we can use this information
1036/// below to update aliases.
1037bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
1038  // Compute the final value assignment, assuming that the live ranges can be
1039  // coallesced.
1040  SmallVector<int, 16> LHSValNoAssignments;
1041  SmallVector<int, 16> RHSValNoAssignments;
1042  SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
1043
1044  // Compute ultimate value numbers for the LHS and RHS values.
1045  if (RHS.containsOneValue()) {
1046    // Copies from a liveinterval with a single value are simple to handle and
1047    // very common, handle the special case here.  This is important, because
1048    // often RHS is small and LHS is large (e.g. a physreg).
1049
1050    // Find out if the RHS is defined as a copy from some value in the LHS.
1051    int RHSValID = -1;
1052    std::pair<unsigned,unsigned> RHSValNoInfo;
1053    unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1054    if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1055      // If RHS is not defined as a copy from the LHS, we can use simpler and
1056      // faster checks to see if the live ranges are coallescable.  This joiner
1057      // can't swap the LHS/RHS intervals though.
1058      if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1059        return SimpleJoin(LHS, RHS);
1060      } else {
1061        RHSValNoInfo = RHS.getValNumInfo(0);
1062      }
1063    } else {
1064      // It was defined as a copy from the LHS, find out what value # it is.
1065      unsigned ValInst = RHS.getInstForValNum(0);
1066      RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1067      RHSValNoInfo = LHS.getValNumInfo(RHSValID);
1068    }
1069
1070    LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1071    RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1072    ValueNumberInfo.resize(LHS.getNumValNums());
1073
1074    // Okay, *all* of the values in LHS that are defined as a copy from RHS
1075    // should now get updated.
1076    for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1077      if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1078        if (rep(LHSSrcReg) != RHS.reg) {
1079          // If this is not a copy from the RHS, its value number will be
1080          // unmodified by the coallescing.
1081          ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1082          LHSValNoAssignments[VN] = VN;
1083        } else if (RHSValID == -1) {
1084          // Otherwise, it is a copy from the RHS, and we don't already have a
1085          // value# for it.  Keep the current value number, but remember it.
1086          LHSValNoAssignments[VN] = RHSValID = VN;
1087          ValueNumberInfo[VN] = RHSValNoInfo;
1088        } else {
1089          // Otherwise, use the specified value #.
1090          LHSValNoAssignments[VN] = RHSValID;
1091          if (VN != (unsigned)RHSValID)
1092            ValueNumberInfo[VN].first = ~1U;
1093          else
1094            ValueNumberInfo[VN] = RHSValNoInfo;
1095        }
1096      } else {
1097        ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1098        LHSValNoAssignments[VN] = VN;
1099      }
1100    }
1101
1102    assert(RHSValID != -1 && "Didn't find value #?");
1103    RHSValNoAssignments[0] = RHSValID;
1104
1105  } else {
1106    // Loop over the value numbers of the LHS, seeing if any are defined from
1107    // the RHS.
1108    SmallVector<int, 16> LHSValsDefinedFromRHS;
1109    LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1110    for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1111      unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1112      if (ValSrcReg == 0)  // Src not defined by a copy?
1113        continue;
1114
1115      // DstReg is known to be a register in the LHS interval.  If the src is
1116      // from the RHS interval, we can use its value #.
1117      if (rep(ValSrcReg) != RHS.reg)
1118        continue;
1119
1120      // Figure out the value # from the RHS.
1121      unsigned ValInst = LHS.getInstForValNum(VN);
1122      LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1123    }
1124
1125    // Loop over the value numbers of the RHS, seeing if any are defined from
1126    // the LHS.
1127    SmallVector<int, 16> RHSValsDefinedFromLHS;
1128    RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1129    for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1130      unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1131      if (ValSrcReg == 0)  // Src not defined by a copy?
1132        continue;
1133
1134      // DstReg is known to be a register in the RHS interval.  If the src is
1135      // from the LHS interval, we can use its value #.
1136      if (rep(ValSrcReg) != LHS.reg)
1137        continue;
1138
1139      // Figure out the value # from the LHS.
1140      unsigned ValInst = RHS.getInstForValNum(VN);
1141      RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1142    }
1143
1144    LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1145    RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1146    ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1147
1148    for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1149      if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U)
1150        continue;
1151      ComputeUltimateVN(VN, ValueNumberInfo,
1152                        LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1153                        LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1154    }
1155    for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1156      if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1157        continue;
1158      // If this value number isn't a copy from the LHS, it's a new number.
1159      if (RHSValsDefinedFromLHS[VN] == -1) {
1160        ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1161        RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1162        continue;
1163      }
1164
1165      ComputeUltimateVN(VN, ValueNumberInfo,
1166                        RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1167                        RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1168    }
1169  }
1170
1171  // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1172  // interval lists to see if these intervals are coallescable.
1173  LiveInterval::const_iterator I = LHS.begin();
1174  LiveInterval::const_iterator IE = LHS.end();
1175  LiveInterval::const_iterator J = RHS.begin();
1176  LiveInterval::const_iterator JE = RHS.end();
1177
1178  // Skip ahead until the first place of potential sharing.
1179  if (I->start < J->start) {
1180    I = std::upper_bound(I, IE, J->start);
1181    if (I != LHS.begin()) --I;
1182  } else if (J->start < I->start) {
1183    J = std::upper_bound(J, JE, I->start);
1184    if (J != RHS.begin()) --J;
1185  }
1186
1187  while (1) {
1188    // Determine if these two live ranges overlap.
1189    bool Overlaps;
1190    if (I->start < J->start) {
1191      Overlaps = I->end > J->start;
1192    } else {
1193      Overlaps = J->end > I->start;
1194    }
1195
1196    // If so, check value # info to determine if they are really different.
1197    if (Overlaps) {
1198      // If the live range overlap will map to the same value number in the
1199      // result liverange, we can still coallesce them.  If not, we can't.
1200      if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1201        return false;
1202    }
1203
1204    if (I->end < J->end) {
1205      ++I;
1206      if (I == IE) break;
1207    } else {
1208      ++J;
1209      if (J == JE) break;
1210    }
1211  }
1212
1213  // If we get here, we know that we can coallesce the live ranges.  Ask the
1214  // intervals to coallesce themselves now.
1215  LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
1216           ValueNumberInfo);
1217  return true;
1218}
1219
1220
1221namespace {
1222  // DepthMBBCompare - Comparison predicate that sort first based on the loop
1223  // depth of the basic block (the unsigned), and then on the MBB number.
1224  struct DepthMBBCompare {
1225    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1226    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1227      if (LHS.first > RHS.first) return true;   // Deeper loops first
1228      return LHS.first == RHS.first &&
1229        LHS.second->getNumber() < RHS.second->getNumber();
1230    }
1231  };
1232}
1233
1234
1235void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1236                                       std::vector<CopyRec> &TryAgain) {
1237  DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
1238
1239  for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1240       MII != E;) {
1241    MachineInstr *Inst = MII++;
1242
1243    // If this isn't a copy, we can't join intervals.
1244    unsigned SrcReg, DstReg;
1245    if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1246
1247    if (!JoinCopy(Inst, SrcReg, DstReg))
1248      TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1249  }
1250}
1251
1252
1253void LiveIntervals::joinIntervals() {
1254  DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
1255
1256  std::vector<CopyRec> TryAgainList;
1257
1258  const LoopInfo &LI = getAnalysis<LoopInfo>();
1259  if (LI.begin() == LI.end()) {
1260    // If there are no loops in the function, join intervals in function order.
1261    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1262         I != E; ++I)
1263      CopyCoallesceInMBB(I, TryAgainList);
1264  } else {
1265    // Otherwise, join intervals in inner loops before other intervals.
1266    // Unfortunately we can't just iterate over loop hierarchy here because
1267    // there may be more MBB's than BB's.  Collect MBB's for sorting.
1268    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1269    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1270         I != E; ++I)
1271      MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1272
1273    // Sort by loop depth.
1274    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1275
1276    // Finally, join intervals in loop nest order.
1277    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1278      CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1279  }
1280
1281  // Joining intervals can allow other intervals to be joined.  Iteratively join
1282  // until we make no progress.
1283  bool ProgressMade = true;
1284  while (ProgressMade) {
1285    ProgressMade = false;
1286
1287    for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1288      CopyRec &TheCopy = TryAgainList[i];
1289      if (TheCopy.MI &&
1290          JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1291        TheCopy.MI = 0;   // Mark this one as done.
1292        ProgressMade = true;
1293      }
1294    }
1295  }
1296
1297  DEBUG(std::cerr << "*** Register mapping ***\n");
1298  DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1299          if (r2rMap_[i]) {
1300            std::cerr << "  reg " << i << " -> ";
1301            printRegName(r2rMap_[i]);
1302            std::cerr << "\n";
1303          });
1304}
1305
1306/// Return true if the two specified registers belong to different register
1307/// classes.  The registers may be either phys or virt regs.
1308bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1309                                             unsigned RegB) const {
1310
1311  // Get the register classes for the first reg.
1312  if (MRegisterInfo::isPhysicalRegister(RegA)) {
1313    assert(MRegisterInfo::isVirtualRegister(RegB) &&
1314           "Shouldn't consider two physregs!");
1315    return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1316  }
1317
1318  // Compare against the regclass for the second reg.
1319  const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1320  if (MRegisterInfo::isVirtualRegister(RegB))
1321    return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1322  else
1323    return !RegClass->contains(RegB);
1324}
1325
1326LiveInterval LiveIntervals::createInterval(unsigned reg) {
1327  float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1328                       (float)HUGE_VAL : 0.0F;
1329  return LiveInterval(reg, Weight);
1330}
1331