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