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