Do not use MachineOperand::isVirtualRegister either!
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervals.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/LiveIntervals.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CFG.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 #include <cmath>
34 #include <iostream>
35 #include <limits>
36
37 using namespace llvm;
38
39 namespace {
40     RegisterAnalysis<LiveIntervals> X("liveintervals",
41                                       "Live Interval Analysis");
42
43     Statistic<> numIntervals("liveintervals", "Number of intervals");
44     Statistic<> numJoined   ("liveintervals", "Number of joined intervals");
45
46     cl::opt<bool>
47     join("join-liveintervals",
48          cl::desc("Join compatible live intervals"),
49          cl::init(true));
50 };
51
52 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
53 {
54     AU.addPreserved<LiveVariables>();
55     AU.addRequired<LiveVariables>();
56     AU.addPreservedID(PHIEliminationID);
57     AU.addRequiredID(PHIEliminationID);
58     AU.addRequiredID(TwoAddressInstructionPassID);
59     AU.addRequired<LoopInfo>();
60     MachineFunctionPass::getAnalysisUsage(AU);
61 }
62
63 void LiveIntervals::releaseMemory()
64 {
65     mbbi2mbbMap_.clear();
66     mi2iMap_.clear();
67     r2iMap_.clear();
68     r2iMap_.clear();
69     r2rMap_.clear();
70     intervals_.clear();
71 }
72
73
74 /// runOnMachineFunction - Register allocate the whole function
75 ///
76 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
77     DEBUG(std::cerr << "Machine Function\n");
78     mf_ = &fn;
79     tm_ = &fn.getTarget();
80     mri_ = tm_->getRegisterInfo();
81     lv_ = &getAnalysis<LiveVariables>();
82
83     // number MachineInstrs
84     unsigned miIndex = 0;
85     for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
86          mbb != mbbEnd; ++mbb) {
87         const std::pair<MachineBasicBlock*, unsigned>& entry =
88             lv_->getMachineBasicBlockInfo(mbb);
89         bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
90                                                            entry.first)).second;
91         assert(inserted && "multiple index -> MachineBasicBlock");
92
93         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
94              mi != miEnd; ++mi) {
95             inserted = mi2iMap_.insert(std::make_pair(*mi, miIndex)).second;
96             assert(inserted && "multiple MachineInstr -> index mappings");
97             miIndex += 2;
98         }
99     }
100
101     computeIntervals();
102
103     // compute spill weights
104     const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
105     const TargetInstrInfo& tii = tm_->getInstrInfo();
106
107     for (MachineFunction::const_iterator mbbi = mf_->begin(),
108              mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
109         const MachineBasicBlock* mbb = mbbi;
110         unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
111
112         for (MachineBasicBlock::const_iterator mii = mbb->begin(),
113                  mie = mbb->end(); mii != mie; ++mii) {
114             MachineInstr* mi = *mii;
115
116             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
117                 MachineOperand& mop = mi->getOperand(i);
118                 if (mop.isRegister() &&
119                     MRegisterInfo::isVirtualRegister(mop.getReg())) {
120                     unsigned reg = mop.getAllocatedRegNum();
121                     Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
122                     assert(r2iit != r2iMap_.end());
123                     r2iit->second->weight += pow(10.0F, loopDepth);
124                 }
125             }
126         }
127     }
128
129     // join intervals if requested
130     if (join) joinIntervals();
131
132     numIntervals += intervals_.size();
133
134     intervals_.sort(StartPointComp());
135     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
136                     std::ostream_iterator<Interval>(std::cerr, "\n")));
137     return true;
138 }
139
140 void LiveIntervals::printRegName(unsigned reg) const
141 {
142     if (MRegisterInfo::isPhysicalRegister(reg))
143         std::cerr << mri_->getName(reg);
144     else
145         std::cerr << '%' << reg;
146 }
147
148 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
149                                              MachineBasicBlock::iterator mi,
150                                              unsigned reg)
151 {
152     DEBUG(std::cerr << "\t\tregister: ";printRegName(reg); std::cerr << '\n');
153
154     LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
155
156     Interval* interval = 0;
157     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
158     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
159         // add new interval
160         intervals_.push_back(Interval(reg));
161         // update interval index for this register
162         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
163         interval = &intervals_.back();
164
165         // iterate over all of the blocks that the variable is
166         // completely live in, adding them to the live
167         // interval. obviously we only need to do this once.
168         for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
169             if (vi.AliveBlocks[i]) {
170                 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
171                 if (!mbb->empty()) {
172                     interval->addRange(getInstructionIndex(mbb->front()),
173                                        getInstructionIndex(mbb->back()) + 1);
174                 }
175             }
176         }
177     }
178     else {
179         interval = &*r2iit->second;
180     }
181
182     // we consider defs to happen at the second time slot of the
183     // instruction
184     unsigned instrIndex = getInstructionIndex(*mi) + 1;
185
186     bool killedInDefiningBasicBlock = false;
187     for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
188         MachineBasicBlock* killerBlock = vi.Kills[i].first;
189         MachineInstr* killerInstr = vi.Kills[i].second;
190         unsigned start = (mbb == killerBlock ?
191                           instrIndex :
192                           getInstructionIndex(killerBlock->front()));
193         unsigned end = (killerInstr == *mi ?
194                         instrIndex + 1 : // dead
195                         getInstructionIndex(killerInstr) + 1); // killed
196         // we do not want to add invalid ranges. these can happen when
197         // a variable has its latest use and is redefined later on in
198         // the same basic block (common with variables introduced by
199         // PHI elimination)
200         if (start < end) {
201             killedInDefiningBasicBlock |= mbb == killerBlock;
202             interval->addRange(start, end);
203         }
204     }
205
206     if (!killedInDefiningBasicBlock) {
207         unsigned end = getInstructionIndex(mbb->back()) + 1;
208         interval->addRange(instrIndex, end);
209     }
210 }
211
212 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
213                                               MachineBasicBlock::iterator mi,
214                                               unsigned reg)
215 {
216     typedef LiveVariables::killed_iterator KillIter;
217
218     DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
219
220     MachineBasicBlock::iterator e = mbb->end();
221     // we consider defs to happen at the second time slot of the
222     // instruction
223     unsigned start, end;
224     start = end = getInstructionIndex(*mi) + 1;
225
226     // a variable can be dead by the instruction defining it
227     for (KillIter ki = lv_->dead_begin(*mi), ke = lv_->dead_end(*mi);
228          ki != ke; ++ki) {
229         if (reg == ki->second) {
230             DEBUG(std::cerr << " dead\n");
231             ++end;
232             goto exit;
233         }
234     }
235
236     // a variable can only be killed by subsequent instructions
237     do {
238         ++mi;
239         end += 2;
240         for (KillIter ki = lv_->killed_begin(*mi), ke = lv_->killed_end(*mi);
241              ki != ke; ++ki) {
242             if (reg == ki->second) {
243                 DEBUG(std::cerr << " killed\n");
244                 goto exit;
245             }
246         }
247     } while (mi != e);
248
249 exit:
250     assert(start < end && "did not find end of interval?");
251
252     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
253     if (r2iit != r2iMap_.end() && r2iit->first == reg) {
254         r2iit->second->addRange(start, end);
255     }
256     else {
257         intervals_.push_back(Interval(reg));
258         // update interval index for this register
259         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
260         intervals_.back().addRange(start, end);
261     }
262 }
263
264 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
265                                       MachineBasicBlock::iterator mi,
266                                       unsigned reg)
267 {
268     if (MRegisterInfo::isPhysicalRegister(reg)) {
269         if (lv_->getAllocatablePhysicalRegisters()[reg]) {
270             handlePhysicalRegisterDef(mbb, mi, reg);
271             for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
272                 handlePhysicalRegisterDef(mbb, mi, *as);
273         }
274     }
275     else {
276         handleVirtualRegisterDef(mbb, mi, reg);
277     }
278 }
279
280 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
281 {
282     assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
283            "instruction not assigned a number");
284     return mi2iMap_.find(instr)->second;
285 }
286
287 /// computeIntervals - computes the live intervals for virtual
288 /// registers. for some ordering of the machine instructions [1,N] a
289 /// live interval is an interval [i, j) where 1 <= i <= j < N for
290 /// which a variable is live
291 void LiveIntervals::computeIntervals()
292 {
293     DEBUG(std::cerr << "computing live intervals:\n");
294
295     for (MbbIndex2MbbMap::iterator
296              it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
297          it != itEnd; ++it) {
298         MachineBasicBlock* mbb = it->second;
299         DEBUG(std::cerr << "machine basic block: "
300               << mbb->getBasicBlock()->getName() << "\n");
301
302         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
303              mi != miEnd; ++mi) {
304             MachineInstr* instr = *mi;
305             const TargetInstrDescriptor& tid =
306                 tm_->getInstrInfo().get(instr->getOpcode());
307             DEBUG(std::cerr << "\t[" << getInstructionIndex(instr) << "] ";
308                   instr->print(std::cerr, *tm_););
309
310             // handle implicit defs
311             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
312                 handleRegisterDef(mbb, mi, *id);
313
314             // handle explicit defs
315             for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
316                 MachineOperand& mop = instr->getOperand(i);
317                 // handle register defs - build intervals
318                 if (mop.isRegister() && mop.isDef())
319                     handleRegisterDef(mbb, mi, mop.getAllocatedRegNum());
320             }
321         }
322     }
323 }
324
325 unsigned LiveIntervals::rep(unsigned reg)
326 {
327     Reg2RegMap::iterator it = r2rMap_.find(reg);
328     if (it != r2rMap_.end())
329         return it->second = rep(it->second);
330     return reg;
331 }
332
333 void LiveIntervals::joinIntervals()
334 {
335     DEBUG(std::cerr << "joining compatible intervals:\n");
336
337     const TargetInstrInfo& tii = tm_->getInstrInfo();
338
339     for (MachineFunction::const_iterator mbbi = mf_->begin(),
340              mbbe = mf_->end(); mbbi != mbbe; ++mbbi) {
341         const MachineBasicBlock* mbb = mbbi;
342         DEBUG(std::cerr << "machine basic block: "
343               << mbb->getBasicBlock()->getName() << "\n");
344
345         for (MachineBasicBlock::const_iterator mii = mbb->begin(),
346                  mie = mbb->end(); mii != mie; ++mii) {
347             MachineInstr* mi = *mii;
348             const TargetInstrDescriptor& tid =
349                 tm_->getInstrInfo().get(mi->getOpcode());
350             DEBUG(std::cerr << "\t\tinstruction["
351                   << getInstructionIndex(mi) << "]: ";
352                   mi->print(std::cerr, *tm_););
353
354             // we only join virtual registers with allocatable
355             // physical registers since we do not have liveness information
356             // on not allocatable physical registers
357             unsigned regA, regB;
358             if (tii.isMoveInstr(*mi, regA, regB) &&
359                 (MRegisterInfo::isVirtualRegister(regA) ||
360                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
361                 (MRegisterInfo::isVirtualRegister(regB) ||
362                  lv_->getAllocatablePhysicalRegisters()[regB])) {
363
364                 // get representative registers
365                 regA = rep(regA);
366                 regB = rep(regB);
367
368                 // if they are already joined we continue
369                 if (regA == regB)
370                     continue;
371
372                 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
373                 assert(r2iA != r2iMap_.end());
374                 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
375                 assert(r2iB != r2iMap_.end());
376
377                 Intervals::iterator intA = r2iA->second;
378                 Intervals::iterator intB = r2iB->second;
379
380                 // both A and B are virtual registers
381                 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
382                     MRegisterInfo::isVirtualRegister(intB->reg)) {
383
384                     const TargetRegisterClass *rcA, *rcB;
385                     rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
386                     rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
387                     assert(rcA == rcB && "registers must be of the same class");
388
389                     // if their intervals do not overlap we join them
390                     if (!intB->overlaps(*intA)) {
391                         intA->join(*intB);
392                         r2iB->second = r2iA->second;
393                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
394                         intervals_.erase(intB);
395                         ++numJoined;
396                     }
397                 }
398                 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
399                          MRegisterInfo::isPhysicalRegister(intB->reg)) {
400                     if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
401                         std::swap(regA, regB);
402                         std::swap(intA, intB);
403                         std::swap(r2iA, r2iB);
404                     }
405
406                     assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
407                            MRegisterInfo::isVirtualRegister(intB->reg) &&
408                            "A must be physical and B must be virtual");
409
410                     if (!intA->overlaps(*intB) &&
411                          !overlapsAliases(*intA, *intB)) {
412                         intA->join(*intB);
413                         r2iB->second = r2iA->second;
414                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
415                         intervals_.erase(intB);
416                         ++numJoined;
417                     }
418                 }
419             }
420         }
421     }
422 }
423
424 bool LiveIntervals::overlapsAliases(const Interval& lhs,
425                                     const Interval& rhs) const
426 {
427     assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
428            "first interval must describe a physical register");
429
430     for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
431         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
432         assert(r2i != r2iMap_.end() && "alias does not have interval?");
433         if (rhs.overlaps(*r2i->second))
434             return true;
435     }
436
437     return false;
438 }
439
440 LiveIntervals::Interval::Interval(unsigned r)
441     : reg(r),
442       weight((MRegisterInfo::isPhysicalRegister(r) ?
443               std::numeric_limits<float>::max() : 0.0F))
444 {
445
446 }
447
448 // An example for liveAt():
449 //
450 // this = [1,2), liveAt(0) will return false. The instruction defining
451 // this spans slots [0,1]. Since it is a definition we say that it is
452 // live in the second slot onwards. By ending the lifetime of this
453 // interval at 2 it means that it is not used at all. liveAt(1)
454 // returns true which means that this clobbers a register at
455 // instruction at 0.
456 //
457 // this = [1,4), liveAt(0) will return false and liveAt(2) will return
458 // true.  The variable is defined at instruction 0 and last used at 2.
459 bool LiveIntervals::Interval::liveAt(unsigned index) const
460 {
461     Range dummy(index, index+1);
462     Ranges::const_iterator r = std::upper_bound(ranges.begin(),
463                                                 ranges.end(),
464                                                 dummy);
465     if (r == ranges.begin())
466         return false;
467
468     --r;
469     return index >= r->first && index < r->second;
470 }
471
472 // An example for overlaps():
473 //
474 // 0: A = ...
475 // 2: B = ...
476 // 4: C = A + B ;; last use of A
477 //
478 // The live intervals should look like:
479 //
480 // A = [1, 5)
481 // B = [3, x)
482 // C = [5, y)
483 //
484 // A->overlaps(C) should return false since we want to be able to join
485 // A and C.
486 bool LiveIntervals::Interval::overlaps(const Interval& other) const
487 {
488     Ranges::const_iterator i = ranges.begin();
489     Ranges::const_iterator ie = ranges.end();
490     Ranges::const_iterator j = other.ranges.begin();
491     Ranges::const_iterator je = other.ranges.end();
492     if (i->first < j->first) {
493         i = std::upper_bound(i, ie, *j);
494         if (i != ranges.begin()) --i;
495     }
496     else if (j->first < i->first) {
497         j = std::upper_bound(j, je, *i);
498         if (j != other.ranges.begin()) --j;
499     }
500
501     while (i != ie && j != je) {
502         if (i->first == j->first) {
503             return true;
504         }
505         else {
506             if (i->first > j->first) {
507                 swap(i, j);
508                 swap(ie, je);
509             }
510             assert(i->first < j->first);
511
512             if (i->second > j->first) {
513                 return true;
514             }
515             else {
516                 ++i;
517             }
518         }
519     }
520
521     return false;
522 }
523
524 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
525 {
526     assert(start < end && "Invalid range to add!");
527     DEBUG(std::cerr << "\t\t\tadding range: [" << start <<','<< end << ") -> ");
528     //assert(start < end && "invalid range?");
529     Range range = std::make_pair(start, end);
530     Ranges::iterator it =
531         ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
532                       range);
533
534     it = mergeRangesForward(it);
535     it = mergeRangesBackward(it);
536     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
537 }
538
539 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
540 {
541     DEBUG(std::cerr << "\t\t\t\tjoining intervals: "
542           << other << " and " << *this << '\n');
543     Ranges::iterator cur = ranges.begin();
544
545     for (Ranges::const_iterator i = other.ranges.begin(),
546              e = other.ranges.end(); i != e; ++i) {
547         cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
548         cur = mergeRangesForward(cur);
549         cur = mergeRangesBackward(cur);
550     }
551     if (MRegisterInfo::isVirtualRegister(reg))
552         weight += other.weight;
553
554     DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
555 }
556
557 LiveIntervals::Interval::Ranges::iterator
558 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
559 {
560     for (Ranges::iterator next = it + 1;
561          next != ranges.end() && it->second >= next->first; ) {
562         it->second = std::max(it->second, next->second);
563         next = ranges.erase(next);
564     }
565     return it;
566 }
567
568 LiveIntervals::Interval::Ranges::iterator
569 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
570 {
571     while (it != ranges.begin()) {
572         Ranges::iterator prev = it - 1;
573         if (it->first > prev->second) break;
574
575         it->first = std::min(it->first, prev->first);
576         it->second = std::max(it->second, prev->second);
577         it = ranges.erase(prev);
578     }
579
580     return it;
581 }
582
583 std::ostream& llvm::operator<<(std::ostream& os,
584                                const LiveIntervals::Interval& li)
585 {
586     os << "%reg" << li.reg << ',' << li.weight << " = ";
587     for (LiveIntervals::Interval::Ranges::const_iterator
588              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
589         os << "[" << i->first << "," << i->second << ")";
590     }
591     return os;
592 }