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