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