Refactored the LiveRangeEdit interface so that MachineFunction, TargetInstrInfo,...
[oota-llvm.git] / lib / CodeGen / LiveRangeEdit.cpp
1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
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 // The LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeEdit.h"
16 #include "VirtRegMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 STATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
29 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
30 STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
31
32 void LiveRangeEdit::Delegate::anchor() { }
33
34 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
35   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36   VRM->grow();
37   VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38   LiveInterval &LI = LIS.getOrCreateInterval(VReg);
39   newRegs_.push_back(&LI);
40   return LI;
41 }
42
43 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
44                                           const MachineInstr *DefMI,
45                                           AliasAnalysis *aa) {
46   assert(DefMI && "Missing instruction");
47   scannedRemattable_ = true;
48   if (!TII.isTriviallyReMaterializable(DefMI, aa))
49     return false;
50   remattable_.insert(VNI);
51   return true;
52 }
53
54 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
55   for (LiveInterval::vni_iterator I = parent_.vni_begin(),
56        E = parent_.vni_end(); I != E; ++I) {
57     VNInfo *VNI = *I;
58     if (VNI->isUnused())
59       continue;
60     MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
61     if (!DefMI)
62       continue;
63     checkRematerializable(VNI, DefMI, aa);
64   }
65   scannedRemattable_ = true;
66 }
67
68 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
69   if (!scannedRemattable_)
70     scanRemattable(aa);
71   return !remattable_.empty();
72 }
73
74 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
75 /// OrigIdx are also available with the same value at UseIdx.
76 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
77                                        SlotIndex OrigIdx,
78                                        SlotIndex UseIdx) {
79   OrigIdx = OrigIdx.getRegSlot(true);
80   UseIdx = UseIdx.getRegSlot(true);
81   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
82     const MachineOperand &MO = OrigMI->getOperand(i);
83     if (!MO.isReg() || !MO.getReg() || MO.isDef())
84       continue;
85     // Reserved registers are OK.
86     if (MO.isUndef() || !LIS.hasInterval(MO.getReg()))
87       continue;
88
89     LiveInterval &li = LIS.getInterval(MO.getReg());
90     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
91     if (!OVNI)
92       continue;
93     if (OVNI != li.getVNInfoAt(UseIdx))
94       return false;
95   }
96   return true;
97 }
98
99 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
100                                        SlotIndex UseIdx,
101                                        bool cheapAsAMove) {
102   assert(scannedRemattable_ && "Call anyRematerializable first");
103
104   // Use scanRemattable info.
105   if (!remattable_.count(RM.ParentVNI))
106     return false;
107
108   // No defining instruction provided.
109   SlotIndex DefIdx;
110   if (RM.OrigMI)
111     DefIdx = LIS.getInstructionIndex(RM.OrigMI);
112   else {
113     DefIdx = RM.ParentVNI->def;
114     RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
115     assert(RM.OrigMI && "No defining instruction for remattable value");
116   }
117
118   // If only cheap remats were requested, bail out early.
119   if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
120     return false;
121
122   // Verify that all used registers are available with the same values.
123   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
124     return false;
125
126   return true;
127 }
128
129 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
130                                          MachineBasicBlock::iterator MI,
131                                          unsigned DestReg,
132                                          const Remat &RM,
133                                          const TargetRegisterInfo &tri,
134                                          bool Late) {
135   assert(RM.OrigMI && "Invalid remat");
136   TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
137   rematted_.insert(RM.ParentVNI);
138   return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
139            .getRegSlot();
140 }
141
142 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
143   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
144     LIS.removeInterval(Reg);
145 }
146
147 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
148                                SmallVectorImpl<MachineInstr*> &Dead) {
149   MachineInstr *DefMI = 0, *UseMI = 0;
150
151   // Check that there is a single def and a single use.
152   for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
153        E = MRI.reg_nodbg_end(); I != E; ++I) {
154     MachineOperand &MO = I.getOperand();
155     MachineInstr *MI = MO.getParent();
156     if (MO.isDef()) {
157       if (DefMI && DefMI != MI)
158         return false;
159       if (!MI->canFoldAsLoad())
160         return false;
161       DefMI = MI;
162     } else if (!MO.isUndef()) {
163       if (UseMI && UseMI != MI)
164         return false;
165       // FIXME: Targets don't know how to fold subreg uses.
166       if (MO.getSubReg())
167         return false;
168       UseMI = MI;
169     }
170   }
171   if (!DefMI || !UseMI)
172     return false;
173
174   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
175                << "       into single use: " << *UseMI);
176
177   SmallVector<unsigned, 8> Ops;
178   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
179     return false;
180
181   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
182   if (!FoldMI)
183     return false;
184   DEBUG(dbgs() << "                folded: " << *FoldMI);
185   LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
186   UseMI->eraseFromParent();
187   DefMI->addRegisterDead(LI->reg, 0);
188   Dead.push_back(DefMI);
189   ++NumDCEFoldedLoads;
190   return true;
191 }
192
193 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
194                                       ArrayRef<unsigned> RegsBeingSpilled) {
195   SetVector<LiveInterval*,
196             SmallVector<LiveInterval*, 8>,
197             SmallPtrSet<LiveInterval*, 8> > ToShrink;
198
199   for (;;) {
200     // Erase all dead defs.
201     while (!Dead.empty()) {
202       MachineInstr *MI = Dead.pop_back_val();
203       assert(MI->allDefsAreDead() && "Def isn't really dead");
204       SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
205
206       // Never delete inline asm.
207       if (MI->isInlineAsm()) {
208         DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
209         continue;
210       }
211
212       // Use the same criteria as DeadMachineInstructionElim.
213       bool SawStore = false;
214       if (!MI->isSafeToMove(&TII, 0, SawStore)) {
215         DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
216         continue;
217       }
218
219       DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
220
221       // Check for live intervals that may shrink
222       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
223              MOE = MI->operands_end(); MOI != MOE; ++MOI) {
224         if (!MOI->isReg())
225           continue;
226         unsigned Reg = MOI->getReg();
227         if (!TargetRegisterInfo::isVirtualRegister(Reg))
228           continue;
229         LiveInterval &LI = LIS.getInterval(Reg);
230
231         // Shrink read registers, unless it is likely to be expensive and
232         // unlikely to change anything. We typically don't want to shrink the
233         // PIC base register that has lots of uses everywhere.
234         // Always shrink COPY uses that probably come from live range splitting.
235         if (MI->readsVirtualRegister(Reg) &&
236             (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
237              LI.killedAt(Idx)))
238           ToShrink.insert(&LI);
239
240         // Remove defined value.
241         if (MOI->isDef()) {
242           if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
243             if (delegate_)
244               delegate_->LRE_WillShrinkVirtReg(LI.reg);
245             LI.removeValNo(VNI);
246             if (LI.empty()) {
247               ToShrink.remove(&LI);
248               eraseVirtReg(Reg);
249             }
250           }
251         }
252       }
253
254       if (delegate_)
255         delegate_->LRE_WillEraseInstruction(MI);
256       LIS.RemoveMachineInstrFromMaps(MI);
257       MI->eraseFromParent();
258       ++NumDCEDeleted;
259     }
260
261     if (ToShrink.empty())
262       break;
263
264     // Shrink just one live interval. Then delete new dead defs.
265     LiveInterval *LI = ToShrink.back();
266     ToShrink.pop_back();
267     if (foldAsLoad(LI, Dead))
268       continue;
269     if (delegate_)
270       delegate_->LRE_WillShrinkVirtReg(LI->reg);
271     if (!LIS.shrinkToUses(LI, &Dead))
272       continue;
273     if (!VRM)
274       continue;
275     
276     // Don't create new intervals for a register being spilled.
277     // The new intervals would have to be spilled anyway so its not worth it.
278     // Also they currently aren't spilled so creating them and not spilling
279     // them results in incorrect code.
280     bool BeingSpilled = false;
281     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
282       if (LI->reg == RegsBeingSpilled[i]) {
283         BeingSpilled = true;
284         break;
285       }
286     }
287     
288     if (BeingSpilled) continue;
289     if (!VRM) continue;
290
291     // LI may have been separated, create new intervals.
292     LI->RenumberValues(LIS);
293     ConnectedVNInfoEqClasses ConEQ(LIS);
294     unsigned NumComp = ConEQ.Classify(LI);
295     if (NumComp <= 1)
296       continue;
297     ++NumFracRanges;
298     bool IsOriginal = VRM->getOriginal(LI->reg) == LI->reg;
299     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
300     SmallVector<LiveInterval*, 8> Dups(1, LI);
301     for (unsigned i = 1; i != NumComp; ++i) {
302       Dups.push_back(&createFrom(LI->reg));
303       // If LI is an original interval that hasn't been split yet, make the new
304       // intervals their own originals instead of referring to LI. The original
305       // interval must contain all the split products, and LI doesn't.
306       if (IsOriginal)
307         VRM->setIsSplitFromReg(Dups.back()->reg, 0);
308       if (delegate_)
309         delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
310     }
311     ConEQ.Distribute(&Dups[0], MRI);
312   }
313 }
314
315 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
316                                              const MachineLoopInfo &Loops) {
317   VirtRegAuxInfo VRAI(MF, LIS, Loops);
318   for (iterator I = begin(), E = end(); I != E; ++I) {
319     LiveInterval &LI = **I;
320     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
321       DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
322                    << MRI.getRegClass(LI.reg)->getName() << '\n');
323     VRAI.CalculateWeightAndHint(LI);
324   }
325 }