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