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