LLVM API Documentation

Instruction.cpp
Go to the documentation of this file.
00001 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
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 // This file implements the Instruction class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Instruction.h"
00015 #include "llvm/IR/CallSite.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/Instructions.h"
00018 #include "llvm/IR/LeakDetector.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/IR/Operator.h"
00021 #include "llvm/IR/Type.h"
00022 using namespace llvm;
00023 
00024 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
00025                          Instruction *InsertBefore)
00026   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
00027   // Make sure that we get added to a basicblock
00028   LeakDetector::addGarbageObject(this);
00029 
00030   // If requested, insert this instruction into a basic block...
00031   if (InsertBefore) {
00032     assert(InsertBefore->getParent() &&
00033            "Instruction to insert before is not in a basic block!");
00034     InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
00035   }
00036 }
00037 
00038 const DataLayout *Instruction::getDataLayout() const {
00039   return getParent()->getDataLayout();
00040 }
00041 
00042 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
00043                          BasicBlock *InsertAtEnd)
00044   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
00045   // Make sure that we get added to a basicblock
00046   LeakDetector::addGarbageObject(this);
00047 
00048   // append this instruction into the basic block
00049   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
00050   InsertAtEnd->getInstList().push_back(this);
00051 }
00052 
00053 
00054 // Out of line virtual method, so the vtable, etc has a home.
00055 Instruction::~Instruction() {
00056   assert(!Parent && "Instruction still linked in the program!");
00057   if (hasMetadataHashEntry())
00058     clearMetadataHashEntries();
00059 }
00060 
00061 
00062 void Instruction::setParent(BasicBlock *P) {
00063   if (getParent()) {
00064     if (!P) LeakDetector::addGarbageObject(this);
00065   } else {
00066     if (P) LeakDetector::removeGarbageObject(this);
00067   }
00068 
00069   Parent = P;
00070 }
00071 
00072 void Instruction::removeFromParent() {
00073   getParent()->getInstList().remove(this);
00074 }
00075 
00076 void Instruction::eraseFromParent() {
00077   getParent()->getInstList().erase(this);
00078 }
00079 
00080 /// insertBefore - Insert an unlinked instructions into a basic block
00081 /// immediately before the specified instruction.
00082 void Instruction::insertBefore(Instruction *InsertPos) {
00083   InsertPos->getParent()->getInstList().insert(InsertPos, this);
00084 }
00085 
00086 /// insertAfter - Insert an unlinked instructions into a basic block
00087 /// immediately after the specified instruction.
00088 void Instruction::insertAfter(Instruction *InsertPos) {
00089   InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
00090 }
00091 
00092 /// moveBefore - Unlink this instruction from its current basic block and
00093 /// insert it into the basic block that MovePos lives in, right before
00094 /// MovePos.
00095 void Instruction::moveBefore(Instruction *MovePos) {
00096   MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
00097                                              this);
00098 }
00099 
00100 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
00101 /// operator which supports this flag. See LangRef.html for the meaning of this
00102 /// flag.
00103 void Instruction::setHasUnsafeAlgebra(bool B) {
00104   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00105   cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
00106 }
00107 
00108 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
00109 /// which supports this flag. See LangRef.html for the meaning of this flag.
00110 void Instruction::setHasNoNaNs(bool B) {
00111   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00112   cast<FPMathOperator>(this)->setHasNoNaNs(B);
00113 }
00114 
00115 /// Set or clear the no-infs flag on this instruction, which must be an operator
00116 /// which supports this flag. See LangRef.html for the meaning of this flag.
00117 void Instruction::setHasNoInfs(bool B) {
00118   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00119   cast<FPMathOperator>(this)->setHasNoInfs(B);
00120 }
00121 
00122 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
00123 /// operator which supports this flag. See LangRef.html for the meaning of this
00124 /// flag.
00125 void Instruction::setHasNoSignedZeros(bool B) {
00126   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00127   cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
00128 }
00129 
00130 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
00131 /// operator which supports this flag. See LangRef.html for the meaning of this
00132 /// flag.
00133 void Instruction::setHasAllowReciprocal(bool B) {
00134   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00135   cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
00136 }
00137 
00138 /// Convenience function for setting all the fast-math flags on this
00139 /// instruction, which must be an operator which supports these flags. See
00140 /// LangRef.html for the meaning of these flats.
00141 void Instruction::setFastMathFlags(FastMathFlags FMF) {
00142   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00143   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
00144 }
00145 
00146 /// Determine whether the unsafe-algebra flag is set.
00147 bool Instruction::hasUnsafeAlgebra() const {
00148   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00149   return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
00150 }
00151 
00152 /// Determine whether the no-NaNs flag is set.
00153 bool Instruction::hasNoNaNs() const {
00154   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00155   return cast<FPMathOperator>(this)->hasNoNaNs();
00156 }
00157 
00158 /// Determine whether the no-infs flag is set.
00159 bool Instruction::hasNoInfs() const {
00160   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00161   return cast<FPMathOperator>(this)->hasNoInfs();
00162 }
00163 
00164 /// Determine whether the no-signed-zeros flag is set.
00165 bool Instruction::hasNoSignedZeros() const {
00166   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00167   return cast<FPMathOperator>(this)->hasNoSignedZeros();
00168 }
00169 
00170 /// Determine whether the allow-reciprocal flag is set.
00171 bool Instruction::hasAllowReciprocal() const {
00172   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00173   return cast<FPMathOperator>(this)->hasAllowReciprocal();
00174 }
00175 
00176 /// Convenience function for getting all the fast-math flags, which must be an
00177 /// operator which supports these flags. See LangRef.html for the meaning of
00178 /// these flats.
00179 FastMathFlags Instruction::getFastMathFlags() const {
00180   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00181   return cast<FPMathOperator>(this)->getFastMathFlags();
00182 }
00183 
00184 /// Copy I's fast-math flags
00185 void Instruction::copyFastMathFlags(const Instruction *I) {
00186   setFastMathFlags(I->getFastMathFlags());
00187 }
00188 
00189 
00190 const char *Instruction::getOpcodeName(unsigned OpCode) {
00191   switch (OpCode) {
00192   // Terminators
00193   case Ret:    return "ret";
00194   case Br:     return "br";
00195   case Switch: return "switch";
00196   case IndirectBr: return "indirectbr";
00197   case Invoke: return "invoke";
00198   case Resume: return "resume";
00199   case Unreachable: return "unreachable";
00200 
00201   // Standard binary operators...
00202   case Add: return "add";
00203   case FAdd: return "fadd";
00204   case Sub: return "sub";
00205   case FSub: return "fsub";
00206   case Mul: return "mul";
00207   case FMul: return "fmul";
00208   case UDiv: return "udiv";
00209   case SDiv: return "sdiv";
00210   case FDiv: return "fdiv";
00211   case URem: return "urem";
00212   case SRem: return "srem";
00213   case FRem: return "frem";
00214 
00215   // Logical operators...
00216   case And: return "and";
00217   case Or : return "or";
00218   case Xor: return "xor";
00219 
00220   // Memory instructions...
00221   case Alloca:        return "alloca";
00222   case Load:          return "load";
00223   case Store:         return "store";
00224   case AtomicCmpXchg: return "cmpxchg";
00225   case AtomicRMW:     return "atomicrmw";
00226   case Fence:         return "fence";
00227   case GetElementPtr: return "getelementptr";
00228 
00229   // Convert instructions...
00230   case Trunc:         return "trunc";
00231   case ZExt:          return "zext";
00232   case SExt:          return "sext";
00233   case FPTrunc:       return "fptrunc";
00234   case FPExt:         return "fpext";
00235   case FPToUI:        return "fptoui";
00236   case FPToSI:        return "fptosi";
00237   case UIToFP:        return "uitofp";
00238   case SIToFP:        return "sitofp";
00239   case IntToPtr:      return "inttoptr";
00240   case PtrToInt:      return "ptrtoint";
00241   case BitCast:       return "bitcast";
00242   case AddrSpaceCast: return "addrspacecast";
00243 
00244   // Other instructions...
00245   case ICmp:           return "icmp";
00246   case FCmp:           return "fcmp";
00247   case PHI:            return "phi";
00248   case Select:         return "select";
00249   case Call:           return "call";
00250   case Shl:            return "shl";
00251   case LShr:           return "lshr";
00252   case AShr:           return "ashr";
00253   case VAArg:          return "va_arg";
00254   case ExtractElement: return "extractelement";
00255   case InsertElement:  return "insertelement";
00256   case ShuffleVector:  return "shufflevector";
00257   case ExtractValue:   return "extractvalue";
00258   case InsertValue:    return "insertvalue";
00259   case LandingPad:     return "landingpad";
00260 
00261   default: return "<Invalid operator> ";
00262   }
00263 }
00264 
00265 /// Return true if both instructions have the same special state
00266 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
00267 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
00268                                  bool IgnoreAlignment = false) {
00269   assert(I1->getOpcode() == I2->getOpcode() &&
00270          "Can not compare special state of different instructions");
00271 
00272   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
00273     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
00274            (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
00275             IgnoreAlignment) &&
00276            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
00277            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
00278   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
00279     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
00280            (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
00281             IgnoreAlignment) &&
00282            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
00283            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
00284   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
00285     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
00286   if (const CallInst *CI = dyn_cast<CallInst>(I1))
00287     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
00288            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
00289            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
00290   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
00291     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
00292            CI->getAttributes() ==
00293              cast<InvokeInst>(I2)->getAttributes();
00294   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
00295     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
00296   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
00297     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
00298   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
00299     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
00300            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
00301   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
00302     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
00303            CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
00304            CXI->getSuccessOrdering() ==
00305                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
00306            CXI->getFailureOrdering() ==
00307                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
00308            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
00309   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
00310     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
00311            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
00312            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
00313            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
00314 
00315   return true;
00316 }
00317 
00318 /// isIdenticalTo - Return true if the specified instruction is exactly
00319 /// identical to the current one.  This means that all operands match and any
00320 /// extra information (e.g. load is volatile) agree.
00321 bool Instruction::isIdenticalTo(const Instruction *I) const {
00322   return isIdenticalToWhenDefined(I) &&
00323          SubclassOptionalData == I->SubclassOptionalData;
00324 }
00325 
00326 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
00327 /// ignores the SubclassOptionalData flags, which specify conditions
00328 /// under which the instruction's result is undefined.
00329 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
00330   if (getOpcode() != I->getOpcode() ||
00331       getNumOperands() != I->getNumOperands() ||
00332       getType() != I->getType())
00333     return false;
00334 
00335   // If both instructions have no operands, they are identical.
00336   if (getNumOperands() == 0 && I->getNumOperands() == 0)
00337     return haveSameSpecialState(this, I);
00338 
00339   // We have two instructions of identical opcode and #operands.  Check to see
00340   // if all operands are the same.
00341   if (!std::equal(op_begin(), op_end(), I->op_begin()))
00342     return false;
00343 
00344   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
00345     const PHINode *otherPHI = cast<PHINode>(I);
00346     return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
00347                       otherPHI->block_begin());
00348   }
00349 
00350   return haveSameSpecialState(this, I);
00351 }
00352 
00353 // isSameOperationAs
00354 // This should be kept in sync with isEquivalentOperation in
00355 // lib/Transforms/IPO/MergeFunctions.cpp.
00356 bool Instruction::isSameOperationAs(const Instruction *I,
00357                                     unsigned flags) const {
00358   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
00359   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
00360 
00361   if (getOpcode() != I->getOpcode() ||
00362       getNumOperands() != I->getNumOperands() ||
00363       (UseScalarTypes ?
00364        getType()->getScalarType() != I->getType()->getScalarType() :
00365        getType() != I->getType()))
00366     return false;
00367 
00368   // We have two instructions of identical opcode and #operands.  Check to see
00369   // if all operands are the same type
00370   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00371     if (UseScalarTypes ?
00372         getOperand(i)->getType()->getScalarType() !=
00373           I->getOperand(i)->getType()->getScalarType() :
00374         getOperand(i)->getType() != I->getOperand(i)->getType())
00375       return false;
00376 
00377   return haveSameSpecialState(this, I, IgnoreAlignment);
00378 }
00379 
00380 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
00381 /// specified block.  Note that PHI nodes are considered to evaluate their
00382 /// operands in the corresponding predecessor block.
00383 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
00384   for (const Use &U : uses()) {
00385     // PHI nodes uses values in the corresponding predecessor block.  For other
00386     // instructions, just check to see whether the parent of the use matches up.
00387     const Instruction *I = cast<Instruction>(U.getUser());
00388     const PHINode *PN = dyn_cast<PHINode>(I);
00389     if (!PN) {
00390       if (I->getParent() != BB)
00391         return true;
00392       continue;
00393     }
00394 
00395     if (PN->getIncomingBlock(U) != BB)
00396       return true;
00397   }
00398   return false;
00399 }
00400 
00401 /// mayReadFromMemory - Return true if this instruction may read memory.
00402 ///
00403 bool Instruction::mayReadFromMemory() const {
00404   switch (getOpcode()) {
00405   default: return false;
00406   case Instruction::VAArg:
00407   case Instruction::Load:
00408   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
00409   case Instruction::AtomicCmpXchg:
00410   case Instruction::AtomicRMW:
00411     return true;
00412   case Instruction::Call:
00413     return !cast<CallInst>(this)->doesNotAccessMemory();
00414   case Instruction::Invoke:
00415     return !cast<InvokeInst>(this)->doesNotAccessMemory();
00416   case Instruction::Store:
00417     return !cast<StoreInst>(this)->isUnordered();
00418   }
00419 }
00420 
00421 /// mayWriteToMemory - Return true if this instruction may modify memory.
00422 ///
00423 bool Instruction::mayWriteToMemory() const {
00424   switch (getOpcode()) {
00425   default: return false;
00426   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
00427   case Instruction::Store:
00428   case Instruction::VAArg:
00429   case Instruction::AtomicCmpXchg:
00430   case Instruction::AtomicRMW:
00431     return true;
00432   case Instruction::Call:
00433     return !cast<CallInst>(this)->onlyReadsMemory();
00434   case Instruction::Invoke:
00435     return !cast<InvokeInst>(this)->onlyReadsMemory();
00436   case Instruction::Load:
00437     return !cast<LoadInst>(this)->isUnordered();
00438   }
00439 }
00440 
00441 bool Instruction::mayThrow() const {
00442   if (const CallInst *CI = dyn_cast<CallInst>(this))
00443     return !CI->doesNotThrow();
00444   return isa<ResumeInst>(this);
00445 }
00446 
00447 bool Instruction::mayReturn() const {
00448   if (const CallInst *CI = dyn_cast<CallInst>(this))
00449     return !CI->doesNotReturn();
00450   return true;
00451 }
00452 
00453 /// isAssociative - Return true if the instruction is associative:
00454 ///
00455 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
00456 ///
00457 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
00458 ///
00459 bool Instruction::isAssociative(unsigned Opcode) {
00460   return Opcode == And || Opcode == Or || Opcode == Xor ||
00461          Opcode == Add || Opcode == Mul;
00462 }
00463 
00464 bool Instruction::isAssociative() const {
00465   unsigned Opcode = getOpcode();
00466   if (isAssociative(Opcode))
00467     return true;
00468 
00469   switch (Opcode) {
00470   case FMul:
00471   case FAdd:
00472     return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
00473   default:
00474     return false;
00475   }
00476 }
00477 
00478 /// isCommutative - Return true if the instruction is commutative:
00479 ///
00480 ///   Commutative operators satisfy: (x op y) === (y op x)
00481 ///
00482 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
00483 /// applied to any type.
00484 ///
00485 bool Instruction::isCommutative(unsigned op) {
00486   switch (op) {
00487   case Add:
00488   case FAdd:
00489   case Mul:
00490   case FMul:
00491   case And:
00492   case Or:
00493   case Xor:
00494     return true;
00495   default:
00496     return false;
00497   }
00498 }
00499 
00500 /// isIdempotent - Return true if the instruction is idempotent:
00501 ///
00502 ///   Idempotent operators satisfy:  x op x === x
00503 ///
00504 /// In LLVM, the And and Or operators are idempotent.
00505 ///
00506 bool Instruction::isIdempotent(unsigned Opcode) {
00507   return Opcode == And || Opcode == Or;
00508 }
00509 
00510 /// isNilpotent - Return true if the instruction is nilpotent:
00511 ///
00512 ///   Nilpotent operators satisfy:  x op x === Id,
00513 ///
00514 ///   where Id is the identity for the operator, i.e. a constant such that
00515 ///     x op Id === x and Id op x === x for all x.
00516 ///
00517 /// In LLVM, the Xor operator is nilpotent.
00518 ///
00519 bool Instruction::isNilpotent(unsigned Opcode) {
00520   return Opcode == Xor;
00521 }
00522 
00523 Instruction *Instruction::clone() const {
00524   Instruction *New = clone_impl();
00525   New->SubclassOptionalData = SubclassOptionalData;
00526   if (!hasMetadata())
00527     return New;
00528 
00529   // Otherwise, enumerate and copy over metadata from the old instruction to the
00530   // new one.
00531   SmallVector<std::pair<unsigned, MDNode*>, 4> TheMDs;
00532   getAllMetadataOtherThanDebugLoc(TheMDs);
00533   for (const auto &MD : TheMDs)
00534     New->setMetadata(MD.first, MD.second);
00535 
00536   New->setDebugLoc(getDebugLoc());
00537   return New;
00538 }