1235633Sdim//===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim// The LiveRangeEdit class represents changes done to a virtual register when it
11218885Sdim// is spilled or split.
12218885Sdim//===----------------------------------------------------------------------===//
13218885Sdim
14221345Sdim#define DEBUG_TYPE "regalloc"
15252723Sdim#include "llvm/CodeGen/LiveRangeEdit.h"
16223017Sdim#include "llvm/ADT/Statistic.h"
17221345Sdim#include "llvm/CodeGen/CalcSpillWeights.h"
18218885Sdim#include "llvm/CodeGen/LiveIntervalAnalysis.h"
19218885Sdim#include "llvm/CodeGen/MachineRegisterInfo.h"
20252723Sdim#include "llvm/CodeGen/VirtRegMap.h"
21221345Sdim#include "llvm/Support/Debug.h"
22221345Sdim#include "llvm/Support/raw_ostream.h"
23252723Sdim#include "llvm/Target/TargetInstrInfo.h"
24218885Sdim
25218885Sdimusing namespace llvm;
26218885Sdim
27223017SdimSTATISTIC(NumDCEDeleted,     "Number of instructions deleted by DCE");
28223017SdimSTATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29223017SdimSTATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
30223017Sdim
31235633Sdimvoid LiveRangeEdit::Delegate::anchor() { }
32235633Sdim
33263509SdimLiveInterval &LiveRangeEdit::createEmptyIntervalFrom(unsigned OldReg) {
34221345Sdim  unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
35235633Sdim  if (VRM) {
36235633Sdim    VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
37235633Sdim  }
38263509Sdim  LiveInterval &LI = LIS.createEmptyInterval(VReg);
39221345Sdim  return LI;
40218885Sdim}
41218885Sdim
42263509Sdimunsigned LiveRangeEdit::createFrom(unsigned OldReg) {
43263509Sdim  unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
44263509Sdim  if (VRM) {
45263509Sdim    VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
46263509Sdim  }
47263509Sdim  return VReg;
48263509Sdim}
49263509Sdim
50221345Sdimbool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
51221345Sdim                                          const MachineInstr *DefMI,
52221345Sdim                                          AliasAnalysis *aa) {
53221345Sdim  assert(DefMI && "Missing instruction");
54245431Sdim  ScannedRemattable = true;
55235633Sdim  if (!TII.isTriviallyReMaterializable(DefMI, aa))
56221345Sdim    return false;
57245431Sdim  Remattable.insert(VNI);
58221345Sdim  return true;
59221345Sdim}
60221345Sdim
61235633Sdimvoid LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
62245431Sdim  for (LiveInterval::vni_iterator I = getParent().vni_begin(),
63245431Sdim       E = getParent().vni_end(); I != E; ++I) {
64218885Sdim    VNInfo *VNI = *I;
65218885Sdim    if (VNI->isUnused())
66218885Sdim      continue;
67235633Sdim    MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
68218885Sdim    if (!DefMI)
69218885Sdim      continue;
70235633Sdim    checkRematerializable(VNI, DefMI, aa);
71218885Sdim  }
72245431Sdim  ScannedRemattable = true;
73218885Sdim}
74218885Sdim
75235633Sdimbool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
76245431Sdim  if (!ScannedRemattable)
77235633Sdim    scanRemattable(aa);
78245431Sdim  return !Remattable.empty();
79218885Sdim}
80218885Sdim
81218885Sdim/// allUsesAvailableAt - Return true if all registers used by OrigMI at
82218885Sdim/// OrigIdx are also available with the same value at UseIdx.
83218885Sdimbool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
84218885Sdim                                       SlotIndex OrigIdx,
85252723Sdim                                       SlotIndex UseIdx) const {
86235633Sdim  OrigIdx = OrigIdx.getRegSlot(true);
87235633Sdim  UseIdx = UseIdx.getRegSlot(true);
88218885Sdim  for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
89218885Sdim    const MachineOperand &MO = OrigMI->getOperand(i);
90245431Sdim    if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
91218885Sdim      continue;
92218885Sdim
93245431Sdim    // We can't remat physreg uses, unless it is a constant.
94245431Sdim    if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
95245431Sdim      if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
96245431Sdim        continue;
97245431Sdim      return false;
98245431Sdim    }
99245431Sdim
100235633Sdim    LiveInterval &li = LIS.getInterval(MO.getReg());
101218885Sdim    const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
102218885Sdim    if (!OVNI)
103218885Sdim      continue;
104245431Sdim
105245431Sdim    // Don't allow rematerialization immediately after the original def.
106245431Sdim    // It would be incorrect if OrigMI redefines the register.
107245431Sdim    // See PR14098.
108245431Sdim    if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
109245431Sdim      return false;
110245431Sdim
111218885Sdim    if (OVNI != li.getVNInfoAt(UseIdx))
112218885Sdim      return false;
113218885Sdim  }
114218885Sdim  return true;
115218885Sdim}
116218885Sdim
117218885Sdimbool LiveRangeEdit::canRematerializeAt(Remat &RM,
118218885Sdim                                       SlotIndex UseIdx,
119235633Sdim                                       bool cheapAsAMove) {
120245431Sdim  assert(ScannedRemattable && "Call anyRematerializable first");
121218885Sdim
122218885Sdim  // Use scanRemattable info.
123245431Sdim  if (!Remattable.count(RM.ParentVNI))
124218885Sdim    return false;
125218885Sdim
126221345Sdim  // No defining instruction provided.
127221345Sdim  SlotIndex DefIdx;
128221345Sdim  if (RM.OrigMI)
129235633Sdim    DefIdx = LIS.getInstructionIndex(RM.OrigMI);
130221345Sdim  else {
131221345Sdim    DefIdx = RM.ParentVNI->def;
132235633Sdim    RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
133221345Sdim    assert(RM.OrigMI && "No defining instruction for remattable value");
134221345Sdim  }
135218885Sdim
136218885Sdim  // If only cheap remats were requested, bail out early.
137235633Sdim  if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
138218885Sdim    return false;
139218885Sdim
140218885Sdim  // Verify that all used registers are available with the same values.
141235633Sdim  if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
142218885Sdim    return false;
143218885Sdim
144218885Sdim  return true;
145218885Sdim}
146218885Sdim
147218885SdimSlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
148218885Sdim                                         MachineBasicBlock::iterator MI,
149218885Sdim                                         unsigned DestReg,
150218885Sdim                                         const Remat &RM,
151221345Sdim                                         const TargetRegisterInfo &tri,
152221345Sdim                                         bool Late) {
153218885Sdim  assert(RM.OrigMI && "Invalid remat");
154235633Sdim  TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
155245431Sdim  Rematted.insert(RM.ParentVNI);
156235633Sdim  return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
157235633Sdim           .getRegSlot();
158218885Sdim}
159218885Sdim
160235633Sdimvoid LiveRangeEdit::eraseVirtReg(unsigned Reg) {
161245431Sdim  if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
162221345Sdim    LIS.removeInterval(Reg);
163221345Sdim}
164221345Sdim
165221345Sdimbool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
166235633Sdim                               SmallVectorImpl<MachineInstr*> &Dead) {
167221345Sdim  MachineInstr *DefMI = 0, *UseMI = 0;
168221345Sdim
169221345Sdim  // Check that there is a single def and a single use.
170221345Sdim  for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
171221345Sdim       E = MRI.reg_nodbg_end(); I != E; ++I) {
172221345Sdim    MachineOperand &MO = I.getOperand();
173221345Sdim    MachineInstr *MI = MO.getParent();
174221345Sdim    if (MO.isDef()) {
175221345Sdim      if (DefMI && DefMI != MI)
176221345Sdim        return false;
177235633Sdim      if (!MI->canFoldAsLoad())
178221345Sdim        return false;
179221345Sdim      DefMI = MI;
180221345Sdim    } else if (!MO.isUndef()) {
181221345Sdim      if (UseMI && UseMI != MI)
182221345Sdim        return false;
183221345Sdim      // FIXME: Targets don't know how to fold subreg uses.
184221345Sdim      if (MO.getSubReg())
185221345Sdim        return false;
186221345Sdim      UseMI = MI;
187221345Sdim    }
188221345Sdim  }
189221345Sdim  if (!DefMI || !UseMI)
190221345Sdim    return false;
191221345Sdim
192245431Sdim  // Since we're moving the DefMI load, make sure we're not extending any live
193245431Sdim  // ranges.
194245431Sdim  if (!allUsesAvailableAt(DefMI,
195245431Sdim                          LIS.getInstructionIndex(DefMI),
196245431Sdim                          LIS.getInstructionIndex(UseMI)))
197245431Sdim    return false;
198245431Sdim
199245431Sdim  // We also need to make sure it is safe to move the load.
200245431Sdim  // Assume there are stores between DefMI and UseMI.
201245431Sdim  bool SawStore = true;
202245431Sdim  if (!DefMI->isSafeToMove(&TII, 0, SawStore))
203245431Sdim    return false;
204245431Sdim
205221345Sdim  DEBUG(dbgs() << "Try to fold single def: " << *DefMI
206221345Sdim               << "       into single use: " << *UseMI);
207221345Sdim
208221345Sdim  SmallVector<unsigned, 8> Ops;
209221345Sdim  if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
210221345Sdim    return false;
211221345Sdim
212221345Sdim  MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
213221345Sdim  if (!FoldMI)
214221345Sdim    return false;
215221345Sdim  DEBUG(dbgs() << "                folded: " << *FoldMI);
216221345Sdim  LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
217221345Sdim  UseMI->eraseFromParent();
218221345Sdim  DefMI->addRegisterDead(LI->reg, 0);
219221345Sdim  Dead.push_back(DefMI);
220223017Sdim  ++NumDCEFoldedLoads;
221221345Sdim  return true;
222221345Sdim}
223221345Sdim
224263509Sdim/// Find all live intervals that need to shrink, then remove the instruction.
225263509Sdimvoid LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
226263509Sdim  assert(MI->allDefsAreDead() && "Def isn't really dead");
227263509Sdim  SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
228221345Sdim
229263509Sdim  // Never delete a bundled instruction.
230263509Sdim  if (MI->isBundled()) {
231263509Sdim    return;
232263509Sdim  }
233263509Sdim  // Never delete inline asm.
234263509Sdim  if (MI->isInlineAsm()) {
235263509Sdim    DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
236263509Sdim    return;
237263509Sdim  }
238221345Sdim
239263509Sdim  // Use the same criteria as DeadMachineInstructionElim.
240263509Sdim  bool SawStore = false;
241263509Sdim  if (!MI->isSafeToMove(&TII, 0, SawStore)) {
242263509Sdim    DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
243263509Sdim    return;
244263509Sdim  }
245221345Sdim
246263509Sdim  DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
247221345Sdim
248263509Sdim  // Collect virtual registers to be erased after MI is gone.
249263509Sdim  SmallVector<unsigned, 8> RegsToErase;
250263509Sdim  bool ReadsPhysRegs = false;
251221345Sdim
252263509Sdim  // Check for live intervals that may shrink
253263509Sdim  for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
254263509Sdim         MOE = MI->operands_end(); MOI != MOE; ++MOI) {
255263509Sdim    if (!MOI->isReg())
256263509Sdim      continue;
257263509Sdim    unsigned Reg = MOI->getReg();
258263509Sdim    if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
259263509Sdim      // Check if MI reads any unreserved physregs.
260263509Sdim      if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
261263509Sdim        ReadsPhysRegs = true;
262263509Sdim      else if (MOI->isDef()) {
263263509Sdim        for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
264263509Sdim             Units.isValid(); ++Units) {
265263509Sdim          if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
266263509Sdim            if (VNInfo *VNI = LR->getVNInfoAt(Idx))
267263509Sdim              LR->removeValNo(VNI);
268221345Sdim          }
269221345Sdim        }
270221345Sdim      }
271263509Sdim      continue;
272263509Sdim    }
273263509Sdim    LiveInterval &LI = LIS.getInterval(Reg);
274221345Sdim
275263509Sdim    // Shrink read registers, unless it is likely to be expensive and
276263509Sdim    // unlikely to change anything. We typically don't want to shrink the
277263509Sdim    // PIC base register that has lots of uses everywhere.
278263509Sdim    // Always shrink COPY uses that probably come from live range splitting.
279263509Sdim    if (MI->readsVirtualRegister(Reg) &&
280263509Sdim        (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
281263509Sdim         LI.Query(Idx).isKill()))
282263509Sdim      ToShrink.insert(&LI);
283263509Sdim
284263509Sdim    // Remove defined value.
285263509Sdim    if (MOI->isDef()) {
286263509Sdim      if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
287245431Sdim        if (TheDelegate)
288263509Sdim          TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
289263509Sdim        LI.removeValNo(VNI);
290263509Sdim        if (LI.empty())
291263509Sdim          RegsToErase.push_back(Reg);
292245431Sdim      }
293263509Sdim    }
294263509Sdim  }
295245431Sdim
296263509Sdim  // Currently, we don't support DCE of physreg live ranges. If MI reads
297263509Sdim  // any unreserved physregs, don't erase the instruction, but turn it into
298263509Sdim  // a KILL instead. This way, the physreg live ranges don't end up
299263509Sdim  // dangling.
300263509Sdim  // FIXME: It would be better to have something like shrinkToUses() for
301263509Sdim  // physregs. That could potentially enable more DCE and it would free up
302263509Sdim  // the physreg. It would not happen often, though.
303263509Sdim  if (ReadsPhysRegs) {
304263509Sdim    MI->setDesc(TII.get(TargetOpcode::KILL));
305263509Sdim    // Remove all operands that aren't physregs.
306263509Sdim    for (unsigned i = MI->getNumOperands(); i; --i) {
307263509Sdim      const MachineOperand &MO = MI->getOperand(i-1);
308263509Sdim      if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
309263509Sdim        continue;
310263509Sdim      MI->RemoveOperand(i-1);
311221345Sdim    }
312263509Sdim    DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
313263509Sdim  } else {
314263509Sdim    if (TheDelegate)
315263509Sdim      TheDelegate->LRE_WillEraseInstruction(MI);
316263509Sdim    LIS.RemoveMachineInstrFromMaps(MI);
317263509Sdim    MI->eraseFromParent();
318263509Sdim    ++NumDCEDeleted;
319263509Sdim  }
320221345Sdim
321263509Sdim  // Erase any virtregs that are now empty and unused. There may be <undef>
322263509Sdim  // uses around. Keep the empty live range in that case.
323263509Sdim  for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
324263509Sdim    unsigned Reg = RegsToErase[i];
325263509Sdim    if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
326263509Sdim      ToShrink.remove(&LIS.getInterval(Reg));
327263509Sdim      eraseVirtReg(Reg);
328263509Sdim    }
329263509Sdim  }
330263509Sdim}
331263509Sdim
332263509Sdimvoid LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
333263509Sdim                                      ArrayRef<unsigned> RegsBeingSpilled) {
334263509Sdim  ToShrinkSet ToShrink;
335263509Sdim
336263509Sdim  for (;;) {
337263509Sdim    // Erase all dead defs.
338263509Sdim    while (!Dead.empty())
339263509Sdim      eliminateDeadDef(Dead.pop_back_val(), ToShrink);
340263509Sdim
341221345Sdim    if (ToShrink.empty())
342221345Sdim      break;
343221345Sdim
344221345Sdim    // Shrink just one live interval. Then delete new dead defs.
345221345Sdim    LiveInterval *LI = ToShrink.back();
346221345Sdim    ToShrink.pop_back();
347235633Sdim    if (foldAsLoad(LI, Dead))
348221345Sdim      continue;
349245431Sdim    if (TheDelegate)
350245431Sdim      TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
351221345Sdim    if (!LIS.shrinkToUses(LI, &Dead))
352221345Sdim      continue;
353263509Sdim
354235633Sdim    // Don't create new intervals for a register being spilled.
355235633Sdim    // The new intervals would have to be spilled anyway so its not worth it.
356235633Sdim    // Also they currently aren't spilled so creating them and not spilling
357235633Sdim    // them results in incorrect code.
358235633Sdim    bool BeingSpilled = false;
359235633Sdim    for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
360235633Sdim      if (LI->reg == RegsBeingSpilled[i]) {
361235633Sdim        BeingSpilled = true;
362235633Sdim        break;
363235633Sdim      }
364235633Sdim    }
365263509Sdim
366235633Sdim    if (BeingSpilled) continue;
367221345Sdim
368221345Sdim    // LI may have been separated, create new intervals.
369263509Sdim    LI->RenumberValues();
370221345Sdim    ConnectedVNInfoEqClasses ConEQ(LIS);
371221345Sdim    unsigned NumComp = ConEQ.Classify(LI);
372221345Sdim    if (NumComp <= 1)
373221345Sdim      continue;
374223017Sdim    ++NumFracRanges;
375235633Sdim    bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
376221345Sdim    DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
377221345Sdim    SmallVector<LiveInterval*, 8> Dups(1, LI);
378221345Sdim    for (unsigned i = 1; i != NumComp; ++i) {
379263509Sdim      Dups.push_back(&createEmptyIntervalFrom(LI->reg));
380224145Sdim      // If LI is an original interval that hasn't been split yet, make the new
381224145Sdim      // intervals their own originals instead of referring to LI. The original
382224145Sdim      // interval must contain all the split products, and LI doesn't.
383224145Sdim      if (IsOriginal)
384235633Sdim        VRM->setIsSplitFromReg(Dups.back()->reg, 0);
385245431Sdim      if (TheDelegate)
386245431Sdim        TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
387221345Sdim    }
388221345Sdim    ConEQ.Distribute(&Dups[0], MRI);
389245431Sdim    DEBUG({
390245431Sdim      for (unsigned i = 0; i != NumComp; ++i)
391245431Sdim        dbgs() << '\t' << *Dups[i] << '\n';
392245431Sdim    });
393221345Sdim  }
394221345Sdim}
395221345Sdim
396263509Sdim// Keep track of new virtual registers created via
397263509Sdim// MachineRegisterInfo::createVirtualRegister.
398263509Sdimvoid
399263509SdimLiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
400263509Sdim{
401263509Sdim  if (VRM)
402263509Sdim    VRM->grow();
403263509Sdim
404263509Sdim  NewRegs.push_back(VReg);
405263509Sdim}
406263509Sdim
407263509Sdimvoid
408263509SdimLiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
409263509Sdim                                        const MachineLoopInfo &Loops,
410263509Sdim                                        const MachineBlockFrequencyInfo &MBFI) {
411263509Sdim  VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
412263509Sdim  for (unsigned I = 0, Size = size(); I < Size; ++I) {
413263509Sdim    LiveInterval &LI = LIS.getInterval(get(I));
414226890Sdim    if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
415226890Sdim      DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
416226890Sdim                   << MRI.getRegClass(LI.reg)->getName() << '\n');
417263509Sdim    VRAI.calculateSpillWeightAndHint(LI);
418221345Sdim  }
419221345Sdim}
420