Implement support for the formal_arguments node. To get this, targets shouldcustom...
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
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>
38 using namespace llvm;
39
40 namespace {
41   RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
42
43   Statistic<> numIntervals
44   ("liveintervals", "Number of original intervals");
45
46   Statistic<> numIntervalsAfter
47   ("liveintervals", "Number of intervals after coalescing");
48
49   Statistic<> numJoins
50   ("liveintervals", "Number of interval joins performed");
51
52   Statistic<> numPeep
53   ("liveintervals", "Number of identity moves eliminated after coalescing");
54
55   Statistic<> numFolded
56   ("liveintervals", "Number of loads/stores folded into instructions");
57
58   cl::opt<bool>
59   EnableJoining("join-liveintervals",
60                 cl::desc("Join compatible live intervals"),
61                 cl::init(true));
62 };
63
64 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
65 {
66   AU.addRequired<LiveVariables>();
67   AU.addPreservedID(PHIEliminationID);
68   AU.addRequiredID(PHIEliminationID);
69   AU.addRequiredID(TwoAddressInstructionPassID);
70   AU.addRequired<LoopInfo>();
71   MachineFunctionPass::getAnalysisUsage(AU);
72 }
73
74 void LiveIntervals::releaseMemory()
75 {
76   mi2iMap_.clear();
77   i2miMap_.clear();
78   r2iMap_.clear();
79   r2rMap_.clear();
80 }
81
82
83 /// runOnMachineFunction - Register allocate the whole function
84 ///
85 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
86   mf_ = &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());
93
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;
99
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)) {
105         RC = *RCI;
106         break;
107       }
108
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!");
114   }
115
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();
121          mi != miEnd; ++mi) {
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;
126     }
127
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, true);
135       for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
136         handlePhysicalRegisterDef(Entry, Entry->begin(),
137                                   getOrCreateInterval(*AS), 0, 0, true);
138     }
139   }
140
141   computeIntervals();
142
143   numIntervals += getNumIntervals();
144
145   DEBUG(std::cerr << "********** INTERVALS **********\n";
146         for (iterator I = begin(), E = end(); I != E; ++I) {
147           I->second.print(std::cerr, mri_);
148           std::cerr << "\n";
149         });
150
151   // join intervals if requested
152   if (EnableJoining) joinIntervals();
153
154   numIntervalsAfter += getNumIntervals();
155
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>();
159
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());
164
165     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
166          mii != mie; ) {
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);
179         }
180         mii = mbbi->erase(mii);
181         ++numPeep;
182       }
183       else {
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);
191
192             LiveInterval &RegInt = getInterval(reg);
193             RegInt.weight +=
194               (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
195           }
196         }
197         ++mii;
198       }
199     }
200   }
201
202   DEBUG(dump());
203   return true;
204 }
205
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_);
211     std::cerr << "\n";
212   }
213
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;
221     }
222   }
223 }
224
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>();
230
231   std::vector<LiveInterval*> added;
232
233   assert(li.weight != HUGE_VAL &&
234          "attempt to spill already spilled interval!");
235
236   DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
237         << li << '\n');
238
239   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
240
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;
250
251       MachineInstr *MI = getInstructionFromIndex(index);
252
253       // NewRegLiveIn - This instruction might have multiple uses of the spilled
254       // register.  In this case, for the first use, keep track of the new vreg
255       // that we reload it into.  If we see a second use, reuse this vreg
256       // instead of creating live ranges for two reloads.
257       unsigned NewRegLiveIn = 0;
258
259     for_operand:
260       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
261         MachineOperand& mop = MI->getOperand(i);
262         if (mop.isRegister() && mop.getReg() == li.reg) {
263           if (NewRegLiveIn && mop.isUse()) {
264             // We already emitted a reload of this value, reuse it for
265             // subsequent operands.
266             MI->SetMachineOperandReg(i, NewRegLiveIn);
267             DEBUG(std::cerr << "\t\t\t\treused reload into reg" << NewRegLiveIn
268                             << " for operand #" << i << '\n');
269           } else 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             vrm.virtFolded(li.reg, MI, i, fmi);
275             mi2iMap_.erase(MI);
276             i2miMap_[index/InstrSlots::NUM] = fmi;
277             mi2iMap_[fmi] = index;
278             MachineBasicBlock &MBB = *MI->getParent();
279             MI = MBB.insert(MBB.erase(MI), fmi);
280             ++numFolded;
281
282             // Folding the load/store can completely change the instruction in
283             // unpredictable ways, rescan it from the beginning.
284             goto for_operand;
285           } else {
286             // This is tricky. We need to add information in the interval about
287             // the spill code so we have to use our extra load/store slots.
288             //
289             // If we have a use we are going to have a load so we start the
290             // interval from the load slot onwards. Otherwise we start from the
291             // def slot.
292             unsigned start = (mop.isUse() ?
293                               getLoadIndex(index) :
294                               getDefIndex(index));
295             // If we have a def we are going to have a store right after it so
296             // we end the interval after the use of the next
297             // instruction. Otherwise we end after the use of this instruction.
298             unsigned end = 1 + (mop.isDef() ?
299                                 getStoreIndex(index) :
300                                 getUseIndex(index));
301
302             // create a new register for this spill
303             NewRegLiveIn = mf_->getSSARegMap()->createVirtualRegister(rc);
304             MI->SetMachineOperandReg(i, NewRegLiveIn);
305             vrm.grow();
306             vrm.assignVirt2StackSlot(NewRegLiveIn, slot);
307             LiveInterval& nI = getOrCreateInterval(NewRegLiveIn);
308             assert(nI.empty());
309
310             // the spill weight is now infinity as it
311             // cannot be spilled again
312             nI.weight = float(HUGE_VAL);
313             LiveRange LR(start, end, nI.getNextValue());
314             DEBUG(std::cerr << " +" << LR);
315             nI.addRange(LR);
316             added.push_back(&nI);
317
318             // update live variables if it is available
319             if (lv_)
320               lv_->addVirtualRegisterKilled(NewRegLiveIn, MI);
321             
322             // If this is a live in, reuse it for subsequent live-ins.  If it's
323             // a def, we can't do this.
324             if (!mop.isUse()) NewRegLiveIn = 0;
325             
326             DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
327           }
328         }
329       }
330     }
331   }
332
333   return added;
334 }
335
336 void LiveIntervals::printRegName(unsigned reg) const
337 {
338   if (MRegisterInfo::isPhysicalRegister(reg))
339     std::cerr << mri_->getName(reg);
340   else
341     std::cerr << "%reg" << reg;
342 }
343
344 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
345                                              MachineBasicBlock::iterator mi,
346                                              LiveInterval& interval)
347 {
348   DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
349   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
350
351   // Virtual registers may be defined multiple times (due to phi
352   // elimination and 2-addr elimination).  Much of what we do only has to be
353   // done once for the vreg.  We use an empty interval to detect the first
354   // time we see a vreg.
355   if (interval.empty()) {
356     // Get the Idx of the defining instructions.
357     unsigned defIndex = getDefIndex(getInstructionIndex(mi));
358
359     unsigned ValNum = interval.getNextValue();
360     assert(ValNum == 0 && "First value in interval is not 0?");
361     ValNum = 0;  // Clue in the optimizer.
362
363     // Loop over all of the blocks that the vreg is defined in.  There are
364     // two cases we have to handle here.  The most common case is a vreg
365     // whose lifetime is contained within a basic block.  In this case there
366     // will be a single kill, in MBB, which comes after the definition.
367     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
368       // FIXME: what about dead vars?
369       unsigned killIdx;
370       if (vi.Kills[0] != mi)
371         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
372       else
373         killIdx = defIndex+1;
374
375       // If the kill happens after the definition, we have an intra-block
376       // live range.
377       if (killIdx > defIndex) {
378         assert(vi.AliveBlocks.empty() &&
379                "Shouldn't be alive across any blocks!");
380         LiveRange LR(defIndex, killIdx, ValNum);
381         interval.addRange(LR);
382         DEBUG(std::cerr << " +" << LR << "\n");
383         return;
384       }
385     }
386
387     // The other case we handle is when a virtual register lives to the end
388     // of the defining block, potentially live across some blocks, then is
389     // live into some number of blocks, but gets killed.  Start by adding a
390     // range that goes from this definition to the end of the defining block.
391     LiveRange NewLR(defIndex,
392                     getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
393                     ValNum);
394     DEBUG(std::cerr << " +" << NewLR);
395     interval.addRange(NewLR);
396
397     // Iterate over all of the blocks that the variable is completely
398     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
399     // live interval.
400     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
401       if (vi.AliveBlocks[i]) {
402         MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
403         if (!mbb->empty()) {
404           LiveRange LR(getInstructionIndex(&mbb->front()),
405                        getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
406                        ValNum);
407           interval.addRange(LR);
408           DEBUG(std::cerr << " +" << LR);
409         }
410       }
411     }
412
413     // Finally, this virtual register is live from the start of any killing
414     // block to the 'use' slot of the killing instruction.
415     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
416       MachineInstr *Kill = vi.Kills[i];
417       LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
418                    getUseIndex(getInstructionIndex(Kill))+1,
419                    ValNum);
420       interval.addRange(LR);
421       DEBUG(std::cerr << " +" << LR);
422     }
423
424   } else {
425     // If this is the second time we see a virtual register definition, it
426     // must be due to phi elimination or two addr elimination.  If this is
427     // the result of two address elimination, then the vreg is the first
428     // operand, and is a def-and-use.
429     if (mi->getOperand(0).isRegister() &&
430         mi->getOperand(0).getReg() == interval.reg &&
431         mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
432       // If this is a two-address definition, then we have already processed
433       // the live range.  The only problem is that we didn't realize there
434       // are actually two values in the live interval.  Because of this we
435       // need to take the LiveRegion that defines this register and split it
436       // into two values.
437       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
438       unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
439
440       // Delete the initial value, which should be short and continuous,
441       // becuase the 2-addr copy must be in the same MBB as the redef.
442       interval.removeRange(DefIndex, RedefIndex);
443
444       LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
445       DEBUG(std::cerr << " replace range with " << LR);
446       interval.addRange(LR);
447
448       // If this redefinition is dead, we need to add a dummy unit live
449       // range covering the def slot.
450       if (lv_->RegisterDefIsDead(mi, interval.reg))
451         interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
452
453       DEBUG(std::cerr << "RESULT: " << interval);
454
455     } else {
456       // Otherwise, this must be because of phi elimination.  If this is the
457       // first redefinition of the vreg that we have seen, go back and change
458       // the live range in the PHI block to be a different value number.
459       if (interval.containsOneValue()) {
460         assert(vi.Kills.size() == 1 &&
461                "PHI elimination vreg should have one kill, the PHI itself!");
462
463         // Remove the old range that we now know has an incorrect number.
464         MachineInstr *Killer = vi.Kills[0];
465         unsigned Start = getInstructionIndex(Killer->getParent()->begin());
466         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
467         DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
468               << interval << "\n");
469         interval.removeRange(Start, End);
470         DEBUG(std::cerr << "RESULT: " << interval);
471
472         // Replace the interval with one of a NEW value number.
473         LiveRange LR(Start, End, interval.getNextValue());
474         DEBUG(std::cerr << " replace range with " << LR);
475         interval.addRange(LR);
476         DEBUG(std::cerr << "RESULT: " << interval);
477       }
478
479       // In the case of PHI elimination, each variable definition is only
480       // live until the end of the block.  We've already taken care of the
481       // rest of the live range.
482       unsigned defIndex = getDefIndex(getInstructionIndex(mi));
483       LiveRange LR(defIndex,
484                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
485                    interval.getNextValue());
486       interval.addRange(LR);
487       DEBUG(std::cerr << " +" << LR);
488     }
489   }
490
491   DEBUG(std::cerr << '\n');
492 }
493
494 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
495                                               MachineBasicBlock::iterator mi,
496                                               LiveInterval& interval,
497                                               unsigned SrcReg, unsigned DestReg,
498                                               bool isLiveIn)
499 {
500   // A physical register cannot be live across basic block, so its
501   // lifetime must end somewhere in its defining basic block.
502   DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
503   typedef LiveVariables::killed_iterator KillIter;
504
505   unsigned baseIndex = getInstructionIndex(mi);
506   unsigned start = getDefIndex(baseIndex);
507   unsigned end = start;
508
509   // If it is not used after definition, it is considered dead at
510   // the instruction defining it. Hence its interval is:
511   // [defSlot(def), defSlot(def)+1)
512   if (lv_->RegisterDefIsDead(mi, interval.reg)) {
513     DEBUG(std::cerr << " dead");
514     end = getDefIndex(start) + 1;
515     goto exit;
516   }
517
518   // If it is not dead on definition, it must be killed by a
519   // subsequent instruction. Hence its interval is:
520   // [defSlot(def), useSlot(kill)+1)
521   while (++mi != MBB->end()) {
522     baseIndex += InstrSlots::NUM;
523     if (lv_->KillsRegister(mi, interval.reg)) {
524       DEBUG(std::cerr << " killed");
525       end = getUseIndex(baseIndex) + 1;
526       goto exit;
527     }
528   }
529   
530   // The only case we should have a dead physreg here without a killing or
531   // instruction where we know it's dead is if it is live-in to the function
532   // and never used.
533   assert(isLiveIn && "physreg was not killed in defining block!");
534   end = getDefIndex(start) + 1;  // It's dead.
535
536 exit:
537   assert(start < end && "did not find end of interval?");
538
539   // Finally, if this is defining a new range for the physical register, and if
540   // that physreg is just a copy from a vreg, and if THAT vreg was a copy from
541   // the physreg, then the new fragment has the same value as the one copied
542   // into the vreg.
543   if (interval.reg == DestReg && !interval.empty() &&
544       MRegisterInfo::isVirtualRegister(SrcReg)) {
545
546     // Get the live interval for the vreg, see if it is defined by a copy.
547     LiveInterval &SrcInterval = getOrCreateInterval(SrcReg);
548
549     if (SrcInterval.containsOneValue()) {
550       assert(!SrcInterval.empty() && "Can't contain a value and be empty!");
551
552       // Get the first index of the first range.  Though the interval may have
553       // multiple liveranges in it, we only check the first.
554       unsigned StartIdx = SrcInterval.begin()->start;
555       MachineInstr *SrcDefMI = getInstructionFromIndex(StartIdx);
556
557       // Check to see if the vreg was defined by a copy instruction, and that
558       // the source was this physreg.
559       unsigned VRegSrcSrc, VRegSrcDest;
560       if (tii_->isMoveInstr(*SrcDefMI, VRegSrcSrc, VRegSrcDest) &&
561           SrcReg == VRegSrcDest && VRegSrcSrc == DestReg) {
562         // Okay, now we know that the vreg was defined by a copy from this
563         // physreg.  Find the value number being copied and use it as the value
564         // for this range.
565         const LiveRange *DefRange = interval.getLiveRangeContaining(StartIdx-1);
566         if (DefRange) {
567           LiveRange LR(start, end, DefRange->ValId);
568           interval.addRange(LR);
569           DEBUG(std::cerr << " +" << LR << '\n');
570           return;
571         }
572       }
573     }
574   }
575
576
577   LiveRange LR(start, end, interval.getNextValue());
578   interval.addRange(LR);
579   DEBUG(std::cerr << " +" << LR << '\n');
580 }
581
582 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
583                                       MachineBasicBlock::iterator MI,
584                                       unsigned reg) {
585   if (MRegisterInfo::isVirtualRegister(reg))
586     handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
587   else if (allocatableRegs_[reg]) {
588     unsigned SrcReg = 0, DestReg = 0;
589     if (!tii_->isMoveInstr(*MI, SrcReg, DestReg))
590       SrcReg = DestReg = 0;
591
592     handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg),
593                               SrcReg, DestReg);
594     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
595       handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS),
596                                 SrcReg, DestReg);
597   }
598 }
599
600 /// computeIntervals - computes the live intervals for virtual
601 /// registers. for some ordering of the machine instructions [1,N] a
602 /// live interval is an interval [i, j) where 1 <= i <= j < N for
603 /// which a variable is live
604 void LiveIntervals::computeIntervals()
605 {
606   DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
607   DEBUG(std::cerr << "********** Function: "
608         << ((Value*)mf_->getFunction())->getName() << '\n');
609   bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
610
611   for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
612        I != E; ++I) {
613     MachineBasicBlock* mbb = I;
614     DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
615
616     MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
617     if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
618     for (; mi != miEnd; ++mi) {
619       const TargetInstrDescriptor& tid =
620         tm_->getInstrInfo()->get(mi->getOpcode());
621       DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
622
623       // handle implicit defs
624       for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
625         handleRegisterDef(mbb, mi, *id);
626
627       // handle explicit defs
628       for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
629         MachineOperand& mop = mi->getOperand(i);
630         // handle register defs - build intervals
631         if (mop.isRegister() && mop.getReg() && mop.isDef())
632           handleRegisterDef(mbb, mi, mop.getReg());
633       }
634     }
635   }
636 }
637
638 /// IntA is defined as a copy from IntB and we know it only has one value
639 /// number.  If all of the places that IntA and IntB overlap are defined by
640 /// copies from IntA to IntB, we know that these two ranges can really be
641 /// merged if we adjust the value numbers.  If it is safe, adjust the value
642 /// numbers and return true, allowing coalescing to occur.
643 bool LiveIntervals::
644 AdjustIfAllOverlappingRangesAreCopiesFrom(LiveInterval &IntA,
645                                           LiveInterval &IntB,
646                                           unsigned CopyIdx) {
647   std::vector<LiveRange*> Ranges;
648   IntA.getOverlapingRanges(IntB, CopyIdx, Ranges);
649   
650   assert(!Ranges.empty() && "Why didn't we do a simple join of this?");
651   
652   unsigned IntBRep = rep(IntB.reg);
653   
654   // Check to see if all of the overlaps (entries in Ranges) are defined by a
655   // copy from IntA.  If not, exit.
656   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
657     unsigned Idx = Ranges[i]->start;
658     MachineInstr *MI = getInstructionFromIndex(Idx);
659     unsigned SrcReg, DestReg;
660     if (!tii_->isMoveInstr(*MI, SrcReg, DestReg)) return false;
661     
662     // If this copy isn't actually defining this range, it must be a live
663     // range spanning basic blocks or something.
664     if (rep(DestReg) != rep(IntA.reg)) return false;
665     
666     // Check to see if this is coming from IntB.  If not, bail out.
667     if (rep(SrcReg) != IntBRep) return false;
668   }
669
670   // Okay, we can change this one.  Get the IntB value number that IntA is
671   // copied from.
672   unsigned ActualValNo = IntA.getLiveRangeContaining(CopyIdx-1)->ValId;
673   
674   // Change all of the value numbers to the same as what we IntA is copied from.
675   for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
676     Ranges[i]->ValId = ActualValNo;
677   
678   return true;
679 }
680
681 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
682   DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
683
684   for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
685        mi != mie; ++mi) {
686     DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
687
688     // we only join virtual registers with allocatable
689     // physical registers since we do not have liveness information
690     // on not allocatable physical registers
691     unsigned SrcReg, DestReg;
692     if (tii_->isMoveInstr(*mi, SrcReg, DestReg) &&
693         (MRegisterInfo::isVirtualRegister(SrcReg) || allocatableRegs_[SrcReg])&&
694         (MRegisterInfo::isVirtualRegister(DestReg)||allocatableRegs_[DestReg])){
695
696       // Get representative registers.
697       SrcReg = rep(SrcReg);
698       DestReg = rep(DestReg);
699
700       // If they are already joined we continue.
701       if (SrcReg == DestReg)
702         continue;
703
704       // If they are both physical registers, we cannot join them.
705       if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
706           MRegisterInfo::isPhysicalRegister(DestReg))
707         continue;
708
709       // If they are not of the same register class, we cannot join them.
710       if (differingRegisterClasses(SrcReg, DestReg))
711         continue;
712
713       LiveInterval &SrcInt = getInterval(SrcReg);
714       LiveInterval &DestInt = getInterval(DestReg);
715       assert(SrcInt.reg == SrcReg && DestInt.reg == DestReg &&
716              "Register mapping is horribly broken!");
717
718       DEBUG(std::cerr << "\t\tInspecting " << SrcInt << " and " << DestInt
719                       << ": ");
720
721       // If two intervals contain a single value and are joined by a copy, it
722       // does not matter if the intervals overlap, they can always be joined.
723       bool Joinable = SrcInt.containsOneValue() && DestInt.containsOneValue();
724
725       unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
726       
727       // If the intervals think that this is joinable, do so now.
728       if (!Joinable && DestInt.joinable(SrcInt, MIDefIdx))
729         Joinable = true;
730
731       // If DestInt is actually a copy from SrcInt (which we know) that is used
732       // to define another value of SrcInt, we can change the other range of
733       // SrcInt to be the value of the range that defines DestInt, allowing a
734       // coalesce.
735       if (!Joinable && DestInt.containsOneValue() &&
736           AdjustIfAllOverlappingRangesAreCopiesFrom(SrcInt, DestInt, MIDefIdx))
737         Joinable = true;
738       
739       if (!Joinable || overlapsAliases(&SrcInt, &DestInt)) {
740         DEBUG(std::cerr << "Interference!\n");
741       } else {
742         DestInt.join(SrcInt, MIDefIdx);
743         DEBUG(std::cerr << "Joined.  Result = " << DestInt << "\n");
744
745         if (!MRegisterInfo::isPhysicalRegister(SrcReg)) {
746           r2iMap_.erase(SrcReg);
747           r2rMap_[SrcReg] = DestReg;
748         } else {
749           // Otherwise merge the data structures the other way so we don't lose
750           // the physreg information.
751           r2rMap_[DestReg] = SrcReg;
752           DestInt.reg = SrcReg;
753           SrcInt.swap(DestInt);
754           r2iMap_.erase(DestReg);
755         }
756         ++numJoins;
757       }
758     }
759   }
760 }
761
762 namespace {
763   // DepthMBBCompare - Comparison predicate that sort first based on the loop
764   // depth of the basic block (the unsigned), and then on the MBB number.
765   struct DepthMBBCompare {
766     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
767     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
768       if (LHS.first > RHS.first) return true;   // Deeper loops first
769       return LHS.first == RHS.first &&
770         LHS.second->getNumber() < RHS.second->getNumber();
771     }
772   };
773 }
774
775 void LiveIntervals::joinIntervals() {
776   DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
777
778   const LoopInfo &LI = getAnalysis<LoopInfo>();
779   if (LI.begin() == LI.end()) {
780     // If there are no loops in the function, join intervals in function order.
781     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
782          I != E; ++I)
783       joinIntervalsInMachineBB(I);
784   } else {
785     // Otherwise, join intervals in inner loops before other intervals.
786     // Unfortunately we can't just iterate over loop hierarchy here because
787     // there may be more MBB's than BB's.  Collect MBB's for sorting.
788     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
789     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
790          I != E; ++I)
791       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
792
793     // Sort by loop depth.
794     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
795
796     // Finally, join intervals in loop nest order.
797     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
798       joinIntervalsInMachineBB(MBBs[i].second);
799   }
800
801   DEBUG(std::cerr << "*** Register mapping ***\n");
802   DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
803           if (r2rMap_[i])
804              std::cerr << "  reg " << i << " -> reg " << r2rMap_[i] << "\n");
805 }
806
807 /// Return true if the two specified registers belong to different register
808 /// classes.  The registers may be either phys or virt regs.
809 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
810                                              unsigned RegB) const {
811
812   // Get the register classes for the first reg.
813   if (MRegisterInfo::isPhysicalRegister(RegA)) {
814     assert(MRegisterInfo::isVirtualRegister(RegB) &&
815            "Shouldn't consider two physregs!");
816     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
817   }
818
819   // Compare against the regclass for the second reg.
820   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
821   if (MRegisterInfo::isVirtualRegister(RegB))
822     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
823   else
824     return !RegClass->contains(RegB);
825 }
826
827 bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
828                                     const LiveInterval *RHS) const {
829   if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
830     if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
831       return false;   // vreg-vreg merge has no aliases!
832     std::swap(LHS, RHS);
833   }
834
835   assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
836          MRegisterInfo::isVirtualRegister(RHS->reg) &&
837          "first interval must describe a physical register");
838
839   for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
840     if (RHS->overlaps(getInterval(*AS)))
841       return true;
842
843   return false;
844 }
845
846 LiveInterval LiveIntervals::createInterval(unsigned reg) {
847   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
848                        (float)HUGE_VAL :0.0F;
849   return LiveInterval(reg, Weight);
850 }