LLVM API Documentation

MachineInstr.cpp
Go to the documentation of this file.
00001 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Methods common to all machine instructions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/MachineInstr.h"
00015 #include "llvm/ADT/FoldingSet.h"
00016 #include "llvm/ADT/Hashing.h"
00017 #include "llvm/Analysis/AliasAnalysis.h"
00018 #include "llvm/Assembly/Writer.h"
00019 #include "llvm/CodeGen/MachineConstantPool.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineMemOperand.h"
00022 #include "llvm/CodeGen/MachineModuleInfo.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/PseudoSourceValue.h"
00025 #include "llvm/DebugInfo.h"
00026 #include "llvm/IR/Constants.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/InlineAsm.h"
00029 #include "llvm/IR/LLVMContext.h"
00030 #include "llvm/IR/Metadata.h"
00031 #include "llvm/IR/Module.h"
00032 #include "llvm/IR/Type.h"
00033 #include "llvm/IR/Value.h"
00034 #include "llvm/MC/MCInstrDesc.h"
00035 #include "llvm/MC/MCSymbol.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/MathExtras.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include "llvm/Target/TargetInstrInfo.h"
00041 #include "llvm/Target/TargetMachine.h"
00042 #include "llvm/Target/TargetRegisterInfo.h"
00043 using namespace llvm;
00044 
00045 //===----------------------------------------------------------------------===//
00046 // MachineOperand Implementation
00047 //===----------------------------------------------------------------------===//
00048 
00049 void MachineOperand::setReg(unsigned Reg) {
00050   if (getReg() == Reg) return; // No change.
00051 
00052   // Otherwise, we have to change the register.  If this operand is embedded
00053   // into a machine function, we need to update the old and new register's
00054   // use/def lists.
00055   if (MachineInstr *MI = getParent())
00056     if (MachineBasicBlock *MBB = MI->getParent())
00057       if (MachineFunction *MF = MBB->getParent()) {
00058         MachineRegisterInfo &MRI = MF->getRegInfo();
00059         MRI.removeRegOperandFromUseList(this);
00060         SmallContents.RegNo = Reg;
00061         MRI.addRegOperandToUseList(this);
00062         return;
00063       }
00064 
00065   // Otherwise, just change the register, no problem.  :)
00066   SmallContents.RegNo = Reg;
00067 }
00068 
00069 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
00070                                   const TargetRegisterInfo &TRI) {
00071   assert(TargetRegisterInfo::isVirtualRegister(Reg));
00072   if (SubIdx && getSubReg())
00073     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
00074   setReg(Reg);
00075   if (SubIdx)
00076     setSubReg(SubIdx);
00077 }
00078 
00079 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
00080   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
00081   if (getSubReg()) {
00082     Reg = TRI.getSubReg(Reg, getSubReg());
00083     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
00084     // That won't happen in legal code.
00085     setSubReg(0);
00086   }
00087   setReg(Reg);
00088 }
00089 
00090 /// Change a def to a use, or a use to a def.
00091 void MachineOperand::setIsDef(bool Val) {
00092   assert(isReg() && "Wrong MachineOperand accessor");
00093   assert((!Val || !isDebug()) && "Marking a debug operation as def");
00094   if (IsDef == Val)
00095     return;
00096   // MRI may keep uses and defs in different list positions.
00097   if (MachineInstr *MI = getParent())
00098     if (MachineBasicBlock *MBB = MI->getParent())
00099       if (MachineFunction *MF = MBB->getParent()) {
00100         MachineRegisterInfo &MRI = MF->getRegInfo();
00101         MRI.removeRegOperandFromUseList(this);
00102         IsDef = Val;
00103         MRI.addRegOperandToUseList(this);
00104         return;
00105       }
00106   IsDef = Val;
00107 }
00108 
00109 /// ChangeToImmediate - Replace this operand with a new immediate operand of
00110 /// the specified value.  If an operand is known to be an immediate already,
00111 /// the setImm method should be used.
00112 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
00113   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
00114   // If this operand is currently a register operand, and if this is in a
00115   // function, deregister the operand from the register's use/def list.
00116   if (isReg() && isOnRegUseList())
00117     if (MachineInstr *MI = getParent())
00118       if (MachineBasicBlock *MBB = MI->getParent())
00119         if (MachineFunction *MF = MBB->getParent())
00120           MF->getRegInfo().removeRegOperandFromUseList(this);
00121 
00122   OpKind = MO_Immediate;
00123   Contents.ImmVal = ImmVal;
00124 }
00125 
00126 /// ChangeToRegister - Replace this operand with a new register operand of
00127 /// the specified value.  If an operand is known to be an register already,
00128 /// the setReg method should be used.
00129 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
00130                                       bool isKill, bool isDead, bool isUndef,
00131                                       bool isDebug) {
00132   MachineRegisterInfo *RegInfo = 0;
00133   if (MachineInstr *MI = getParent())
00134     if (MachineBasicBlock *MBB = MI->getParent())
00135       if (MachineFunction *MF = MBB->getParent())
00136         RegInfo = &MF->getRegInfo();
00137   // If this operand is already a register operand, remove it from the
00138   // register's use/def lists.
00139   bool WasReg = isReg();
00140   if (RegInfo && WasReg)
00141     RegInfo->removeRegOperandFromUseList(this);
00142 
00143   // Change this to a register and set the reg#.
00144   OpKind = MO_Register;
00145   SmallContents.RegNo = Reg;
00146   SubReg_TargetFlags = 0;
00147   IsDef = isDef;
00148   IsImp = isImp;
00149   IsKill = isKill;
00150   IsDead = isDead;
00151   IsUndef = isUndef;
00152   IsInternalRead = false;
00153   IsEarlyClobber = false;
00154   IsDebug = isDebug;
00155   // Ensure isOnRegUseList() returns false.
00156   Contents.Reg.Prev = 0;
00157   // Preserve the tie when the operand was already a register.
00158   if (!WasReg)
00159     TiedTo = 0;
00160 
00161   // If this operand is embedded in a function, add the operand to the
00162   // register's use/def list.
00163   if (RegInfo)
00164     RegInfo->addRegOperandToUseList(this);
00165 }
00166 
00167 /// isIdenticalTo - Return true if this operand is identical to the specified
00168 /// operand. Note that this should stay in sync with the hash_value overload
00169 /// below.
00170 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
00171   if (getType() != Other.getType() ||
00172       getTargetFlags() != Other.getTargetFlags())
00173     return false;
00174 
00175   switch (getType()) {
00176   case MachineOperand::MO_Register:
00177     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
00178            getSubReg() == Other.getSubReg();
00179   case MachineOperand::MO_Immediate:
00180     return getImm() == Other.getImm();
00181   case MachineOperand::MO_CImmediate:
00182     return getCImm() == Other.getCImm();
00183   case MachineOperand::MO_FPImmediate:
00184     return getFPImm() == Other.getFPImm();
00185   case MachineOperand::MO_MachineBasicBlock:
00186     return getMBB() == Other.getMBB();
00187   case MachineOperand::MO_FrameIndex:
00188     return getIndex() == Other.getIndex();
00189   case MachineOperand::MO_ConstantPoolIndex:
00190   case MachineOperand::MO_TargetIndex:
00191     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
00192   case MachineOperand::MO_JumpTableIndex:
00193     return getIndex() == Other.getIndex();
00194   case MachineOperand::MO_GlobalAddress:
00195     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
00196   case MachineOperand::MO_ExternalSymbol:
00197     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
00198            getOffset() == Other.getOffset();
00199   case MachineOperand::MO_BlockAddress:
00200     return getBlockAddress() == Other.getBlockAddress() &&
00201            getOffset() == Other.getOffset();
00202   case MO_RegisterMask:
00203     return getRegMask() == Other.getRegMask();
00204   case MachineOperand::MO_MCSymbol:
00205     return getMCSymbol() == Other.getMCSymbol();
00206   case MachineOperand::MO_Metadata:
00207     return getMetadata() == Other.getMetadata();
00208   }
00209   llvm_unreachable("Invalid machine operand type");
00210 }
00211 
00212 // Note: this must stay exactly in sync with isIdenticalTo above.
00213 hash_code llvm::hash_value(const MachineOperand &MO) {
00214   switch (MO.getType()) {
00215   case MachineOperand::MO_Register:
00216     // Register operands don't have target flags.
00217     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
00218   case MachineOperand::MO_Immediate:
00219     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
00220   case MachineOperand::MO_CImmediate:
00221     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
00222   case MachineOperand::MO_FPImmediate:
00223     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
00224   case MachineOperand::MO_MachineBasicBlock:
00225     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
00226   case MachineOperand::MO_FrameIndex:
00227     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
00228   case MachineOperand::MO_ConstantPoolIndex:
00229   case MachineOperand::MO_TargetIndex:
00230     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
00231                         MO.getOffset());
00232   case MachineOperand::MO_JumpTableIndex:
00233     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
00234   case MachineOperand::MO_ExternalSymbol:
00235     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
00236                         MO.getSymbolName());
00237   case MachineOperand::MO_GlobalAddress:
00238     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
00239                         MO.getOffset());
00240   case MachineOperand::MO_BlockAddress:
00241     return hash_combine(MO.getType(), MO.getTargetFlags(),
00242                         MO.getBlockAddress(), MO.getOffset());
00243   case MachineOperand::MO_RegisterMask:
00244     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
00245   case MachineOperand::MO_Metadata:
00246     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
00247   case MachineOperand::MO_MCSymbol:
00248     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
00249   }
00250   llvm_unreachable("Invalid machine operand type");
00251 }
00252 
00253 /// print - Print the specified machine operand.
00254 ///
00255 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
00256   // If the instruction is embedded into a basic block, we can find the
00257   // target info for the instruction.
00258   if (!TM)
00259     if (const MachineInstr *MI = getParent())
00260       if (const MachineBasicBlock *MBB = MI->getParent())
00261         if (const MachineFunction *MF = MBB->getParent())
00262           TM = &MF->getTarget();
00263   const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
00264 
00265   switch (getType()) {
00266   case MachineOperand::MO_Register:
00267     OS << PrintReg(getReg(), TRI, getSubReg());
00268 
00269     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
00270         isInternalRead() || isEarlyClobber() || isTied()) {
00271       OS << '<';
00272       bool NeedComma = false;
00273       if (isDef()) {
00274         if (NeedComma) OS << ',';
00275         if (isEarlyClobber())
00276           OS << "earlyclobber,";
00277         if (isImplicit())
00278           OS << "imp-";
00279         OS << "def";
00280         NeedComma = true;
00281         // <def,read-undef> only makes sense when getSubReg() is set.
00282         // Don't clutter the output otherwise.
00283         if (isUndef() && getSubReg())
00284           OS << ",read-undef";
00285       } else if (isImplicit()) {
00286           OS << "imp-use";
00287           NeedComma = true;
00288       }
00289 
00290       if (isKill()) {
00291         if (NeedComma) OS << ',';
00292         OS << "kill";
00293         NeedComma = true;
00294       }
00295       if (isDead()) {
00296         if (NeedComma) OS << ',';
00297         OS << "dead";
00298         NeedComma = true;
00299       }
00300       if (isUndef() && isUse()) {
00301         if (NeedComma) OS << ',';
00302         OS << "undef";
00303         NeedComma = true;
00304       }
00305       if (isInternalRead()) {
00306         if (NeedComma) OS << ',';
00307         OS << "internal";
00308         NeedComma = true;
00309       }
00310       if (isTied()) {
00311         if (NeedComma) OS << ',';
00312         OS << "tied";
00313         if (TiedTo != 15)
00314           OS << unsigned(TiedTo - 1);
00315         NeedComma = true;
00316       }
00317       OS << '>';
00318     }
00319     break;
00320   case MachineOperand::MO_Immediate:
00321     OS << getImm();
00322     break;
00323   case MachineOperand::MO_CImmediate:
00324     getCImm()->getValue().print(OS, false);
00325     break;
00326   case MachineOperand::MO_FPImmediate:
00327     if (getFPImm()->getType()->isFloatTy())
00328       OS << getFPImm()->getValueAPF().convertToFloat();
00329     else
00330       OS << getFPImm()->getValueAPF().convertToDouble();
00331     break;
00332   case MachineOperand::MO_MachineBasicBlock:
00333     OS << "<BB#" << getMBB()->getNumber() << ">";
00334     break;
00335   case MachineOperand::MO_FrameIndex:
00336     OS << "<fi#" << getIndex() << '>';
00337     break;
00338   case MachineOperand::MO_ConstantPoolIndex:
00339     OS << "<cp#" << getIndex();
00340     if (getOffset()) OS << "+" << getOffset();
00341     OS << '>';
00342     break;
00343   case MachineOperand::MO_TargetIndex:
00344     OS << "<ti#" << getIndex();
00345     if (getOffset()) OS << "+" << getOffset();
00346     OS << '>';
00347     break;
00348   case MachineOperand::MO_JumpTableIndex:
00349     OS << "<jt#" << getIndex() << '>';
00350     break;
00351   case MachineOperand::MO_GlobalAddress:
00352     OS << "<ga:";
00353     WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
00354     if (getOffset()) OS << "+" << getOffset();
00355     OS << '>';
00356     break;
00357   case MachineOperand::MO_ExternalSymbol:
00358     OS << "<es:" << getSymbolName();
00359     if (getOffset()) OS << "+" << getOffset();
00360     OS << '>';
00361     break;
00362   case MachineOperand::MO_BlockAddress:
00363     OS << '<';
00364     WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
00365     if (getOffset()) OS << "+" << getOffset();
00366     OS << '>';
00367     break;
00368   case MachineOperand::MO_RegisterMask:
00369     OS << "<regmask>";
00370     break;
00371   case MachineOperand::MO_Metadata:
00372     OS << '<';
00373     WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
00374     OS << '>';
00375     break;
00376   case MachineOperand::MO_MCSymbol:
00377     OS << "<MCSym=" << *getMCSymbol() << '>';
00378     break;
00379   }
00380 
00381   if (unsigned TF = getTargetFlags())
00382     OS << "[TF=" << TF << ']';
00383 }
00384 
00385 //===----------------------------------------------------------------------===//
00386 // MachineMemOperand Implementation
00387 //===----------------------------------------------------------------------===//
00388 
00389 /// getAddrSpace - Return the LLVM IR address space number that this pointer
00390 /// points into.
00391 unsigned MachinePointerInfo::getAddrSpace() const {
00392   if (V == 0) return 0;
00393   return cast<PointerType>(V->getType())->getAddressSpace();
00394 }
00395 
00396 /// getConstantPool - Return a MachinePointerInfo record that refers to the
00397 /// constant pool.
00398 MachinePointerInfo MachinePointerInfo::getConstantPool() {
00399   return MachinePointerInfo(PseudoSourceValue::getConstantPool());
00400 }
00401 
00402 /// getFixedStack - Return a MachinePointerInfo record that refers to the
00403 /// the specified FrameIndex.
00404 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
00405   return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
00406 }
00407 
00408 MachinePointerInfo MachinePointerInfo::getJumpTable() {
00409   return MachinePointerInfo(PseudoSourceValue::getJumpTable());
00410 }
00411 
00412 MachinePointerInfo MachinePointerInfo::getGOT() {
00413   return MachinePointerInfo(PseudoSourceValue::getGOT());
00414 }
00415 
00416 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
00417   return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
00418 }
00419 
00420 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
00421                                      uint64_t s, unsigned int a,
00422                                      const MDNode *TBAAInfo,
00423                                      const MDNode *Ranges)
00424   : PtrInfo(ptrinfo), Size(s),
00425     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
00426     TBAAInfo(TBAAInfo), Ranges(Ranges) {
00427   assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
00428          "invalid pointer value");
00429   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
00430   assert((isLoad() || isStore()) && "Not a load/store!");
00431 }
00432 
00433 /// Profile - Gather unique data for the object.
00434 ///
00435 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
00436   ID.AddInteger(getOffset());
00437   ID.AddInteger(Size);
00438   ID.AddPointer(getValue());
00439   ID.AddInteger(Flags);
00440 }
00441 
00442 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
00443   // The Value and Offset may differ due to CSE. But the flags and size
00444   // should be the same.
00445   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
00446   assert(MMO->getSize() == getSize() && "Size mismatch!");
00447 
00448   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
00449     // Update the alignment value.
00450     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
00451       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
00452     // Also update the base and offset, because the new alignment may
00453     // not be applicable with the old ones.
00454     PtrInfo = MMO->PtrInfo;
00455   }
00456 }
00457 
00458 /// getAlignment - Return the minimum known alignment in bytes of the
00459 /// actual memory reference.
00460 uint64_t MachineMemOperand::getAlignment() const {
00461   return MinAlign(getBaseAlignment(), getOffset());
00462 }
00463 
00464 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
00465   assert((MMO.isLoad() || MMO.isStore()) &&
00466          "SV has to be a load, store or both.");
00467 
00468   if (MMO.isVolatile())
00469     OS << "Volatile ";
00470 
00471   if (MMO.isLoad())
00472     OS << "LD";
00473   if (MMO.isStore())
00474     OS << "ST";
00475   OS << MMO.getSize();
00476 
00477   // Print the address information.
00478   OS << "[";
00479   if (!MMO.getValue())
00480     OS << "<unknown>";
00481   else
00482     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
00483 
00484   // If the alignment of the memory reference itself differs from the alignment
00485   // of the base pointer, print the base alignment explicitly, next to the base
00486   // pointer.
00487   if (MMO.getBaseAlignment() != MMO.getAlignment())
00488     OS << "(align=" << MMO.getBaseAlignment() << ")";
00489 
00490   if (MMO.getOffset() != 0)
00491     OS << "+" << MMO.getOffset();
00492   OS << "]";
00493 
00494   // Print the alignment of the reference.
00495   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
00496       MMO.getBaseAlignment() != MMO.getSize())
00497     OS << "(align=" << MMO.getAlignment() << ")";
00498 
00499   // Print TBAA info.
00500   if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
00501     OS << "(tbaa=";
00502     if (TBAAInfo->getNumOperands() > 0)
00503       WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
00504     else
00505       OS << "<unknown>";
00506     OS << ")";
00507   }
00508 
00509   // Print nontemporal info.
00510   if (MMO.isNonTemporal())
00511     OS << "(nontemporal)";
00512 
00513   return OS;
00514 }
00515 
00516 //===----------------------------------------------------------------------===//
00517 // MachineInstr Implementation
00518 //===----------------------------------------------------------------------===//
00519 
00520 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
00521   if (MCID->ImplicitDefs)
00522     for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
00523       addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
00524   if (MCID->ImplicitUses)
00525     for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
00526       addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
00527 }
00528 
00529 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
00530 /// implicit operands. It reserves space for the number of operands specified by
00531 /// the MCInstrDesc.
00532 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
00533                            const DebugLoc dl, bool NoImp)
00534   : MCID(&tid), Parent(0), Operands(0), NumOperands(0),
00535     Flags(0), AsmPrinterFlags(0),
00536     NumMemRefs(0), MemRefs(0), debugLoc(dl) {
00537   // Reserve space for the expected number of operands.
00538   if (unsigned NumOps = MCID->getNumOperands() +
00539     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
00540     CapOperands = OperandCapacity::get(NumOps);
00541     Operands = MF.allocateOperandArray(CapOperands);
00542   }
00543 
00544   if (!NoImp)
00545     addImplicitDefUseOperands(MF);
00546 }
00547 
00548 /// MachineInstr ctor - Copies MachineInstr arg exactly
00549 ///
00550 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
00551   : MCID(&MI.getDesc()), Parent(0), Operands(0), NumOperands(0),
00552     Flags(0), AsmPrinterFlags(0),
00553     NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
00554     debugLoc(MI.getDebugLoc()) {
00555   CapOperands = OperandCapacity::get(MI.getNumOperands());
00556   Operands = MF.allocateOperandArray(CapOperands);
00557 
00558   // Copy operands.
00559   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
00560     addOperand(MF, MI.getOperand(i));
00561 
00562   // Copy all the sensible flags.
00563   setFlags(MI.Flags);
00564 }
00565 
00566 /// getRegInfo - If this instruction is embedded into a MachineFunction,
00567 /// return the MachineRegisterInfo object for the current function, otherwise
00568 /// return null.
00569 MachineRegisterInfo *MachineInstr::getRegInfo() {
00570   if (MachineBasicBlock *MBB = getParent())
00571     return &MBB->getParent()->getRegInfo();
00572   return 0;
00573 }
00574 
00575 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
00576 /// this instruction from their respective use lists.  This requires that the
00577 /// operands already be on their use lists.
00578 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
00579   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00580     if (Operands[i].isReg())
00581       MRI.removeRegOperandFromUseList(&Operands[i]);
00582 }
00583 
00584 /// AddRegOperandsToUseLists - Add all of the register operands in
00585 /// this instruction from their respective use lists.  This requires that the
00586 /// operands not be on their use lists yet.
00587 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
00588   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00589     if (Operands[i].isReg())
00590       MRI.addRegOperandToUseList(&Operands[i]);
00591 }
00592 
00593 void MachineInstr::addOperand(const MachineOperand &Op) {
00594   MachineBasicBlock *MBB = getParent();
00595   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
00596   MachineFunction *MF = MBB->getParent();
00597   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
00598   addOperand(*MF, Op);
00599 }
00600 
00601 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
00602 /// ranges. If MRI is non-null also update use-def chains.
00603 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
00604                          unsigned NumOps, MachineRegisterInfo *MRI) {
00605   if (MRI)
00606     return MRI->moveOperands(Dst, Src, NumOps);
00607 
00608   // Here it would be convenient to call memmove, so that isn't allowed because
00609   // MachineOperand has a constructor and so isn't a POD type.
00610   if (Dst < Src)
00611     for (unsigned i = 0; i != NumOps; ++i)
00612       new (Dst + i) MachineOperand(Src[i]);
00613   else
00614     for (unsigned i = NumOps; i ; --i)
00615       new (Dst + i - 1) MachineOperand(Src[i - 1]);
00616 }
00617 
00618 /// addOperand - Add the specified operand to the instruction.  If it is an
00619 /// implicit operand, it is added to the end of the operand list.  If it is
00620 /// an explicit operand it is added at the end of the explicit operand list
00621 /// (before the first implicit operand).
00622 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
00623   assert(MCID && "Cannot add operands before providing an instr descriptor");
00624 
00625   // Check if we're adding one of our existing operands.
00626   if (&Op >= Operands && &Op < Operands + NumOperands) {
00627     // This is unusual: MI->addOperand(MI->getOperand(i)).
00628     // If adding Op requires reallocating or moving existing operands around,
00629     // the Op reference could go stale. Support it by copying Op.
00630     MachineOperand CopyOp(Op);
00631     return addOperand(MF, CopyOp);
00632   }
00633 
00634   // Find the insert location for the new operand.  Implicit registers go at
00635   // the end, everything else goes before the implicit regs.
00636   //
00637   // FIXME: Allow mixed explicit and implicit operands on inline asm.
00638   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
00639   // implicit-defs, but they must not be moved around.  See the FIXME in
00640   // InstrEmitter.cpp.
00641   unsigned OpNo = getNumOperands();
00642   bool isImpReg = Op.isReg() && Op.isImplicit();
00643   if (!isImpReg && !isInlineAsm()) {
00644     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
00645       --OpNo;
00646       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
00647     }
00648   }
00649 
00650   // OpNo now points as the desired insertion point.  Unless this is a variadic
00651   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
00652   // RegMask operands go between the explicit and implicit operands.
00653   assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
00654           OpNo < MCID->getNumOperands()) &&
00655          "Trying to add an operand to a machine instr that is already done!");
00656 
00657   MachineRegisterInfo *MRI = getRegInfo();
00658 
00659   // Determine if the Operands array needs to be reallocated.
00660   // Save the old capacity and operand array.
00661   OperandCapacity OldCap = CapOperands;
00662   MachineOperand *OldOperands = Operands;
00663   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
00664     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
00665     Operands = MF.allocateOperandArray(CapOperands);
00666     // Move the operands before the insertion point.
00667     if (OpNo)
00668       moveOperands(Operands, OldOperands, OpNo, MRI);
00669   }
00670 
00671   // Move the operands following the insertion point.
00672   if (OpNo != NumOperands)
00673     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
00674                  MRI);
00675   ++NumOperands;
00676 
00677   // Deallocate the old operand array.
00678   if (OldOperands != Operands && OldOperands)
00679     MF.deallocateOperandArray(OldCap, OldOperands);
00680 
00681   // Copy Op into place. It still needs to be inserted into the MRI use lists.
00682   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
00683   NewMO->ParentMI = this;
00684 
00685   // When adding a register operand, tell MRI about it.
00686   if (NewMO->isReg()) {
00687     // Ensure isOnRegUseList() returns false, regardless of Op's status.
00688     NewMO->Contents.Reg.Prev = 0;
00689     // Ignore existing ties. This is not a property that can be copied.
00690     NewMO->TiedTo = 0;
00691     // Add the new operand to MRI, but only for instructions in an MBB.
00692     if (MRI)
00693       MRI->addRegOperandToUseList(NewMO);
00694     // The MCID operand information isn't accurate until we start adding
00695     // explicit operands. The implicit operands are added first, then the
00696     // explicits are inserted before them.
00697     if (!isImpReg) {
00698       // Tie uses to defs as indicated in MCInstrDesc.
00699       if (NewMO->isUse()) {
00700         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
00701         if (DefIdx != -1)
00702           tieOperands(DefIdx, OpNo);
00703       }
00704       // If the register operand is flagged as early, mark the operand as such.
00705       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
00706         NewMO->setIsEarlyClobber(true);
00707     }
00708   }
00709 }
00710 
00711 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
00712 /// fewer operand than it started with.
00713 ///
00714 void MachineInstr::RemoveOperand(unsigned OpNo) {
00715   assert(OpNo < getNumOperands() && "Invalid operand number");
00716   untieRegOperand(OpNo);
00717 
00718 #ifndef NDEBUG
00719   // Moving tied operands would break the ties.
00720   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
00721     if (Operands[i].isReg())
00722       assert(!Operands[i].isTied() && "Cannot move tied operands");
00723 #endif
00724 
00725   MachineRegisterInfo *MRI = getRegInfo();
00726   if (MRI && Operands[OpNo].isReg())
00727     MRI->removeRegOperandFromUseList(Operands + OpNo);
00728 
00729   // Don't call the MachineOperand destructor. A lot of this code depends on
00730   // MachineOperand having a trivial destructor anyway, and adding a call here
00731   // wouldn't make it 'destructor-correct'.
00732 
00733   if (unsigned N = NumOperands - 1 - OpNo)
00734     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
00735   --NumOperands;
00736 }
00737 
00738 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
00739 /// This function should be used only occasionally. The setMemRefs function
00740 /// is the primary method for setting up a MachineInstr's MemRefs list.
00741 void MachineInstr::addMemOperand(MachineFunction &MF,
00742                                  MachineMemOperand *MO) {
00743   mmo_iterator OldMemRefs = MemRefs;
00744   unsigned OldNumMemRefs = NumMemRefs;
00745 
00746   unsigned NewNum = NumMemRefs + 1;
00747   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
00748 
00749   std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
00750   NewMemRefs[NewNum - 1] = MO;
00751   setMemRefs(NewMemRefs, NewMemRefs + NewNum);
00752 }
00753 
00754 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
00755   assert(!isBundledWithPred() && "Must be called on bundle header");
00756   for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
00757     if (MII->getDesc().getFlags() & Mask) {
00758       if (Type == AnyInBundle)
00759         return true;
00760     } else {
00761       if (Type == AllInBundle && !MII->isBundle())
00762         return false;
00763     }
00764     // This was the last instruction in the bundle.
00765     if (!MII->isBundledWithSucc())
00766       return Type == AllInBundle;
00767   }
00768 }
00769 
00770 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
00771                                  MICheckType Check) const {
00772   // If opcodes or number of operands are not the same then the two
00773   // instructions are obviously not identical.
00774   if (Other->getOpcode() != getOpcode() ||
00775       Other->getNumOperands() != getNumOperands())
00776     return false;
00777 
00778   if (isBundle()) {
00779     // Both instructions are bundles, compare MIs inside the bundle.
00780     MachineBasicBlock::const_instr_iterator I1 = *this;
00781     MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
00782     MachineBasicBlock::const_instr_iterator I2 = *Other;
00783     MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
00784     while (++I1 != E1 && I1->isInsideBundle()) {
00785       ++I2;
00786       if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
00787         return false;
00788     }
00789   }
00790 
00791   // Check operands to make sure they match.
00792   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00793     const MachineOperand &MO = getOperand(i);
00794     const MachineOperand &OMO = Other->getOperand(i);
00795     if (!MO.isReg()) {
00796       if (!MO.isIdenticalTo(OMO))
00797         return false;
00798       continue;
00799     }
00800 
00801     // Clients may or may not want to ignore defs when testing for equality.
00802     // For example, machine CSE pass only cares about finding common
00803     // subexpressions, so it's safe to ignore virtual register defs.
00804     if (MO.isDef()) {
00805       if (Check == IgnoreDefs)
00806         continue;
00807       else if (Check == IgnoreVRegDefs) {
00808         if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
00809             TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
00810           if (MO.getReg() != OMO.getReg())
00811             return false;
00812       } else {
00813         if (!MO.isIdenticalTo(OMO))
00814           return false;
00815         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
00816           return false;
00817       }
00818     } else {
00819       if (!MO.isIdenticalTo(OMO))
00820         return false;
00821       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
00822         return false;
00823     }
00824   }
00825   // If DebugLoc does not match then two dbg.values are not identical.
00826   if (isDebugValue())
00827     if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
00828         && getDebugLoc() != Other->getDebugLoc())
00829       return false;
00830   return true;
00831 }
00832 
00833 MachineInstr *MachineInstr::removeFromParent() {
00834   assert(getParent() && "Not embedded in a basic block!");
00835   return getParent()->remove(this);
00836 }
00837 
00838 MachineInstr *MachineInstr::removeFromBundle() {
00839   assert(getParent() && "Not embedded in a basic block!");
00840   return getParent()->remove_instr(this);
00841 }
00842 
00843 void MachineInstr::eraseFromParent() {
00844   assert(getParent() && "Not embedded in a basic block!");
00845   getParent()->erase(this);
00846 }
00847 
00848 void MachineInstr::eraseFromBundle() {
00849   assert(getParent() && "Not embedded in a basic block!");
00850   getParent()->erase_instr(this);
00851 }
00852 
00853 /// getNumExplicitOperands - Returns the number of non-implicit operands.
00854 ///
00855 unsigned MachineInstr::getNumExplicitOperands() const {
00856   unsigned NumOperands = MCID->getNumOperands();
00857   if (!MCID->isVariadic())
00858     return NumOperands;
00859 
00860   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
00861     const MachineOperand &MO = getOperand(i);
00862     if (!MO.isReg() || !MO.isImplicit())
00863       NumOperands++;
00864   }
00865   return NumOperands;
00866 }
00867 
00868 void MachineInstr::bundleWithPred() {
00869   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
00870   setFlag(BundledPred);
00871   MachineBasicBlock::instr_iterator Pred = this;
00872   --Pred;
00873   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
00874   Pred->setFlag(BundledSucc);
00875 }
00876 
00877 void MachineInstr::bundleWithSucc() {
00878   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
00879   setFlag(BundledSucc);
00880   MachineBasicBlock::instr_iterator Succ = this;
00881   ++Succ;
00882   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
00883   Succ->setFlag(BundledPred);
00884 }
00885 
00886 void MachineInstr::unbundleFromPred() {
00887   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
00888   clearFlag(BundledPred);
00889   MachineBasicBlock::instr_iterator Pred = this;
00890   --Pred;
00891   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
00892   Pred->clearFlag(BundledSucc);
00893 }
00894 
00895 void MachineInstr::unbundleFromSucc() {
00896   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
00897   clearFlag(BundledSucc);
00898   MachineBasicBlock::instr_iterator Succ = this;
00899   ++Succ;
00900   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
00901   Succ->clearFlag(BundledPred);
00902 }
00903 
00904 bool MachineInstr::isStackAligningInlineAsm() const {
00905   if (isInlineAsm()) {
00906     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
00907     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
00908       return true;
00909   }
00910   return false;
00911 }
00912 
00913 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
00914   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
00915   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
00916   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
00917 }
00918 
00919 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
00920                                        unsigned *GroupNo) const {
00921   assert(isInlineAsm() && "Expected an inline asm instruction");
00922   assert(OpIdx < getNumOperands() && "OpIdx out of range");
00923 
00924   // Ignore queries about the initial operands.
00925   if (OpIdx < InlineAsm::MIOp_FirstOperand)
00926     return -1;
00927 
00928   unsigned Group = 0;
00929   unsigned NumOps;
00930   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
00931        i += NumOps) {
00932     const MachineOperand &FlagMO = getOperand(i);
00933     // If we reach the implicit register operands, stop looking.
00934     if (!FlagMO.isImm())
00935       return -1;
00936     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
00937     if (i + NumOps > OpIdx) {
00938       if (GroupNo)
00939         *GroupNo = Group;
00940       return i;
00941     }
00942     ++Group;
00943   }
00944   return -1;
00945 }
00946 
00947 const TargetRegisterClass*
00948 MachineInstr::getRegClassConstraint(unsigned OpIdx,
00949                                     const TargetInstrInfo *TII,
00950                                     const TargetRegisterInfo *TRI) const {
00951   assert(getParent() && "Can't have an MBB reference here!");
00952   assert(getParent()->getParent() && "Can't have an MF reference here!");
00953   const MachineFunction &MF = *getParent()->getParent();
00954 
00955   // Most opcodes have fixed constraints in their MCInstrDesc.
00956   if (!isInlineAsm())
00957     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
00958 
00959   if (!getOperand(OpIdx).isReg())
00960     return NULL;
00961 
00962   // For tied uses on inline asm, get the constraint from the def.
00963   unsigned DefIdx;
00964   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
00965     OpIdx = DefIdx;
00966 
00967   // Inline asm stores register class constraints in the flag word.
00968   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
00969   if (FlagIdx < 0)
00970     return NULL;
00971 
00972   unsigned Flag = getOperand(FlagIdx).getImm();
00973   unsigned RCID;
00974   if (InlineAsm::hasRegClassConstraint(Flag, RCID))
00975     return TRI->getRegClass(RCID);
00976 
00977   // Assume that all registers in a memory operand are pointers.
00978   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
00979     return TRI->getPointerRegClass(MF);
00980 
00981   return NULL;
00982 }
00983 
00984 /// Return the number of instructions inside the MI bundle, not counting the
00985 /// header instruction.
00986 unsigned MachineInstr::getBundleSize() const {
00987   MachineBasicBlock::const_instr_iterator I = this;
00988   unsigned Size = 0;
00989   while (I->isBundledWithSucc())
00990     ++Size, ++I;
00991   return Size;
00992 }
00993 
00994 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
00995 /// the specific register or -1 if it is not found. It further tightens
00996 /// the search criteria to a use that kills the register if isKill is true.
00997 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
00998                                           const TargetRegisterInfo *TRI) const {
00999   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01000     const MachineOperand &MO = getOperand(i);
01001     if (!MO.isReg() || !MO.isUse())
01002       continue;
01003     unsigned MOReg = MO.getReg();
01004     if (!MOReg)
01005       continue;
01006     if (MOReg == Reg ||
01007         (TRI &&
01008          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
01009          TargetRegisterInfo::isPhysicalRegister(Reg) &&
01010          TRI->isSubRegister(MOReg, Reg)))
01011       if (!isKill || MO.isKill())
01012         return i;
01013   }
01014   return -1;
01015 }
01016 
01017 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
01018 /// indicating if this instruction reads or writes Reg. This also considers
01019 /// partial defines.
01020 std::pair<bool,bool>
01021 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
01022                                          SmallVectorImpl<unsigned> *Ops) const {
01023   bool PartDef = false; // Partial redefine.
01024   bool FullDef = false; // Full define.
01025   bool Use = false;
01026 
01027   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01028     const MachineOperand &MO = getOperand(i);
01029     if (!MO.isReg() || MO.getReg() != Reg)
01030       continue;
01031     if (Ops)
01032       Ops->push_back(i);
01033     if (MO.isUse())
01034       Use |= !MO.isUndef();
01035     else if (MO.getSubReg() && !MO.isUndef())
01036       // A partial <def,undef> doesn't count as reading the register.
01037       PartDef = true;
01038     else
01039       FullDef = true;
01040   }
01041   // A partial redefine uses Reg unless there is also a full define.
01042   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
01043 }
01044 
01045 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
01046 /// the specified register or -1 if it is not found. If isDead is true, defs
01047 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
01048 /// also checks if there is a def of a super-register.
01049 int
01050 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
01051                                         const TargetRegisterInfo *TRI) const {
01052   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
01053   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01054     const MachineOperand &MO = getOperand(i);
01055     // Accept regmask operands when Overlap is set.
01056     // Ignore them when looking for a specific def operand (Overlap == false).
01057     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
01058       return i;
01059     if (!MO.isReg() || !MO.isDef())
01060       continue;
01061     unsigned MOReg = MO.getReg();
01062     bool Found = (MOReg == Reg);
01063     if (!Found && TRI && isPhys &&
01064         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
01065       if (Overlap)
01066         Found = TRI->regsOverlap(MOReg, Reg);
01067       else
01068         Found = TRI->isSubRegister(MOReg, Reg);
01069     }
01070     if (Found && (!isDead || MO.isDead()))
01071       return i;
01072   }
01073   return -1;
01074 }
01075 
01076 /// findFirstPredOperandIdx() - Find the index of the first operand in the
01077 /// operand list that is used to represent the predicate. It returns -1 if
01078 /// none is found.
01079 int MachineInstr::findFirstPredOperandIdx() const {
01080   // Don't call MCID.findFirstPredOperandIdx() because this variant
01081   // is sometimes called on an instruction that's not yet complete, and
01082   // so the number of operands is less than the MCID indicates. In
01083   // particular, the PTX target does this.
01084   const MCInstrDesc &MCID = getDesc();
01085   if (MCID.isPredicable()) {
01086     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01087       if (MCID.OpInfo[i].isPredicate())
01088         return i;
01089   }
01090 
01091   return -1;
01092 }
01093 
01094 // MachineOperand::TiedTo is 4 bits wide.
01095 const unsigned TiedMax = 15;
01096 
01097 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
01098 ///
01099 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
01100 /// field. TiedTo can have these values:
01101 ///
01102 /// 0:              Operand is not tied to anything.
01103 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
01104 /// TiedMax:        Tied to an operand >= TiedMax-1.
01105 ///
01106 /// The tied def must be one of the first TiedMax operands on a normal
01107 /// instruction. INLINEASM instructions allow more tied defs.
01108 ///
01109 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
01110   MachineOperand &DefMO = getOperand(DefIdx);
01111   MachineOperand &UseMO = getOperand(UseIdx);
01112   assert(DefMO.isDef() && "DefIdx must be a def operand");
01113   assert(UseMO.isUse() && "UseIdx must be a use operand");
01114   assert(!DefMO.isTied() && "Def is already tied to another use");
01115   assert(!UseMO.isTied() && "Use is already tied to another def");
01116 
01117   if (DefIdx < TiedMax)
01118     UseMO.TiedTo = DefIdx + 1;
01119   else {
01120     // Inline asm can use the group descriptors to find tied operands, but on
01121     // normal instruction, the tied def must be within the first TiedMax
01122     // operands.
01123     assert(isInlineAsm() && "DefIdx out of range");
01124     UseMO.TiedTo = TiedMax;
01125   }
01126 
01127   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
01128   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
01129 }
01130 
01131 /// Given the index of a tied register operand, find the operand it is tied to.
01132 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
01133 /// which must exist.
01134 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
01135   const MachineOperand &MO = getOperand(OpIdx);
01136   assert(MO.isTied() && "Operand isn't tied");
01137 
01138   // Normally TiedTo is in range.
01139   if (MO.TiedTo < TiedMax)
01140     return MO.TiedTo - 1;
01141 
01142   // Uses on normal instructions can be out of range.
01143   if (!isInlineAsm()) {
01144     // Normal tied defs must be in the 0..TiedMax-1 range.
01145     if (MO.isUse())
01146       return TiedMax - 1;
01147     // MO is a def. Search for the tied use.
01148     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
01149       const MachineOperand &UseMO = getOperand(i);
01150       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
01151         return i;
01152     }
01153     llvm_unreachable("Can't find tied use");
01154   }
01155 
01156   // Now deal with inline asm by parsing the operand group descriptor flags.
01157   // Find the beginning of each operand group.
01158   SmallVector<unsigned, 8> GroupIdx;
01159   unsigned OpIdxGroup = ~0u;
01160   unsigned NumOps;
01161   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
01162        i += NumOps) {
01163     const MachineOperand &FlagMO = getOperand(i);
01164     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
01165     unsigned CurGroup = GroupIdx.size();
01166     GroupIdx.push_back(i);
01167     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
01168     // OpIdx belongs to this operand group.
01169     if (OpIdx > i && OpIdx < i + NumOps)
01170       OpIdxGroup = CurGroup;
01171     unsigned TiedGroup;
01172     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
01173       continue;
01174     // Operands in this group are tied to operands in TiedGroup which must be
01175     // earlier. Find the number of operands between the two groups.
01176     unsigned Delta = i - GroupIdx[TiedGroup];
01177 
01178     // OpIdx is a use tied to TiedGroup.
01179     if (OpIdxGroup == CurGroup)
01180       return OpIdx - Delta;
01181 
01182     // OpIdx is a def tied to this use group.
01183     if (OpIdxGroup == TiedGroup)
01184       return OpIdx + Delta;
01185   }
01186   llvm_unreachable("Invalid tied operand on inline asm");
01187 }
01188 
01189 /// clearKillInfo - Clears kill flags on all operands.
01190 ///
01191 void MachineInstr::clearKillInfo() {
01192   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01193     MachineOperand &MO = getOperand(i);
01194     if (MO.isReg() && MO.isUse())
01195       MO.setIsKill(false);
01196   }
01197 }
01198 
01199 void MachineInstr::substituteRegister(unsigned FromReg,
01200                                       unsigned ToReg,
01201                                       unsigned SubIdx,
01202                                       const TargetRegisterInfo &RegInfo) {
01203   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
01204     if (SubIdx)
01205       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
01206     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01207       MachineOperand &MO = getOperand(i);
01208       if (!MO.isReg() || MO.getReg() != FromReg)
01209         continue;
01210       MO.substPhysReg(ToReg, RegInfo);
01211     }
01212   } else {
01213     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01214       MachineOperand &MO = getOperand(i);
01215       if (!MO.isReg() || MO.getReg() != FromReg)
01216         continue;
01217       MO.substVirtReg(ToReg, SubIdx, RegInfo);
01218     }
01219   }
01220 }
01221 
01222 /// isSafeToMove - Return true if it is safe to move this instruction. If
01223 /// SawStore is set to true, it means that there is a store (or call) between
01224 /// the instruction's location and its intended destination.
01225 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
01226                                 AliasAnalysis *AA,
01227                                 bool &SawStore) const {
01228   // Ignore stuff that we obviously can't move.
01229   //
01230   // Treat volatile loads as stores. This is not strictly necessary for
01231   // volatiles, but it is required for atomic loads. It is not allowed to move
01232   // a load across an atomic load with Ordering > Monotonic.
01233   if (mayStore() || isCall() ||
01234       (mayLoad() && hasOrderedMemoryRef())) {
01235     SawStore = true;
01236     return false;
01237   }
01238 
01239   if (isLabel() || isDebugValue() ||
01240       isTerminator() || hasUnmodeledSideEffects())
01241     return false;
01242 
01243   // See if this instruction does a load.  If so, we have to guarantee that the
01244   // loaded value doesn't change between the load and the its intended
01245   // destination. The check for isInvariantLoad gives the targe the chance to
01246   // classify the load as always returning a constant, e.g. a constant pool
01247   // load.
01248   if (mayLoad() && !isInvariantLoad(AA))
01249     // Otherwise, this is a real load.  If there is a store between the load and
01250     // end of block, we can't move it.
01251     return !SawStore;
01252 
01253   return true;
01254 }
01255 
01256 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
01257 /// instruction which defined the specified register instead of copying it.
01258 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
01259                                  AliasAnalysis *AA,
01260                                  unsigned DstReg) const {
01261   bool SawStore = false;
01262   if (!TII->isTriviallyReMaterializable(this, AA) ||
01263       !isSafeToMove(TII, AA, SawStore))
01264     return false;
01265   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01266     const MachineOperand &MO = getOperand(i);
01267     if (!MO.isReg())
01268       continue;
01269     // FIXME: For now, do not remat any instruction with register operands.
01270     // Later on, we can loosen the restriction is the register operands have
01271     // not been modified between the def and use. Note, this is different from
01272     // MachineSink because the code is no longer in two-address form (at least
01273     // partially).
01274     if (MO.isUse())
01275       return false;
01276     else if (!MO.isDead() && MO.getReg() != DstReg)
01277       return false;
01278   }
01279   return true;
01280 }
01281 
01282 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
01283 /// or volatile memory reference, or if the information describing the memory
01284 /// reference is not available. Return false if it is known to have no ordered
01285 /// memory references.
01286 bool MachineInstr::hasOrderedMemoryRef() const {
01287   // An instruction known never to access memory won't have a volatile access.
01288   if (!mayStore() &&
01289       !mayLoad() &&
01290       !isCall() &&
01291       !hasUnmodeledSideEffects())
01292     return false;
01293 
01294   // Otherwise, if the instruction has no memory reference information,
01295   // conservatively assume it wasn't preserved.
01296   if (memoperands_empty())
01297     return true;
01298 
01299   // Check the memory reference information for ordered references.
01300   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
01301     if (!(*I)->isUnordered())
01302       return true;
01303 
01304   return false;
01305 }
01306 
01307 /// isInvariantLoad - Return true if this instruction is loading from a
01308 /// location whose value is invariant across the function.  For example,
01309 /// loading a value from the constant pool or from the argument area
01310 /// of a function if it does not change.  This should only return true of
01311 /// *all* loads the instruction does are invariant (if it does multiple loads).
01312 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
01313   // If the instruction doesn't load at all, it isn't an invariant load.
01314   if (!mayLoad())
01315     return false;
01316 
01317   // If the instruction has lost its memoperands, conservatively assume that
01318   // it may not be an invariant load.
01319   if (memoperands_empty())
01320     return false;
01321 
01322   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
01323 
01324   for (mmo_iterator I = memoperands_begin(),
01325        E = memoperands_end(); I != E; ++I) {
01326     if ((*I)->isVolatile()) return false;
01327     if ((*I)->isStore()) return false;
01328     if ((*I)->isInvariant()) return true;
01329 
01330     if (const Value *V = (*I)->getValue()) {
01331       // A load from a constant PseudoSourceValue is invariant.
01332       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
01333         if (PSV->isConstant(MFI))
01334           continue;
01335       // If we have an AliasAnalysis, ask it whether the memory is constant.
01336       if (AA && AA->pointsToConstantMemory(
01337                       AliasAnalysis::Location(V, (*I)->getSize(),
01338                                               (*I)->getTBAAInfo())))
01339         continue;
01340     }
01341 
01342     // Otherwise assume conservatively.
01343     return false;
01344   }
01345 
01346   // Everything checks out.
01347   return true;
01348 }
01349 
01350 /// isConstantValuePHI - If the specified instruction is a PHI that always
01351 /// merges together the same virtual register, return the register, otherwise
01352 /// return 0.
01353 unsigned MachineInstr::isConstantValuePHI() const {
01354   if (!isPHI())
01355     return 0;
01356   assert(getNumOperands() >= 3 &&
01357          "It's illegal to have a PHI without source operands");
01358 
01359   unsigned Reg = getOperand(1).getReg();
01360   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
01361     if (getOperand(i).getReg() != Reg)
01362       return 0;
01363   return Reg;
01364 }
01365 
01366 bool MachineInstr::hasUnmodeledSideEffects() const {
01367   if (hasProperty(MCID::UnmodeledSideEffects))
01368     return true;
01369   if (isInlineAsm()) {
01370     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
01371     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
01372       return true;
01373   }
01374 
01375   return false;
01376 }
01377 
01378 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
01379 ///
01380 bool MachineInstr::allDefsAreDead() const {
01381   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
01382     const MachineOperand &MO = getOperand(i);
01383     if (!MO.isReg() || MO.isUse())
01384       continue;
01385     if (!MO.isDead())
01386       return false;
01387   }
01388   return true;
01389 }
01390 
01391 /// copyImplicitOps - Copy implicit register operands from specified
01392 /// instruction to this instruction.
01393 void MachineInstr::copyImplicitOps(MachineFunction &MF,
01394                                    const MachineInstr *MI) {
01395   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
01396        i != e; ++i) {
01397     const MachineOperand &MO = MI->getOperand(i);
01398     if (MO.isReg() && MO.isImplicit())
01399       addOperand(MF, MO);
01400   }
01401 }
01402 
01403 void MachineInstr::dump() const {
01404 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01405   dbgs() << "  " << *this;
01406 #endif
01407 }
01408 
01409 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
01410                          raw_ostream &CommentOS) {
01411   const LLVMContext &Ctx = MF->getFunction()->getContext();
01412   if (!DL.isUnknown()) {          // Print source line info.
01413     DIScope Scope(DL.getScope(Ctx));
01414     // Omit the directory, because it's likely to be long and uninteresting.
01415     if (Scope.Verify())
01416       CommentOS << Scope.getFilename();
01417     else
01418       CommentOS << "<unknown>";
01419     CommentOS << ':' << DL.getLine();
01420     if (DL.getCol() != 0)
01421       CommentOS << ':' << DL.getCol();
01422     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
01423     if (!InlinedAtDL.isUnknown()) {
01424       CommentOS << " @[ ";
01425       printDebugLoc(InlinedAtDL, MF, CommentOS);
01426       CommentOS << " ]";
01427     }
01428   }
01429 }
01430 
01431 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
01432                          bool SkipOpers) const {
01433   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
01434   const MachineFunction *MF = 0;
01435   const MachineRegisterInfo *MRI = 0;
01436   if (const MachineBasicBlock *MBB = getParent()) {
01437     MF = MBB->getParent();
01438     if (!TM && MF)
01439       TM = &MF->getTarget();
01440     if (MF)
01441       MRI = &MF->getRegInfo();
01442   }
01443 
01444   // Save a list of virtual registers.
01445   SmallVector<unsigned, 8> VirtRegs;
01446 
01447   // Print explicitly defined operands on the left of an assignment syntax.
01448   unsigned StartOp = 0, e = getNumOperands();
01449   for (; StartOp < e && getOperand(StartOp).isReg() &&
01450          getOperand(StartOp).isDef() &&
01451          !getOperand(StartOp).isImplicit();
01452        ++StartOp) {
01453     if (StartOp != 0) OS << ", ";
01454     getOperand(StartOp).print(OS, TM);
01455     unsigned Reg = getOperand(StartOp).getReg();
01456     if (TargetRegisterInfo::isVirtualRegister(Reg))
01457       VirtRegs.push_back(Reg);
01458   }
01459 
01460   if (StartOp != 0)
01461     OS << " = ";
01462 
01463   // Print the opcode name.
01464   if (TM && TM->getInstrInfo())
01465     OS << TM->getInstrInfo()->getName(getOpcode());
01466   else
01467     OS << "UNKNOWN";
01468 
01469   if (SkipOpers)
01470     return;
01471 
01472   // Print the rest of the operands.
01473   bool OmittedAnyCallClobbers = false;
01474   bool FirstOp = true;
01475   unsigned AsmDescOp = ~0u;
01476   unsigned AsmOpCount = 0;
01477 
01478   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
01479     // Print asm string.
01480     OS << " ";
01481     getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
01482 
01483     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
01484     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
01485     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
01486       OS << " [sideeffect]";
01487     if (ExtraInfo & InlineAsm::Extra_MayLoad)
01488       OS << " [mayload]";
01489     if (ExtraInfo & InlineAsm::Extra_MayStore)
01490       OS << " [maystore]";
01491     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
01492       OS << " [alignstack]";
01493     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
01494       OS << " [attdialect]";
01495     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
01496       OS << " [inteldialect]";
01497 
01498     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
01499     FirstOp = false;
01500   }
01501 
01502 
01503   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
01504     const MachineOperand &MO = getOperand(i);
01505 
01506     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
01507       VirtRegs.push_back(MO.getReg());
01508 
01509     // Omit call-clobbered registers which aren't used anywhere. This makes
01510     // call instructions much less noisy on targets where calls clobber lots
01511     // of registers. Don't rely on MO.isDead() because we may be called before
01512     // LiveVariables is run, or we may be looking at a non-allocatable reg.
01513     if (MF && isCall() &&
01514         MO.isReg() && MO.isImplicit() && MO.isDef()) {
01515       unsigned Reg = MO.getReg();
01516       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
01517         const MachineRegisterInfo &MRI = MF->getRegInfo();
01518         if (MRI.use_empty(Reg)) {
01519           bool HasAliasLive = false;
01520           for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
01521                AI.isValid(); ++AI) {
01522             unsigned AliasReg = *AI;
01523             if (!MRI.use_empty(AliasReg)) {
01524               HasAliasLive = true;
01525               break;
01526             }
01527           }
01528           if (!HasAliasLive) {
01529             OmittedAnyCallClobbers = true;
01530             continue;
01531           }
01532         }
01533       }
01534     }
01535 
01536     if (FirstOp) FirstOp = false; else OS << ",";
01537     OS << " ";
01538     if (i < getDesc().NumOperands) {
01539       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
01540       if (MCOI.isPredicate())
01541         OS << "pred:";
01542       if (MCOI.isOptionalDef())
01543         OS << "opt:";
01544     }
01545     if (isDebugValue() && MO.isMetadata()) {
01546       // Pretty print DBG_VALUE instructions.
01547       const MDNode *MD = MO.getMetadata();
01548       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
01549         OS << "!\"" << MDS->getString() << '\"';
01550       else
01551         MO.print(OS, TM);
01552     } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
01553       OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
01554     } else if (i == AsmDescOp && MO.isImm()) {
01555       // Pretty print the inline asm operand descriptor.
01556       OS << '$' << AsmOpCount++;
01557       unsigned Flag = MO.getImm();
01558       switch (InlineAsm::getKind(Flag)) {
01559       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
01560       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
01561       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
01562       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
01563       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
01564       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
01565       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
01566       }
01567 
01568       unsigned RCID = 0;
01569       if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
01570         if (TM)
01571           OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
01572         else
01573           OS << ":RC" << RCID;
01574       }
01575 
01576       unsigned TiedTo = 0;
01577       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
01578         OS << " tiedto:$" << TiedTo;
01579 
01580       OS << ']';
01581 
01582       // Compute the index of the next operand descriptor.
01583       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
01584     } else
01585       MO.print(OS, TM);
01586   }
01587 
01588   // Briefly indicate whether any call clobbers were omitted.
01589   if (OmittedAnyCallClobbers) {
01590     if (!FirstOp) OS << ",";
01591     OS << " ...";
01592   }
01593 
01594   bool HaveSemi = false;
01595   const unsigned PrintableFlags = FrameSetup;
01596   if (Flags & PrintableFlags) {
01597     if (!HaveSemi) OS << ";"; HaveSemi = true;
01598     OS << " flags: ";
01599 
01600     if (Flags & FrameSetup)
01601       OS << "FrameSetup";
01602   }
01603 
01604   if (!memoperands_empty()) {
01605     if (!HaveSemi) OS << ";"; HaveSemi = true;
01606 
01607     OS << " mem:";
01608     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
01609          i != e; ++i) {
01610       OS << **i;
01611       if (llvm::next(i) != e)
01612         OS << " ";
01613     }
01614   }
01615 
01616   // Print the regclass of any virtual registers encountered.
01617   if (MRI && !VirtRegs.empty()) {
01618     if (!HaveSemi) OS << ";"; HaveSemi = true;
01619     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
01620       const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
01621       OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
01622       for (unsigned j = i+1; j != VirtRegs.size();) {
01623         if (MRI->getRegClass(VirtRegs[j]) != RC) {
01624           ++j;
01625           continue;
01626         }
01627         if (VirtRegs[i] != VirtRegs[j])
01628           OS << "," << PrintReg(VirtRegs[j]);
01629         VirtRegs.erase(VirtRegs.begin()+j);
01630       }
01631     }
01632   }
01633 
01634   // Print debug location information.
01635   if (isDebugValue() && getOperand(e - 1).isMetadata()) {
01636     if (!HaveSemi) OS << ";"; HaveSemi = true;
01637     DIVariable DV(getOperand(e - 1).getMetadata());
01638     OS << " line no:" <<  DV.getLineNumber();
01639     if (MDNode *InlinedAt = DV.getInlinedAt()) {
01640       DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
01641       if (!InlinedAtDL.isUnknown()) {
01642         OS << " inlined @[ ";
01643         printDebugLoc(InlinedAtDL, MF, OS);
01644         OS << " ]";
01645       }
01646     }
01647   } else if (!debugLoc.isUnknown() && MF) {
01648     if (!HaveSemi) OS << ";"; HaveSemi = true;
01649     OS << " dbg:";
01650     printDebugLoc(debugLoc, MF, OS);
01651   }
01652 
01653   OS << '\n';
01654 }
01655 
01656 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
01657                                      const TargetRegisterInfo *RegInfo,
01658                                      bool AddIfNotFound) {
01659   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
01660   bool hasAliases = isPhysReg &&
01661     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
01662   bool Found = false;
01663   SmallVector<unsigned,4> DeadOps;
01664   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01665     MachineOperand &MO = getOperand(i);
01666     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
01667       continue;
01668     unsigned Reg = MO.getReg();
01669     if (!Reg)
01670       continue;
01671 
01672     if (Reg == IncomingReg) {
01673       if (!Found) {
01674         if (MO.isKill())
01675           // The register is already marked kill.
01676           return true;
01677         if (isPhysReg && isRegTiedToDefOperand(i))
01678           // Two-address uses of physregs must not be marked kill.
01679           return true;
01680         MO.setIsKill();
01681         Found = true;
01682       }
01683     } else if (hasAliases && MO.isKill() &&
01684                TargetRegisterInfo::isPhysicalRegister(Reg)) {
01685       // A super-register kill already exists.
01686       if (RegInfo->isSuperRegister(IncomingReg, Reg))
01687         return true;
01688       if (RegInfo->isSubRegister(IncomingReg, Reg))
01689         DeadOps.push_back(i);
01690     }
01691   }
01692 
01693   // Trim unneeded kill operands.
01694   while (!DeadOps.empty()) {
01695     unsigned OpIdx = DeadOps.back();
01696     if (getOperand(OpIdx).isImplicit())
01697       RemoveOperand(OpIdx);
01698     else
01699       getOperand(OpIdx).setIsKill(false);
01700     DeadOps.pop_back();
01701   }
01702 
01703   // If not found, this means an alias of one of the operands is killed. Add a
01704   // new implicit operand if required.
01705   if (!Found && AddIfNotFound) {
01706     addOperand(MachineOperand::CreateReg(IncomingReg,
01707                                          false /*IsDef*/,
01708                                          true  /*IsImp*/,
01709                                          true  /*IsKill*/));
01710     return true;
01711   }
01712   return Found;
01713 }
01714 
01715 void MachineInstr::clearRegisterKills(unsigned Reg,
01716                                       const TargetRegisterInfo *RegInfo) {
01717   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
01718     RegInfo = 0;
01719   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01720     MachineOperand &MO = getOperand(i);
01721     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
01722       continue;
01723     unsigned OpReg = MO.getReg();
01724     if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
01725       MO.setIsKill(false);
01726   }
01727 }
01728 
01729 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
01730                                    const TargetRegisterInfo *RegInfo,
01731                                    bool AddIfNotFound) {
01732   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
01733   bool hasAliases = isPhysReg &&
01734     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
01735   bool Found = false;
01736   SmallVector<unsigned,4> DeadOps;
01737   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01738     MachineOperand &MO = getOperand(i);
01739     if (!MO.isReg() || !MO.isDef())
01740       continue;
01741     unsigned Reg = MO.getReg();
01742     if (!Reg)
01743       continue;
01744 
01745     if (Reg == IncomingReg) {
01746       MO.setIsDead();
01747       Found = true;
01748     } else if (hasAliases && MO.isDead() &&
01749                TargetRegisterInfo::isPhysicalRegister(Reg)) {
01750       // There exists a super-register that's marked dead.
01751       if (RegInfo->isSuperRegister(IncomingReg, Reg))
01752         return true;
01753       if (RegInfo->isSubRegister(IncomingReg, Reg))
01754         DeadOps.push_back(i);
01755     }
01756   }
01757 
01758   // Trim unneeded dead operands.
01759   while (!DeadOps.empty()) {
01760     unsigned OpIdx = DeadOps.back();
01761     if (getOperand(OpIdx).isImplicit())
01762       RemoveOperand(OpIdx);
01763     else
01764       getOperand(OpIdx).setIsDead(false);
01765     DeadOps.pop_back();
01766   }
01767 
01768   // If not found, this means an alias of one of the operands is dead. Add a
01769   // new implicit operand if required.
01770   if (Found || !AddIfNotFound)
01771     return Found;
01772 
01773   addOperand(MachineOperand::CreateReg(IncomingReg,
01774                                        true  /*IsDef*/,
01775                                        true  /*IsImp*/,
01776                                        false /*IsKill*/,
01777                                        true  /*IsDead*/));
01778   return true;
01779 }
01780 
01781 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
01782                                       const TargetRegisterInfo *RegInfo) {
01783   if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
01784     MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
01785     if (MO)
01786       return;
01787   } else {
01788     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01789       const MachineOperand &MO = getOperand(i);
01790       if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
01791           MO.getSubReg() == 0)
01792         return;
01793     }
01794   }
01795   addOperand(MachineOperand::CreateReg(IncomingReg,
01796                                        true  /*IsDef*/,
01797                                        true  /*IsImp*/));
01798 }
01799 
01800 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
01801                                          const TargetRegisterInfo &TRI) {
01802   bool HasRegMask = false;
01803   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01804     MachineOperand &MO = getOperand(i);
01805     if (MO.isRegMask()) {
01806       HasRegMask = true;
01807       continue;
01808     }
01809     if (!MO.isReg() || !MO.isDef()) continue;
01810     unsigned Reg = MO.getReg();
01811     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
01812     bool Dead = true;
01813     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
01814          I != E; ++I)
01815       if (TRI.regsOverlap(*I, Reg)) {
01816         Dead = false;
01817         break;
01818       }
01819     // If there are no uses, including partial uses, the def is dead.
01820     if (Dead) MO.setIsDead();
01821   }
01822 
01823   // This is a call with a register mask operand.
01824   // Mask clobbers are always dead, so add defs for the non-dead defines.
01825   if (HasRegMask)
01826     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
01827          I != E; ++I)
01828       addRegisterDefined(*I, &TRI);
01829 }
01830 
01831 unsigned
01832 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
01833   // Build up a buffer of hash code components.
01834   SmallVector<size_t, 8> HashComponents;
01835   HashComponents.reserve(MI->getNumOperands() + 1);
01836   HashComponents.push_back(MI->getOpcode());
01837   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01838     const MachineOperand &MO = MI->getOperand(i);
01839     if (MO.isReg() && MO.isDef() &&
01840         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
01841       continue;  // Skip virtual register defs.
01842 
01843     HashComponents.push_back(hash_value(MO));
01844   }
01845   return hash_combine_range(HashComponents.begin(), HashComponents.end());
01846 }
01847 
01848 void MachineInstr::emitError(StringRef Msg) const {
01849   // Find the source location cookie.
01850   unsigned LocCookie = 0;
01851   const MDNode *LocMD = 0;
01852   for (unsigned i = getNumOperands(); i != 0; --i) {
01853     if (getOperand(i-1).isMetadata() &&
01854         (LocMD = getOperand(i-1).getMetadata()) &&
01855         LocMD->getNumOperands() != 0) {
01856       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
01857         LocCookie = CI->getZExtValue();
01858         break;
01859       }
01860     }
01861   }
01862 
01863   if (const MachineBasicBlock *MBB = getParent())
01864     if (const MachineFunction *MF = MBB->getParent())
01865       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
01866   report_fatal_error(Msg);
01867 }