Be a bit more efficient when processing the active and inactive
[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 #include <iostream>
25
26 using namespace llvm;
27
28 // Global variable holding an array of descriptors for machine instructions.
29 // The actual object needs to be created separately for each target machine.
30 // This variable is initialized and reset by class TargetInstrInfo.
31 // 
32 // FIXME: This should be a property of the target so that more than one target
33 // at a time can be active...
34 //
35 namespace llvm {
36   extern const TargetInstrDescriptor *TargetInstrDescriptors;
37 }
38
39 // Constructor for instructions with variable #operands
40 MachineInstr::MachineInstr(short opcode, unsigned numOperands)
41   : Opcode(opcode),
42     numImplicitRefs(0),
43     operands(numOperands, MachineOperand()),
44     parent(0) {
45   // Make sure that we get added to a machine basicblock
46   LeakDetector::addGarbageObject(this);
47 }
48
49 /// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
50 /// not a resize for them.  It is expected that if you use this that you call
51 /// add* methods below to fill up the operands, instead of the Set methods.
52 /// Eventually, the "resizing" ctors will be phased out.
53 ///
54 MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY)
55   : Opcode(opcode), numImplicitRefs(0), parent(0) {
56   operands.reserve(numOperands);
57   // Make sure that we get added to a machine basicblock
58   LeakDetector::addGarbageObject(this);
59 }
60
61 /// MachineInstr ctor - Work exactly the same as the ctor above, except that the
62 /// MachineInstr is created and added to the end of the specified basic block.
63 ///
64 MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode,
65                            unsigned numOperands)
66   : Opcode(opcode), numImplicitRefs(0), parent(0) {
67   assert(MBB && "Cannot use inserting ctor with null basic block!");
68   operands.reserve(numOperands);
69   // Make sure that we get added to a machine basicblock
70   LeakDetector::addGarbageObject(this);
71   MBB->push_back(this);  // Add instruction to end of basic block!
72 }
73
74 /// MachineInstr ctor - Copies MachineInstr arg exactly
75 ///
76 MachineInstr::MachineInstr(const MachineInstr &MI) {
77   Opcode = MI.getOpcode();
78   numImplicitRefs = MI.getNumImplicitRefs();
79   operands.reserve(MI.getNumOperands());
80
81   // Add operands
82   for (unsigned i = 0; i < MI.getNumOperands(); ++i)
83     operands.push_back(MachineOperand(MI.getOperand(i)));
84
85   // Set parent, next, and prev to null
86   parent = 0;
87   prev = 0;
88   next = 0;
89 }
90
91
92 MachineInstr::~MachineInstr() {
93   LeakDetector::removeGarbageObject(this);
94 }
95
96 /// clone - Create a copy of 'this' instruction that is identical in all ways
97 /// except the following: the new instruction has no parent and it has no name
98 ///
99 MachineInstr* MachineInstr::clone() const {
100   return new MachineInstr(*this);
101 }
102
103 /// OperandComplete - Return true if it's illegal to add a new operand
104 ///
105 bool MachineInstr::OperandsComplete() const {
106   int NumOperands = TargetInstrDescriptors[Opcode].numOperands;
107   if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
108     return true;  // Broken: we have all the operands of this instruction!
109   return false;
110 }
111
112 /// replace - Support for replacing opcode and operands of a MachineInstr in
113 /// place. This only resets the size of the operand vector and initializes it.
114 /// The new operands must be set explicitly later.
115 /// 
116 void MachineInstr::replace(short opcode, unsigned numOperands) {
117   assert(getNumImplicitRefs() == 0 &&
118          "This is probably broken because implicit refs are going to be lost.");
119   Opcode = opcode;
120   operands.clear();
121   operands.resize(numOperands, MachineOperand());
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       } else
194         someArgsWereIgnored = true;
195
196   // Substitute implicit refs
197   for (unsigned i = 0, N = getNumImplicitRefs(); i < N; ++i)
198     if (getImplicitRef(i) == oldVal) {
199       MachineOperand Op = getImplicitOp(i);
200       if (!defsOnly ||
201           notDefsAndUses && (Op.isDef() && !Op.isUse()) ||
202           !notDefsAndUses && Op.isDef())
203       {
204         Op.contents.value = newVal;
205         ++numSubst;
206       } else
207         someArgsWereIgnored = true;
208     }
209   return numSubst;
210 }
211
212 void MachineInstr::dump() const {
213   std::cerr << "  " << *this;
214 }
215
216 static inline std::ostream& OutputValue(std::ostream &os, const Value* val) {
217   os << "(val ";
218   os << (void*) val;                // print address always
219   if (val && val->hasName())
220     os << " " << val->getName();    // print name also, if available
221   os << ")";
222   return os;
223 }
224
225 static inline void OutputReg(std::ostream &os, unsigned RegNo,
226                              const MRegisterInfo *MRI = 0) {
227   if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) {
228     if (MRI)
229       os << "%" << MRI->get(RegNo).Name;
230     else
231       os << "%mreg(" << RegNo << ")";
232   } else
233     os << "%reg" << RegNo;
234 }
235
236 static void print(const MachineOperand &MO, std::ostream &OS,
237                   const TargetMachine *TM) {
238   const MRegisterInfo *MRI = 0;
239   
240   if (TM) MRI = TM->getRegisterInfo();
241
242   bool CloseParen = true;
243   if (MO.isHiBits32())
244     OS << "%lm(";
245   else if (MO.isLoBits32())
246     OS << "%lo(";
247   else if (MO.isHiBits64())
248     OS << "%hh(";
249   else if (MO.isLoBits64())
250     OS << "%hm(";
251   else
252     CloseParen = false;
253   
254   switch (MO.getType()) {
255   case MachineOperand::MO_VirtualRegister:
256     if (MO.getVRegValue()) {
257       OS << "%reg";
258       OutputValue(OS, MO.getVRegValue());
259       if (MO.hasAllocatedReg())
260         OS << "==";
261     }
262     if (MO.hasAllocatedReg())
263       OutputReg(OS, MO.getReg(), MRI);
264     break;
265   case MachineOperand::MO_CCRegister:
266     OS << "%ccreg";
267     OutputValue(OS, MO.getVRegValue());
268     if (MO.hasAllocatedReg()) {
269       OS << "==";
270       OutputReg(OS, MO.getReg(), MRI);
271     }
272     break;
273   case MachineOperand::MO_MachineRegister:
274     OutputReg(OS, MO.getMachineRegNum(), MRI);
275     break;
276   case MachineOperand::MO_SignExtendedImmed:
277     OS << (long)MO.getImmedValue();
278     break;
279   case MachineOperand::MO_UnextendedImmed:
280     OS << (long)MO.getImmedValue();
281     break;
282   case MachineOperand::MO_PCRelativeDisp: {
283     const Value* opVal = MO.getVRegValue();
284     bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
285     OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
286     if (opVal->hasName())
287       OS << opVal->getName();
288     else
289       OS << (const void*) opVal;
290     OS << ")";
291     break;
292   }
293   case MachineOperand::MO_MachineBasicBlock:
294     OS << "mbb<"
295        << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
296        << "," << (void*)MO.getMachineBasicBlock() << ">";
297     break;
298   case MachineOperand::MO_FrameIndex:
299     OS << "<fi#" << MO.getFrameIndex() << ">";
300     break;
301   case MachineOperand::MO_ConstantPoolIndex:
302     OS << "<cp#" << MO.getConstantPoolIndex() << ">";
303     break;
304   case MachineOperand::MO_GlobalAddress:
305     OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
306     break;
307   case MachineOperand::MO_ExternalSymbol:
308     OS << "<es:" << MO.getSymbolName() << ">";
309     break;
310   default:
311     assert(0 && "Unrecognized operand type");
312   }
313
314   if (CloseParen)
315     OS << ")";
316 }
317
318 void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
319   unsigned StartOp = 0;
320
321    // Specialize printing if op#0 is definition
322   if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) {
323     ::print(getOperand(0), OS, TM);
324     OS << " = ";
325     ++StartOp;   // Don't print this operand again!
326   }
327
328   // Must check if Target machine is not null because machine BB could not
329   // be attached to a Machine function yet
330   if (TM)
331     OS << TM->getInstrInfo()->getName(getOpcode());
332   
333   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
334     const MachineOperand& mop = getOperand(i);
335     if (i != StartOp)
336       OS << ",";
337     OS << " ";
338     ::print(mop, OS, TM);
339     
340     if (mop.isDef())
341       if (mop.isUse())
342         OS << "<def&use>";
343       else
344         OS << "<def>";
345   }
346     
347   // code for printing implicit references
348   if (getNumImplicitRefs()) {
349     OS << "\tImplicitRefs: ";
350     for (unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) {
351       OS << "\t";
352       OutputValue(OS, getImplicitRef(i));
353       if (getImplicitOp(i).isDef())
354         if (getImplicitOp(i).isUse())
355           OS << "<def&use>";
356         else
357           OS << "<def>";
358     }
359   }
360   
361   OS << "\n";
362 }
363
364 namespace llvm {
365 std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) {
366   // If the instruction is embedded into a basic block, we can find the target
367   // info for the instruction.
368   if (const MachineBasicBlock *MBB = MI.getParent()) {
369     const MachineFunction *MF = MBB->getParent();
370     if (MF)
371       MI.print(os, &MF->getTarget());
372     else
373       MI.print(os, 0);
374     return os;
375   }
376
377   // Otherwise, print it out in the "raw" format without symbolic register names
378   // and such.
379   os << TargetInstrDescriptors[MI.getOpcode()].Name;
380   
381   for (unsigned i = 0, N = MI.getNumOperands(); i < N; i++) {
382     os << "\t" << MI.getOperand(i);
383     if (MI.getOperand(i).isDef())
384       if (MI.getOperand(i).isUse())
385         os << "<d&u>";
386       else
387         os << "<d>";
388   }
389   
390   // code for printing implicit references
391   unsigned NumOfImpRefs = MI.getNumImplicitRefs();
392   if (NumOfImpRefs > 0) {
393     os << "\tImplicit: ";
394     for (unsigned z = 0; z < NumOfImpRefs; z++) {
395       OutputValue(os, MI.getImplicitRef(z)); 
396       if (MI.getImplicitOp(z).isDef())
397           if (MI.getImplicitOp(z).isUse())
398             os << "<d&u>";
399           else
400             os << "<d>";
401       os << "\t";
402     }
403   }
404   
405   return os << "\n";
406 }
407
408 std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) {
409   if (MO.isHiBits32())
410     OS << "%lm(";
411   else if (MO.isLoBits32())
412     OS << "%lo(";
413   else if (MO.isHiBits64())
414     OS << "%hh(";
415   else if (MO.isLoBits64())
416     OS << "%hm(";
417   
418   switch (MO.getType()) {
419   case MachineOperand::MO_VirtualRegister:
420     if (MO.hasAllocatedReg())
421       OutputReg(OS, MO.getReg());
422
423     if (MO.getVRegValue()) {
424       if (MO.hasAllocatedReg()) OS << "==";
425       OS << "%vreg";
426       OutputValue(OS, MO.getVRegValue());
427     }
428     break;
429   case MachineOperand::MO_CCRegister:
430     OS << "%ccreg";
431     OutputValue(OS, MO.getVRegValue());
432     if (MO.hasAllocatedReg()) {
433       OS << "==";
434       OutputReg(OS, MO.getReg());
435     }
436     break;
437   case MachineOperand::MO_MachineRegister:
438     OutputReg(OS, MO.getMachineRegNum());
439     break;
440   case MachineOperand::MO_SignExtendedImmed:
441     OS << (long)MO.getImmedValue();
442     break;
443   case MachineOperand::MO_UnextendedImmed:
444     OS << (long)MO.getImmedValue();
445     break;
446   case MachineOperand::MO_PCRelativeDisp: {
447     const Value* opVal = MO.getVRegValue();
448     bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
449     OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
450     if (opVal->hasName())
451       OS << opVal->getName();
452     else
453       OS << (const void*) opVal;
454     OS << ")";
455     break;
456   }
457   case MachineOperand::MO_MachineBasicBlock:
458     OS << "<mbb:"
459        << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName()
460        << "@" << (void*)MO.getMachineBasicBlock() << ">";
461     break;
462   case MachineOperand::MO_FrameIndex:
463     OS << "<fi#" << MO.getFrameIndex() << ">";
464     break;
465   case MachineOperand::MO_ConstantPoolIndex:
466     OS << "<cp#" << MO.getConstantPoolIndex() << ">";
467     break;
468   case MachineOperand::MO_GlobalAddress:
469     OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">";
470     break;
471   case MachineOperand::MO_ExternalSymbol:
472     OS << "<es:" << MO.getSymbolName() << ">";
473     break;
474   default:
475     assert(0 && "Unrecognized operand type");
476     break;
477   }
478   
479   if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64())
480     OS << ")";
481   
482   return OS;
483 }
484
485 }