c6f3e319f2f6df22a2fc60da1345ca093971e34c
[oota-llvm.git] / lib / CodeGen / MachineInstr.cpp
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
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 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Constants.h"
16 #include "llvm/InlineAsm.h"
17 #include "llvm/Value.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetInstrDesc.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Streams.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/FoldingSet.h"
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // MachineOperand Implementation
36 //===----------------------------------------------------------------------===//
37
38 /// AddRegOperandToRegInfo - Add this register operand to the specified
39 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
40 /// explicitly nulled out.
41 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
42   assert(isReg() && "Can only add reg operand to use lists");
43   
44   // If the reginfo pointer is null, just explicitly null out or next/prev
45   // pointers, to ensure they are not garbage.
46   if (RegInfo == 0) {
47     Contents.Reg.Prev = 0;
48     Contents.Reg.Next = 0;
49     return;
50   }
51   
52   // Otherwise, add this operand to the head of the registers use/def list.
53   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
54   
55   // For SSA values, we prefer to keep the definition at the start of the list.
56   // we do this by skipping over the definition if it is at the head of the
57   // list.
58   if (*Head && (*Head)->isDef())
59     Head = &(*Head)->Contents.Reg.Next;
60   
61   Contents.Reg.Next = *Head;
62   if (Contents.Reg.Next) {
63     assert(getReg() == Contents.Reg.Next->getReg() &&
64            "Different regs on the same list!");
65     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
66   }
67   
68   Contents.Reg.Prev = Head;
69   *Head = this;
70 }
71
72 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
73 /// MachineRegisterInfo it is linked with.
74 void MachineOperand::RemoveRegOperandFromRegInfo() {
75   assert(isOnRegUseList() && "Reg operand is not on a use list");
76   // Unlink this from the doubly linked list of operands.
77   MachineOperand *NextOp = Contents.Reg.Next;
78   *Contents.Reg.Prev = NextOp; 
79   if (NextOp) {
80     assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
81     NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
82   }
83   Contents.Reg.Prev = 0;
84   Contents.Reg.Next = 0;
85 }
86
87 void MachineOperand::setReg(unsigned Reg) {
88   if (getReg() == Reg) return; // No change.
89   
90   // Otherwise, we have to change the register.  If this operand is embedded
91   // into a machine function, we need to update the old and new register's
92   // use/def lists.
93   if (MachineInstr *MI = getParent())
94     if (MachineBasicBlock *MBB = MI->getParent())
95       if (MachineFunction *MF = MBB->getParent()) {
96         RemoveRegOperandFromRegInfo();
97         Contents.Reg.RegNo = Reg;
98         AddRegOperandToRegInfo(&MF->getRegInfo());
99         return;
100       }
101         
102   // Otherwise, just change the register, no problem.  :)
103   Contents.Reg.RegNo = Reg;
104 }
105
106 /// ChangeToImmediate - Replace this operand with a new immediate operand of
107 /// the specified value.  If an operand is known to be an immediate already,
108 /// the setImm method should be used.
109 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
110   // If this operand is currently a register operand, and if this is in a
111   // function, deregister the operand from the register's use/def list.
112   if (isReg() && getParent() && getParent()->getParent() &&
113       getParent()->getParent()->getParent())
114     RemoveRegOperandFromRegInfo();
115   
116   OpKind = MO_Immediate;
117   Contents.ImmVal = ImmVal;
118 }
119
120 /// ChangeToRegister - Replace this operand with a new register operand of
121 /// the specified value.  If an operand is known to be an register already,
122 /// the setReg method should be used.
123 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
124                                       bool isKill, bool isDead, bool isUndef) {
125   // If this operand is already a register operand, use setReg to update the 
126   // register's use/def lists.
127   if (isReg()) {
128     assert(!isEarlyClobber());
129     setReg(Reg);
130   } else {
131     // Otherwise, change this to a register and set the reg#.
132     OpKind = MO_Register;
133     Contents.Reg.RegNo = Reg;
134
135     // If this operand is embedded in a function, add the operand to the
136     // register's use/def list.
137     if (MachineInstr *MI = getParent())
138       if (MachineBasicBlock *MBB = MI->getParent())
139         if (MachineFunction *MF = MBB->getParent())
140           AddRegOperandToRegInfo(&MF->getRegInfo());
141   }
142
143   IsDef = isDef;
144   IsImp = isImp;
145   IsKill = isKill;
146   IsDead = isDead;
147   IsUndef = isUndef;
148   IsEarlyClobber = false;
149   SubReg = 0;
150 }
151
152 /// isIdenticalTo - Return true if this operand is identical to the specified
153 /// operand.
154 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
155   if (getType() != Other.getType() ||
156       getTargetFlags() != Other.getTargetFlags())
157     return false;
158   
159   switch (getType()) {
160   default: llvm_unreachable("Unrecognized operand type");
161   case MachineOperand::MO_Register:
162     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
163            getSubReg() == Other.getSubReg();
164   case MachineOperand::MO_Immediate:
165     return getImm() == Other.getImm();
166   case MachineOperand::MO_FPImmediate:
167     return getFPImm() == Other.getFPImm();
168   case MachineOperand::MO_MachineBasicBlock:
169     return getMBB() == Other.getMBB();
170   case MachineOperand::MO_FrameIndex:
171     return getIndex() == Other.getIndex();
172   case MachineOperand::MO_ConstantPoolIndex:
173     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
174   case MachineOperand::MO_JumpTableIndex:
175     return getIndex() == Other.getIndex();
176   case MachineOperand::MO_GlobalAddress:
177     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
178   case MachineOperand::MO_ExternalSymbol:
179     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
180            getOffset() == Other.getOffset();
181   }
182 }
183
184 /// print - Print the specified machine operand.
185 ///
186 void MachineOperand::print(std::ostream &OS, const TargetMachine *TM) const {
187   raw_os_ostream RawOS(OS);
188   print(RawOS, TM);
189 }
190
191 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
192   switch (getType()) {
193   case MachineOperand::MO_Register:
194     if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
195       OS << "%reg" << getReg();
196     } else {
197       // If the instruction is embedded into a basic block, we can find the
198       // target info for the instruction.
199       if (TM == 0)
200         if (const MachineInstr *MI = getParent())
201           if (const MachineBasicBlock *MBB = MI->getParent())
202             if (const MachineFunction *MF = MBB->getParent())
203               TM = &MF->getTarget();
204       
205       if (TM)
206         OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
207       else
208         OS << "%mreg" << getReg();
209     }
210
211     if (getSubReg() != 0)
212       OS << ':' << getSubReg();
213
214     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
215         isEarlyClobber()) {
216       OS << '<';
217       bool NeedComma = false;
218       if (isImplicit()) {
219         if (NeedComma) OS << ',';
220         OS << (isDef() ? "imp-def" : "imp-use");
221         NeedComma = true;
222       } else if (isDef()) {
223         if (NeedComma) OS << ',';
224         if (isEarlyClobber())
225           OS << "earlyclobber,";
226         OS << "def";
227         NeedComma = true;
228       }
229       if (isKill() || isDead() || isUndef()) {
230         if (NeedComma) OS << ',';
231         if (isKill())  OS << "kill";
232         if (isDead())  OS << "dead";
233         if (isUndef()) {
234           if (isKill() || isDead())
235             OS << ',';
236           OS << "undef";
237         }
238       }
239       OS << '>';
240     }
241     break;
242   case MachineOperand::MO_Immediate:
243     OS << getImm();
244     break;
245   case MachineOperand::MO_FPImmediate:
246     if (getFPImm()->getType() == Type::FloatTy)
247       OS << getFPImm()->getValueAPF().convertToFloat();
248     else
249       OS << getFPImm()->getValueAPF().convertToDouble();
250     break;
251   case MachineOperand::MO_MachineBasicBlock:
252     OS << "mbb<"
253        << ((Value*)getMBB()->getBasicBlock())->getName()
254        << "," << (void*)getMBB() << '>';
255     break;
256   case MachineOperand::MO_FrameIndex:
257     OS << "<fi#" << getIndex() << '>';
258     break;
259   case MachineOperand::MO_ConstantPoolIndex:
260     OS << "<cp#" << getIndex();
261     if (getOffset()) OS << "+" << getOffset();
262     OS << '>';
263     break;
264   case MachineOperand::MO_JumpTableIndex:
265     OS << "<jt#" << getIndex() << '>';
266     break;
267   case MachineOperand::MO_GlobalAddress:
268     OS << "<ga:" << ((Value*)getGlobal())->getName();
269     if (getOffset()) OS << "+" << getOffset();
270     OS << '>';
271     break;
272   case MachineOperand::MO_ExternalSymbol:
273     OS << "<es:" << getSymbolName();
274     if (getOffset()) OS << "+" << getOffset();
275     OS << '>';
276     break;
277   default:
278     llvm_unreachable("Unrecognized operand type");
279   }
280   
281   if (unsigned TF = getTargetFlags())
282     OS << "[TF=" << TF << ']';
283 }
284
285 //===----------------------------------------------------------------------===//
286 // MachineMemOperand Implementation
287 //===----------------------------------------------------------------------===//
288
289 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
290                                      int64_t o, uint64_t s, unsigned int a)
291   : Offset(o), Size(s), V(v),
292     Flags((f & 7) | ((Log2_32(a) + 1) << 3)) {
293   assert(isPowerOf2_32(a) && "Alignment is not a power of 2!");
294   assert((isLoad() || isStore()) && "Not a load/store!");
295 }
296
297 /// Profile - Gather unique data for the object.
298 ///
299 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
300   ID.AddInteger(Offset);
301   ID.AddInteger(Size);
302   ID.AddPointer(V);
303   ID.AddInteger(Flags);
304 }
305
306 //===----------------------------------------------------------------------===//
307 // MachineInstr Implementation
308 //===----------------------------------------------------------------------===//
309
310 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
311 /// TID NULL and no operands.
312 MachineInstr::MachineInstr()
313   : TID(0), NumImplicitOps(0), Parent(0), debugLoc(DebugLoc::getUnknownLoc()) {
314   // Make sure that we get added to a machine basicblock
315   LeakDetector::addGarbageObject(this);
316 }
317
318 void MachineInstr::addImplicitDefUseOperands() {
319   if (TID->ImplicitDefs)
320     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
321       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
322   if (TID->ImplicitUses)
323     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
324       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
325 }
326
327 /// MachineInstr ctor - This constructor create a MachineInstr and add the
328 /// implicit operands. It reserves space for number of operands specified by
329 /// TargetInstrDesc or the numOperands if it is not zero. (for
330 /// instructions with variable number of operands).
331 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
332   : TID(&tid), NumImplicitOps(0), Parent(0), 
333     debugLoc(DebugLoc::getUnknownLoc()) {
334   if (!NoImp && TID->getImplicitDefs())
335     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
336       NumImplicitOps++;
337   if (!NoImp && TID->getImplicitUses())
338     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
339       NumImplicitOps++;
340   Operands.reserve(NumImplicitOps + TID->getNumOperands());
341   if (!NoImp)
342     addImplicitDefUseOperands();
343   // Make sure that we get added to a machine basicblock
344   LeakDetector::addGarbageObject(this);
345 }
346
347 /// MachineInstr ctor - As above, but with a DebugLoc.
348 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
349                            bool NoImp)
350   : TID(&tid), NumImplicitOps(0), Parent(0), debugLoc(dl) {
351   if (!NoImp && TID->getImplicitDefs())
352     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
353       NumImplicitOps++;
354   if (!NoImp && TID->getImplicitUses())
355     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
356       NumImplicitOps++;
357   Operands.reserve(NumImplicitOps + TID->getNumOperands());
358   if (!NoImp)
359     addImplicitDefUseOperands();
360   // Make sure that we get added to a machine basicblock
361   LeakDetector::addGarbageObject(this);
362 }
363
364 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
365 /// that the MachineInstr is created and added to the end of the specified 
366 /// basic block.
367 ///
368 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
369   : TID(&tid), NumImplicitOps(0), Parent(0), 
370     debugLoc(DebugLoc::getUnknownLoc()) {
371   assert(MBB && "Cannot use inserting ctor with null basic block!");
372   if (TID->ImplicitDefs)
373     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
374       NumImplicitOps++;
375   if (TID->ImplicitUses)
376     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
377       NumImplicitOps++;
378   Operands.reserve(NumImplicitOps + TID->getNumOperands());
379   addImplicitDefUseOperands();
380   // Make sure that we get added to a machine basicblock
381   LeakDetector::addGarbageObject(this);
382   MBB->push_back(this);  // Add instruction to end of basic block!
383 }
384
385 /// MachineInstr ctor - As above, but with a DebugLoc.
386 ///
387 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
388                            const TargetInstrDesc &tid)
389   : TID(&tid), NumImplicitOps(0), Parent(0), debugLoc(dl) {
390   assert(MBB && "Cannot use inserting ctor with null basic block!");
391   if (TID->ImplicitDefs)
392     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
393       NumImplicitOps++;
394   if (TID->ImplicitUses)
395     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
396       NumImplicitOps++;
397   Operands.reserve(NumImplicitOps + TID->getNumOperands());
398   addImplicitDefUseOperands();
399   // Make sure that we get added to a machine basicblock
400   LeakDetector::addGarbageObject(this);
401   MBB->push_back(this);  // Add instruction to end of basic block!
402 }
403
404 /// MachineInstr ctor - Copies MachineInstr arg exactly
405 ///
406 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
407   : TID(&MI.getDesc()), NumImplicitOps(0), Parent(0), 
408         debugLoc(MI.getDebugLoc()) {
409   Operands.reserve(MI.getNumOperands());
410
411   // Add operands
412   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
413     addOperand(MI.getOperand(i));
414   NumImplicitOps = MI.NumImplicitOps;
415
416   // Add memory operands.
417   for (std::list<MachineMemOperand>::const_iterator i = MI.memoperands_begin(),
418        j = MI.memoperands_end(); i != j; ++i)
419     addMemOperand(MF, *i);
420
421   // Set parent to null.
422   Parent = 0;
423
424   LeakDetector::addGarbageObject(this);
425 }
426
427 MachineInstr::~MachineInstr() {
428   LeakDetector::removeGarbageObject(this);
429   assert(MemOperands.empty() &&
430          "MachineInstr being deleted with live memoperands!");
431 #ifndef NDEBUG
432   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
433     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
434     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
435            "Reg operand def/use list corrupted");
436   }
437 #endif
438 }
439
440 /// getRegInfo - If this instruction is embedded into a MachineFunction,
441 /// return the MachineRegisterInfo object for the current function, otherwise
442 /// return null.
443 MachineRegisterInfo *MachineInstr::getRegInfo() {
444   if (MachineBasicBlock *MBB = getParent())
445     return &MBB->getParent()->getRegInfo();
446   return 0;
447 }
448
449 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
450 /// this instruction from their respective use lists.  This requires that the
451 /// operands already be on their use lists.
452 void MachineInstr::RemoveRegOperandsFromUseLists() {
453   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
454     if (Operands[i].isReg())
455       Operands[i].RemoveRegOperandFromRegInfo();
456   }
457 }
458
459 /// AddRegOperandsToUseLists - Add all of the register operands in
460 /// this instruction from their respective use lists.  This requires that the
461 /// operands not be on their use lists yet.
462 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
463   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
464     if (Operands[i].isReg())
465       Operands[i].AddRegOperandToRegInfo(&RegInfo);
466   }
467 }
468
469
470 /// addOperand - Add the specified operand to the instruction.  If it is an
471 /// implicit operand, it is added to the end of the operand list.  If it is
472 /// an explicit operand it is added at the end of the explicit operand list
473 /// (before the first implicit operand). 
474 void MachineInstr::addOperand(const MachineOperand &Op) {
475   bool isImpReg = Op.isReg() && Op.isImplicit();
476   assert((isImpReg || !OperandsComplete()) &&
477          "Trying to add an operand to a machine instr that is already done!");
478
479   MachineRegisterInfo *RegInfo = getRegInfo();
480
481   // If we are adding the operand to the end of the list, our job is simpler.
482   // This is true most of the time, so this is a reasonable optimization.
483   if (isImpReg || NumImplicitOps == 0) {
484     // We can only do this optimization if we know that the operand list won't
485     // reallocate.
486     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
487       Operands.push_back(Op);
488     
489       // Set the parent of the operand.
490       Operands.back().ParentMI = this;
491   
492       // If the operand is a register, update the operand's use list.
493       if (Op.isReg())
494         Operands.back().AddRegOperandToRegInfo(RegInfo);
495       return;
496     }
497   }
498   
499   // Otherwise, we have to insert a real operand before any implicit ones.
500   unsigned OpNo = Operands.size()-NumImplicitOps;
501
502   // If this instruction isn't embedded into a function, then we don't need to
503   // update any operand lists.
504   if (RegInfo == 0) {
505     // Simple insertion, no reginfo update needed for other register operands.
506     Operands.insert(Operands.begin()+OpNo, Op);
507     Operands[OpNo].ParentMI = this;
508
509     // Do explicitly set the reginfo for this operand though, to ensure the
510     // next/prev fields are properly nulled out.
511     if (Operands[OpNo].isReg())
512       Operands[OpNo].AddRegOperandToRegInfo(0);
513
514   } else if (Operands.size()+1 <= Operands.capacity()) {
515     // Otherwise, we have to remove register operands from their register use
516     // list, add the operand, then add the register operands back to their use
517     // list.  This also must handle the case when the operand list reallocates
518     // to somewhere else.
519   
520     // If insertion of this operand won't cause reallocation of the operand
521     // list, just remove the implicit operands, add the operand, then re-add all
522     // the rest of the operands.
523     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
524       assert(Operands[i].isReg() && "Should only be an implicit reg!");
525       Operands[i].RemoveRegOperandFromRegInfo();
526     }
527     
528     // Add the operand.  If it is a register, add it to the reg list.
529     Operands.insert(Operands.begin()+OpNo, Op);
530     Operands[OpNo].ParentMI = this;
531
532     if (Operands[OpNo].isReg())
533       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
534     
535     // Re-add all the implicit ops.
536     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
537       assert(Operands[i].isReg() && "Should only be an implicit reg!");
538       Operands[i].AddRegOperandToRegInfo(RegInfo);
539     }
540   } else {
541     // Otherwise, we will be reallocating the operand list.  Remove all reg
542     // operands from their list, then readd them after the operand list is
543     // reallocated.
544     RemoveRegOperandsFromUseLists();
545     
546     Operands.insert(Operands.begin()+OpNo, Op);
547     Operands[OpNo].ParentMI = this;
548   
549     // Re-add all the operands.
550     AddRegOperandsToUseLists(*RegInfo);
551   }
552 }
553
554 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
555 /// fewer operand than it started with.
556 ///
557 void MachineInstr::RemoveOperand(unsigned OpNo) {
558   assert(OpNo < Operands.size() && "Invalid operand number");
559   
560   // Special case removing the last one.
561   if (OpNo == Operands.size()-1) {
562     // If needed, remove from the reg def/use list.
563     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
564       Operands.back().RemoveRegOperandFromRegInfo();
565     
566     Operands.pop_back();
567     return;
568   }
569
570   // Otherwise, we are removing an interior operand.  If we have reginfo to
571   // update, remove all operands that will be shifted down from their reg lists,
572   // move everything down, then re-add them.
573   MachineRegisterInfo *RegInfo = getRegInfo();
574   if (RegInfo) {
575     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
576       if (Operands[i].isReg())
577         Operands[i].RemoveRegOperandFromRegInfo();
578     }
579   }
580   
581   Operands.erase(Operands.begin()+OpNo);
582
583   if (RegInfo) {
584     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
585       if (Operands[i].isReg())
586         Operands[i].AddRegOperandToRegInfo(RegInfo);
587     }
588   }
589 }
590
591 /// addMemOperand - Add a MachineMemOperand to the machine instruction,
592 /// referencing arbitrary storage.
593 void MachineInstr::addMemOperand(MachineFunction &MF,
594                                  const MachineMemOperand &MO) {
595   MemOperands.push_back(MO);
596 }
597
598 /// clearMemOperands - Erase all of this MachineInstr's MachineMemOperands.
599 void MachineInstr::clearMemOperands(MachineFunction &MF) {
600   MemOperands.clear();
601 }
602
603
604 /// removeFromParent - This method unlinks 'this' from the containing basic
605 /// block, and returns it, but does not delete it.
606 MachineInstr *MachineInstr::removeFromParent() {
607   assert(getParent() && "Not embedded in a basic block!");
608   getParent()->remove(this);
609   return this;
610 }
611
612
613 /// eraseFromParent - This method unlinks 'this' from the containing basic
614 /// block, and deletes it.
615 void MachineInstr::eraseFromParent() {
616   assert(getParent() && "Not embedded in a basic block!");
617   getParent()->erase(this);
618 }
619
620
621 /// OperandComplete - Return true if it's illegal to add a new operand
622 ///
623 bool MachineInstr::OperandsComplete() const {
624   unsigned short NumOperands = TID->getNumOperands();
625   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
626     return true;  // Broken: we have all the operands of this instruction!
627   return false;
628 }
629
630 /// getNumExplicitOperands - Returns the number of non-implicit operands.
631 ///
632 unsigned MachineInstr::getNumExplicitOperands() const {
633   unsigned NumOperands = TID->getNumOperands();
634   if (!TID->isVariadic())
635     return NumOperands;
636
637   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
638     const MachineOperand &MO = getOperand(i);
639     if (!MO.isReg() || !MO.isImplicit())
640       NumOperands++;
641   }
642   return NumOperands;
643 }
644
645
646 /// isLabel - Returns true if the MachineInstr represents a label.
647 ///
648 bool MachineInstr::isLabel() const {
649   return getOpcode() == TargetInstrInfo::DBG_LABEL ||
650          getOpcode() == TargetInstrInfo::EH_LABEL ||
651          getOpcode() == TargetInstrInfo::GC_LABEL;
652 }
653
654 /// isDebugLabel - Returns true if the MachineInstr represents a debug label.
655 ///
656 bool MachineInstr::isDebugLabel() const {
657   return getOpcode() == TargetInstrInfo::DBG_LABEL;
658 }
659
660 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
661 /// the specific register or -1 if it is not found. It further tightening
662 /// the search criteria to a use that kills the register if isKill is true.
663 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
664                                           const TargetRegisterInfo *TRI) const {
665   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
666     const MachineOperand &MO = getOperand(i);
667     if (!MO.isReg() || !MO.isUse())
668       continue;
669     unsigned MOReg = MO.getReg();
670     if (!MOReg)
671       continue;
672     if (MOReg == Reg ||
673         (TRI &&
674          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
675          TargetRegisterInfo::isPhysicalRegister(Reg) &&
676          TRI->isSubRegister(MOReg, Reg)))
677       if (!isKill || MO.isKill())
678         return i;
679   }
680   return -1;
681 }
682   
683 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
684 /// the specified register or -1 if it is not found. If isDead is true, defs
685 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
686 /// also checks if there is a def of a super-register.
687 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
688                                           const TargetRegisterInfo *TRI) const {
689   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
690     const MachineOperand &MO = getOperand(i);
691     if (!MO.isReg() || !MO.isDef())
692       continue;
693     unsigned MOReg = MO.getReg();
694     if (MOReg == Reg ||
695         (TRI &&
696          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
697          TargetRegisterInfo::isPhysicalRegister(Reg) &&
698          TRI->isSubRegister(MOReg, Reg)))
699       if (!isDead || MO.isDead())
700         return i;
701   }
702   return -1;
703 }
704
705 /// findFirstPredOperandIdx() - Find the index of the first operand in the
706 /// operand list that is used to represent the predicate. It returns -1 if
707 /// none is found.
708 int MachineInstr::findFirstPredOperandIdx() const {
709   const TargetInstrDesc &TID = getDesc();
710   if (TID.isPredicable()) {
711     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
712       if (TID.OpInfo[i].isPredicate())
713         return i;
714   }
715
716   return -1;
717 }
718   
719 /// isRegTiedToUseOperand - Given the index of a register def operand,
720 /// check if the register def is tied to a source operand, due to either
721 /// two-address elimination or inline assembly constraints. Returns the
722 /// first tied use operand index by reference is UseOpIdx is not null.
723 bool MachineInstr::
724 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
725   if (getOpcode() == TargetInstrInfo::INLINEASM) {
726     assert(DefOpIdx >= 2);
727     const MachineOperand &MO = getOperand(DefOpIdx);
728     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
729       return false;
730     // Determine the actual operand index that corresponds to this index.
731     unsigned DefNo = 0;
732     unsigned DefPart = 0;
733     for (unsigned i = 1, e = getNumOperands(); i < e; ) {
734       const MachineOperand &FMO = getOperand(i);
735       assert(FMO.isImm());
736       // Skip over this def.
737       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
738       unsigned PrevDef = i + 1;
739       i = PrevDef + NumOps;
740       if (i > DefOpIdx) {
741         DefPart = DefOpIdx - PrevDef;
742         break;
743       }
744       ++DefNo;
745     }
746     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
747       const MachineOperand &FMO = getOperand(i);
748       if (!FMO.isImm())
749         continue;
750       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
751         continue;
752       unsigned Idx;
753       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
754           Idx == DefNo) {
755         if (UseOpIdx)
756           *UseOpIdx = (unsigned)i + 1 + DefPart;
757         return true;
758       }
759     }
760     return false;
761   }
762
763   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
764   const TargetInstrDesc &TID = getDesc();
765   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
766     const MachineOperand &MO = getOperand(i);
767     if (MO.isReg() && MO.isUse() &&
768         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
769       if (UseOpIdx)
770         *UseOpIdx = (unsigned)i;
771       return true;
772     }
773   }
774   return false;
775 }
776
777 /// isRegTiedToDefOperand - Return true if the operand of the specified index
778 /// is a register use and it is tied to an def operand. It also returns the def
779 /// operand index by reference.
780 bool MachineInstr::
781 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
782   if (getOpcode() == TargetInstrInfo::INLINEASM) {
783     const MachineOperand &MO = getOperand(UseOpIdx);
784     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
785       return false;
786
787     // Find the flag operand corresponding to UseOpIdx
788     unsigned FlagIdx, NumOps=0;
789     for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
790       const MachineOperand &UFMO = getOperand(FlagIdx);
791       assert(UFMO.isImm() && "Expecting flag operand on inline asm");
792       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
793       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
794       if (UseOpIdx < FlagIdx+NumOps+1)
795         break;
796     }
797     if (FlagIdx >= UseOpIdx)
798       return false;
799     const MachineOperand &UFMO = getOperand(FlagIdx);
800     unsigned DefNo;
801     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
802       if (!DefOpIdx)
803         return true;
804
805       unsigned DefIdx = 1;
806       // Remember to adjust the index. First operand is asm string, then there
807       // is a flag for each.
808       while (DefNo) {
809         const MachineOperand &FMO = getOperand(DefIdx);
810         assert(FMO.isImm());
811         // Skip over this def.
812         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
813         --DefNo;
814       }
815       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
816       return true;
817     }
818     return false;
819   }
820
821   const TargetInstrDesc &TID = getDesc();
822   if (UseOpIdx >= TID.getNumOperands())
823     return false;
824   const MachineOperand &MO = getOperand(UseOpIdx);
825   if (!MO.isReg() || !MO.isUse())
826     return false;
827   int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
828   if (DefIdx == -1)
829     return false;
830   if (DefOpIdx)
831     *DefOpIdx = (unsigned)DefIdx;
832   return true;
833 }
834
835 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
836 ///
837 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
838   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
839     const MachineOperand &MO = MI->getOperand(i);
840     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
841       continue;
842     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
843       MachineOperand &MOp = getOperand(j);
844       if (!MOp.isIdenticalTo(MO))
845         continue;
846       if (MO.isKill())
847         MOp.setIsKill();
848       else
849         MOp.setIsDead();
850       break;
851     }
852   }
853 }
854
855 /// copyPredicates - Copies predicate operand(s) from MI.
856 void MachineInstr::copyPredicates(const MachineInstr *MI) {
857   const TargetInstrDesc &TID = MI->getDesc();
858   if (!TID.isPredicable())
859     return;
860   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
861     if (TID.OpInfo[i].isPredicate()) {
862       // Predicated operands must be last operands.
863       addOperand(MI->getOperand(i));
864     }
865   }
866 }
867
868 /// isSafeToMove - Return true if it is safe to move this instruction. If
869 /// SawStore is set to true, it means that there is a store (or call) between
870 /// the instruction's location and its intended destination.
871 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
872                                 bool &SawStore) const {
873   // Ignore stuff that we obviously can't move.
874   if (TID->mayStore() || TID->isCall()) {
875     SawStore = true;
876     return false;
877   }
878   if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
879     return false;
880
881   // See if this instruction does a load.  If so, we have to guarantee that the
882   // loaded value doesn't change between the load and the its intended
883   // destination. The check for isInvariantLoad gives the targe the chance to
884   // classify the load as always returning a constant, e.g. a constant pool
885   // load.
886   if (TID->mayLoad() && !TII->isInvariantLoad(this))
887     // Otherwise, this is a real load.  If there is a store between the load and
888     // end of block, or if the laod is volatile, we can't move it.
889     return !SawStore && !hasVolatileMemoryRef();
890
891   return true;
892 }
893
894 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
895 /// instruction which defined the specified register instead of copying it.
896 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
897                                  unsigned DstReg) const {
898   bool SawStore = false;
899   if (!getDesc().isRematerializable() ||
900       !TII->isTriviallyReMaterializable(this) ||
901       !isSafeToMove(TII, SawStore))
902     return false;
903   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
904     const MachineOperand &MO = getOperand(i);
905     if (!MO.isReg())
906       continue;
907     // FIXME: For now, do not remat any instruction with register operands.
908     // Later on, we can loosen the restriction is the register operands have
909     // not been modified between the def and use. Note, this is different from
910     // MachineSink because the code is no longer in two-address form (at least
911     // partially).
912     if (MO.isUse())
913       return false;
914     else if (!MO.isDead() && MO.getReg() != DstReg)
915       return false;
916   }
917   return true;
918 }
919
920 /// hasVolatileMemoryRef - Return true if this instruction may have a
921 /// volatile memory reference, or if the information describing the
922 /// memory reference is not available. Return false if it is known to
923 /// have no volatile memory references.
924 bool MachineInstr::hasVolatileMemoryRef() const {
925   // An instruction known never to access memory won't have a volatile access.
926   if (!TID->mayStore() &&
927       !TID->mayLoad() &&
928       !TID->isCall() &&
929       !TID->hasUnmodeledSideEffects())
930     return false;
931
932   // Otherwise, if the instruction has no memory reference information,
933   // conservatively assume it wasn't preserved.
934   if (memoperands_empty())
935     return true;
936   
937   // Check the memory reference information for volatile references.
938   for (std::list<MachineMemOperand>::const_iterator I = memoperands_begin(),
939        E = memoperands_end(); I != E; ++I)
940     if (I->isVolatile())
941       return true;
942
943   return false;
944 }
945
946 void MachineInstr::dump() const {
947   cerr << "  " << *this;
948 }
949
950 void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
951   raw_os_ostream RawOS(OS);
952   print(RawOS, TM);
953 }
954
955 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
956   // Specialize printing if op#0 is definition
957   unsigned StartOp = 0;
958   if (getNumOperands() && getOperand(0).isReg() && getOperand(0).isDef()) {
959     getOperand(0).print(OS, TM);
960     OS << " = ";
961     ++StartOp;   // Don't print this operand again!
962   }
963
964   OS << getDesc().getName();
965
966   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
967     if (i != StartOp)
968       OS << ",";
969     OS << " ";
970     getOperand(i).print(OS, TM);
971   }
972
973   if (!memoperands_empty()) {
974     OS << ", Mem:";
975     for (std::list<MachineMemOperand>::const_iterator i = memoperands_begin(),
976          e = memoperands_end(); i != e; ++i) {
977       const MachineMemOperand &MRO = *i;
978       const Value *V = MRO.getValue();
979
980       assert((MRO.isLoad() || MRO.isStore()) &&
981              "SV has to be a load, store or both.");
982       
983       if (MRO.isVolatile())
984         OS << "Volatile ";
985
986       if (MRO.isLoad())
987         OS << "LD";
988       if (MRO.isStore())
989         OS << "ST";
990         
991       OS << "(" << MRO.getSize() << "," << MRO.getAlignment() << ") [";
992       
993       if (!V)
994         OS << "<unknown>";
995       else if (!V->getName().empty())
996         OS << V->getName();
997       else if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
998         PSV->print(OS);
999       } else
1000         OS << V;
1001
1002       OS << " + " << MRO.getOffset() << "]";
1003     }
1004   }
1005
1006   if (!debugLoc.isUnknown()) {
1007     const MachineFunction *MF = getParent()->getParent();
1008     DebugLocTuple DLT = MF->getDebugLocTuple(debugLoc);
1009     DICompileUnit CU(DLT.CompileUnit);
1010     std::string Dir, Fn;
1011     OS << " [dbg: "
1012        << CU.getDirectory(Dir) << '/' << CU.getFilename(Fn) << ","
1013        << DLT.Line << ","
1014        << DLT.Col  << "]";
1015   }
1016
1017   OS << "\n";
1018 }
1019
1020 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1021                                      const TargetRegisterInfo *RegInfo,
1022                                      bool AddIfNotFound) {
1023   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1024   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1025   bool Found = false;
1026   SmallVector<unsigned,4> DeadOps;
1027   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1028     MachineOperand &MO = getOperand(i);
1029     if (!MO.isReg() || !MO.isUse())
1030       continue;
1031     unsigned Reg = MO.getReg();
1032     if (!Reg)
1033       continue;
1034
1035     if (Reg == IncomingReg) {
1036       if (!Found) {
1037         if (MO.isKill())
1038           // The register is already marked kill.
1039           return true;
1040         MO.setIsKill();
1041         Found = true;
1042       }
1043     } else if (hasAliases && MO.isKill() &&
1044                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1045       // A super-register kill already exists.
1046       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1047         return true;
1048       if (RegInfo->isSubRegister(IncomingReg, Reg))
1049         DeadOps.push_back(i);
1050     }
1051   }
1052
1053   // Trim unneeded kill operands.
1054   while (!DeadOps.empty()) {
1055     unsigned OpIdx = DeadOps.back();
1056     if (getOperand(OpIdx).isImplicit())
1057       RemoveOperand(OpIdx);
1058     else
1059       getOperand(OpIdx).setIsKill(false);
1060     DeadOps.pop_back();
1061   }
1062
1063   // If not found, this means an alias of one of the operands is killed. Add a
1064   // new implicit operand if required.
1065   if (!Found && AddIfNotFound) {
1066     addOperand(MachineOperand::CreateReg(IncomingReg,
1067                                          false /*IsDef*/,
1068                                          true  /*IsImp*/,
1069                                          true  /*IsKill*/));
1070     return true;
1071   }
1072   return Found;
1073 }
1074
1075 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1076                                    const TargetRegisterInfo *RegInfo,
1077                                    bool AddIfNotFound) {
1078   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1079   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1080   bool Found = false;
1081   SmallVector<unsigned,4> DeadOps;
1082   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1083     MachineOperand &MO = getOperand(i);
1084     if (!MO.isReg() || !MO.isDef())
1085       continue;
1086     unsigned Reg = MO.getReg();
1087     if (!Reg)
1088       continue;
1089
1090     if (Reg == IncomingReg) {
1091       if (!Found) {
1092         if (MO.isDead())
1093           // The register is already marked dead.
1094           return true;
1095         MO.setIsDead();
1096         Found = true;
1097       }
1098     } else if (hasAliases && MO.isDead() &&
1099                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1100       // There exists a super-register that's marked dead.
1101       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1102         return true;
1103       if (RegInfo->getSubRegisters(IncomingReg) &&
1104           RegInfo->getSuperRegisters(Reg) &&
1105           RegInfo->isSubRegister(IncomingReg, Reg))
1106         DeadOps.push_back(i);
1107     }
1108   }
1109
1110   // Trim unneeded dead operands.
1111   while (!DeadOps.empty()) {
1112     unsigned OpIdx = DeadOps.back();
1113     if (getOperand(OpIdx).isImplicit())
1114       RemoveOperand(OpIdx);
1115     else
1116       getOperand(OpIdx).setIsDead(false);
1117     DeadOps.pop_back();
1118   }
1119
1120   // If not found, this means an alias of one of the operands is dead. Add a
1121   // new implicit operand if required.
1122   if (Found || !AddIfNotFound)
1123     return Found;
1124     
1125   addOperand(MachineOperand::CreateReg(IncomingReg,
1126                                        true  /*IsDef*/,
1127                                        true  /*IsImp*/,
1128                                        false /*IsKill*/,
1129                                        true  /*IsDead*/));
1130   return true;
1131 }