]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/LiveRangeEdit.cpp
Merge llvm trunk r321017 to contrib/llvm.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 #include "llvm/CodeGen/LiveRangeEdit.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/CodeGen/CalcSpillWeights.h"
17 #include "llvm/CodeGen/LiveIntervals.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/TargetInstrInfo.h"
20 #include "llvm/CodeGen/VirtRegMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace llvm;
25
26 #define DEBUG_TYPE "regalloc"
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::createEmptyIntervalFrom(unsigned OldReg) {
35   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36   if (VRM) {
37     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38   }
39   LiveInterval &LI = LIS.createEmptyInterval(VReg);
40   if (Parent && !Parent->isSpillable())
41     LI.markNotSpillable();
42   // Create empty subranges if the OldReg's interval has them. Do not create
43   // the main range here---it will be constructed later after the subranges
44   // have been finalized.
45   LiveInterval &OldLI = LIS.getInterval(OldReg);
46   VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
47   for (LiveInterval::SubRange &S : OldLI.subranges())
48     LI.createSubRange(Alloc, S.LaneMask);
49   return LI;
50 }
51
52 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
53   unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
54   if (VRM) {
55     VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
56   }
57   // FIXME: Getting the interval here actually computes it.
58   // In theory, this may not be what we want, but in practice
59   // the createEmptyIntervalFrom API is used when this is not
60   // the case. Generally speaking we just want to annotate the
61   // LiveInterval when it gets created but we cannot do that at
62   // the moment.
63   if (Parent && !Parent->isSpillable())
64     LIS.getInterval(VReg).markNotSpillable();
65   return VReg;
66 }
67
68 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
69                                           const MachineInstr *DefMI,
70                                           AliasAnalysis *aa) {
71   assert(DefMI && "Missing instruction");
72   ScannedRemattable = true;
73   if (!TII.isTriviallyReMaterializable(*DefMI, aa))
74     return false;
75   Remattable.insert(VNI);
76   return true;
77 }
78
79 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
80   for (VNInfo *VNI : getParent().valnos) {
81     if (VNI->isUnused())
82       continue;
83     unsigned Original = VRM->getOriginal(getReg());
84     LiveInterval &OrigLI = LIS.getInterval(Original);
85     VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
86     if (!OrigVNI)
87       continue;
88     MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
89     if (!DefMI)
90       continue;
91     checkRematerializable(OrigVNI, DefMI, aa);
92   }
93   ScannedRemattable = true;
94 }
95
96 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
97   if (!ScannedRemattable)
98     scanRemattable(aa);
99   return !Remattable.empty();
100 }
101
102 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
103 /// OrigIdx are also available with the same value at UseIdx.
104 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
105                                        SlotIndex OrigIdx,
106                                        SlotIndex UseIdx) const {
107   OrigIdx = OrigIdx.getRegSlot(true);
108   UseIdx = UseIdx.getRegSlot(true);
109   for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
110     const MachineOperand &MO = OrigMI->getOperand(i);
111     if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
112       continue;
113
114     // We can't remat physreg uses, unless it is a constant.
115     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
116       if (MRI.isConstantPhysReg(MO.getReg()))
117         continue;
118       return false;
119     }
120
121     LiveInterval &li = LIS.getInterval(MO.getReg());
122     const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
123     if (!OVNI)
124       continue;
125
126     // Don't allow rematerialization immediately after the original def.
127     // It would be incorrect if OrigMI redefines the register.
128     // See PR14098.
129     if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
130       return false;
131
132     if (OVNI != li.getVNInfoAt(UseIdx))
133       return false;
134   }
135   return true;
136 }
137
138 bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
139                                        SlotIndex UseIdx, bool cheapAsAMove) {
140   assert(ScannedRemattable && "Call anyRematerializable first");
141
142   // Use scanRemattable info.
143   if (!Remattable.count(OrigVNI))
144     return false;
145
146   // No defining instruction provided.
147   SlotIndex DefIdx;
148   assert(RM.OrigMI && "No defining instruction for remattable value");
149   DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
150
151   // If only cheap remats were requested, bail out early.
152   if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
153     return false;
154
155   // Verify that all used registers are available with the same values.
156   if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
157     return false;
158
159   return true;
160 }
161
162 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
163                                          MachineBasicBlock::iterator MI,
164                                          unsigned DestReg,
165                                          const Remat &RM,
166                                          const TargetRegisterInfo &tri,
167                                          bool Late) {
168   assert(RM.OrigMI && "Invalid remat");
169   TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri);
170   // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
171   // to false anyway in case the isDead flag of RM.OrigMI's dest register
172   // is true.
173   (*--MI).getOperand(0).setIsDead(false);
174   Rematted.insert(RM.ParentVNI);
175   return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
176 }
177
178 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
179   if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
180     LIS.removeInterval(Reg);
181 }
182
183 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
184                                SmallVectorImpl<MachineInstr*> &Dead) {
185   MachineInstr *DefMI = nullptr, *UseMI = nullptr;
186
187   // Check that there is a single def and a single use.
188   for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
189     MachineInstr *MI = MO.getParent();
190     if (MO.isDef()) {
191       if (DefMI && DefMI != MI)
192         return false;
193       if (!MI->canFoldAsLoad())
194         return false;
195       DefMI = MI;
196     } else if (!MO.isUndef()) {
197       if (UseMI && UseMI != MI)
198         return false;
199       // FIXME: Targets don't know how to fold subreg uses.
200       if (MO.getSubReg())
201         return false;
202       UseMI = MI;
203     }
204   }
205   if (!DefMI || !UseMI)
206     return false;
207
208   // Since we're moving the DefMI load, make sure we're not extending any live
209   // ranges.
210   if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
211                           LIS.getInstructionIndex(*UseMI)))
212     return false;
213
214   // We also need to make sure it is safe to move the load.
215   // Assume there are stores between DefMI and UseMI.
216   bool SawStore = true;
217   if (!DefMI->isSafeToMove(nullptr, SawStore))
218     return false;
219
220   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
221                << "       into single use: " << *UseMI);
222
223   SmallVector<unsigned, 8> Ops;
224   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
225     return false;
226
227   MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
228   if (!FoldMI)
229     return false;
230   DEBUG(dbgs() << "                folded: " << *FoldMI);
231   LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
232   UseMI->eraseFromParent();
233   DefMI->addRegisterDead(LI->reg, nullptr);
234   Dead.push_back(DefMI);
235   ++NumDCEFoldedLoads;
236   return true;
237 }
238
239 bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
240                               const MachineOperand &MO) const {
241   const MachineInstr &MI = *MO.getParent();
242   SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
243   if (LI.Query(Idx).isKill())
244     return true;
245   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
246   unsigned SubReg = MO.getSubReg();
247   LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
248   for (const LiveInterval::SubRange &S : LI.subranges()) {
249     if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
250       return true;
251   }
252   return false;
253 }
254
255 /// Find all live intervals that need to shrink, then remove the instruction.
256 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink,
257                                      AliasAnalysis *AA) {
258   assert(MI->allDefsAreDead() && "Def isn't really dead");
259   SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
260
261   // Never delete a bundled instruction.
262   if (MI->isBundled()) {
263     return;
264   }
265   // Never delete inline asm.
266   if (MI->isInlineAsm()) {
267     DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
268     return;
269   }
270
271   // Use the same criteria as DeadMachineInstructionElim.
272   bool SawStore = false;
273   if (!MI->isSafeToMove(nullptr, SawStore)) {
274     DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
275     return;
276   }
277
278   DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
279
280   // Collect virtual registers to be erased after MI is gone.
281   SmallVector<unsigned, 8> RegsToErase;
282   bool ReadsPhysRegs = false;
283   bool isOrigDef = false;
284   unsigned Dest;
285   // Only optimize rematerialize case when the instruction has one def, since
286   // otherwise we could leave some dead defs in the code.  This case is
287   // extremely rare.
288   if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
289       MI->getDesc().getNumDefs() == 1) {
290     Dest = MI->getOperand(0).getReg();
291     unsigned Original = VRM->getOriginal(Dest);
292     LiveInterval &OrigLI = LIS.getInterval(Original);
293     VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
294     // The original live-range may have been shrunk to
295     // an empty live-range. It happens when it is dead, but
296     // we still keep it around to be able to rematerialize
297     // other values that depend on it.
298     if (OrigVNI)
299       isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
300   }
301
302   // Check for live intervals that may shrink
303   for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
304          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
305     if (!MOI->isReg())
306       continue;
307     unsigned Reg = MOI->getReg();
308     if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
309       // Check if MI reads any unreserved physregs.
310       if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
311         ReadsPhysRegs = true;
312       else if (MOI->isDef())
313         LIS.removePhysRegDefAt(Reg, Idx);
314       continue;
315     }
316     LiveInterval &LI = LIS.getInterval(Reg);
317
318     // Shrink read registers, unless it is likely to be expensive and
319     // unlikely to change anything. We typically don't want to shrink the
320     // PIC base register that has lots of uses everywhere.
321     // Always shrink COPY uses that probably come from live range splitting.
322     if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef())) ||
323         (MOI->readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, *MOI))))
324       ToShrink.insert(&LI);
325
326     // Remove defined value.
327     if (MOI->isDef()) {
328       if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
329         TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
330       LIS.removeVRegDefAt(LI, Idx);
331       if (LI.empty())
332         RegsToErase.push_back(Reg);
333     }
334   }
335
336   // Currently, we don't support DCE of physreg live ranges. If MI reads
337   // any unreserved physregs, don't erase the instruction, but turn it into
338   // a KILL instead. This way, the physreg live ranges don't end up
339   // dangling.
340   // FIXME: It would be better to have something like shrinkToUses() for
341   // physregs. That could potentially enable more DCE and it would free up
342   // the physreg. It would not happen often, though.
343   if (ReadsPhysRegs) {
344     MI->setDesc(TII.get(TargetOpcode::KILL));
345     // Remove all operands that aren't physregs.
346     for (unsigned i = MI->getNumOperands(); i; --i) {
347       const MachineOperand &MO = MI->getOperand(i-1);
348       if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
349         continue;
350       MI->RemoveOperand(i-1);
351     }
352     DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
353   } else {
354     // If the dest of MI is an original reg and MI is reMaterializable,
355     // don't delete the inst. Replace the dest with a new reg, and keep
356     // the inst for remat of other siblings. The inst is saved in
357     // LiveRangeEdit::DeadRemats and will be deleted after all the
358     // allocations of the func are done.
359     if (isOrigDef && DeadRemats && TII.isTriviallyReMaterializable(*MI, AA)) {
360       LiveInterval &NewLI = createEmptyIntervalFrom(Dest);
361       NewLI.removeEmptySubRanges();
362       VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
363       NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
364       pop_back();
365       markDeadRemat(MI);
366       const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
367       MI->substituteRegister(Dest, NewLI.reg, 0, TRI);
368       MI->getOperand(0).setIsDead(true);
369     } else {
370       if (TheDelegate)
371         TheDelegate->LRE_WillEraseInstruction(MI);
372       LIS.RemoveMachineInstrFromMaps(*MI);
373       MI->eraseFromParent();
374       ++NumDCEDeleted;
375     }
376   }
377
378   // Erase any virtregs that are now empty and unused. There may be <undef>
379   // uses around. Keep the empty live range in that case.
380   for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
381     unsigned Reg = RegsToErase[i];
382     if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
383       ToShrink.remove(&LIS.getInterval(Reg));
384       eraseVirtReg(Reg);
385     }
386   }
387 }
388
389 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
390                                       ArrayRef<unsigned> RegsBeingSpilled,
391                                       AliasAnalysis *AA) {
392   ToShrinkSet ToShrink;
393
394   for (;;) {
395     // Erase all dead defs.
396     while (!Dead.empty())
397       eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA);
398
399     if (ToShrink.empty())
400       break;
401
402     // Shrink just one live interval. Then delete new dead defs.
403     LiveInterval *LI = ToShrink.back();
404     ToShrink.pop_back();
405     if (foldAsLoad(LI, Dead))
406       continue;
407     unsigned VReg = LI->reg;
408     if (TheDelegate)
409       TheDelegate->LRE_WillShrinkVirtReg(VReg);
410     if (!LIS.shrinkToUses(LI, &Dead))
411       continue;
412
413     // Don't create new intervals for a register being spilled.
414     // The new intervals would have to be spilled anyway so its not worth it.
415     // Also they currently aren't spilled so creating them and not spilling
416     // them results in incorrect code.
417     bool BeingSpilled = false;
418     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
419       if (VReg == RegsBeingSpilled[i]) {
420         BeingSpilled = true;
421         break;
422       }
423     }
424
425     if (BeingSpilled) continue;
426
427     // LI may have been separated, create new intervals.
428     LI->RenumberValues();
429     SmallVector<LiveInterval*, 8> SplitLIs;
430     LIS.splitSeparateComponents(*LI, SplitLIs);
431     if (!SplitLIs.empty())
432       ++NumFracRanges;
433
434     unsigned Original = VRM ? VRM->getOriginal(VReg) : 0;
435     for (const LiveInterval *SplitLI : SplitLIs) {
436       // If LI is an original interval that hasn't been split yet, make the new
437       // intervals their own originals instead of referring to LI. The original
438       // interval must contain all the split products, and LI doesn't.
439       if (Original != VReg && Original != 0)
440         VRM->setIsSplitFromReg(SplitLI->reg, Original);
441       if (TheDelegate)
442         TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg, VReg);
443     }
444   }
445 }
446
447 // Keep track of new virtual registers created via
448 // MachineRegisterInfo::createVirtualRegister.
449 void
450 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
451 {
452   if (VRM)
453     VRM->grow();
454
455   NewRegs.push_back(VReg);
456 }
457
458 void
459 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
460                                         const MachineLoopInfo &Loops,
461                                         const MachineBlockFrequencyInfo &MBFI) {
462   VirtRegAuxInfo VRAI(MF, LIS, VRM, Loops, MBFI);
463   for (unsigned I = 0, Size = size(); I < Size; ++I) {
464     LiveInterval &LI = LIS.getInterval(get(I));
465     if (MRI.recomputeRegClass(LI.reg))
466       DEBUG({
467         const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
468         dbgs() << "Inflated " << printReg(LI.reg) << " to "
469                << TRI->getRegClassName(MRI.getRegClass(LI.reg)) << '\n';
470       });
471     VRAI.calculateSpillWeightAndHint(LI);
472   }
473 }