cea75ef4b4d5d091d56c0fe8608473eee7d55496
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "regalloc"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/ProcessImplicitDefs.h"
28 #include "llvm/Target/TargetRegisterInfo.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/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include <algorithm>
38 #include <limits>
39 #include <cmath>
40 using namespace llvm;
41
42 // Hidden options for help debugging.
43 static cl::opt<bool> DisableReMat("disable-rematerialization",
44                                   cl::init(false), cl::Hidden);
45
46 STATISTIC(numIntervals , "Number of original intervals");
47
48 char LiveIntervals::ID = 0;
49 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
50                 "Live Interval Analysis", false, false)
51 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
52 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
53 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
54 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
55 INITIALIZE_PASS_DEPENDENCY(ProcessImplicitDefs)
56 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
57 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
58 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
59                 "Live Interval Analysis", false, false)
60
61 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
62   AU.setPreservesCFG();
63   AU.addRequired<AliasAnalysis>();
64   AU.addPreserved<AliasAnalysis>();
65   AU.addRequired<LiveVariables>();
66   AU.addPreserved<LiveVariables>();
67   AU.addRequired<MachineLoopInfo>();
68   AU.addPreserved<MachineLoopInfo>();
69   AU.addPreservedID(MachineDominatorsID);
70
71   if (!StrongPHIElim) {
72     AU.addPreservedID(PHIEliminationID);
73     AU.addRequiredID(PHIEliminationID);
74   }
75
76   AU.addRequiredID(TwoAddressInstructionPassID);
77   AU.addPreserved<ProcessImplicitDefs>();
78   AU.addRequired<ProcessImplicitDefs>();
79   AU.addPreserved<SlotIndexes>();
80   AU.addRequiredTransitive<SlotIndexes>();
81   MachineFunctionPass::getAnalysisUsage(AU);
82 }
83
84 void LiveIntervals::releaseMemory() {
85   // Free the live intervals themselves.
86   for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
87        E = r2iMap_.end(); I != E; ++I)
88     delete I->second;
89
90   r2iMap_.clear();
91
92   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
93   VNInfoAllocator.Reset();
94 }
95
96 /// runOnMachineFunction - Register allocate the whole function
97 ///
98 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
99   mf_ = &fn;
100   mri_ = &mf_->getRegInfo();
101   tm_ = &fn.getTarget();
102   tri_ = tm_->getRegisterInfo();
103   tii_ = tm_->getInstrInfo();
104   aa_ = &getAnalysis<AliasAnalysis>();
105   lv_ = &getAnalysis<LiveVariables>();
106   indexes_ = &getAnalysis<SlotIndexes>();
107   allocatableRegs_ = tri_->getAllocatableSet(fn);
108
109   computeIntervals();
110
111   numIntervals += getNumIntervals();
112
113   DEBUG(dump());
114   return true;
115 }
116
117 /// print - Implement the dump method.
118 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
119   OS << "********** INTERVALS **********\n";
120   for (const_iterator I = begin(), E = end(); I != E; ++I) {
121     I->second->print(OS, tri_);
122     OS << "\n";
123   }
124
125   printInstrs(OS);
126 }
127
128 void LiveIntervals::printInstrs(raw_ostream &OS) const {
129   OS << "********** MACHINEINSTRS **********\n";
130   mf_->print(OS, indexes_);
131 }
132
133 void LiveIntervals::dumpInstrs() const {
134   printInstrs(dbgs());
135 }
136
137 static
138 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
139   unsigned Reg = MI.getOperand(MOIdx).getReg();
140   for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
141     const MachineOperand &MO = MI.getOperand(i);
142     if (!MO.isReg())
143       continue;
144     if (MO.getReg() == Reg && MO.isDef()) {
145       assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
146              MI.getOperand(MOIdx).getSubReg() &&
147              (MO.getSubReg() || MO.isImplicit()));
148       return true;
149     }
150   }
151   return false;
152 }
153
154 /// isPartialRedef - Return true if the specified def at the specific index is
155 /// partially re-defining the specified live interval. A common case of this is
156 /// a definition of the sub-register.
157 bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
158                                    LiveInterval &interval) {
159   if (!MO.getSubReg() || MO.isEarlyClobber())
160     return false;
161
162   SlotIndex RedefIndex = MIIdx.getRegSlot();
163   const LiveRange *OldLR =
164     interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
165   MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
166   if (DefMI != 0) {
167     return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
168   }
169   return false;
170 }
171
172 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
173                                              MachineBasicBlock::iterator mi,
174                                              SlotIndex MIIdx,
175                                              MachineOperand& MO,
176                                              unsigned MOIdx,
177                                              LiveInterval &interval) {
178   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
179
180   // Virtual registers may be defined multiple times (due to phi
181   // elimination and 2-addr elimination).  Much of what we do only has to be
182   // done once for the vreg.  We use an empty interval to detect the first
183   // time we see a vreg.
184   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
185   if (interval.empty()) {
186     // Get the Idx of the defining instructions.
187     SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
188
189     // Make sure the first definition is not a partial redefinition. Add an
190     // <imp-def> of the full register.
191     // FIXME: LiveIntervals shouldn't modify the code like this.  Whoever
192     // created the machine instruction should annotate it with <undef> flags
193     // as needed.  Then we can simply assert here.  The REG_SEQUENCE lowering
194     // is the main suspect.
195     if (MO.getSubReg()) {
196       mi->addRegisterDefined(interval.reg);
197       // Mark all defs of interval.reg on this instruction as reading <undef>.
198       for (unsigned i = MOIdx, e = mi->getNumOperands(); i != e; ++i) {
199         MachineOperand &MO2 = mi->getOperand(i);
200         if (MO2.isReg() && MO2.getReg() == interval.reg && MO2.getSubReg())
201           MO2.setIsUndef();
202       }
203     }
204
205     VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
206     assert(ValNo->id == 0 && "First value in interval is not 0?");
207
208     // Loop over all of the blocks that the vreg is defined in.  There are
209     // two cases we have to handle here.  The most common case is a vreg
210     // whose lifetime is contained within a basic block.  In this case there
211     // will be a single kill, in MBB, which comes after the definition.
212     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
213       // FIXME: what about dead vars?
214       SlotIndex killIdx;
215       if (vi.Kills[0] != mi)
216         killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
217       else
218         killIdx = defIndex.getDeadSlot();
219
220       // If the kill happens after the definition, we have an intra-block
221       // live range.
222       if (killIdx > defIndex) {
223         assert(vi.AliveBlocks.empty() &&
224                "Shouldn't be alive across any blocks!");
225         LiveRange LR(defIndex, killIdx, ValNo);
226         interval.addRange(LR);
227         DEBUG(dbgs() << " +" << LR << "\n");
228         return;
229       }
230     }
231
232     // The other case we handle is when a virtual register lives to the end
233     // of the defining block, potentially live across some blocks, then is
234     // live into some number of blocks, but gets killed.  Start by adding a
235     // range that goes from this definition to the end of the defining block.
236     LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
237     DEBUG(dbgs() << " +" << NewLR);
238     interval.addRange(NewLR);
239
240     bool PHIJoin = lv_->isPHIJoin(interval.reg);
241
242     if (PHIJoin) {
243       // A phi join register is killed at the end of the MBB and revived as a new
244       // valno in the killing blocks.
245       assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
246       DEBUG(dbgs() << " phi-join");
247       ValNo->setHasPHIKill(true);
248     } else {
249       // Iterate over all of the blocks that the variable is completely
250       // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
251       // live interval.
252       for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
253                E = vi.AliveBlocks.end(); I != E; ++I) {
254         MachineBasicBlock *aliveBlock = mf_->getBlockNumbered(*I);
255         LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock), ValNo);
256         interval.addRange(LR);
257         DEBUG(dbgs() << " +" << LR);
258       }
259     }
260
261     // Finally, this virtual register is live from the start of any killing
262     // block to the 'use' slot of the killing instruction.
263     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
264       MachineInstr *Kill = vi.Kills[i];
265       SlotIndex Start = getMBBStartIdx(Kill->getParent());
266       SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
267
268       // Create interval with one of a NEW value number.  Note that this value
269       // number isn't actually defined by an instruction, weird huh? :)
270       if (PHIJoin) {
271         assert(getInstructionFromIndex(Start) == 0 &&
272                "PHI def index points at actual instruction.");
273         ValNo = interval.getNextValue(Start, VNInfoAllocator);
274         ValNo->setIsPHIDef(true);
275       }
276       LiveRange LR(Start, killIdx, ValNo);
277       interval.addRange(LR);
278       DEBUG(dbgs() << " +" << LR);
279     }
280
281   } else {
282     if (MultipleDefsBySameMI(*mi, MOIdx))
283       // Multiple defs of the same virtual register by the same instruction.
284       // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
285       // This is likely due to elimination of REG_SEQUENCE instructions. Return
286       // here since there is nothing to do.
287       return;
288
289     // If this is the second time we see a virtual register definition, it
290     // must be due to phi elimination or two addr elimination.  If this is
291     // the result of two address elimination, then the vreg is one of the
292     // def-and-use register operand.
293
294     // It may also be partial redef like this:
295     // 80  %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
296     // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
297     bool PartReDef = isPartialRedef(MIIdx, MO, interval);
298     if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
299       // If this is a two-address definition, then we have already processed
300       // the live range.  The only problem is that we didn't realize there
301       // are actually two values in the live interval.  Because of this we
302       // need to take the LiveRegion that defines this register and split it
303       // into two values.
304       SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
305
306       const LiveRange *OldLR =
307         interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
308       VNInfo *OldValNo = OldLR->valno;
309       SlotIndex DefIndex = OldValNo->def.getRegSlot();
310
311       // Delete the previous value, which should be short and continuous,
312       // because the 2-addr copy must be in the same MBB as the redef.
313       interval.removeRange(DefIndex, RedefIndex);
314
315       // The new value number (#1) is defined by the instruction we claimed
316       // defined value #0.
317       VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
318
319       // Value#0 is now defined by the 2-addr instruction.
320       OldValNo->def = RedefIndex;
321
322       // Add the new live interval which replaces the range for the input copy.
323       LiveRange LR(DefIndex, RedefIndex, ValNo);
324       DEBUG(dbgs() << " replace range with " << LR);
325       interval.addRange(LR);
326
327       // If this redefinition is dead, we need to add a dummy unit live
328       // range covering the def slot.
329       if (MO.isDead())
330         interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
331                                     OldValNo));
332
333       DEBUG({
334           dbgs() << " RESULT: ";
335           interval.print(dbgs(), tri_);
336         });
337     } else if (lv_->isPHIJoin(interval.reg)) {
338       // In the case of PHI elimination, each variable definition is only
339       // live until the end of the block.  We've already taken care of the
340       // rest of the live range.
341
342       SlotIndex defIndex = MIIdx.getRegSlot();
343       if (MO.isEarlyClobber())
344         defIndex = MIIdx.getRegSlot(true);
345
346       VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
347
348       SlotIndex killIndex = getMBBEndIdx(mbb);
349       LiveRange LR(defIndex, killIndex, ValNo);
350       interval.addRange(LR);
351       ValNo->setHasPHIKill(true);
352       DEBUG(dbgs() << " phi-join +" << LR);
353     } else {
354       llvm_unreachable("Multiply defined register");
355     }
356   }
357
358   DEBUG(dbgs() << '\n');
359 }
360
361 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
362                                               MachineBasicBlock::iterator mi,
363                                               SlotIndex MIIdx,
364                                               MachineOperand& MO,
365                                               LiveInterval &interval) {
366   // A physical register cannot be live across basic block, so its
367   // lifetime must end somewhere in its defining basic block.
368   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
369
370   SlotIndex baseIndex = MIIdx;
371   SlotIndex start = baseIndex.getRegSlot(MO.isEarlyClobber());
372   SlotIndex end = start;
373
374   // If it is not used after definition, it is considered dead at
375   // the instruction defining it. Hence its interval is:
376   // [defSlot(def), defSlot(def)+1)
377   // For earlyclobbers, the defSlot was pushed back one; the extra
378   // advance below compensates.
379   if (MO.isDead()) {
380     DEBUG(dbgs() << " dead");
381     end = start.getDeadSlot();
382     goto exit;
383   }
384
385   // If it is not dead on definition, it must be killed by a
386   // subsequent instruction. Hence its interval is:
387   // [defSlot(def), useSlot(kill)+1)
388   baseIndex = baseIndex.getNextIndex();
389   while (++mi != MBB->end()) {
390
391     if (mi->isDebugValue())
392       continue;
393     if (getInstructionFromIndex(baseIndex) == 0)
394       baseIndex = indexes_->getNextNonNullIndex(baseIndex);
395
396     if (mi->killsRegister(interval.reg, tri_)) {
397       DEBUG(dbgs() << " killed");
398       end = baseIndex.getRegSlot();
399       goto exit;
400     } else {
401       int DefIdx = mi->findRegisterDefOperandIdx(interval.reg,false,false,tri_);
402       if (DefIdx != -1) {
403         if (mi->isRegTiedToUseOperand(DefIdx)) {
404           // Two-address instruction.
405           end = baseIndex.getRegSlot(mi->getOperand(DefIdx).isEarlyClobber());
406         } else {
407           // Another instruction redefines the register before it is ever read.
408           // Then the register is essentially dead at the instruction that
409           // defines it. Hence its interval is:
410           // [defSlot(def), defSlot(def)+1)
411           DEBUG(dbgs() << " dead");
412           end = start.getDeadSlot();
413         }
414         goto exit;
415       }
416     }
417
418     baseIndex = baseIndex.getNextIndex();
419   }
420
421   // The only case we should have a dead physreg here without a killing or
422   // instruction where we know it's dead is if it is live-in to the function
423   // and never used. Another possible case is the implicit use of the
424   // physical register has been deleted by two-address pass.
425   end = start.getDeadSlot();
426
427 exit:
428   assert(start < end && "did not find end of interval?");
429
430   // Already exists? Extend old live interval.
431   VNInfo *ValNo = interval.getVNInfoAt(start);
432   bool Extend = ValNo != 0;
433   if (!Extend)
434     ValNo = interval.getNextValue(start, VNInfoAllocator);
435   LiveRange LR(start, end, ValNo);
436   interval.addRange(LR);
437   DEBUG(dbgs() << " +" << LR << '\n');
438 }
439
440 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
441                                       MachineBasicBlock::iterator MI,
442                                       SlotIndex MIIdx,
443                                       MachineOperand& MO,
444                                       unsigned MOIdx) {
445   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
446     handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
447                              getOrCreateInterval(MO.getReg()));
448   else
449     handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
450                               getOrCreateInterval(MO.getReg()));
451 }
452
453 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
454                                          SlotIndex MIIdx,
455                                          LiveInterval &interval, bool isAlias) {
456   DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
457
458   // Look for kills, if it reaches a def before it's killed, then it shouldn't
459   // be considered a livein.
460   MachineBasicBlock::iterator mi = MBB->begin();
461   MachineBasicBlock::iterator E = MBB->end();
462   // Skip over DBG_VALUE at the start of the MBB.
463   if (mi != E && mi->isDebugValue()) {
464     while (++mi != E && mi->isDebugValue())
465       ;
466     if (mi == E)
467       // MBB is empty except for DBG_VALUE's.
468       return;
469   }
470
471   SlotIndex baseIndex = MIIdx;
472   SlotIndex start = baseIndex;
473   if (getInstructionFromIndex(baseIndex) == 0)
474     baseIndex = indexes_->getNextNonNullIndex(baseIndex);
475
476   SlotIndex end = baseIndex;
477   bool SeenDefUse = false;
478
479   while (mi != E) {
480     if (mi->killsRegister(interval.reg, tri_)) {
481       DEBUG(dbgs() << " killed");
482       end = baseIndex.getRegSlot();
483       SeenDefUse = true;
484       break;
485     } else if (mi->definesRegister(interval.reg, tri_)) {
486       // Another instruction redefines the register before it is ever read.
487       // Then the register is essentially dead at the instruction that defines
488       // it. Hence its interval is:
489       // [defSlot(def), defSlot(def)+1)
490       DEBUG(dbgs() << " dead");
491       end = start.getDeadSlot();
492       SeenDefUse = true;
493       break;
494     }
495
496     while (++mi != E && mi->isDebugValue())
497       // Skip over DBG_VALUE.
498       ;
499     if (mi != E)
500       baseIndex = indexes_->getNextNonNullIndex(baseIndex);
501   }
502
503   // Live-in register might not be used at all.
504   if (!SeenDefUse) {
505     if (isAlias) {
506       DEBUG(dbgs() << " dead");
507       end = MIIdx.getDeadSlot();
508     } else {
509       DEBUG(dbgs() << " live through");
510       end = getMBBEndIdx(MBB);
511     }
512   }
513
514   SlotIndex defIdx = getMBBStartIdx(MBB);
515   assert(getInstructionFromIndex(defIdx) == 0 &&
516          "PHI def index points at actual instruction.");
517   VNInfo *vni = interval.getNextValue(defIdx, VNInfoAllocator);
518   vni->setIsPHIDef(true);
519   LiveRange LR(start, end, vni);
520
521   interval.addRange(LR);
522   DEBUG(dbgs() << " +" << LR << '\n');
523 }
524
525 /// computeIntervals - computes the live intervals for virtual
526 /// registers. for some ordering of the machine instructions [1,N] a
527 /// live interval is an interval [i, j) where 1 <= i <= j < N for
528 /// which a variable is live
529 void LiveIntervals::computeIntervals() {
530   DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
531                << "********** Function: "
532                << ((Value*)mf_->getFunction())->getName() << '\n');
533
534   SmallVector<unsigned, 8> UndefUses;
535   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
536        MBBI != E; ++MBBI) {
537     MachineBasicBlock *MBB = MBBI;
538     if (MBB->empty())
539       continue;
540
541     // Track the index of the current machine instr.
542     SlotIndex MIIndex = getMBBStartIdx(MBB);
543     DEBUG(dbgs() << "BB#" << MBB->getNumber()
544           << ":\t\t# derived from " << MBB->getName() << "\n");
545
546     // Create intervals for live-ins to this BB first.
547     for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
548            LE = MBB->livein_end(); LI != LE; ++LI) {
549       handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
550     }
551
552     // Skip over empty initial indices.
553     if (getInstructionFromIndex(MIIndex) == 0)
554       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
555
556     for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
557          MI != miEnd; ++MI) {
558       DEBUG(dbgs() << MIIndex << "\t" << *MI);
559       if (MI->isDebugValue())
560         continue;
561
562       // Handle defs.
563       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
564         MachineOperand &MO = MI->getOperand(i);
565         if (!MO.isReg() || !MO.getReg())
566           continue;
567
568         // handle register defs - build intervals
569         if (MO.isDef())
570           handleRegisterDef(MBB, MI, MIIndex, MO, i);
571         else if (MO.isUndef())
572           UndefUses.push_back(MO.getReg());
573       }
574
575       // Move to the next instr slot.
576       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
577     }
578   }
579
580   // Create empty intervals for registers defined by implicit_def's (except
581   // for those implicit_def that define values which are liveout of their
582   // blocks.
583   for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
584     unsigned UndefReg = UndefUses[i];
585     (void)getOrCreateInterval(UndefReg);
586   }
587 }
588
589 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
590   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
591   return new LiveInterval(reg, Weight);
592 }
593
594 /// dupInterval - Duplicate a live interval. The caller is responsible for
595 /// managing the allocated memory.
596 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
597   LiveInterval *NewLI = createInterval(li->reg);
598   NewLI->Copy(*li, mri_, getVNInfoAllocator());
599   return NewLI;
600 }
601
602 /// shrinkToUses - After removing some uses of a register, shrink its live
603 /// range to just the remaining uses. This method does not compute reaching
604 /// defs for new uses, and it doesn't remove dead defs.
605 bool LiveIntervals::shrinkToUses(LiveInterval *li,
606                                  SmallVectorImpl<MachineInstr*> *dead) {
607   DEBUG(dbgs() << "Shrink: " << *li << '\n');
608   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
609          && "Can only shrink virtual registers");
610   // Find all the values used, including PHI kills.
611   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
612
613   // Blocks that have already been added to WorkList as live-out.
614   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
615
616   // Visit all instructions reading li->reg.
617   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li->reg);
618        MachineInstr *UseMI = I.skipInstruction();) {
619     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
620       continue;
621     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
622     // Note: This intentionally picks up the wrong VNI in case of an EC redef.
623     // See below.
624     VNInfo *VNI = li->getVNInfoBefore(Idx);
625     if (!VNI) {
626       // This shouldn't happen: readsVirtualRegister returns true, but there is
627       // no live value. It is likely caused by a target getting <undef> flags
628       // wrong.
629       DEBUG(dbgs() << Idx << '\t' << *UseMI
630                    << "Warning: Instr claims to read non-existent value in "
631                     << *li << '\n');
632       continue;
633     }
634     // Special case: An early-clobber tied operand reads and writes the
635     // register one slot early.  The getVNInfoBefore call above would have
636     // picked up the value defined by UseMI.  Adjust the kill slot and value.
637     if (SlotIndex::isSameInstr(VNI->def, Idx)) {
638       Idx = VNI->def;
639       VNI = li->getVNInfoBefore(Idx);
640       assert(VNI && "Early-clobber tied value not available");
641     }
642     WorkList.push_back(std::make_pair(Idx, VNI));
643   }
644
645   // Create a new live interval with only minimal live segments per def.
646   LiveInterval NewLI(li->reg, 0);
647   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
648        I != E; ++I) {
649     VNInfo *VNI = *I;
650     if (VNI->isUnused())
651       continue;
652     NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
653   }
654
655   // Keep track of the PHIs that are in use.
656   SmallPtrSet<VNInfo*, 8> UsedPHIs;
657
658   // Extend intervals to reach all uses in WorkList.
659   while (!WorkList.empty()) {
660     SlotIndex Idx = WorkList.back().first;
661     VNInfo *VNI = WorkList.back().second;
662     WorkList.pop_back();
663     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
664     SlotIndex BlockStart = getMBBStartIdx(MBB);
665
666     // Extend the live range for VNI to be live at Idx.
667     if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
668       (void)ExtVNI;
669       assert(ExtVNI == VNI && "Unexpected existing value number");
670       // Is this a PHIDef we haven't seen before?
671       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
672         continue;
673       // The PHI is live, make sure the predecessors are live-out.
674       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
675            PE = MBB->pred_end(); PI != PE; ++PI) {
676         if (!LiveOut.insert(*PI))
677           continue;
678         SlotIndex Stop = getMBBEndIdx(*PI);
679         // A predecessor is not required to have a live-out value for a PHI.
680         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
681           WorkList.push_back(std::make_pair(Stop, PVNI));
682       }
683       continue;
684     }
685
686     // VNI is live-in to MBB.
687     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
688     NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
689
690     // Make sure VNI is live-out from the predecessors.
691     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
692          PE = MBB->pred_end(); PI != PE; ++PI) {
693       if (!LiveOut.insert(*PI))
694         continue;
695       SlotIndex Stop = getMBBEndIdx(*PI);
696       assert(li->getVNInfoBefore(Stop) == VNI &&
697              "Wrong value out of predecessor");
698       WorkList.push_back(std::make_pair(Stop, VNI));
699     }
700   }
701
702   // Handle dead values.
703   bool CanSeparate = false;
704   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
705        I != E; ++I) {
706     VNInfo *VNI = *I;
707     if (VNI->isUnused())
708       continue;
709     LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
710     assert(LII != NewLI.end() && "Missing live range for PHI");
711     if (LII->end != VNI->def.getDeadSlot())
712       continue;
713     if (VNI->isPHIDef()) {
714       // This is a dead PHI. Remove it.
715       VNI->setIsUnused(true);
716       NewLI.removeRange(*LII);
717       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
718       CanSeparate = true;
719     } else {
720       // This is a dead def. Make sure the instruction knows.
721       MachineInstr *MI = getInstructionFromIndex(VNI->def);
722       assert(MI && "No instruction defining live value");
723       MI->addRegisterDead(li->reg, tri_);
724       if (dead && MI->allDefsAreDead()) {
725         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
726         dead->push_back(MI);
727       }
728     }
729   }
730
731   // Move the trimmed ranges back.
732   li->ranges.swap(NewLI.ranges);
733   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
734   return CanSeparate;
735 }
736
737
738 //===----------------------------------------------------------------------===//
739 // Register allocator hooks.
740 //
741
742 void LiveIntervals::addKillFlags() {
743   for (iterator I = begin(), E = end(); I != E; ++I) {
744     unsigned Reg = I->first;
745     if (TargetRegisterInfo::isPhysicalRegister(Reg))
746       continue;
747     if (mri_->reg_nodbg_empty(Reg))
748       continue;
749     LiveInterval *LI = I->second;
750
751     // Every instruction that kills Reg corresponds to a live range end point.
752     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
753          ++RI) {
754       // A block index indicates an MBB edge.
755       if (RI->end.isBlock())
756         continue;
757       MachineInstr *MI = getInstructionFromIndex(RI->end);
758       if (!MI)
759         continue;
760       MI->addRegisterKilled(Reg, NULL);
761     }
762   }
763 }
764
765 #ifndef NDEBUG
766 static bool intervalRangesSane(const LiveInterval& li) {
767   if (li.empty()) {
768     return true;
769   }
770
771   SlotIndex lastEnd = li.begin()->start;
772   for (LiveInterval::const_iterator lrItr = li.begin(), lrEnd = li.end();
773        lrItr != lrEnd; ++lrItr) {
774     const LiveRange& lr = *lrItr;
775     if (lastEnd > lr.start || lr.start >= lr.end)
776       return false;
777     lastEnd = lr.end;
778   }
779
780   return true;
781 }
782 #endif
783
784 template <typename DefSetT>
785 static void handleMoveDefs(LiveIntervals& lis, SlotIndex origIdx,
786                            SlotIndex miIdx, const DefSetT& defs) {
787   for (typename DefSetT::const_iterator defItr = defs.begin(),
788                                         defEnd = defs.end();
789        defItr != defEnd; ++defItr) {
790     unsigned def = *defItr;
791     LiveInterval& li = lis.getInterval(def);
792     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
793     assert(lr != 0 && "No range for def?");
794     lr->start = miIdx.getRegSlot();
795     lr->valno->def = miIdx.getRegSlot();
796     assert(intervalRangesSane(li) && "Broke live interval moving def.");
797   }
798 }
799
800 template <typename DeadDefSetT>
801 static void handleMoveDeadDefs(LiveIntervals& lis, SlotIndex origIdx,
802                                SlotIndex miIdx, const DeadDefSetT& deadDefs) {
803   for (typename DeadDefSetT::const_iterator deadDefItr = deadDefs.begin(),
804                                             deadDefEnd = deadDefs.end();
805        deadDefItr != deadDefEnd; ++deadDefItr) {
806     unsigned deadDef = *deadDefItr;
807     LiveInterval& li = lis.getInterval(deadDef);
808     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
809     assert(lr != 0 && "No range for dead def?");
810     assert(lr->start == origIdx.getRegSlot() && "Bad dead range start?");
811     assert(lr->end == origIdx.getDeadSlot() && "Bad dead range end?");
812     assert(lr->valno->def == origIdx.getRegSlot() && "Bad dead valno def.");
813     LiveRange t(*lr);
814     t.start = miIdx.getRegSlot();
815     t.valno->def = miIdx.getRegSlot();
816     t.end = miIdx.getDeadSlot();
817     li.removeRange(*lr);
818     li.addRange(t);
819     assert(intervalRangesSane(li) && "Broke live interval moving dead def.");
820   }
821 }
822
823 template <typename ECSetT>
824 static void handleMoveECs(LiveIntervals& lis, SlotIndex origIdx,
825                           SlotIndex miIdx, const ECSetT& ecs) {
826   for (typename ECSetT::const_iterator ecItr = ecs.begin(), ecEnd = ecs.end();
827        ecItr != ecEnd; ++ecItr) {
828     unsigned ec = *ecItr;
829     LiveInterval& li = lis.getInterval(ec);
830     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot(true));
831     assert(lr != 0 && "No range for early clobber?");
832     assert(lr->start == origIdx.getRegSlot(true) && "Bad EC range start?");
833     assert(lr->end == origIdx.getRegSlot() && "Bad EC range end.");
834     assert(lr->valno->def == origIdx.getRegSlot(true) && "Bad EC valno def.");
835     LiveRange t(*lr);
836     t.start = miIdx.getRegSlot(true);
837     t.valno->def = miIdx.getRegSlot(true);
838     t.end = miIdx.getRegSlot();
839     li.removeRange(*lr);
840     li.addRange(t);
841     assert(intervalRangesSane(li) && "Broke live interval moving EC.");
842   }
843 }
844
845 template <typename UseSetT>
846 static void handleMoveUses(const MachineBasicBlock *mbb,
847                            const MachineRegisterInfo& mri,
848                            const BitVector& reservedRegs, LiveIntervals &lis,
849                            SlotIndex origIdx, SlotIndex miIdx,
850                            const UseSetT &uses) {
851   bool movingUp = miIdx < origIdx;
852   for (typename UseSetT::const_iterator usesItr = uses.begin(),
853                                         usesEnd = uses.end();
854        usesItr != usesEnd; ++usesItr) {
855     unsigned use = *usesItr;
856     if (!lis.hasInterval(use))
857       continue;
858     if (TargetRegisterInfo::isPhysicalRegister(use) && reservedRegs.test(use))
859       continue;
860     LiveInterval& li = lis.getInterval(use);
861     LiveRange* lr = li.getLiveRangeBefore(origIdx.getRegSlot());
862     assert(lr != 0 && "No range for use?");
863     bool liveThrough = lr->end > origIdx.getRegSlot();
864
865     if (movingUp) {
866       // If moving up and liveThrough - nothing to do.
867       // If not live through we need to extend the range to the last use
868       // between the old location and the new one.
869       if (!liveThrough) {
870         SlotIndex lastUseInRange = miIdx.getRegSlot();
871         for (MachineRegisterInfo::use_iterator useI = mri.use_begin(use),
872                                                useE = mri.use_end();
873              useI != useE; ++useI) {
874           const MachineInstr* mopI = &*useI;
875           const MachineOperand& mop = useI.getOperand();
876           SlotIndex instSlot = lis.getSlotIndexes()->getInstructionIndex(mopI);
877           SlotIndex opSlot = instSlot.getRegSlot(mop.isEarlyClobber());
878           if (opSlot >= lastUseInRange && opSlot < origIdx) {
879             lastUseInRange = opSlot;
880           }
881         }
882         lr->end = lastUseInRange;
883       }
884     } else {
885       // Moving down is easy - the existing live range end tells us where
886       // the last kill is.
887       if (!liveThrough) {
888         // Easy fix - just update the range endpoint.
889         lr->end = miIdx.getRegSlot();
890       } else {
891         bool liveOut = lr->end >= lis.getSlotIndexes()->getMBBEndIdx(mbb);
892         if (!liveOut && miIdx.getRegSlot() > lr->end) {
893           lr->end = miIdx.getRegSlot();
894         }
895       }
896     }
897     assert(intervalRangesSane(li) && "Broke live interval moving use.");
898   }
899 }
900
901 void LiveIntervals::moveInstr(MachineBasicBlock::iterator insertPt,
902                               MachineInstr *mi) {
903   MachineBasicBlock* mbb = mi->getParent();
904   assert((insertPt == mbb->end() || insertPt->getParent() == mbb) &&
905          "Cannot handle moves across basic block boundaries.");
906   assert(&*insertPt != mi && "No-op move requested?");
907   assert(!mi->isInsideBundle() && "Can't handle bundled instructions yet.");
908
909   // Grab the original instruction index.
910   SlotIndex origIdx = indexes_->getInstructionIndex(mi);
911
912   // Move the machine instr and obtain its new index.
913   indexes_->removeMachineInstrFromMaps(mi);
914   mbb->remove(mi);
915   mbb->insert(insertPt, mi);
916   SlotIndex miIdx = indexes_->insertMachineInstrInMaps(mi);
917
918   // Pick the direction.
919   bool movingUp = miIdx < origIdx;
920
921   // Collect the operands.
922   DenseSet<unsigned> uses, defs, deadDefs, ecs;
923   for (MachineInstr::mop_iterator mopItr = mi->operands_begin(),
924          mopEnd = mi->operands_end();
925        mopItr != mopEnd; ++mopItr) {
926     const MachineOperand& mop = *mopItr;
927
928     if (!mop.isReg() || mop.getReg() == 0)
929       continue;
930     unsigned reg = mop.getReg();
931     if (mop.isUse()) {
932       assert(mop.readsReg());
933     }
934
935     if (mop.readsReg() && !ecs.count(reg)) {
936       uses.insert(reg);
937     }
938     if (mop.isDef()) {
939       if (mop.isDead()) {
940         assert(!defs.count(reg) && "Can't mix defs with dead-defs.");
941         deadDefs.insert(reg);
942       } else if (mop.isEarlyClobber()) {
943         uses.erase(reg);
944         ecs.insert(reg);
945       } else {
946         assert(!deadDefs.count(reg) && "Can't mix defs with dead-defs.");
947         defs.insert(reg);
948       }
949     }
950   }
951
952   BitVector reservedRegs(tri_->getReservedRegs(*mbb->getParent()));
953
954   if (movingUp) {
955     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
956     handleMoveECs(*this, origIdx, miIdx, ecs);
957     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
958     handleMoveDefs(*this, origIdx, miIdx, defs);
959   } else {
960     handleMoveDefs(*this, origIdx, miIdx, defs);
961     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
962     handleMoveECs(*this, origIdx, miIdx, ecs);
963     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
964   }
965 }
966
967 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only
968 /// allow one) virtual register operand, then its uses are implicitly using
969 /// the register. Returns the virtual register.
970 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
971                                             MachineInstr *MI) const {
972   unsigned RegOp = 0;
973   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
974     MachineOperand &MO = MI->getOperand(i);
975     if (!MO.isReg() || !MO.isUse())
976       continue;
977     unsigned Reg = MO.getReg();
978     if (Reg == 0 || Reg == li.reg)
979       continue;
980
981     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
982         !allocatableRegs_[Reg])
983       continue;
984     RegOp = MO.getReg();
985     break; // Found vreg operand - leave the loop.
986   }
987   return RegOp;
988 }
989
990 /// isValNoAvailableAt - Return true if the val# of the specified interval
991 /// which reaches the given instruction also reaches the specified use index.
992 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
993                                        SlotIndex UseIdx) const {
994   VNInfo *UValNo = li.getVNInfoAt(UseIdx);
995   return UValNo && UValNo == li.getVNInfoAt(getInstructionIndex(MI));
996 }
997
998 /// isReMaterializable - Returns true if the definition MI of the specified
999 /// val# of the specified interval is re-materializable.
1000 bool
1001 LiveIntervals::isReMaterializable(const LiveInterval &li,
1002                                   const VNInfo *ValNo, MachineInstr *MI,
1003                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1004                                   bool &isLoad) {
1005   if (DisableReMat)
1006     return false;
1007
1008   if (!tii_->isTriviallyReMaterializable(MI, aa_))
1009     return false;
1010
1011   // Target-specific code can mark an instruction as being rematerializable
1012   // if it has one virtual reg use, though it had better be something like
1013   // a PIC base register which is likely to be live everywhere.
1014   unsigned ImpUse = getReMatImplicitUse(li, MI);
1015   if (ImpUse) {
1016     const LiveInterval &ImpLi = getInterval(ImpUse);
1017     for (MachineRegisterInfo::use_nodbg_iterator
1018            ri = mri_->use_nodbg_begin(li.reg), re = mri_->use_nodbg_end();
1019          ri != re; ++ri) {
1020       MachineInstr *UseMI = &*ri;
1021       SlotIndex UseIdx = getInstructionIndex(UseMI);
1022       if (li.getVNInfoAt(UseIdx) != ValNo)
1023         continue;
1024       if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1025         return false;
1026     }
1027
1028     // If a register operand of the re-materialized instruction is going to
1029     // be spilled next, then it's not legal to re-materialize this instruction.
1030     if (SpillIs)
1031       for (unsigned i = 0, e = SpillIs->size(); i != e; ++i)
1032         if (ImpUse == (*SpillIs)[i]->reg)
1033           return false;
1034   }
1035   return true;
1036 }
1037
1038 /// isReMaterializable - Returns true if every definition of MI of every
1039 /// val# of the specified interval is re-materializable.
1040 bool
1041 LiveIntervals::isReMaterializable(const LiveInterval &li,
1042                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1043                                   bool &isLoad) {
1044   isLoad = false;
1045   for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1046        i != e; ++i) {
1047     const VNInfo *VNI = *i;
1048     if (VNI->isUnused())
1049       continue; // Dead val#.
1050     // Is the def for the val# rematerializable?
1051     MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
1052     if (!ReMatDefMI)
1053       return false;
1054     bool DefIsLoad = false;
1055     if (!ReMatDefMI ||
1056         !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
1057       return false;
1058     isLoad |= DefIsLoad;
1059   }
1060   return true;
1061 }
1062
1063 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1064   LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1065
1066   MachineBasicBlock *mbb =  indexes_->getMBBCoveringRange(itr->start, itr->end);
1067
1068   if (mbb == 0)
1069     return false;
1070
1071   for (++itr; itr != li.ranges.end(); ++itr) {
1072     MachineBasicBlock *mbb2 =
1073       indexes_->getMBBCoveringRange(itr->start, itr->end);
1074
1075     if (mbb2 != mbb)
1076       return false;
1077   }
1078
1079   return true;
1080 }
1081
1082 float
1083 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
1084   // Limit the loop depth ridiculousness.
1085   if (loopDepth > 200)
1086     loopDepth = 200;
1087
1088   // The loop depth is used to roughly estimate the number of times the
1089   // instruction is executed. Something like 10^d is simple, but will quickly
1090   // overflow a float. This expression behaves like 10^d for small d, but is
1091   // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
1092   // headroom before overflow.
1093   // By the way, powf() might be unavailable here. For consistency,
1094   // We may take pow(double,double).
1095   float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
1096
1097   return (isDef + isUse) * lc;
1098 }
1099
1100 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1101                                                   MachineInstr* startInst) {
1102   LiveInterval& Interval = getOrCreateInterval(reg);
1103   VNInfo* VN = Interval.getNextValue(
1104     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1105     getVNInfoAllocator());
1106   VN->setHasPHIKill(true);
1107   LiveRange LR(
1108      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1109      getMBBEndIdx(startInst->getParent()), VN);
1110   Interval.addRange(LR);
1111
1112   return LR;
1113 }