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