xref: /llvm-project/llvm/lib/CodeGen/LiveRangeEdit.cpp (revision d307909a50ae7a9404dfbdd1db34e53b4d196f2e)
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   // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
152   // to false anyway in case the isDead flag of RM.OrigMI's dest register
153   // is true.
154   (*--MI).getOperand(0).setIsDead(false);
155   Rematted.insert(RM.ParentVNI);
156   return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
157 }
158 
159 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
160   if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
161     LIS.removeInterval(Reg);
162 }
163 
164 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
165                                SmallVectorImpl<MachineInstr*> &Dead) {
166   MachineInstr *DefMI = nullptr, *UseMI = nullptr;
167 
168   // Check that there is a single def and a single use.
169   for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
170     MachineInstr *MI = MO.getParent();
171     if (MO.isDef()) {
172       if (DefMI && DefMI != MI)
173         return false;
174       if (!MI->canFoldAsLoad())
175         return false;
176       DefMI = MI;
177     } else if (!MO.isUndef()) {
178       if (UseMI && UseMI != MI)
179         return false;
180       // FIXME: Targets don't know how to fold subreg uses.
181       if (MO.getSubReg())
182         return false;
183       UseMI = MI;
184     }
185   }
186   if (!DefMI || !UseMI)
187     return false;
188 
189   // Since we're moving the DefMI load, make sure we're not extending any live
190   // ranges.
191   if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
192                           LIS.getInstructionIndex(*UseMI)))
193     return false;
194 
195   // We also need to make sure it is safe to move the load.
196   // Assume there are stores between DefMI and UseMI.
197   bool SawStore = true;
198   if (!DefMI->isSafeToMove(nullptr, SawStore))
199     return false;
200 
201   DEBUG(dbgs() << "Try to fold single def: " << *DefMI
202                << "       into single use: " << *UseMI);
203 
204   SmallVector<unsigned, 8> Ops;
205   if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
206     return false;
207 
208   MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI, &LIS);
209   if (!FoldMI)
210     return false;
211   DEBUG(dbgs() << "                folded: " << *FoldMI);
212   LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
213   UseMI->eraseFromParent();
214   DefMI->addRegisterDead(LI->reg, nullptr);
215   Dead.push_back(DefMI);
216   ++NumDCEFoldedLoads;
217   return true;
218 }
219 
220 bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
221                               const MachineOperand &MO) const {
222   const MachineInstr &MI = *MO.getParent();
223   SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
224   if (LI.Query(Idx).isKill())
225     return true;
226   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
227   unsigned SubReg = MO.getSubReg();
228   LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
229   for (const LiveInterval::SubRange &S : LI.subranges()) {
230     if ((S.LaneMask & LaneMask) != 0 && S.Query(Idx).isKill())
231       return true;
232   }
233   return false;
234 }
235 
236 /// Find all live intervals that need to shrink, then remove the instruction.
237 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
238   assert(MI->allDefsAreDead() && "Def isn't really dead");
239   SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
240 
241   // Never delete a bundled instruction.
242   if (MI->isBundled()) {
243     return;
244   }
245   // Never delete inline asm.
246   if (MI->isInlineAsm()) {
247     DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
248     return;
249   }
250 
251   // Use the same criteria as DeadMachineInstructionElim.
252   bool SawStore = false;
253   if (!MI->isSafeToMove(nullptr, SawStore)) {
254     DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
255     return;
256   }
257 
258   DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
259 
260   // Collect virtual registers to be erased after MI is gone.
261   SmallVector<unsigned, 8> RegsToErase;
262   bool ReadsPhysRegs = false;
263   bool isOrigDef = false;
264   unsigned Dest;
265   if (VRM && MI->getOperand(0).isReg()) {
266     Dest = MI->getOperand(0).getReg();
267     unsigned Original = VRM->getOriginal(Dest);
268     LiveInterval &OrigLI = LIS.getInterval(Original);
269     VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
270     // The original live-range may have been shrunk to
271     // an empty live-range. It happens when it is dead, but
272     // we still keep it around to be able to rematerialize
273     // other values that depend on it.
274     if (OrigVNI)
275       isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
276   }
277 
278   // Check for live intervals that may shrink
279   for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
280          MOE = MI->operands_end(); MOI != MOE; ++MOI) {
281     if (!MOI->isReg())
282       continue;
283     unsigned Reg = MOI->getReg();
284     if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
285       // Check if MI reads any unreserved physregs.
286       if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
287         ReadsPhysRegs = true;
288       else if (MOI->isDef())
289         LIS.removePhysRegDefAt(Reg, Idx);
290       continue;
291     }
292     LiveInterval &LI = LIS.getInterval(Reg);
293 
294     // Shrink read registers, unless it is likely to be expensive and
295     // unlikely to change anything. We typically don't want to shrink the
296     // PIC base register that has lots of uses everywhere.
297     // Always shrink COPY uses that probably come from live range splitting.
298     if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MOI->isDef())) ||
299         (MOI->readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, *MOI))))
300       ToShrink.insert(&LI);
301 
302     // Remove defined value.
303     if (MOI->isDef()) {
304       if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
305         TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
306       LIS.removeVRegDefAt(LI, Idx);
307       if (LI.empty())
308         RegsToErase.push_back(Reg);
309     }
310   }
311 
312   // Currently, we don't support DCE of physreg live ranges. If MI reads
313   // any unreserved physregs, don't erase the instruction, but turn it into
314   // a KILL instead. This way, the physreg live ranges don't end up
315   // dangling.
316   // FIXME: It would be better to have something like shrinkToUses() for
317   // physregs. That could potentially enable more DCE and it would free up
318   // the physreg. It would not happen often, though.
319   if (ReadsPhysRegs) {
320     MI->setDesc(TII.get(TargetOpcode::KILL));
321     // Remove all operands that aren't physregs.
322     for (unsigned i = MI->getNumOperands(); i; --i) {
323       const MachineOperand &MO = MI->getOperand(i-1);
324       if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
325         continue;
326       MI->RemoveOperand(i-1);
327     }
328     DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
329   } else {
330     // If the dest of MI is an original reg, don't delete the inst. Replace
331     // the dest with a new reg, keep the inst for remat of other siblings.
332     // The inst is saved in LiveRangeEdit::DeadRemats and will be deleted
333     // after all the allocations of the func are done.
334     if (isOrigDef) {
335       LiveInterval &NewLI = createEmptyIntervalFrom(Dest);
336       VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
337       NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
338       pop_back();
339       markDeadRemat(MI);
340       const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
341       MI->substituteRegister(Dest, NewLI.reg, 0, TRI);
342       MI->getOperand(0).setIsDead(true);
343     } else {
344       if (TheDelegate)
345         TheDelegate->LRE_WillEraseInstruction(MI);
346       LIS.RemoveMachineInstrFromMaps(*MI);
347       MI->eraseFromParent();
348       ++NumDCEDeleted;
349     }
350   }
351 
352   // Erase any virtregs that are now empty and unused. There may be <undef>
353   // uses around. Keep the empty live range in that case.
354   for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
355     unsigned Reg = RegsToErase[i];
356     if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
357       ToShrink.remove(&LIS.getInterval(Reg));
358       eraseVirtReg(Reg);
359     }
360   }
361 }
362 
363 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
364                                       ArrayRef<unsigned> RegsBeingSpilled) {
365   ToShrinkSet ToShrink;
366 
367   for (;;) {
368     // Erase all dead defs.
369     while (!Dead.empty())
370       eliminateDeadDef(Dead.pop_back_val(), ToShrink);
371 
372     if (ToShrink.empty())
373       break;
374 
375     // Shrink just one live interval. Then delete new dead defs.
376     LiveInterval *LI = ToShrink.back();
377     ToShrink.pop_back();
378     if (foldAsLoad(LI, Dead))
379       continue;
380     unsigned VReg = LI->reg;
381     if (TheDelegate)
382       TheDelegate->LRE_WillShrinkVirtReg(VReg);
383     if (!LIS.shrinkToUses(LI, &Dead))
384       continue;
385 
386     // Don't create new intervals for a register being spilled.
387     // The new intervals would have to be spilled anyway so its not worth it.
388     // Also they currently aren't spilled so creating them and not spilling
389     // them results in incorrect code.
390     bool BeingSpilled = false;
391     for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
392       if (VReg == RegsBeingSpilled[i]) {
393         BeingSpilled = true;
394         break;
395       }
396     }
397 
398     if (BeingSpilled) continue;
399 
400     // LI may have been separated, create new intervals.
401     LI->RenumberValues();
402     SmallVector<LiveInterval*, 8> SplitLIs;
403     LIS.splitSeparateComponents(*LI, SplitLIs);
404     if (!SplitLIs.empty())
405       ++NumFracRanges;
406 
407     unsigned Original = VRM ? VRM->getOriginal(VReg) : 0;
408     for (const LiveInterval *SplitLI : SplitLIs) {
409       // If LI is an original interval that hasn't been split yet, make the new
410       // intervals their own originals instead of referring to LI. The original
411       // interval must contain all the split products, and LI doesn't.
412       if (Original != VReg && Original != 0)
413         VRM->setIsSplitFromReg(SplitLI->reg, Original);
414       if (TheDelegate)
415         TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg, VReg);
416     }
417   }
418 }
419 
420 // Keep track of new virtual registers created via
421 // MachineRegisterInfo::createVirtualRegister.
422 void
423 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
424 {
425   if (VRM)
426     VRM->grow();
427 
428   NewRegs.push_back(VReg);
429 }
430 
431 void
432 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
433                                         const MachineLoopInfo &Loops,
434                                         const MachineBlockFrequencyInfo &MBFI) {
435   VirtRegAuxInfo VRAI(MF, LIS, VRM, Loops, MBFI);
436   for (unsigned I = 0, Size = size(); I < Size; ++I) {
437     LiveInterval &LI = LIS.getInterval(get(I));
438     if (MRI.recomputeRegClass(LI.reg))
439       DEBUG({
440         const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
441         dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
442                << TRI->getRegClassName(MRI.getRegClass(LI.reg)) << '\n';
443       });
444     VRAI.calculateSpillWeightAndHint(LI);
445   }
446 }
447