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