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