d72009ccd222581ab42db8402f3bc6786eb510df
[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   if (Extend && MO.isEarlyClobber())
436     ValNo->setHasRedefByEC(true);
437   LiveRange LR(start, end, ValNo);
438   interval.addRange(LR);
439   DEBUG(dbgs() << " +" << LR << '\n');
440 }
441
442 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
443                                       MachineBasicBlock::iterator MI,
444                                       SlotIndex MIIdx,
445                                       MachineOperand& MO,
446                                       unsigned MOIdx) {
447   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
448     handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
449                              getOrCreateInterval(MO.getReg()));
450   else
451     handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
452                               getOrCreateInterval(MO.getReg()));
453 }
454
455 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
456                                          SlotIndex MIIdx,
457                                          LiveInterval &interval, bool isAlias) {
458   DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
459
460   // Look for kills, if it reaches a def before it's killed, then it shouldn't
461   // be considered a livein.
462   MachineBasicBlock::iterator mi = MBB->begin();
463   MachineBasicBlock::iterator E = MBB->end();
464   // Skip over DBG_VALUE at the start of the MBB.
465   if (mi != E && mi->isDebugValue()) {
466     while (++mi != E && mi->isDebugValue())
467       ;
468     if (mi == E)
469       // MBB is empty except for DBG_VALUE's.
470       return;
471   }
472
473   SlotIndex baseIndex = MIIdx;
474   SlotIndex start = baseIndex;
475   if (getInstructionFromIndex(baseIndex) == 0)
476     baseIndex = indexes_->getNextNonNullIndex(baseIndex);
477
478   SlotIndex end = baseIndex;
479   bool SeenDefUse = false;
480
481   while (mi != E) {
482     if (mi->killsRegister(interval.reg, tri_)) {
483       DEBUG(dbgs() << " killed");
484       end = baseIndex.getRegSlot();
485       SeenDefUse = true;
486       break;
487     } else if (mi->definesRegister(interval.reg, tri_)) {
488       // Another instruction redefines the register before it is ever read.
489       // Then the register is essentially dead at the instruction that defines
490       // it. Hence its interval is:
491       // [defSlot(def), defSlot(def)+1)
492       DEBUG(dbgs() << " dead");
493       end = start.getDeadSlot();
494       SeenDefUse = true;
495       break;
496     }
497
498     while (++mi != E && mi->isDebugValue())
499       // Skip over DBG_VALUE.
500       ;
501     if (mi != E)
502       baseIndex = indexes_->getNextNonNullIndex(baseIndex);
503   }
504
505   // Live-in register might not be used at all.
506   if (!SeenDefUse) {
507     if (isAlias) {
508       DEBUG(dbgs() << " dead");
509       end = MIIdx.getDeadSlot();
510     } else {
511       DEBUG(dbgs() << " live through");
512       end = getMBBEndIdx(MBB);
513     }
514   }
515
516   SlotIndex defIdx = getMBBStartIdx(MBB);
517   assert(getInstructionFromIndex(defIdx) == 0 &&
518          "PHI def index points at actual instruction.");
519   VNInfo *vni = interval.getNextValue(defIdx, VNInfoAllocator);
520   vni->setIsPHIDef(true);
521   LiveRange LR(start, end, vni);
522
523   interval.addRange(LR);
524   DEBUG(dbgs() << " +" << LR << '\n');
525 }
526
527 /// computeIntervals - computes the live intervals for virtual
528 /// registers. for some ordering of the machine instructions [1,N] a
529 /// live interval is an interval [i, j) where 1 <= i <= j < N for
530 /// which a variable is live
531 void LiveIntervals::computeIntervals() {
532   DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
533                << "********** Function: "
534                << ((Value*)mf_->getFunction())->getName() << '\n');
535
536   SmallVector<unsigned, 8> UndefUses;
537   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
538        MBBI != E; ++MBBI) {
539     MachineBasicBlock *MBB = MBBI;
540     if (MBB->empty())
541       continue;
542
543     // Track the index of the current machine instr.
544     SlotIndex MIIndex = getMBBStartIdx(MBB);
545     DEBUG(dbgs() << "BB#" << MBB->getNumber()
546           << ":\t\t# derived from " << MBB->getName() << "\n");
547
548     // Create intervals for live-ins to this BB first.
549     for (MachineBasicBlock::livein_iterator LI = MBB->livein_begin(),
550            LE = MBB->livein_end(); LI != LE; ++LI) {
551       handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
552     }
553
554     // Skip over empty initial indices.
555     if (getInstructionFromIndex(MIIndex) == 0)
556       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
557
558     for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
559          MI != miEnd; ++MI) {
560       DEBUG(dbgs() << MIIndex << "\t" << *MI);
561       if (MI->isDebugValue())
562         continue;
563
564       // Handle defs.
565       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
566         MachineOperand &MO = MI->getOperand(i);
567         if (!MO.isReg() || !MO.getReg())
568           continue;
569
570         // handle register defs - build intervals
571         if (MO.isDef())
572           handleRegisterDef(MBB, MI, MIIndex, MO, i);
573         else if (MO.isUndef())
574           UndefUses.push_back(MO.getReg());
575       }
576
577       // Move to the next instr slot.
578       MIIndex = indexes_->getNextNonNullIndex(MIIndex);
579     }
580   }
581
582   // Create empty intervals for registers defined by implicit_def's (except
583   // for those implicit_def that define values which are liveout of their
584   // blocks.
585   for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
586     unsigned UndefReg = UndefUses[i];
587     (void)getOrCreateInterval(UndefReg);
588   }
589 }
590
591 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
592   float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
593   return new LiveInterval(reg, Weight);
594 }
595
596 /// dupInterval - Duplicate a live interval. The caller is responsible for
597 /// managing the allocated memory.
598 LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
599   LiveInterval *NewLI = createInterval(li->reg);
600   NewLI->Copy(*li, mri_, getVNInfoAllocator());
601   return NewLI;
602 }
603
604 /// shrinkToUses - After removing some uses of a register, shrink its live
605 /// range to just the remaining uses. This method does not compute reaching
606 /// defs for new uses, and it doesn't remove dead defs.
607 bool LiveIntervals::shrinkToUses(LiveInterval *li,
608                                  SmallVectorImpl<MachineInstr*> *dead) {
609   DEBUG(dbgs() << "Shrink: " << *li << '\n');
610   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
611          && "Can only shrink virtual registers");
612   // Find all the values used, including PHI kills.
613   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
614
615   // Blocks that have already been added to WorkList as live-out.
616   SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
617
618   // Visit all instructions reading li->reg.
619   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li->reg);
620        MachineInstr *UseMI = I.skipInstruction();) {
621     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
622       continue;
623     SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
624     // Note: This intentionally picks up the wrong VNI in case of an EC redef.
625     // See below.
626     VNInfo *VNI = li->getVNInfoBefore(Idx);
627     if (!VNI) {
628       // This shouldn't happen: readsVirtualRegister returns true, but there is
629       // no live value. It is likely caused by a target getting <undef> flags
630       // wrong.
631       DEBUG(dbgs() << Idx << '\t' << *UseMI
632                    << "Warning: Instr claims to read non-existent value in "
633                     << *li << '\n');
634       continue;
635     }
636     // Special case: An early-clobber tied operand reads and writes the
637     // register one slot early.  The getVNInfoBefore call above would have
638     // picked up the value defined by UseMI.  Adjust the kill slot and value.
639     if (SlotIndex::isSameInstr(VNI->def, Idx)) {
640       Idx = VNI->def;
641       VNI = li->getVNInfoBefore(Idx);
642       assert(VNI && "Early-clobber tied value not available");
643     }
644     WorkList.push_back(std::make_pair(Idx, VNI));
645   }
646
647   // Create a new live interval with only minimal live segments per def.
648   LiveInterval NewLI(li->reg, 0);
649   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
650        I != E; ++I) {
651     VNInfo *VNI = *I;
652     if (VNI->isUnused())
653       continue;
654     NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
655   }
656
657   // Keep track of the PHIs that are in use.
658   SmallPtrSet<VNInfo*, 8> UsedPHIs;
659
660   // Extend intervals to reach all uses in WorkList.
661   while (!WorkList.empty()) {
662     SlotIndex Idx = WorkList.back().first;
663     VNInfo *VNI = WorkList.back().second;
664     WorkList.pop_back();
665     const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
666     SlotIndex BlockStart = getMBBStartIdx(MBB);
667
668     // Extend the live range for VNI to be live at Idx.
669     if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
670       (void)ExtVNI;
671       assert(ExtVNI == VNI && "Unexpected existing value number");
672       // Is this a PHIDef we haven't seen before?
673       if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
674         continue;
675       // The PHI is live, make sure the predecessors are live-out.
676       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
677            PE = MBB->pred_end(); PI != PE; ++PI) {
678         if (!LiveOut.insert(*PI))
679           continue;
680         SlotIndex Stop = getMBBEndIdx(*PI);
681         // A predecessor is not required to have a live-out value for a PHI.
682         if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
683           WorkList.push_back(std::make_pair(Stop, PVNI));
684       }
685       continue;
686     }
687
688     // VNI is live-in to MBB.
689     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
690     NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
691
692     // Make sure VNI is live-out from the predecessors.
693     for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
694          PE = MBB->pred_end(); PI != PE; ++PI) {
695       if (!LiveOut.insert(*PI))
696         continue;
697       SlotIndex Stop = getMBBEndIdx(*PI);
698       assert(li->getVNInfoBefore(Stop) == VNI &&
699              "Wrong value out of predecessor");
700       WorkList.push_back(std::make_pair(Stop, VNI));
701     }
702   }
703
704   // Handle dead values.
705   bool CanSeparate = false;
706   for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
707        I != E; ++I) {
708     VNInfo *VNI = *I;
709     if (VNI->isUnused())
710       continue;
711     LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
712     assert(LII != NewLI.end() && "Missing live range for PHI");
713     if (LII->end != VNI->def.getDeadSlot())
714       continue;
715     if (VNI->isPHIDef()) {
716       // This is a dead PHI. Remove it.
717       VNI->setIsUnused(true);
718       NewLI.removeRange(*LII);
719       DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
720       CanSeparate = true;
721     } else {
722       // This is a dead def. Make sure the instruction knows.
723       MachineInstr *MI = getInstructionFromIndex(VNI->def);
724       assert(MI && "No instruction defining live value");
725       MI->addRegisterDead(li->reg, tri_);
726       if (dead && MI->allDefsAreDead()) {
727         DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
728         dead->push_back(MI);
729       }
730     }
731   }
732
733   // Move the trimmed ranges back.
734   li->ranges.swap(NewLI.ranges);
735   DEBUG(dbgs() << "Shrunk: " << *li << '\n');
736   return CanSeparate;
737 }
738
739
740 //===----------------------------------------------------------------------===//
741 // Register allocator hooks.
742 //
743
744 void LiveIntervals::addKillFlags() {
745   for (iterator I = begin(), E = end(); I != E; ++I) {
746     unsigned Reg = I->first;
747     if (TargetRegisterInfo::isPhysicalRegister(Reg))
748       continue;
749     if (mri_->reg_nodbg_empty(Reg))
750       continue;
751     LiveInterval *LI = I->second;
752
753     // Every instruction that kills Reg corresponds to a live range end point.
754     for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
755          ++RI) {
756       // A block index indicates an MBB edge.
757       if (RI->end.isBlock())
758         continue;
759       MachineInstr *MI = getInstructionFromIndex(RI->end);
760       if (!MI)
761         continue;
762       MI->addRegisterKilled(Reg, NULL);
763     }
764   }
765 }
766
767 #ifndef NDEBUG
768 static bool intervalRangesSane(const LiveInterval& li) {
769   if (li.empty()) {
770     return true;
771   }
772
773   SlotIndex lastEnd = li.begin()->start;
774   for (LiveInterval::const_iterator lrItr = li.begin(), lrEnd = li.end();
775        lrItr != lrEnd; ++lrItr) {
776     const LiveRange& lr = *lrItr;
777     if (lastEnd > lr.start || lr.start >= lr.end)
778       return false;
779     lastEnd = lr.end;
780   }
781
782   return true;
783 }
784 #endif
785
786 template <typename DefSetT>
787 static void handleMoveDefs(LiveIntervals& lis, SlotIndex origIdx,
788                            SlotIndex miIdx, const DefSetT& defs) {
789   for (typename DefSetT::const_iterator defItr = defs.begin(),
790                                         defEnd = defs.end();
791        defItr != defEnd; ++defItr) {
792     unsigned def = *defItr;
793     LiveInterval& li = lis.getInterval(def);
794     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
795     assert(lr != 0 && "No range for def?");
796     lr->start = miIdx.getRegSlot();
797     lr->valno->def = miIdx.getRegSlot();
798     assert(intervalRangesSane(li) && "Broke live interval moving def.");
799   }
800 }
801
802 template <typename DeadDefSetT>
803 static void handleMoveDeadDefs(LiveIntervals& lis, SlotIndex origIdx,
804                                SlotIndex miIdx, const DeadDefSetT& deadDefs) {
805   for (typename DeadDefSetT::const_iterator deadDefItr = deadDefs.begin(),
806                                             deadDefEnd = deadDefs.end();
807        deadDefItr != deadDefEnd; ++deadDefItr) {
808     unsigned deadDef = *deadDefItr;
809     LiveInterval& li = lis.getInterval(deadDef);
810     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot());
811     assert(lr != 0 && "No range for dead def?");
812     assert(lr->start == origIdx.getRegSlot() && "Bad dead range start?");
813     assert(lr->end == origIdx.getDeadSlot() && "Bad dead range end?");
814     assert(lr->valno->def == origIdx.getRegSlot() && "Bad dead valno def.");
815     LiveRange t(*lr);
816     t.start = miIdx.getRegSlot();
817     t.valno->def = miIdx.getRegSlot();
818     t.end = miIdx.getDeadSlot();
819     li.removeRange(*lr);
820     li.addRange(t);
821     assert(intervalRangesSane(li) && "Broke live interval moving dead def.");
822   }
823 }
824
825 template <typename ECSetT>
826 static void handleMoveECs(LiveIntervals& lis, SlotIndex origIdx,
827                           SlotIndex miIdx, const ECSetT& ecs) {
828   for (typename ECSetT::const_iterator ecItr = ecs.begin(), ecEnd = ecs.end();
829        ecItr != ecEnd; ++ecItr) {
830     unsigned ec = *ecItr;
831     LiveInterval& li = lis.getInterval(ec);
832     LiveRange* lr = li.getLiveRangeContaining(origIdx.getRegSlot(true));
833     assert(lr != 0 && "No range for early clobber?");
834     assert(lr->start == origIdx.getRegSlot(true) && "Bad EC range start?");
835     assert(lr->end == origIdx.getRegSlot() && "Bad EC range end.");
836     assert(lr->valno->def == origIdx.getRegSlot(true) && "Bad EC valno def.");
837     LiveRange t(*lr);
838     t.start = miIdx.getRegSlot(true);
839     t.valno->def = miIdx.getRegSlot(true);
840     t.end = miIdx.getRegSlot();
841     li.removeRange(*lr);
842     li.addRange(t);
843     assert(intervalRangesSane(li) && "Broke live interval moving EC.");
844   }
845 }
846
847 template <typename UseSetT>
848 static void handleMoveUses(const MachineBasicBlock *mbb,
849                            const MachineRegisterInfo& mri,
850                            const BitVector& reservedRegs, LiveIntervals &lis,
851                            SlotIndex origIdx, SlotIndex miIdx,
852                            const UseSetT &uses) {
853   bool movingUp = miIdx < origIdx;
854   for (typename UseSetT::const_iterator usesItr = uses.begin(),
855                                         usesEnd = uses.end();
856        usesItr != usesEnd; ++usesItr) {
857     unsigned use = *usesItr;
858     if (!lis.hasInterval(use))
859       continue;
860     if (TargetRegisterInfo::isPhysicalRegister(use) && reservedRegs.test(use))
861       continue;
862     LiveInterval& li = lis.getInterval(use);
863     LiveRange* lr = li.getLiveRangeBefore(origIdx.getRegSlot());
864     assert(lr != 0 && "No range for use?");
865     bool liveThrough = lr->end > origIdx.getRegSlot();
866
867     if (movingUp) {
868       // If moving up and liveThrough - nothing to do.
869       // If not live through we need to extend the range to the last use
870       // between the old location and the new one.
871       if (!liveThrough) {
872         SlotIndex lastUseInRange = miIdx.getRegSlot();
873         for (MachineRegisterInfo::use_iterator useI = mri.use_begin(use),
874                                                useE = mri.use_end();
875              useI != useE; ++useI) {
876           const MachineInstr* mopI = &*useI;
877           const MachineOperand& mop = useI.getOperand();
878           SlotIndex instSlot = lis.getSlotIndexes()->getInstructionIndex(mopI);
879           SlotIndex opSlot = instSlot.getRegSlot(mop.isEarlyClobber());
880           if (opSlot >= lastUseInRange && opSlot < origIdx) {
881             lastUseInRange = opSlot;
882           }
883         }
884         lr->end = lastUseInRange;
885       }
886     } else {
887       // Moving down is easy - the existing live range end tells us where
888       // the last kill is.
889       if (!liveThrough) {
890         // Easy fix - just update the range endpoint.
891         lr->end = miIdx.getRegSlot();
892       } else {
893         bool liveOut = lr->end >= lis.getSlotIndexes()->getMBBEndIdx(mbb);
894         if (!liveOut && miIdx.getRegSlot() > lr->end) {
895           lr->end = miIdx.getRegSlot();
896         }
897       }
898     }
899     assert(intervalRangesSane(li) && "Broke live interval moving use.");
900   }
901 }
902
903 void LiveIntervals::moveInstr(MachineBasicBlock::iterator insertPt,
904                               MachineInstr *mi) {
905   MachineBasicBlock* mbb = mi->getParent();
906   assert((insertPt == mbb->end() || insertPt->getParent() == mbb) &&
907          "Cannot handle moves across basic block boundaries.");
908   assert(&*insertPt != mi && "No-op move requested?");
909   assert(!mi->isInsideBundle() && "Can't handle bundled instructions yet.");
910
911   // Grab the original instruction index.
912   SlotIndex origIdx = indexes_->getInstructionIndex(mi);
913
914   // Move the machine instr and obtain its new index.
915   indexes_->removeMachineInstrFromMaps(mi);
916   mbb->remove(mi);
917   mbb->insert(insertPt, mi);
918   SlotIndex miIdx = indexes_->insertMachineInstrInMaps(mi);
919
920   // Pick the direction.
921   bool movingUp = miIdx < origIdx;
922
923   // Collect the operands.
924   DenseSet<unsigned> uses, defs, deadDefs, ecs;
925   for (MachineInstr::mop_iterator mopItr = mi->operands_begin(),
926          mopEnd = mi->operands_end();
927        mopItr != mopEnd; ++mopItr) {
928     const MachineOperand& mop = *mopItr;
929
930     if (!mop.isReg() || mop.getReg() == 0)
931       continue;
932     unsigned reg = mop.getReg();
933     if (mop.isUse()) {
934       assert(mop.readsReg());
935     }
936
937     if (mop.readsReg() && !ecs.count(reg)) {
938       uses.insert(reg);
939     }
940     if (mop.isDef()) {
941       if (mop.isDead()) {
942         assert(!defs.count(reg) && "Can't mix defs with dead-defs.");
943         deadDefs.insert(reg);
944       } else if (mop.isEarlyClobber()) {
945         uses.erase(reg);
946         ecs.insert(reg);
947       } else {
948         assert(!deadDefs.count(reg) && "Can't mix defs with dead-defs.");
949         defs.insert(reg);
950       }
951     }
952   }
953
954   BitVector reservedRegs(tri_->getReservedRegs(*mbb->getParent()));
955
956   if (movingUp) {
957     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
958     handleMoveECs(*this, origIdx, miIdx, ecs);
959     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
960     handleMoveDefs(*this, origIdx, miIdx, defs);
961   } else {
962     handleMoveDefs(*this, origIdx, miIdx, defs);
963     handleMoveDeadDefs(*this, origIdx, miIdx, deadDefs);
964     handleMoveECs(*this, origIdx, miIdx, ecs);
965     handleMoveUses(mbb, *mri_, reservedRegs, *this, origIdx, miIdx, uses);
966   }
967 }
968
969 /// getReMatImplicitUse - If the remat definition MI has one (for now, we only
970 /// allow one) virtual register operand, then its uses are implicitly using
971 /// the register. Returns the virtual register.
972 unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
973                                             MachineInstr *MI) const {
974   unsigned RegOp = 0;
975   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
976     MachineOperand &MO = MI->getOperand(i);
977     if (!MO.isReg() || !MO.isUse())
978       continue;
979     unsigned Reg = MO.getReg();
980     if (Reg == 0 || Reg == li.reg)
981       continue;
982
983     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
984         !allocatableRegs_[Reg])
985       continue;
986     RegOp = MO.getReg();
987     break; // Found vreg operand - leave the loop.
988   }
989   return RegOp;
990 }
991
992 /// isValNoAvailableAt - Return true if the val# of the specified interval
993 /// which reaches the given instruction also reaches the specified use index.
994 bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
995                                        SlotIndex UseIdx) const {
996   VNInfo *UValNo = li.getVNInfoAt(UseIdx);
997   return UValNo && UValNo == li.getVNInfoAt(getInstructionIndex(MI));
998 }
999
1000 /// isReMaterializable - Returns true if the definition MI of the specified
1001 /// val# of the specified interval is re-materializable.
1002 bool
1003 LiveIntervals::isReMaterializable(const LiveInterval &li,
1004                                   const VNInfo *ValNo, MachineInstr *MI,
1005                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1006                                   bool &isLoad) {
1007   if (DisableReMat)
1008     return false;
1009
1010   if (!tii_->isTriviallyReMaterializable(MI, aa_))
1011     return false;
1012
1013   // Target-specific code can mark an instruction as being rematerializable
1014   // if it has one virtual reg use, though it had better be something like
1015   // a PIC base register which is likely to be live everywhere.
1016   unsigned ImpUse = getReMatImplicitUse(li, MI);
1017   if (ImpUse) {
1018     const LiveInterval &ImpLi = getInterval(ImpUse);
1019     for (MachineRegisterInfo::use_nodbg_iterator
1020            ri = mri_->use_nodbg_begin(li.reg), re = mri_->use_nodbg_end();
1021          ri != re; ++ri) {
1022       MachineInstr *UseMI = &*ri;
1023       SlotIndex UseIdx = getInstructionIndex(UseMI);
1024       if (li.getVNInfoAt(UseIdx) != ValNo)
1025         continue;
1026       if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1027         return false;
1028     }
1029
1030     // If a register operand of the re-materialized instruction is going to
1031     // be spilled next, then it's not legal to re-materialize this instruction.
1032     if (SpillIs)
1033       for (unsigned i = 0, e = SpillIs->size(); i != e; ++i)
1034         if (ImpUse == (*SpillIs)[i]->reg)
1035           return false;
1036   }
1037   return true;
1038 }
1039
1040 /// isReMaterializable - Returns true if every definition of MI of every
1041 /// val# of the specified interval is re-materializable.
1042 bool
1043 LiveIntervals::isReMaterializable(const LiveInterval &li,
1044                                   const SmallVectorImpl<LiveInterval*> *SpillIs,
1045                                   bool &isLoad) {
1046   isLoad = false;
1047   for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1048        i != e; ++i) {
1049     const VNInfo *VNI = *i;
1050     if (VNI->isUnused())
1051       continue; // Dead val#.
1052     // Is the def for the val# rematerializable?
1053     MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
1054     if (!ReMatDefMI)
1055       return false;
1056     bool DefIsLoad = false;
1057     if (!ReMatDefMI ||
1058         !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
1059       return false;
1060     isLoad |= DefIsLoad;
1061   }
1062   return true;
1063 }
1064
1065 bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1066   LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1067
1068   MachineBasicBlock *mbb =  indexes_->getMBBCoveringRange(itr->start, itr->end);
1069
1070   if (mbb == 0)
1071     return false;
1072
1073   for (++itr; itr != li.ranges.end(); ++itr) {
1074     MachineBasicBlock *mbb2 =
1075       indexes_->getMBBCoveringRange(itr->start, itr->end);
1076
1077     if (mbb2 != mbb)
1078       return false;
1079   }
1080
1081   return true;
1082 }
1083
1084 float
1085 LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
1086   // Limit the loop depth ridiculousness.
1087   if (loopDepth > 200)
1088     loopDepth = 200;
1089
1090   // The loop depth is used to roughly estimate the number of times the
1091   // instruction is executed. Something like 10^d is simple, but will quickly
1092   // overflow a float. This expression behaves like 10^d for small d, but is
1093   // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
1094   // headroom before overflow.
1095   // By the way, powf() might be unavailable here. For consistency,
1096   // We may take pow(double,double).
1097   float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
1098
1099   return (isDef + isUse) * lc;
1100 }
1101
1102 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1103                                                   MachineInstr* startInst) {
1104   LiveInterval& Interval = getOrCreateInterval(reg);
1105   VNInfo* VN = Interval.getNextValue(
1106     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1107     getVNInfoAllocator());
1108   VN->setHasPHIKill(true);
1109   LiveRange LR(
1110      SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1111      getMBBEndIdx(startInst->getParent()), VN);
1112   Interval.addRange(LR);
1113
1114   return LR;
1115 }