MachineInstr.cpp revision 561c0107b20e9be4a02bad57a68ae9e4f96461a9
1//===-- MachineInstr.cpp --------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Methods common to all machine instructions.
11//
12// FIXME: Now that MachineInstrs have parent pointers, they should always
13// print themselves using their MachineFunction's TargetMachine.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/Value.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/MRegisterInfo.h"
23#include "Support/LeakDetector.h"
24using namespace llvm;
25
26// Global variable holding an array of descriptors for machine instructions.
27// The actual object needs to be created separately for each target machine.
28// This variable is initialized and reset by class TargetInstrInfo.
29//
30// FIXME: This should be a property of the target so that more than one target
31// at a time can be active...
32//
33namespace llvm {
34  extern const TargetInstrDescriptor *TargetInstrDescriptors;
35}
36
37// Constructor for instructions with variable #operands
38MachineInstr::MachineInstr(short opcode, unsigned numOperands)
39  : Opcode(opcode),
40    numImplicitRefs(0),
41    operands(numOperands, MachineOperand()),
42    parent(0) {
43  // Make sure that we get added to a machine basicblock
44  LeakDetector::addGarbageObject(this);
45}
46
47/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
48/// not a resize for them.  It is expected that if you use this that you call
49/// add* methods below to fill up the operands, instead of the Set methods.
50/// Eventually, the "resizing" ctors will be phased out.
51///
52MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
53  : Opcode(opcode), numImplicitRefs(0), parent(0) {
54  operands.reserve(numOperands);
55  // Make sure that we get added to a machine basicblock
56  LeakDetector::addGarbageObject(this);
57}
58
59/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
60/// MachineInstr is created and added to the end of the specified basic block.
61///
62MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
63                           unsigned numOperands)
64  : Opcode(opcode), numImplicitRefs(0), parent(0) {
65  assert(MBB && "Cannot use inserting ctor with null basic block!");
66  operands.reserve(numOperands);
67  // Make sure that we get added to a machine basicblock
68  LeakDetector::addGarbageObject(this);
69  MBB->push_back(this);  // Add instruction to end of basic block!
70}
71
72MachineInstr::~MachineInstr()
73{
74  LeakDetector::removeGarbageObject(this);
75}
76
77/// OperandComplete - Return true if it's illegal to add a new operand
78///
79bool MachineInstr::OperandsComplete() const {
80  int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
81  if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
82    return true;  // Broken: we have all the operands of this instruction!
83  return false;
84}
85
86/// replace - Support for replacing opcode and operands of a MachineInstr in
87/// place. This only resets the size of the operand vector and initializes it.
88/// The new operands must be set explicitly later.
89///
90void MachineInstr::replace(short opcode, unsigned numOperands) {
91  assert(getNumImplicitRefs() == 0 &&
92         "This is probably broken because implicit refs are going to be lost.");
93  Opcode = opcode;
94  operands.clear();
95  operands.resize(numOperands, MachineOperand());
96}
97
98void MachineInstr::SetMachineOperandVal(unsigned i,
99                                        MachineOperand::MachineOperandType opTy,
100                                        Value* V) {
101  assert(i < operands.size());          // may be explicit or implicit op
102  operands[i].opType = opTy;
103  operands[i].value = V;
104  operands[i].regNum = -1;
105}
106
107void
108MachineInstr::SetMachineOperandConst(unsigned i,
109                                     MachineOperand::MachineOperandType opTy,
110                                     int intValue) {
111  assert(i < getNumOperands());          // must be explicit op
112  assert(TargetInstrDescriptors[Opcode].resultPos != (int) i &&
113         "immed. constant cannot be defined");
114
115  operands[i].opType = opTy;
116  operands[i].value = NULL;
117  operands[i].immedVal = intValue;
118  operands[i].regNum = -1;
119  operands[i].flags = 0;
120}
121
122void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) {
123  assert(i < getNumOperands());          // must be explicit op
124
125  operands[i].opType = MachineOperand::MO_MachineRegister;
126  operands[i].value = NULL;
127  operands[i].regNum = regNum;
128}
129
130// Used only by the SPARC back-end.
131void MachineInstr::SetRegForOperand(unsigned i, int regNum) {
132  assert(i < getNumOperands());          // must be explicit op
133  operands[i].setRegForValue(regNum);
134}
135
136// Used only by the SPARC back-end.
137void MachineInstr::SetRegForImplicitRef(unsigned i, int regNum) {
138  getImplicitOp(i).setRegForValue(regNum);
139}
140
141/// substituteValue - Substitute all occurrences of Value* oldVal with newVal
142/// in all operands and all implicit refs. If defsOnly == true, substitute defs
143/// only.
144///
145/// FIXME: Fold this into its single caller, at SparcInstrSelection.cpp:2865,
146/// or make it a static function in that file.
147///
148unsigned
149MachineInstr::substituteValue(const Value* oldVal, Value* newVal,
150                              bool defsOnly, bool notDefsAndUses,
151                              bool& someArgsWereIgnored)
152{
153  assert((!defsOnly || !notDefsAndUses) &&
154         "notDefsAndUses is irrelevant if defsOnly == true.");
155
156  unsigned numSubst = 0;
157
158  // Substitute operands
159  for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
160    if (*O == oldVal)
161      if (!defsOnly ||
162          notDefsAndUses && (O.isDef() && !O.isUse()) ||
163          !notDefsAndUses && O.isDef())
164        {
165          O.getMachineOperand().value = newVal;
166          ++numSubst;
167        }
168      else
169        someArgsWereIgnored = true;
170
171  // Substitute implicit refs
172  for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i)
173    if (getImplicitRef(i) == oldVal)
174      if (!defsOnly ||
175          notDefsAndUses && (getImplicitOp(i).isDef() && !getImplicitOp(i).isUse()) ||
176          !notDefsAndUses && getImplicitOp(i).isDef())
177        {
178          getImplicitOp(i).value = newVal;
179          ++numSubst;
180        }
181      else
182        someArgsWereIgnored = true;
183
184  return numSubst;
185}
186
187void MachineInstr::dump() const {
188  std::cerr << "  " << *this;
189}
190
191static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
192  os << "(val ";
193  os << (void*) val;                    // print address always
194  if (val && val->hasName())
195    os << " " << val->getName(); // print name also, if available
196  os << ")";
197  return os;
198}
199
200static inline void OutputReg(std::ostream &os, unsigned RegNo,
201                             const MRegisterInfo *MRI = 0) {
202  if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
203    if (MRI)
204      os << "%" << MRI->get(RegNo).Name;
205    else
206      os << "%mreg(" << RegNo << ")";
207  } else
208    os << "%reg" << RegNo;
209}
210
211static void print(const MachineOperand &MO, std::ostream &OS,
212                  const TargetMachine &TM) {
213  const MRegisterInfo *MRI = TM.getRegisterInfo();
214  bool CloseParen = true;
215  if (MO.isHiBits32())
216    OS << "%lm(";
217  else if (MO.isLoBits32())
218    OS << "%lo(";
219  else if (MO.isHiBits64())
220    OS << "%hh(";
221  else if (MO.isLoBits64())
222    OS << "%hm(";
223  else
224    CloseParen = false;
225
226  switch (MO.getType()) {
227  case MachineOperand::MO_VirtualRegister:
228    if (MO.getVRegValue()) {
229      OS << "%reg";
230      OutputValue(OS, MO.getVRegValue());
231      if (MO.hasAllocatedReg())
232        OS << "==";
233    }
234    if (MO.hasAllocatedReg())
235      OutputReg(OS, MO.getReg(), MRI);
236    break;
237  case MachineOperand::MO_CCRegister:
238    OS << "%ccreg";
239    OutputValue(OS, MO.getVRegValue());
240    if (MO.hasAllocatedReg()) {
241      OS << "==";
242      OutputReg(OS, MO.getReg(), MRI);
243    }
244    break;
245  case MachineOperand::MO_MachineRegister:
246    OutputReg(OS, MO.getMachineRegNum(), MRI);
247    break;
248  case MachineOperand::MO_SignExtendedImmed:
249    OS << (long)MO.getImmedValue();
250    break;
251  case MachineOperand::MO_UnextendedImmed:
252    OS << (long)MO.getImmedValue();
253    break;
254  case MachineOperand::MO_PCRelativeDisp: {
255    const Value* opVal = MO.getVRegValue();
256    bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
257    OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
258    if (opVal->hasName())
259      OS << opVal->getName();
260    else
261      OS << (const void*) opVal;
262    OS << ")";
263    break;
264  }
265  case MachineOperand::MO_MachineBasicBlock:
266    OS << "bb<"
267       << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
268       << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">";
269    break;
270  case MachineOperand::MO_FrameIndex:
271    OS << "<fi#" << MO.getFrameIndex() << ">";
272    break;
273  case MachineOperand::MO_ConstantPoolIndex:
274    OS << "<cp#" << MO.getConstantPoolIndex() << ">";
275    break;
276  case MachineOperand::MO_GlobalAddress:
277    OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
278    break;
279  case MachineOperand::MO_ExternalSymbol:
280    OS << "<es:" << MO.getSymbolName() << ">";
281    break;
282  default:
283    assert(0 && "Unrecognized operand type");
284  }
285
286  if (CloseParen)
287    OS << ")";
288}
289
290void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) const {
291  unsigned StartOp = 0;
292
293   // Specialize printing if op#0 is definition
294  if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
295    ::print(getOperand(0), OS, TM);
296    OS << " = ";
297    ++StartOp;   // Don't print this operand again!
298  }
299  OS << TM.getInstrInfo().getName(getOpcode());
300
301  for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
302    const MachineOperand& mop = getOperand(i);
303    if (i != StartOp)
304      OS << ",";
305    OS << " ";
306    ::print(mop, OS, TM);
307
308    if (mop.isDef())
309      if (mop.isUse())
310        OS << "<def&use>";
311      else
312        OS << "<def>";
313  }
314
315  // code for printing implicit references
316  if (getNumImplicitRefs()) {
317    OS << "\tImplicitRefs: ";
318    for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) {
319      OS << "\t";
320      OutputValue(OS, getImplicitRef(i));
321      if (getImplicitOp(i).isDef())
322          if (getImplicitOp(i).isUse())
323            OS << "<def&use>";
324          else
325            OS << "<def>";
326    }
327  }
328
329  OS << "\n";
330}
331
332namespace llvm {
333std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
334  // If the instruction is embedded into a basic block, we can find the target
335  // info for the instruction.
336  if (const MachineBasicBlock *MBB = MI.getParent()) {
337    const MachineFunction *MF = MBB->getParent();
338    MI.print(os, MF->getTarget());
339    return os;
340  }
341
342  // Otherwise, print it out in the "raw" format without symbolic register names
343  // and such.
344  os << TargetInstrDescriptors[MI.getOpcode()].Name;
345
346  for (unsigned i=0, N=MI.getNumOperands(); i < N; i++) {
347    os << "\t" << MI.getOperand(i);
348    if (MI.getOperand(i).isDef())
349      if (MI.getOperand(i).isUse())
350        os << "<d&u>";
351      else
352        os << "<d>";
353  }
354
355  // code for printing implicit references
356  unsigned NumOfImpRefs = MI.getNumImplicitRefs();
357  if (NumOfImpRefs > 0) {
358    os << "\tImplicit: ";
359    for (unsigned z=0; z < NumOfImpRefs; z++) {
360      OutputValue(os, MI.getImplicitRef(z));
361      if (MI.getImplicitOp(z).isDef())
362          if (MI.getImplicitOp(z).isUse())
363            os << "<d&u>";
364          else
365            os << "<d>";
366      os << "\t";
367    }
368  }
369
370  return os << "\n";
371}
372
373std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
374  if (MO.isHiBits32())
375    OS << "%lm(";
376  else if (MO.isLoBits32())
377    OS << "%lo(";
378  else if (MO.isHiBits64())
379    OS << "%hh(";
380  else if (MO.isLoBits64())
381    OS << "%hm(";
382
383  switch (MO.getType())
384    {
385    case MachineOperand::MO_VirtualRegister:
386      if (MO.hasAllocatedReg())
387        OutputReg(OS, MO.getReg());
388
389      if (MO.getVRegValue()) {
390	if (MO.hasAllocatedReg()) OS << "==";
391	OS << "%vreg";
392	OutputValue(OS, MO.getVRegValue());
393      }
394      break;
395    case MachineOperand::MO_CCRegister:
396      OS << "%ccreg";
397      OutputValue(OS, MO.getVRegValue());
398      if (MO.hasAllocatedReg()) {
399        OS << "==";
400        OutputReg(OS, MO.getReg());
401      }
402      break;
403    case MachineOperand::MO_MachineRegister:
404      OutputReg(OS, MO.getMachineRegNum());
405      break;
406    case MachineOperand::MO_SignExtendedImmed:
407      OS << (long)MO.getImmedValue();
408      break;
409    case MachineOperand::MO_UnextendedImmed:
410      OS << (long)MO.getImmedValue();
411      break;
412    case MachineOperand::MO_PCRelativeDisp:
413      {
414        const Value* opVal = MO.getVRegValue();
415        bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
416        OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
417        if (opVal->hasName())
418          OS << opVal->getName();
419        else
420          OS << (const void*) opVal;
421        OS << ")";
422        break;
423      }
424    case MachineOperand::MO_MachineBasicBlock:
425      OS << "bb<"
426         << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
427         << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">";
428      break;
429    case MachineOperand::MO_FrameIndex:
430      OS << "<fi#" << MO.getFrameIndex() << ">";
431      break;
432    case MachineOperand::MO_ConstantPoolIndex:
433      OS << "<cp#" << MO.getConstantPoolIndex() << ">";
434      break;
435    case MachineOperand::MO_GlobalAddress:
436      OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
437      break;
438    case MachineOperand::MO_ExternalSymbol:
439      OS << "<es:" << MO.getSymbolName() << ">";
440      break;
441    default:
442      assert(0 && "Unrecognized operand type");
443      break;
444    }
445
446  if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
447    OS << ")";
448
449  return OS;
450}
451
452}
453