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