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