Disable my little CopyToReg argument hack with fast-isel. rdar://problem/9413587 .
[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/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Metadata.h"
19 #include "llvm/Type.h"
20 #include "llvm/Value.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetInstrDesc.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/LeakDetector.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/FoldingSet.h"
40 using namespace llvm;
41
42 //===----------------------------------------------------------------------===//
43 // MachineOperand Implementation
44 //===----------------------------------------------------------------------===//
45
46 /// AddRegOperandToRegInfo - Add this register operand to the specified
47 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
48 /// explicitly nulled out.
49 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
50   assert(isReg() && "Can only add reg operand to use lists");
51   
52   // If the reginfo pointer is null, just explicitly null out or next/prev
53   // pointers, to ensure they are not garbage.
54   if (RegInfo == 0) {
55     Contents.Reg.Prev = 0;
56     Contents.Reg.Next = 0;
57     return;
58   }
59   
60   // Otherwise, add this operand to the head of the registers use/def list.
61   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
62   
63   // For SSA values, we prefer to keep the definition at the start of the list.
64   // we do this by skipping over the definition if it is at the head of the
65   // list.
66   if (*Head && (*Head)->isDef())
67     Head = &(*Head)->Contents.Reg.Next;
68   
69   Contents.Reg.Next = *Head;
70   if (Contents.Reg.Next) {
71     assert(getReg() == Contents.Reg.Next->getReg() &&
72            "Different regs on the same list!");
73     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
74   }
75   
76   Contents.Reg.Prev = Head;
77   *Head = this;
78 }
79
80 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
81 /// MachineRegisterInfo it is linked with.
82 void MachineOperand::RemoveRegOperandFromRegInfo() {
83   assert(isOnRegUseList() && "Reg operand is not on a use list");
84   // Unlink this from the doubly linked list of operands.
85   MachineOperand *NextOp = Contents.Reg.Next;
86   *Contents.Reg.Prev = NextOp; 
87   if (NextOp) {
88     assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
89     NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
90   }
91   Contents.Reg.Prev = 0;
92   Contents.Reg.Next = 0;
93 }
94
95 void MachineOperand::setReg(unsigned Reg) {
96   if (getReg() == Reg) return; // No change.
97   
98   // Otherwise, we have to change the register.  If this operand is embedded
99   // into a machine function, we need to update the old and new register's
100   // use/def lists.
101   if (MachineInstr *MI = getParent())
102     if (MachineBasicBlock *MBB = MI->getParent())
103       if (MachineFunction *MF = MBB->getParent()) {
104         RemoveRegOperandFromRegInfo();
105         SmallContents.RegNo = Reg;
106         AddRegOperandToRegInfo(&MF->getRegInfo());
107         return;
108       }
109         
110   // Otherwise, just change the register, no problem.  :)
111   SmallContents.RegNo = Reg;
112 }
113
114 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
115                                   const TargetRegisterInfo &TRI) {
116   assert(TargetRegisterInfo::isVirtualRegister(Reg));
117   if (SubIdx && getSubReg())
118     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
119   setReg(Reg);
120   if (SubIdx)
121     setSubReg(SubIdx);
122 }
123
124 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
125   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
126   if (getSubReg()) {
127     Reg = TRI.getSubReg(Reg, getSubReg());
128     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
129     // That won't happen in legal code.
130     setSubReg(0);
131   }
132   setReg(Reg);
133 }
134
135 /// ChangeToImmediate - Replace this operand with a new immediate operand of
136 /// the specified value.  If an operand is known to be an immediate already,
137 /// the setImm method should be used.
138 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
139   // If this operand is currently a register operand, and if this is in a
140   // function, deregister the operand from the register's use/def list.
141   if (isReg() && getParent() && getParent()->getParent() &&
142       getParent()->getParent()->getParent())
143     RemoveRegOperandFromRegInfo();
144   
145   OpKind = MO_Immediate;
146   Contents.ImmVal = ImmVal;
147 }
148
149 /// ChangeToRegister - Replace this operand with a new register operand of
150 /// the specified value.  If an operand is known to be an register already,
151 /// the setReg method should be used.
152 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
153                                       bool isKill, bool isDead, bool isUndef,
154                                       bool isDebug) {
155   // If this operand is already a register operand, use setReg to update the 
156   // register's use/def lists.
157   if (isReg()) {
158     assert(!isEarlyClobber());
159     setReg(Reg);
160   } else {
161     // Otherwise, change this to a register and set the reg#.
162     OpKind = MO_Register;
163     SmallContents.RegNo = Reg;
164
165     // If this operand is embedded in a function, add the operand to the
166     // register's use/def list.
167     if (MachineInstr *MI = getParent())
168       if (MachineBasicBlock *MBB = MI->getParent())
169         if (MachineFunction *MF = MBB->getParent())
170           AddRegOperandToRegInfo(&MF->getRegInfo());
171   }
172
173   IsDef = isDef;
174   IsImp = isImp;
175   IsKill = isKill;
176   IsDead = isDead;
177   IsUndef = isUndef;
178   IsEarlyClobber = false;
179   IsDebug = isDebug;
180   SubReg = 0;
181 }
182
183 /// isIdenticalTo - Return true if this operand is identical to the specified
184 /// operand.
185 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
186   if (getType() != Other.getType() ||
187       getTargetFlags() != Other.getTargetFlags())
188     return false;
189   
190   switch (getType()) {
191   default: llvm_unreachable("Unrecognized operand type");
192   case MachineOperand::MO_Register:
193     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
194            getSubReg() == Other.getSubReg();
195   case MachineOperand::MO_Immediate:
196     return getImm() == Other.getImm();
197   case MachineOperand::MO_FPImmediate:
198     return getFPImm() == Other.getFPImm();
199   case MachineOperand::MO_MachineBasicBlock:
200     return getMBB() == Other.getMBB();
201   case MachineOperand::MO_FrameIndex:
202     return getIndex() == Other.getIndex();
203   case MachineOperand::MO_ConstantPoolIndex:
204     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
205   case MachineOperand::MO_JumpTableIndex:
206     return getIndex() == Other.getIndex();
207   case MachineOperand::MO_GlobalAddress:
208     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
209   case MachineOperand::MO_ExternalSymbol:
210     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
211            getOffset() == Other.getOffset();
212   case MachineOperand::MO_BlockAddress:
213     return getBlockAddress() == Other.getBlockAddress();
214   case MachineOperand::MO_MCSymbol:
215     return getMCSymbol() == Other.getMCSymbol();
216   case MachineOperand::MO_Metadata:
217     return getMetadata() == Other.getMetadata();
218   }
219 }
220
221 /// print - Print the specified machine operand.
222 ///
223 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
224   // If the instruction is embedded into a basic block, we can find the
225   // target info for the instruction.
226   if (!TM)
227     if (const MachineInstr *MI = getParent())
228       if (const MachineBasicBlock *MBB = MI->getParent())
229         if (const MachineFunction *MF = MBB->getParent())
230           TM = &MF->getTarget();
231   const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
232
233   switch (getType()) {
234   case MachineOperand::MO_Register:
235     OS << PrintReg(getReg(), TRI, getSubReg());
236
237     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
238         isEarlyClobber()) {
239       OS << '<';
240       bool NeedComma = false;
241       if (isDef()) {
242         if (NeedComma) OS << ',';
243         if (isEarlyClobber())
244           OS << "earlyclobber,";
245         if (isImplicit())
246           OS << "imp-";
247         OS << "def";
248         NeedComma = true;
249       } else if (isImplicit()) {
250           OS << "imp-use";
251           NeedComma = true;
252       }
253
254       if (isKill() || isDead() || isUndef()) {
255         if (NeedComma) OS << ',';
256         if (isKill())  OS << "kill";
257         if (isDead())  OS << "dead";
258         if (isUndef()) {
259           if (isKill() || isDead())
260             OS << ',';
261           OS << "undef";
262         }
263       }
264       OS << '>';
265     }
266     break;
267   case MachineOperand::MO_Immediate:
268     OS << getImm();
269     break;
270   case MachineOperand::MO_FPImmediate:
271     if (getFPImm()->getType()->isFloatTy())
272       OS << getFPImm()->getValueAPF().convertToFloat();
273     else
274       OS << getFPImm()->getValueAPF().convertToDouble();
275     break;
276   case MachineOperand::MO_MachineBasicBlock:
277     OS << "<BB#" << getMBB()->getNumber() << ">";
278     break;
279   case MachineOperand::MO_FrameIndex:
280     OS << "<fi#" << getIndex() << '>';
281     break;
282   case MachineOperand::MO_ConstantPoolIndex:
283     OS << "<cp#" << getIndex();
284     if (getOffset()) OS << "+" << getOffset();
285     OS << '>';
286     break;
287   case MachineOperand::MO_JumpTableIndex:
288     OS << "<jt#" << getIndex() << '>';
289     break;
290   case MachineOperand::MO_GlobalAddress:
291     OS << "<ga:";
292     WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
293     if (getOffset()) OS << "+" << getOffset();
294     OS << '>';
295     break;
296   case MachineOperand::MO_ExternalSymbol:
297     OS << "<es:" << getSymbolName();
298     if (getOffset()) OS << "+" << getOffset();
299     OS << '>';
300     break;
301   case MachineOperand::MO_BlockAddress:
302     OS << '<';
303     WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
304     OS << '>';
305     break;
306   case MachineOperand::MO_Metadata:
307     OS << '<';
308     WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
309     OS << '>';
310     break;
311   case MachineOperand::MO_MCSymbol:
312     OS << "<MCSym=" << *getMCSymbol() << '>';
313     break;
314   default:
315     llvm_unreachable("Unrecognized operand type");
316   }
317   
318   if (unsigned TF = getTargetFlags())
319     OS << "[TF=" << TF << ']';
320 }
321
322 //===----------------------------------------------------------------------===//
323 // MachineMemOperand Implementation
324 //===----------------------------------------------------------------------===//
325
326 /// getAddrSpace - Return the LLVM IR address space number that this pointer
327 /// points into.
328 unsigned MachinePointerInfo::getAddrSpace() const {
329   if (V == 0) return 0;
330   return cast<PointerType>(V->getType())->getAddressSpace();
331 }
332
333 /// getConstantPool - Return a MachinePointerInfo record that refers to the
334 /// constant pool.
335 MachinePointerInfo MachinePointerInfo::getConstantPool() {
336   return MachinePointerInfo(PseudoSourceValue::getConstantPool());
337 }
338
339 /// getFixedStack - Return a MachinePointerInfo record that refers to the
340 /// the specified FrameIndex.
341 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
342   return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
343 }
344
345 MachinePointerInfo MachinePointerInfo::getJumpTable() {
346   return MachinePointerInfo(PseudoSourceValue::getJumpTable());
347 }
348
349 MachinePointerInfo MachinePointerInfo::getGOT() {
350   return MachinePointerInfo(PseudoSourceValue::getGOT());
351 }
352
353 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
354   return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
355 }
356
357 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
358                                      uint64_t s, unsigned int a,
359                                      const MDNode *TBAAInfo)
360   : PtrInfo(ptrinfo), Size(s),
361     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
362     TBAAInfo(TBAAInfo) {
363   assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
364          "invalid pointer value");
365   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
366   assert((isLoad() || isStore()) && "Not a load/store!");
367 }
368
369 /// Profile - Gather unique data for the object.
370 ///
371 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
372   ID.AddInteger(getOffset());
373   ID.AddInteger(Size);
374   ID.AddPointer(getValue());
375   ID.AddInteger(Flags);
376 }
377
378 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
379   // The Value and Offset may differ due to CSE. But the flags and size
380   // should be the same.
381   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
382   assert(MMO->getSize() == getSize() && "Size mismatch!");
383
384   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
385     // Update the alignment value.
386     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
387       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
388     // Also update the base and offset, because the new alignment may
389     // not be applicable with the old ones.
390     PtrInfo = MMO->PtrInfo;
391   }
392 }
393
394 /// getAlignment - Return the minimum known alignment in bytes of the
395 /// actual memory reference.
396 uint64_t MachineMemOperand::getAlignment() const {
397   return MinAlign(getBaseAlignment(), getOffset());
398 }
399
400 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
401   assert((MMO.isLoad() || MMO.isStore()) &&
402          "SV has to be a load, store or both.");
403   
404   if (MMO.isVolatile())
405     OS << "Volatile ";
406
407   if (MMO.isLoad())
408     OS << "LD";
409   if (MMO.isStore())
410     OS << "ST";
411   OS << MMO.getSize();
412   
413   // Print the address information.
414   OS << "[";
415   if (!MMO.getValue())
416     OS << "<unknown>";
417   else
418     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
419
420   // If the alignment of the memory reference itself differs from the alignment
421   // of the base pointer, print the base alignment explicitly, next to the base
422   // pointer.
423   if (MMO.getBaseAlignment() != MMO.getAlignment())
424     OS << "(align=" << MMO.getBaseAlignment() << ")";
425
426   if (MMO.getOffset() != 0)
427     OS << "+" << MMO.getOffset();
428   OS << "]";
429
430   // Print the alignment of the reference.
431   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
432       MMO.getBaseAlignment() != MMO.getSize())
433     OS << "(align=" << MMO.getAlignment() << ")";
434
435   // Print TBAA info.
436   if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
437     OS << "(tbaa=";
438     if (TBAAInfo->getNumOperands() > 0)
439       WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
440     else
441       OS << "<unknown>";
442     OS << ")";
443   }
444
445   // Print nontemporal info.
446   if (MMO.isNonTemporal())
447     OS << "(nontemporal)";
448
449   return OS;
450 }
451
452 //===----------------------------------------------------------------------===//
453 // MachineInstr Implementation
454 //===----------------------------------------------------------------------===//
455
456 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
457 /// TID NULL and no operands.
458 MachineInstr::MachineInstr()
459   : TID(0), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
460     MemRefs(0), MemRefsEnd(0),
461     Parent(0) {
462   // Make sure that we get added to a machine basicblock
463   LeakDetector::addGarbageObject(this);
464 }
465
466 void MachineInstr::addImplicitDefUseOperands() {
467   if (TID->ImplicitDefs)
468     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
469       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
470   if (TID->ImplicitUses)
471     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
472       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
473 }
474
475 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
476 /// implicit operands. It reserves space for the number of operands specified by
477 /// the TargetInstrDesc.
478 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
479   : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
480     MemRefs(0), MemRefsEnd(0), Parent(0) {
481   if (!NoImp)
482     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
483   Operands.reserve(NumImplicitOps + TID->getNumOperands());
484   if (!NoImp)
485     addImplicitDefUseOperands();
486   // Make sure that we get added to a machine basicblock
487   LeakDetector::addGarbageObject(this);
488 }
489
490 /// MachineInstr ctor - As above, but with a DebugLoc.
491 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
492                            bool NoImp)
493   : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
494     MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
495   if (!NoImp)
496     NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
497   Operands.reserve(NumImplicitOps + TID->getNumOperands());
498   if (!NoImp)
499     addImplicitDefUseOperands();
500   // Make sure that we get added to a machine basicblock
501   LeakDetector::addGarbageObject(this);
502 }
503
504 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
505 /// that the MachineInstr is created and added to the end of the specified 
506 /// basic block.
507 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
508   : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
509     MemRefs(0), MemRefsEnd(0), Parent(0) {
510   assert(MBB && "Cannot use inserting ctor with null basic block!");
511   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
512   Operands.reserve(NumImplicitOps + TID->getNumOperands());
513   addImplicitDefUseOperands();
514   // Make sure that we get added to a machine basicblock
515   LeakDetector::addGarbageObject(this);
516   MBB->push_back(this);  // Add instruction to end of basic block!
517 }
518
519 /// MachineInstr ctor - As above, but with a DebugLoc.
520 ///
521 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
522                            const TargetInstrDesc &tid)
523   : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
524     MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
525   assert(MBB && "Cannot use inserting ctor with null basic block!");
526   NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
527   Operands.reserve(NumImplicitOps + TID->getNumOperands());
528   addImplicitDefUseOperands();
529   // Make sure that we get added to a machine basicblock
530   LeakDetector::addGarbageObject(this);
531   MBB->push_back(this);  // Add instruction to end of basic block!
532 }
533
534 /// MachineInstr ctor - Copies MachineInstr arg exactly
535 ///
536 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
537   : TID(&MI.getDesc()), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
538     MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
539     Parent(0), debugLoc(MI.getDebugLoc()) {
540   Operands.reserve(MI.getNumOperands());
541
542   // Add operands
543   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
544     addOperand(MI.getOperand(i));
545   NumImplicitOps = MI.NumImplicitOps;
546
547   // Copy all the flags.
548   Flags = MI.Flags;
549
550   // Set parent to null.
551   Parent = 0;
552
553   LeakDetector::addGarbageObject(this);
554 }
555
556 MachineInstr::~MachineInstr() {
557   LeakDetector::removeGarbageObject(this);
558 #ifndef NDEBUG
559   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
560     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
561     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
562            "Reg operand def/use list corrupted");
563   }
564 #endif
565 }
566
567 /// getRegInfo - If this instruction is embedded into a MachineFunction,
568 /// return the MachineRegisterInfo object for the current function, otherwise
569 /// return null.
570 MachineRegisterInfo *MachineInstr::getRegInfo() {
571   if (MachineBasicBlock *MBB = getParent())
572     return &MBB->getParent()->getRegInfo();
573   return 0;
574 }
575
576 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
577 /// this instruction from their respective use lists.  This requires that the
578 /// operands already be on their use lists.
579 void MachineInstr::RemoveRegOperandsFromUseLists() {
580   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
581     if (Operands[i].isReg())
582       Operands[i].RemoveRegOperandFromRegInfo();
583   }
584 }
585
586 /// AddRegOperandsToUseLists - Add all of the register operands in
587 /// this instruction from their respective use lists.  This requires that the
588 /// operands not be on their use lists yet.
589 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
590   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
591     if (Operands[i].isReg())
592       Operands[i].AddRegOperandToRegInfo(&RegInfo);
593   }
594 }
595
596
597 /// addOperand - Add the specified operand to the instruction.  If it is an
598 /// implicit operand, it is added to the end of the operand list.  If it is
599 /// an explicit operand it is added at the end of the explicit operand list
600 /// (before the first implicit operand). 
601 void MachineInstr::addOperand(const MachineOperand &Op) {
602   bool isImpReg = Op.isReg() && Op.isImplicit();
603   assert((isImpReg || !OperandsComplete()) &&
604          "Trying to add an operand to a machine instr that is already done!");
605
606   MachineRegisterInfo *RegInfo = getRegInfo();
607
608   // If we are adding the operand to the end of the list, our job is simpler.
609   // This is true most of the time, so this is a reasonable optimization.
610   if (isImpReg || NumImplicitOps == 0) {
611     // We can only do this optimization if we know that the operand list won't
612     // reallocate.
613     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
614       Operands.push_back(Op);
615     
616       // Set the parent of the operand.
617       Operands.back().ParentMI = this;
618   
619       // If the operand is a register, update the operand's use list.
620       if (Op.isReg()) {
621         Operands.back().AddRegOperandToRegInfo(RegInfo);
622         // If the register operand is flagged as early, mark the operand as such
623         unsigned OpNo = Operands.size() - 1;
624         if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
625           Operands[OpNo].setIsEarlyClobber(true);
626       }
627       return;
628     }
629   }
630   
631   // Otherwise, we have to insert a real operand before any implicit ones.
632   unsigned OpNo = Operands.size()-NumImplicitOps;
633
634   // If this instruction isn't embedded into a function, then we don't need to
635   // update any operand lists.
636   if (RegInfo == 0) {
637     // Simple insertion, no reginfo update needed for other register operands.
638     Operands.insert(Operands.begin()+OpNo, Op);
639     Operands[OpNo].ParentMI = this;
640
641     // Do explicitly set the reginfo for this operand though, to ensure the
642     // next/prev fields are properly nulled out.
643     if (Operands[OpNo].isReg()) {
644       Operands[OpNo].AddRegOperandToRegInfo(0);
645       // If the register operand is flagged as early, mark the operand as such
646       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
647         Operands[OpNo].setIsEarlyClobber(true);
648     }
649
650   } else if (Operands.size()+1 <= Operands.capacity()) {
651     // Otherwise, we have to remove register operands from their register use
652     // list, add the operand, then add the register operands back to their use
653     // list.  This also must handle the case when the operand list reallocates
654     // to somewhere else.
655   
656     // If insertion of this operand won't cause reallocation of the operand
657     // list, just remove the implicit operands, add the operand, then re-add all
658     // the rest of the operands.
659     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
660       assert(Operands[i].isReg() && "Should only be an implicit reg!");
661       Operands[i].RemoveRegOperandFromRegInfo();
662     }
663     
664     // Add the operand.  If it is a register, add it to the reg list.
665     Operands.insert(Operands.begin()+OpNo, Op);
666     Operands[OpNo].ParentMI = this;
667
668     if (Operands[OpNo].isReg()) {
669       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
670       // If the register operand is flagged as early, mark the operand as such
671       if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
672         Operands[OpNo].setIsEarlyClobber(true);
673     }
674     
675     // Re-add all the implicit ops.
676     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
677       assert(Operands[i].isReg() && "Should only be an implicit reg!");
678       Operands[i].AddRegOperandToRegInfo(RegInfo);
679     }
680   } else {
681     // Otherwise, we will be reallocating the operand list.  Remove all reg
682     // operands from their list, then readd them after the operand list is
683     // reallocated.
684     RemoveRegOperandsFromUseLists();
685     
686     Operands.insert(Operands.begin()+OpNo, Op);
687     Operands[OpNo].ParentMI = this;
688   
689     // Re-add all the operands.
690     AddRegOperandsToUseLists(*RegInfo);
691
692       // If the register operand is flagged as early, mark the operand as such
693     if (Operands[OpNo].isReg()
694         && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
695       Operands[OpNo].setIsEarlyClobber(true);
696   }
697 }
698
699 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
700 /// fewer operand than it started with.
701 ///
702 void MachineInstr::RemoveOperand(unsigned OpNo) {
703   assert(OpNo < Operands.size() && "Invalid operand number");
704   
705   // Special case removing the last one.
706   if (OpNo == Operands.size()-1) {
707     // If needed, remove from the reg def/use list.
708     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
709       Operands.back().RemoveRegOperandFromRegInfo();
710     
711     Operands.pop_back();
712     return;
713   }
714
715   // Otherwise, we are removing an interior operand.  If we have reginfo to
716   // update, remove all operands that will be shifted down from their reg lists,
717   // move everything down, then re-add them.
718   MachineRegisterInfo *RegInfo = getRegInfo();
719   if (RegInfo) {
720     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
721       if (Operands[i].isReg())
722         Operands[i].RemoveRegOperandFromRegInfo();
723     }
724   }
725   
726   Operands.erase(Operands.begin()+OpNo);
727
728   if (RegInfo) {
729     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
730       if (Operands[i].isReg())
731         Operands[i].AddRegOperandToRegInfo(RegInfo);
732     }
733   }
734 }
735
736 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
737 /// This function should be used only occasionally. The setMemRefs function
738 /// is the primary method for setting up a MachineInstr's MemRefs list.
739 void MachineInstr::addMemOperand(MachineFunction &MF,
740                                  MachineMemOperand *MO) {
741   mmo_iterator OldMemRefs = MemRefs;
742   mmo_iterator OldMemRefsEnd = MemRefsEnd;
743
744   size_t NewNum = (MemRefsEnd - MemRefs) + 1;
745   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
746   mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
747
748   std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
749   NewMemRefs[NewNum - 1] = MO;
750
751   MemRefs = NewMemRefs;
752   MemRefsEnd = NewMemRefsEnd;
753 }
754
755 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
756                                  MICheckType Check) const {
757   // If opcodes or number of operands are not the same then the two
758   // instructions are obviously not identical.
759   if (Other->getOpcode() != getOpcode() ||
760       Other->getNumOperands() != getNumOperands())
761     return false;
762
763   // Check operands to make sure they match.
764   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
765     const MachineOperand &MO = getOperand(i);
766     const MachineOperand &OMO = Other->getOperand(i);
767     // Clients may or may not want to ignore defs when testing for equality.
768     // For example, machine CSE pass only cares about finding common
769     // subexpressions, so it's safe to ignore virtual register defs.
770     if (Check != CheckDefs && MO.isReg() && MO.isDef()) {
771       if (Check == IgnoreDefs)
772         continue;
773       // Check == IgnoreVRegDefs
774       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
775           TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
776         if (MO.getReg() != OMO.getReg())
777           return false;
778     } else if (!MO.isIdenticalTo(OMO))
779       return false;
780   }
781   return true;
782 }
783
784 /// removeFromParent - This method unlinks 'this' from the containing basic
785 /// block, and returns it, but does not delete it.
786 MachineInstr *MachineInstr::removeFromParent() {
787   assert(getParent() && "Not embedded in a basic block!");
788   getParent()->remove(this);
789   return this;
790 }
791
792
793 /// eraseFromParent - This method unlinks 'this' from the containing basic
794 /// block, and deletes it.
795 void MachineInstr::eraseFromParent() {
796   assert(getParent() && "Not embedded in a basic block!");
797   getParent()->erase(this);
798 }
799
800
801 /// OperandComplete - Return true if it's illegal to add a new operand
802 ///
803 bool MachineInstr::OperandsComplete() const {
804   unsigned short NumOperands = TID->getNumOperands();
805   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
806     return true;  // Broken: we have all the operands of this instruction!
807   return false;
808 }
809
810 /// getNumExplicitOperands - Returns the number of non-implicit operands.
811 ///
812 unsigned MachineInstr::getNumExplicitOperands() const {
813   unsigned NumOperands = TID->getNumOperands();
814   if (!TID->isVariadic())
815     return NumOperands;
816
817   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
818     const MachineOperand &MO = getOperand(i);
819     if (!MO.isReg() || !MO.isImplicit())
820       NumOperands++;
821   }
822   return NumOperands;
823 }
824
825 bool MachineInstr::isStackAligningInlineAsm() const {
826   if (isInlineAsm()) {
827     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
828     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
829       return true;
830   }
831   return false;
832 }
833
834 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
835 /// the specific register or -1 if it is not found. It further tightens
836 /// the search criteria to a use that kills the register if isKill is true.
837 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
838                                           const TargetRegisterInfo *TRI) const {
839   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
840     const MachineOperand &MO = getOperand(i);
841     if (!MO.isReg() || !MO.isUse())
842       continue;
843     unsigned MOReg = MO.getReg();
844     if (!MOReg)
845       continue;
846     if (MOReg == Reg ||
847         (TRI &&
848          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
849          TargetRegisterInfo::isPhysicalRegister(Reg) &&
850          TRI->isSubRegister(MOReg, Reg)))
851       if (!isKill || MO.isKill())
852         return i;
853   }
854   return -1;
855 }
856
857 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
858 /// indicating if this instruction reads or writes Reg. This also considers
859 /// partial defines.
860 std::pair<bool,bool>
861 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
862                                          SmallVectorImpl<unsigned> *Ops) const {
863   bool PartDef = false; // Partial redefine.
864   bool FullDef = false; // Full define.
865   bool Use = false;
866
867   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
868     const MachineOperand &MO = getOperand(i);
869     if (!MO.isReg() || MO.getReg() != Reg)
870       continue;
871     if (Ops)
872       Ops->push_back(i);
873     if (MO.isUse())
874       Use |= !MO.isUndef();
875     else if (MO.getSubReg())
876       PartDef = true;
877     else
878       FullDef = true;
879   }
880   // A partial redefine uses Reg unless there is also a full define.
881   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
882 }
883
884 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
885 /// the specified register or -1 if it is not found. If isDead is true, defs
886 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
887 /// also checks if there is a def of a super-register.
888 int
889 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
890                                         const TargetRegisterInfo *TRI) const {
891   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
892   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
893     const MachineOperand &MO = getOperand(i);
894     if (!MO.isReg() || !MO.isDef())
895       continue;
896     unsigned MOReg = MO.getReg();
897     bool Found = (MOReg == Reg);
898     if (!Found && TRI && isPhys &&
899         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
900       if (Overlap)
901         Found = TRI->regsOverlap(MOReg, Reg);
902       else
903         Found = TRI->isSubRegister(MOReg, Reg);
904     }
905     if (Found && (!isDead || MO.isDead()))
906       return i;
907   }
908   return -1;
909 }
910
911 /// findFirstPredOperandIdx() - Find the index of the first operand in the
912 /// operand list that is used to represent the predicate. It returns -1 if
913 /// none is found.
914 int MachineInstr::findFirstPredOperandIdx() const {
915   const TargetInstrDesc &TID = getDesc();
916   if (TID.isPredicable()) {
917     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
918       if (TID.OpInfo[i].isPredicate())
919         return i;
920   }
921
922   return -1;
923 }
924   
925 /// isRegTiedToUseOperand - Given the index of a register def operand,
926 /// check if the register def is tied to a source operand, due to either
927 /// two-address elimination or inline assembly constraints. Returns the
928 /// first tied use operand index by reference is UseOpIdx is not null.
929 bool MachineInstr::
930 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
931   if (isInlineAsm()) {
932     assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
933     const MachineOperand &MO = getOperand(DefOpIdx);
934     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
935       return false;
936     // Determine the actual operand index that corresponds to this index.
937     unsigned DefNo = 0;
938     unsigned DefPart = 0;
939     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
940          i < e; ) {
941       const MachineOperand &FMO = getOperand(i);
942       // After the normal asm operands there may be additional imp-def regs.
943       if (!FMO.isImm())
944         return false;
945       // Skip over this def.
946       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
947       unsigned PrevDef = i + 1;
948       i = PrevDef + NumOps;
949       if (i > DefOpIdx) {
950         DefPart = DefOpIdx - PrevDef;
951         break;
952       }
953       ++DefNo;
954     }
955     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
956          i != e; ++i) {
957       const MachineOperand &FMO = getOperand(i);
958       if (!FMO.isImm())
959         continue;
960       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
961         continue;
962       unsigned Idx;
963       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
964           Idx == DefNo) {
965         if (UseOpIdx)
966           *UseOpIdx = (unsigned)i + 1 + DefPart;
967         return true;
968       }
969     }
970     return false;
971   }
972
973   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
974   const TargetInstrDesc &TID = getDesc();
975   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
976     const MachineOperand &MO = getOperand(i);
977     if (MO.isReg() && MO.isUse() &&
978         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
979       if (UseOpIdx)
980         *UseOpIdx = (unsigned)i;
981       return true;
982     }
983   }
984   return false;
985 }
986
987 /// isRegTiedToDefOperand - Return true if the operand of the specified index
988 /// is a register use and it is tied to an def operand. It also returns the def
989 /// operand index by reference.
990 bool MachineInstr::
991 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
992   if (isInlineAsm()) {
993     const MachineOperand &MO = getOperand(UseOpIdx);
994     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
995       return false;
996
997     // Find the flag operand corresponding to UseOpIdx
998     unsigned FlagIdx, NumOps=0;
999     for (FlagIdx = InlineAsm::MIOp_FirstOperand;
1000          FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
1001       const MachineOperand &UFMO = getOperand(FlagIdx);
1002       // After the normal asm operands there may be additional imp-def regs.
1003       if (!UFMO.isImm())
1004         return false;
1005       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
1006       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
1007       if (UseOpIdx < FlagIdx+NumOps+1)
1008         break;
1009     }
1010     if (FlagIdx >= UseOpIdx)
1011       return false;
1012     const MachineOperand &UFMO = getOperand(FlagIdx);
1013     unsigned DefNo;
1014     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1015       if (!DefOpIdx)
1016         return true;
1017
1018       unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1019       // Remember to adjust the index. First operand is asm string, second is
1020       // the HasSideEffects and AlignStack bits, then there is a flag for each.
1021       while (DefNo) {
1022         const MachineOperand &FMO = getOperand(DefIdx);
1023         assert(FMO.isImm());
1024         // Skip over this def.
1025         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1026         --DefNo;
1027       }
1028       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1029       return true;
1030     }
1031     return false;
1032   }
1033
1034   const TargetInstrDesc &TID = getDesc();
1035   if (UseOpIdx >= TID.getNumOperands())
1036     return false;
1037   const MachineOperand &MO = getOperand(UseOpIdx);
1038   if (!MO.isReg() || !MO.isUse())
1039     return false;
1040   int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
1041   if (DefIdx == -1)
1042     return false;
1043   if (DefOpIdx)
1044     *DefOpIdx = (unsigned)DefIdx;
1045   return true;
1046 }
1047
1048 /// clearKillInfo - Clears kill flags on all operands.
1049 ///
1050 void MachineInstr::clearKillInfo() {
1051   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1052     MachineOperand &MO = getOperand(i);
1053     if (MO.isReg() && MO.isUse())
1054       MO.setIsKill(false);
1055   }
1056 }
1057
1058 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1059 ///
1060 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1061   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1062     const MachineOperand &MO = MI->getOperand(i);
1063     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1064       continue;
1065     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1066       MachineOperand &MOp = getOperand(j);
1067       if (!MOp.isIdenticalTo(MO))
1068         continue;
1069       if (MO.isKill())
1070         MOp.setIsKill();
1071       else
1072         MOp.setIsDead();
1073       break;
1074     }
1075   }
1076 }
1077
1078 /// copyPredicates - Copies predicate operand(s) from MI.
1079 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1080   const TargetInstrDesc &TID = MI->getDesc();
1081   if (!TID.isPredicable())
1082     return;
1083   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1084     if (TID.OpInfo[i].isPredicate()) {
1085       // Predicated operands must be last operands.
1086       addOperand(MI->getOperand(i));
1087     }
1088   }
1089 }
1090
1091 void MachineInstr::substituteRegister(unsigned FromReg,
1092                                       unsigned ToReg,
1093                                       unsigned SubIdx,
1094                                       const TargetRegisterInfo &RegInfo) {
1095   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1096     if (SubIdx)
1097       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1098     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1099       MachineOperand &MO = getOperand(i);
1100       if (!MO.isReg() || MO.getReg() != FromReg)
1101         continue;
1102       MO.substPhysReg(ToReg, RegInfo);
1103     }
1104   } else {
1105     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1106       MachineOperand &MO = getOperand(i);
1107       if (!MO.isReg() || MO.getReg() != FromReg)
1108         continue;
1109       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1110     }
1111   }
1112 }
1113
1114 /// isSafeToMove - Return true if it is safe to move this instruction. If
1115 /// SawStore is set to true, it means that there is a store (or call) between
1116 /// the instruction's location and its intended destination.
1117 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1118                                 AliasAnalysis *AA,
1119                                 bool &SawStore) const {
1120   // Ignore stuff that we obviously can't move.
1121   if (TID->mayStore() || TID->isCall()) {
1122     SawStore = true;
1123     return false;
1124   }
1125
1126   if (isLabel() || isDebugValue() ||
1127       TID->isTerminator() || hasUnmodeledSideEffects())
1128     return false;
1129
1130   // See if this instruction does a load.  If so, we have to guarantee that the
1131   // loaded value doesn't change between the load and the its intended
1132   // destination. The check for isInvariantLoad gives the targe the chance to
1133   // classify the load as always returning a constant, e.g. a constant pool
1134   // load.
1135   if (TID->mayLoad() && !isInvariantLoad(AA))
1136     // Otherwise, this is a real load.  If there is a store between the load and
1137     // end of block, or if the load is volatile, we can't move it.
1138     return !SawStore && !hasVolatileMemoryRef();
1139
1140   return true;
1141 }
1142
1143 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1144 /// instruction which defined the specified register instead of copying it.
1145 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1146                                  AliasAnalysis *AA,
1147                                  unsigned DstReg) const {
1148   bool SawStore = false;
1149   if (!TII->isTriviallyReMaterializable(this, AA) ||
1150       !isSafeToMove(TII, AA, SawStore))
1151     return false;
1152   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1153     const MachineOperand &MO = getOperand(i);
1154     if (!MO.isReg())
1155       continue;
1156     // FIXME: For now, do not remat any instruction with register operands.
1157     // Later on, we can loosen the restriction is the register operands have
1158     // not been modified between the def and use. Note, this is different from
1159     // MachineSink because the code is no longer in two-address form (at least
1160     // partially).
1161     if (MO.isUse())
1162       return false;
1163     else if (!MO.isDead() && MO.getReg() != DstReg)
1164       return false;
1165   }
1166   return true;
1167 }
1168
1169 /// hasVolatileMemoryRef - Return true if this instruction may have a
1170 /// volatile memory reference, or if the information describing the
1171 /// memory reference is not available. Return false if it is known to
1172 /// have no volatile memory references.
1173 bool MachineInstr::hasVolatileMemoryRef() const {
1174   // An instruction known never to access memory won't have a volatile access.
1175   if (!TID->mayStore() &&
1176       !TID->mayLoad() &&
1177       !TID->isCall() &&
1178       !hasUnmodeledSideEffects())
1179     return false;
1180
1181   // Otherwise, if the instruction has no memory reference information,
1182   // conservatively assume it wasn't preserved.
1183   if (memoperands_empty())
1184     return true;
1185   
1186   // Check the memory reference information for volatile references.
1187   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1188     if ((*I)->isVolatile())
1189       return true;
1190
1191   return false;
1192 }
1193
1194 /// isInvariantLoad - Return true if this instruction is loading from a
1195 /// location whose value is invariant across the function.  For example,
1196 /// loading a value from the constant pool or from the argument area
1197 /// of a function if it does not change.  This should only return true of
1198 /// *all* loads the instruction does are invariant (if it does multiple loads).
1199 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1200   // If the instruction doesn't load at all, it isn't an invariant load.
1201   if (!TID->mayLoad())
1202     return false;
1203
1204   // If the instruction has lost its memoperands, conservatively assume that
1205   // it may not be an invariant load.
1206   if (memoperands_empty())
1207     return false;
1208
1209   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1210
1211   for (mmo_iterator I = memoperands_begin(),
1212        E = memoperands_end(); I != E; ++I) {
1213     if ((*I)->isVolatile()) return false;
1214     if ((*I)->isStore()) return false;
1215
1216     if (const Value *V = (*I)->getValue()) {
1217       // A load from a constant PseudoSourceValue is invariant.
1218       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1219         if (PSV->isConstant(MFI))
1220           continue;
1221       // If we have an AliasAnalysis, ask it whether the memory is constant.
1222       if (AA && AA->pointsToConstantMemory(
1223                       AliasAnalysis::Location(V, (*I)->getSize(),
1224                                               (*I)->getTBAAInfo())))
1225         continue;
1226     }
1227
1228     // Otherwise assume conservatively.
1229     return false;
1230   }
1231
1232   // Everything checks out.
1233   return true;
1234 }
1235
1236 /// isConstantValuePHI - If the specified instruction is a PHI that always
1237 /// merges together the same virtual register, return the register, otherwise
1238 /// return 0.
1239 unsigned MachineInstr::isConstantValuePHI() const {
1240   if (!isPHI())
1241     return 0;
1242   assert(getNumOperands() >= 3 &&
1243          "It's illegal to have a PHI without source operands");
1244
1245   unsigned Reg = getOperand(1).getReg();
1246   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1247     if (getOperand(i).getReg() != Reg)
1248       return 0;
1249   return Reg;
1250 }
1251
1252 bool MachineInstr::hasUnmodeledSideEffects() const {
1253   if (getDesc().hasUnmodeledSideEffects())
1254     return true;
1255   if (isInlineAsm()) {
1256     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1257     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1258       return true;
1259   }
1260
1261   return false;
1262 }
1263
1264 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1265 ///
1266 bool MachineInstr::allDefsAreDead() const {
1267   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1268     const MachineOperand &MO = getOperand(i);
1269     if (!MO.isReg() || MO.isUse())
1270       continue;
1271     if (!MO.isDead())
1272       return false;
1273   }
1274   return true;
1275 }
1276
1277 /// copyImplicitOps - Copy implicit register operands from specified
1278 /// instruction to this instruction.
1279 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1280   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1281        i != e; ++i) {
1282     const MachineOperand &MO = MI->getOperand(i);
1283     if (MO.isReg() && MO.isImplicit())
1284       addOperand(MO);
1285   }
1286 }
1287
1288 void MachineInstr::dump() const {
1289   dbgs() << "  " << *this;
1290 }
1291
1292 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF, 
1293                          raw_ostream &CommentOS) {
1294   const LLVMContext &Ctx = MF->getFunction()->getContext();
1295   if (!DL.isUnknown()) {          // Print source line info.
1296     DIScope Scope(DL.getScope(Ctx));
1297     // Omit the directory, because it's likely to be long and uninteresting.
1298     if (Scope.Verify())
1299       CommentOS << Scope.getFilename();
1300     else
1301       CommentOS << "<unknown>";
1302     CommentOS << ':' << DL.getLine();
1303     if (DL.getCol() != 0)
1304       CommentOS << ':' << DL.getCol();
1305     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1306     if (!InlinedAtDL.isUnknown()) {
1307       CommentOS << " @[ ";
1308       printDebugLoc(InlinedAtDL, MF, CommentOS);
1309       CommentOS << " ]";
1310     }
1311   }
1312 }
1313
1314 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1315   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1316   const MachineFunction *MF = 0;
1317   const MachineRegisterInfo *MRI = 0;
1318   if (const MachineBasicBlock *MBB = getParent()) {
1319     MF = MBB->getParent();
1320     if (!TM && MF)
1321       TM = &MF->getTarget();
1322     if (MF)
1323       MRI = &MF->getRegInfo();
1324   }
1325
1326   // Save a list of virtual registers.
1327   SmallVector<unsigned, 8> VirtRegs;
1328
1329   // Print explicitly defined operands on the left of an assignment syntax.
1330   unsigned StartOp = 0, e = getNumOperands();
1331   for (; StartOp < e && getOperand(StartOp).isReg() &&
1332          getOperand(StartOp).isDef() &&
1333          !getOperand(StartOp).isImplicit();
1334        ++StartOp) {
1335     if (StartOp != 0) OS << ", ";
1336     getOperand(StartOp).print(OS, TM);
1337     unsigned Reg = getOperand(StartOp).getReg();
1338     if (TargetRegisterInfo::isVirtualRegister(Reg))
1339       VirtRegs.push_back(Reg);
1340   }
1341
1342   if (StartOp != 0)
1343     OS << " = ";
1344
1345   // Print the opcode name.
1346   OS << getDesc().getName();
1347
1348   // Print the rest of the operands.
1349   bool OmittedAnyCallClobbers = false;
1350   bool FirstOp = true;
1351
1352   if (isInlineAsm()) {
1353     // Print asm string.
1354     OS << " ";
1355     getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1356
1357     // Print HasSideEffects, IsAlignStack
1358     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1359     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1360       OS << " [sideeffect]";
1361     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1362       OS << " [alignstack]";
1363
1364     StartOp = InlineAsm::MIOp_FirstOperand;
1365     FirstOp = false;
1366   }
1367
1368
1369   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1370     const MachineOperand &MO = getOperand(i);
1371
1372     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1373       VirtRegs.push_back(MO.getReg());
1374
1375     // Omit call-clobbered registers which aren't used anywhere. This makes
1376     // call instructions much less noisy on targets where calls clobber lots
1377     // of registers. Don't rely on MO.isDead() because we may be called before
1378     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1379     if (MF && getDesc().isCall() &&
1380         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1381       unsigned Reg = MO.getReg();
1382       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1383         const MachineRegisterInfo &MRI = MF->getRegInfo();
1384         if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1385           bool HasAliasLive = false;
1386           for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1387                unsigned AliasReg = *Alias; ++Alias)
1388             if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1389               HasAliasLive = true;
1390               break;
1391             }
1392           if (!HasAliasLive) {
1393             OmittedAnyCallClobbers = true;
1394             continue;
1395           }
1396         }
1397       }
1398     }
1399
1400     if (FirstOp) FirstOp = false; else OS << ",";
1401     OS << " ";
1402     if (i < getDesc().NumOperands) {
1403       const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1404       if (TOI.isPredicate())
1405         OS << "pred:";
1406       if (TOI.isOptionalDef())
1407         OS << "opt:";
1408     }
1409     if (isDebugValue() && MO.isMetadata()) {
1410       // Pretty print DBG_VALUE instructions.
1411       const MDNode *MD = MO.getMetadata();
1412       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1413         OS << "!\"" << MDS->getString() << '\"';
1414       else
1415         MO.print(OS, TM);
1416     } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1417       OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1418     } else
1419       MO.print(OS, TM);
1420   }
1421
1422   // Briefly indicate whether any call clobbers were omitted.
1423   if (OmittedAnyCallClobbers) {
1424     if (!FirstOp) OS << ",";
1425     OS << " ...";
1426   }
1427
1428   bool HaveSemi = false;
1429   if (Flags) {
1430     if (!HaveSemi) OS << ";"; HaveSemi = true;
1431     OS << " flags: ";
1432
1433     if (Flags & FrameSetup)
1434       OS << "FrameSetup";
1435   }
1436
1437   if (!memoperands_empty()) {
1438     if (!HaveSemi) OS << ";"; HaveSemi = true;
1439
1440     OS << " mem:";
1441     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1442          i != e; ++i) {
1443       OS << **i;
1444       if (llvm::next(i) != e)
1445         OS << " ";
1446     }
1447   }
1448
1449   // Print the regclass of any virtual registers encountered.
1450   if (MRI && !VirtRegs.empty()) {
1451     if (!HaveSemi) OS << ";"; HaveSemi = true;
1452     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1453       const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1454       OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1455       for (unsigned j = i+1; j != VirtRegs.size();) {
1456         if (MRI->getRegClass(VirtRegs[j]) != RC) {
1457           ++j;
1458           continue;
1459         }
1460         if (VirtRegs[i] != VirtRegs[j])
1461           OS << "," << PrintReg(VirtRegs[j]);
1462         VirtRegs.erase(VirtRegs.begin()+j);
1463       }
1464     }
1465   }
1466
1467   // Print debug location information.
1468   if (!debugLoc.isUnknown() && MF) {
1469     if (!HaveSemi) OS << ";"; HaveSemi = true;
1470     OS << " dbg:";
1471     printDebugLoc(debugLoc, MF, OS);
1472   }
1473
1474   OS << '\n';
1475 }
1476
1477 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1478                                      const TargetRegisterInfo *RegInfo,
1479                                      bool AddIfNotFound) {
1480   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1481   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1482   bool Found = false;
1483   SmallVector<unsigned,4> DeadOps;
1484   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1485     MachineOperand &MO = getOperand(i);
1486     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1487       continue;
1488     unsigned Reg = MO.getReg();
1489     if (!Reg)
1490       continue;
1491
1492     if (Reg == IncomingReg) {
1493       if (!Found) {
1494         if (MO.isKill())
1495           // The register is already marked kill.
1496           return true;
1497         if (isPhysReg && isRegTiedToDefOperand(i))
1498           // Two-address uses of physregs must not be marked kill.
1499           return true;
1500         MO.setIsKill();
1501         Found = true;
1502       }
1503     } else if (hasAliases && MO.isKill() &&
1504                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1505       // A super-register kill already exists.
1506       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1507         return true;
1508       if (RegInfo->isSubRegister(IncomingReg, Reg))
1509         DeadOps.push_back(i);
1510     }
1511   }
1512
1513   // Trim unneeded kill operands.
1514   while (!DeadOps.empty()) {
1515     unsigned OpIdx = DeadOps.back();
1516     if (getOperand(OpIdx).isImplicit())
1517       RemoveOperand(OpIdx);
1518     else
1519       getOperand(OpIdx).setIsKill(false);
1520     DeadOps.pop_back();
1521   }
1522
1523   // If not found, this means an alias of one of the operands is killed. Add a
1524   // new implicit operand if required.
1525   if (!Found && AddIfNotFound) {
1526     addOperand(MachineOperand::CreateReg(IncomingReg,
1527                                          false /*IsDef*/,
1528                                          true  /*IsImp*/,
1529                                          true  /*IsKill*/));
1530     return true;
1531   }
1532   return Found;
1533 }
1534
1535 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1536                                    const TargetRegisterInfo *RegInfo,
1537                                    bool AddIfNotFound) {
1538   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1539   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1540   bool Found = false;
1541   SmallVector<unsigned,4> DeadOps;
1542   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1543     MachineOperand &MO = getOperand(i);
1544     if (!MO.isReg() || !MO.isDef())
1545       continue;
1546     unsigned Reg = MO.getReg();
1547     if (!Reg)
1548       continue;
1549
1550     if (Reg == IncomingReg) {
1551       MO.setIsDead();
1552       Found = true;
1553     } else if (hasAliases && MO.isDead() &&
1554                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1555       // There exists a super-register that's marked dead.
1556       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1557         return true;
1558       if (RegInfo->getSubRegisters(IncomingReg) &&
1559           RegInfo->getSuperRegisters(Reg) &&
1560           RegInfo->isSubRegister(IncomingReg, Reg))
1561         DeadOps.push_back(i);
1562     }
1563   }
1564
1565   // Trim unneeded dead operands.
1566   while (!DeadOps.empty()) {
1567     unsigned OpIdx = DeadOps.back();
1568     if (getOperand(OpIdx).isImplicit())
1569       RemoveOperand(OpIdx);
1570     else
1571       getOperand(OpIdx).setIsDead(false);
1572     DeadOps.pop_back();
1573   }
1574
1575   // If not found, this means an alias of one of the operands is dead. Add a
1576   // new implicit operand if required.
1577   if (Found || !AddIfNotFound)
1578     return Found;
1579     
1580   addOperand(MachineOperand::CreateReg(IncomingReg,
1581                                        true  /*IsDef*/,
1582                                        true  /*IsImp*/,
1583                                        false /*IsKill*/,
1584                                        true  /*IsDead*/));
1585   return true;
1586 }
1587
1588 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1589                                       const TargetRegisterInfo *RegInfo) {
1590   if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1591     MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1592     if (MO)
1593       return;
1594   } else {
1595     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1596       const MachineOperand &MO = getOperand(i);
1597       if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1598           MO.getSubReg() == 0)
1599         return;
1600     }
1601   }
1602   addOperand(MachineOperand::CreateReg(IncomingReg,
1603                                        true  /*IsDef*/,
1604                                        true  /*IsImp*/));
1605 }
1606
1607 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1608                                          const TargetRegisterInfo &TRI) {
1609   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1610     MachineOperand &MO = getOperand(i);
1611     if (!MO.isReg() || !MO.isDef()) continue;
1612     unsigned Reg = MO.getReg();
1613     if (Reg == 0) continue;
1614     bool Dead = true;
1615     for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1616          E = UsedRegs.end(); I != E; ++I)
1617       if (TRI.regsOverlap(*I, Reg)) {
1618         Dead = false;
1619         break;
1620       }
1621     // If there are no uses, including partial uses, the def is dead.
1622     if (Dead) MO.setIsDead();
1623   }
1624 }
1625
1626 unsigned
1627 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1628   unsigned Hash = MI->getOpcode() * 37;
1629   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1630     const MachineOperand &MO = MI->getOperand(i);
1631     uint64_t Key = (uint64_t)MO.getType() << 32;
1632     switch (MO.getType()) {
1633     default: break;
1634     case MachineOperand::MO_Register:
1635       if (MO.isDef() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1636         continue;  // Skip virtual register defs.
1637       Key |= MO.getReg();
1638       break;
1639     case MachineOperand::MO_Immediate:
1640       Key |= MO.getImm();
1641       break;
1642     case MachineOperand::MO_FrameIndex:
1643     case MachineOperand::MO_ConstantPoolIndex:
1644     case MachineOperand::MO_JumpTableIndex:
1645       Key |= MO.getIndex();
1646       break;
1647     case MachineOperand::MO_MachineBasicBlock:
1648       Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1649       break;
1650     case MachineOperand::MO_GlobalAddress:
1651       Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1652       break;
1653     case MachineOperand::MO_BlockAddress:
1654       Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1655       break;
1656     case MachineOperand::MO_MCSymbol:
1657       Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1658       break;
1659     }
1660     Key += ~(Key << 32);
1661     Key ^= (Key >> 22);
1662     Key += ~(Key << 13);
1663     Key ^= (Key >> 8);
1664     Key += (Key << 3);
1665     Key ^= (Key >> 15);
1666     Key += ~(Key << 27);
1667     Key ^= (Key >> 31);
1668     Hash = (unsigned)Key + Hash * 37;
1669   }
1670   return Hash;
1671 }