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