1//===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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// This file implements the VirtRegMap class.
11//
12// It also contains implementations of the Spiller interface, which, given a
13// virtual register map and a machine function, eliminates all virtual
14// references by replacing them with physical register references - adding spill
15// code as necessary.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "virtregmap"
20#include "VirtRegMap.h"
21#include "llvm/Function.h"
22#include "llvm/CodeGen/LiveIntervalAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/SlotIndexes.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Compiler.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/DepthFirstIterator.h"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallSet.h"
41#include <algorithm>
42using namespace llvm;
43
44STATISTIC(NumSpillSlots, "Number of spill slots allocated");
45STATISTIC(NumIdCopies,   "Number of identity moves eliminated after rewriting");
46
47//===----------------------------------------------------------------------===//
48//  VirtRegMap implementation
49//===----------------------------------------------------------------------===//
50
51char VirtRegMap::ID = 0;
52
53INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
54
55bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
56  MRI = &mf.getRegInfo();
57  TII = mf.getTarget().getInstrInfo();
58  TRI = mf.getTarget().getRegisterInfo();
59  MF = &mf;
60
61  ReMatId = MAX_STACK_SLOT+1;
62  LowSpillSlot = HighSpillSlot = NO_STACK_SLOT;
63
64  Virt2PhysMap.clear();
65  Virt2StackSlotMap.clear();
66  Virt2ReMatIdMap.clear();
67  Virt2SplitMap.clear();
68  Virt2SplitKillMap.clear();
69  ReMatMap.clear();
70  ImplicitDefed.clear();
71  SpillSlotToUsesMap.clear();
72  MI2VirtMap.clear();
73  SpillPt2VirtMap.clear();
74  RestorePt2VirtMap.clear();
75  EmergencySpillMap.clear();
76  EmergencySpillSlots.clear();
77
78  SpillSlotToUsesMap.resize(8);
79  ImplicitDefed.resize(MF->getRegInfo().getNumVirtRegs());
80
81  allocatableRCRegs.clear();
82  for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
83         E = TRI->regclass_end(); I != E; ++I)
84    allocatableRCRegs.insert(std::make_pair(*I,
85                                            TRI->getAllocatableSet(mf, *I)));
86
87  grow();
88
89  return false;
90}
91
92void VirtRegMap::grow() {
93  unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
94  Virt2PhysMap.resize(NumRegs);
95  Virt2StackSlotMap.resize(NumRegs);
96  Virt2ReMatIdMap.resize(NumRegs);
97  Virt2SplitMap.resize(NumRegs);
98  Virt2SplitKillMap.resize(NumRegs);
99  ReMatMap.resize(NumRegs);
100  ImplicitDefed.resize(NumRegs);
101}
102
103unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
104  int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
105                                                      RC->getAlignment());
106  if (LowSpillSlot == NO_STACK_SLOT)
107    LowSpillSlot = SS;
108  if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
109    HighSpillSlot = SS;
110  assert(SS >= LowSpillSlot && "Unexpected low spill slot");
111  unsigned Idx = SS-LowSpillSlot;
112  while (Idx >= SpillSlotToUsesMap.size())
113    SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2);
114  ++NumSpillSlots;
115  return SS;
116}
117
118unsigned VirtRegMap::getRegAllocPref(unsigned virtReg) {
119  std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(virtReg);
120  unsigned physReg = Hint.second;
121  if (TargetRegisterInfo::isVirtualRegister(physReg) && hasPhys(physReg))
122    physReg = getPhys(physReg);
123  if (Hint.first == 0)
124    return (TargetRegisterInfo::isPhysicalRegister(physReg))
125      ? physReg : 0;
126  return TRI->ResolveRegAllocHint(Hint.first, physReg, *MF);
127}
128
129int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
130  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
131  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
132         "attempt to assign stack slot to already spilled register");
133  const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
134  return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
135}
136
137void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
138  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
139  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
140         "attempt to assign stack slot to already spilled register");
141  assert((SS >= 0 ||
142          (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
143         "illegal fixed frame index");
144  Virt2StackSlotMap[virtReg] = SS;
145}
146
147int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
148  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
149  assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
150         "attempt to assign re-mat id to already spilled register");
151  Virt2ReMatIdMap[virtReg] = ReMatId;
152  return ReMatId++;
153}
154
155void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
156  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
157  assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
158         "attempt to assign re-mat id to already spilled register");
159  Virt2ReMatIdMap[virtReg] = id;
160}
161
162int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) {
163  std::map<const TargetRegisterClass*, int>::iterator I =
164    EmergencySpillSlots.find(RC);
165  if (I != EmergencySpillSlots.end())
166    return I->second;
167  return EmergencySpillSlots[RC] = createSpillSlot(RC);
168}
169
170void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) {
171  if (!MF->getFrameInfo()->isFixedObjectIndex(FI)) {
172    // If FI < LowSpillSlot, this stack reference was produced by
173    // instruction selection and is not a spill
174    if (FI >= LowSpillSlot) {
175      assert(FI >= 0 && "Spill slot index should not be negative!");
176      assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
177             && "Invalid spill slot");
178      SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI);
179    }
180  }
181}
182
183void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
184                            MachineInstr *NewMI, ModRef MRInfo) {
185  // Move previous memory references folded to new instruction.
186  MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
187  for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
188         E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
189    MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
190    MI2VirtMap.erase(I++);
191  }
192
193  // add new memory reference
194  MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
195}
196
197void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
198  MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
199  MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
200}
201
202void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) {
203  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
204    MachineOperand &MO = MI->getOperand(i);
205    if (!MO.isFI())
206      continue;
207    int FI = MO.getIndex();
208    if (MF->getFrameInfo()->isFixedObjectIndex(FI))
209      continue;
210    // This stack reference was produced by instruction selection and
211    // is not a spill
212    if (FI < LowSpillSlot)
213      continue;
214    assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
215           && "Invalid spill slot");
216    SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI);
217  }
218  MI2VirtMap.erase(MI);
219  SpillPt2VirtMap.erase(MI);
220  RestorePt2VirtMap.erase(MI);
221  EmergencySpillMap.erase(MI);
222}
223
224/// FindUnusedRegisters - Gather a list of allocatable registers that
225/// have not been allocated to any virtual register.
226bool VirtRegMap::FindUnusedRegisters(LiveIntervals* LIs) {
227  unsigned NumRegs = TRI->getNumRegs();
228  UnusedRegs.reset();
229  UnusedRegs.resize(NumRegs);
230
231  BitVector Used(NumRegs);
232  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
233    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
234    if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG)
235      Used.set(Virt2PhysMap[Reg]);
236  }
237
238  BitVector Allocatable = TRI->getAllocatableSet(*MF);
239  bool AnyUnused = false;
240  for (unsigned Reg = 1; Reg < NumRegs; ++Reg) {
241    if (Allocatable[Reg] && !Used[Reg] && !LIs->hasInterval(Reg)) {
242      bool ReallyUnused = true;
243      for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
244        if (Used[*AS] || LIs->hasInterval(*AS)) {
245          ReallyUnused = false;
246          break;
247        }
248      }
249      if (ReallyUnused) {
250        AnyUnused = true;
251        UnusedRegs.set(Reg);
252      }
253    }
254  }
255
256  return AnyUnused;
257}
258
259void VirtRegMap::rewrite(SlotIndexes *Indexes) {
260  DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
261               << "********** Function: "
262               << MF->getFunction()->getName() << '\n');
263  DEBUG(dump());
264  SmallVector<unsigned, 8> SuperDeads;
265  SmallVector<unsigned, 8> SuperDefs;
266  SmallVector<unsigned, 8> SuperKills;
267
268  for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
269       MBBI != MBBE; ++MBBI) {
270    DEBUG(MBBI->print(dbgs(), Indexes));
271    for (MachineBasicBlock::iterator MII = MBBI->begin(), MIE = MBBI->end();
272         MII != MIE;) {
273      MachineInstr *MI = MII;
274      ++MII;
275
276      for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
277           MOE = MI->operands_end(); MOI != MOE; ++MOI) {
278        MachineOperand &MO = *MOI;
279        if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
280          continue;
281        unsigned VirtReg = MO.getReg();
282        unsigned PhysReg = getPhys(VirtReg);
283        assert(PhysReg != NO_PHYS_REG && "Instruction uses unmapped VirtReg");
284
285        // Preserve semantics of sub-register operands.
286        if (MO.getSubReg()) {
287          // A virtual register kill refers to the whole register, so we may
288          // have to add <imp-use,kill> operands for the super-register.  A
289          // partial redef always kills and redefines the super-register.
290          if (MO.readsReg() && (MO.isDef() || MO.isKill()))
291            SuperKills.push_back(PhysReg);
292
293          if (MO.isDef()) {
294            // The <def,undef> flag only makes sense for sub-register defs, and
295            // we are substituting a full physreg.  An <imp-use,kill> operand
296            // from the SuperKills list will represent the partial read of the
297            // super-register.
298            MO.setIsUndef(false);
299
300            // Also add implicit defs for the super-register.
301            if (MO.isDead())
302              SuperDeads.push_back(PhysReg);
303            else
304              SuperDefs.push_back(PhysReg);
305          }
306
307          // PhysReg operands cannot have subregister indexes.
308          PhysReg = TRI->getSubReg(PhysReg, MO.getSubReg());
309          assert(PhysReg && "Invalid SubReg for physical register");
310          MO.setSubReg(0);
311        }
312        // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
313        // we need the inlining here.
314        MO.setReg(PhysReg);
315      }
316
317      // Add any missing super-register kills after rewriting the whole
318      // instruction.
319      while (!SuperKills.empty())
320        MI->addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
321
322      while (!SuperDeads.empty())
323        MI->addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
324
325      while (!SuperDefs.empty())
326        MI->addRegisterDefined(SuperDefs.pop_back_val(), TRI);
327
328      DEBUG(dbgs() << "> " << *MI);
329
330      // Finally, remove any identity copies.
331      if (MI->isIdentityCopy()) {
332        ++NumIdCopies;
333        if (MI->getNumOperands() == 2) {
334          DEBUG(dbgs() << "Deleting identity copy.\n");
335          RemoveMachineInstrFromMaps(MI);
336          if (Indexes)
337            Indexes->removeMachineInstrFromMaps(MI);
338          // It's safe to erase MI because MII has already been incremented.
339          MI->eraseFromParent();
340        } else {
341          // Transform identity copy to a KILL to deal with subregisters.
342          MI->setDesc(TII->get(TargetOpcode::KILL));
343          DEBUG(dbgs() << "Identity copy: " << *MI);
344        }
345      }
346    }
347  }
348
349  // Tell MRI about physical registers in use.
350  for (unsigned Reg = 1, RegE = TRI->getNumRegs(); Reg != RegE; ++Reg)
351    if (!MRI->reg_nodbg_empty(Reg))
352      MRI->setPhysRegUsed(Reg);
353}
354
355void VirtRegMap::print(raw_ostream &OS, const Module* M) const {
356  const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
357  const MachineRegisterInfo &MRI = MF->getRegInfo();
358
359  OS << "********** REGISTER MAP **********\n";
360  for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
361    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
362    if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
363      OS << '[' << PrintReg(Reg, TRI) << " -> "
364         << PrintReg(Virt2PhysMap[Reg], TRI) << "] "
365         << MRI.getRegClass(Reg)->getName() << "\n";
366    }
367  }
368
369  for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
370    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
371    if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
372      OS << '[' << PrintReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
373         << "] " << MRI.getRegClass(Reg)->getName() << "\n";
374    }
375  }
376  OS << '\n';
377}
378
379void VirtRegMap::dump() const {
380  print(dbgs());
381}
382