LLVM  mainline
CallSite.h
Go to the documentation of this file.
00001 //===- CallSite.h - Abstract Call & Invoke instrs ---------------*- C++ -*-===//
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 defines the CallSite class, which is a handy wrapper for code that
00011 // wants to treat Call and Invoke instructions in a generic way. When in non-
00012 // mutation context (e.g. an analysis) ImmutableCallSite should be used.
00013 // Finally, when some degree of customization is necessary between these two
00014 // extremes, CallSiteBase<> can be supplied with fine-tuned parameters.
00015 //
00016 // NOTE: These classes are supposed to have "value semantics". So they should be
00017 // passed by value, not by reference; they should not be "new"ed or "delete"d.
00018 // They are efficiently copyable, assignable and constructable, with cost
00019 // equivalent to copying a pointer (notice that they have only a single data
00020 // member). The internal representation carries a flag which indicates which of
00021 // the two variants is enclosed. This allows for cheaper checks when various
00022 // accessors of CallSite are employed.
00023 //
00024 //===----------------------------------------------------------------------===//
00025 
00026 #ifndef LLVM_IR_CALLSITE_H
00027 #define LLVM_IR_CALLSITE_H
00028 
00029 #include "llvm/ADT/PointerIntPair.h"
00030 #include "llvm/ADT/iterator_range.h"
00031 #include "llvm/IR/Attributes.h"
00032 #include "llvm/IR/CallingConv.h"
00033 #include "llvm/IR/Instructions.h"
00034 
00035 namespace llvm {
00036 
00037 class CallInst;
00038 class InvokeInst;
00039 
00040 template <typename FunTy = const Function,
00041           typename BBTy = const BasicBlock,
00042           typename ValTy = const Value,
00043           typename UserTy = const User,
00044           typename UseTy = const Use,
00045           typename InstrTy = const Instruction,
00046           typename CallTy = const CallInst,
00047           typename InvokeTy = const InvokeInst,
00048           typename IterTy = User::const_op_iterator>
00049 class CallSiteBase {
00050 protected:
00051   PointerIntPair<InstrTy*, 1, bool> I;
00052 
00053   CallSiteBase() : I(nullptr, false) {}
00054   CallSiteBase(CallTy *CI) : I(CI, true) { assert(CI); }
00055   CallSiteBase(InvokeTy *II) : I(II, false) { assert(II); }
00056   explicit CallSiteBase(ValTy *II) { *this = get(II); }
00057 
00058 private:
00059   /// CallSiteBase::get - This static method is sort of like a constructor.  It
00060   /// will create an appropriate call site for a Call or Invoke instruction, but
00061   /// it can also create a null initialized CallSiteBase object for something
00062   /// which is NOT a call site.
00063   ///
00064   static CallSiteBase get(ValTy *V) {
00065     if (InstrTy *II = dyn_cast<InstrTy>(V)) {
00066       if (II->getOpcode() == Instruction::Call)
00067         return CallSiteBase(static_cast<CallTy*>(II));
00068       else if (II->getOpcode() == Instruction::Invoke)
00069         return CallSiteBase(static_cast<InvokeTy*>(II));
00070     }
00071     return CallSiteBase();
00072   }
00073 
00074 public:
00075   /// isCall - true if a CallInst is enclosed.
00076   /// Note that !isCall() does not mean it is an InvokeInst enclosed,
00077   /// it also could signify a NULL Instruction pointer.
00078   bool isCall() const { return I.getInt(); }
00079 
00080   /// isInvoke - true if a InvokeInst is enclosed.
00081   ///
00082   bool isInvoke() const { return getInstruction() && !I.getInt(); }
00083 
00084   InstrTy *getInstruction() const { return I.getPointer(); }
00085   InstrTy *operator->() const { return I.getPointer(); }
00086   explicit operator bool() const { return I.getPointer(); }
00087 
00088   /// Get the basic block containing the call site
00089   BBTy* getParent() const { return getInstruction()->getParent(); }
00090 
00091   /// getCalledValue - Return the pointer to function that is being called.
00092   ///
00093   ValTy *getCalledValue() const {
00094     assert(getInstruction() && "Not a call or invoke instruction!");
00095     return *getCallee();
00096   }
00097 
00098   /// getCalledFunction - Return the function being called if this is a direct
00099   /// call, otherwise return null (if it's an indirect call).
00100   ///
00101   FunTy *getCalledFunction() const {
00102     return dyn_cast<FunTy>(getCalledValue());
00103   }
00104 
00105   /// setCalledFunction - Set the callee to the specified value.
00106   ///
00107   void setCalledFunction(Value *V) {
00108     assert(getInstruction() && "Not a call or invoke instruction!");
00109     *getCallee() = V;
00110   }
00111 
00112   /// isCallee - Determine whether the passed iterator points to the
00113   /// callee operand's Use.
00114   bool isCallee(Value::const_user_iterator UI) const {
00115     return isCallee(&UI.getUse());
00116   }
00117 
00118   /// Determine whether this Use is the callee operand's Use.
00119   bool isCallee(const Use *U) const { return getCallee() == U; }
00120 
00121   /// \brief Determine whether the passed iterator points to an argument
00122   /// operand.
00123   bool isArgOperand(Value::const_user_iterator UI) const {
00124     return isArgOperand(&UI.getUse());
00125   }
00126 
00127   /// \brief Determine whether the passed use points to an argument operand.
00128   bool isArgOperand(const Use *U) const {
00129     assert(getInstruction() == U->getUser());
00130     return arg_begin() <= U && U < arg_end();
00131   }
00132 
00133   /// \brief Determine whether the passed iterator points to a bundle operand.
00134   bool isBundleOperand(Value::const_user_iterator UI) const {
00135     return isBundleOperand(&UI.getUse());
00136   }
00137 
00138   /// \brief Determine whether the passed use points to a bundle operand.
00139   bool isBundleOperand(const Use *U) const {
00140     assert(getInstruction() == U->getUser());
00141     if (!hasOperandBundles())
00142       return false;
00143     unsigned OperandNo = U - (*this)->op_begin();
00144     return getBundleOperandsStartIndex() <= OperandNo &&
00145            OperandNo < getBundleOperandsEndIndex();
00146   }
00147 
00148   /// \brief Determine whether the passed iterator points to a data operand.
00149   bool isDataOperand(Value::const_user_iterator UI) const {
00150     return isDataOperand(&UI.getUse());
00151   }
00152 
00153   /// \brief Determine whether the passed use points to a data operand.
00154   bool isDataOperand(const Use *U) const {
00155     return data_operands_begin() <= U && U < data_operands_end();
00156   }
00157 
00158   ValTy *getArgument(unsigned ArgNo) const {
00159     assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
00160     return *(arg_begin() + ArgNo);
00161   }
00162 
00163   void setArgument(unsigned ArgNo, Value* newVal) {
00164     assert(getInstruction() && "Not a call or invoke instruction!");
00165     assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
00166     getInstruction()->setOperand(ArgNo, newVal);
00167   }
00168 
00169   /// Given a value use iterator, returns the argument that corresponds to it.
00170   /// Iterator must actually correspond to an argument.
00171   unsigned getArgumentNo(Value::const_user_iterator I) const {
00172     return getArgumentNo(&I.getUse());
00173   }
00174 
00175   /// Given a use for an argument, get the argument number that corresponds to
00176   /// it.
00177   unsigned getArgumentNo(const Use *U) const {
00178     assert(getInstruction() && "Not a call or invoke instruction!");
00179     assert(isArgOperand(U) && "Argument # out of range!");
00180     return U - arg_begin();
00181   }
00182 
00183   /// arg_iterator - The type of iterator to use when looping over actual
00184   /// arguments at this call site.
00185   typedef IterTy arg_iterator;
00186 
00187   iterator_range<IterTy> args() const {
00188     return make_range(arg_begin(), arg_end());
00189   }
00190   bool arg_empty() const { return arg_end() == arg_begin(); }
00191   unsigned arg_size() const { return unsigned(arg_end() - arg_begin()); }
00192 
00193   /// Given a value use iterator, returns the data operand that corresponds to
00194   /// it.
00195   /// Iterator must actually correspond to a data operand.
00196   unsigned getDataOperandNo(Value::const_user_iterator UI) const {
00197     return getDataOperandNo(&UI.getUse());
00198   }
00199 
00200   /// Given a use for a data operand, get the data operand number that
00201   /// corresponds to it.
00202   unsigned getDataOperandNo(const Use *U) const {
00203     assert(getInstruction() && "Not a call or invoke instruction!");
00204     assert(isDataOperand(U) && "Data operand # out of range!");
00205     return U - data_operands_begin();
00206   }
00207 
00208   /// Type of iterator to use when looping over data operands at this call site
00209   /// (see below).
00210   typedef IterTy data_operand_iterator;
00211 
00212   /// data_operands_begin/data_operands_end - Return iterators iterating over
00213   /// the call / invoke argument list and bundle operands.  For invokes, this is
00214   /// the set of instruction operands except the invoke target and the two
00215   /// successor blocks; and for calls this is the set of instruction operands
00216   /// except the call target.
00217 
00218   IterTy data_operands_begin() const {
00219     assert(getInstruction() && "Not a call or invoke instruction!");
00220     return (*this)->op_begin();
00221   }
00222   IterTy data_operands_end() const {
00223     assert(getInstruction() && "Not a call or invoke instruction!");
00224     return (*this)->op_end() - (isCall() ? 1 : 3);
00225   }
00226   iterator_range<IterTy> data_ops() const {
00227     return make_range(data_operands_begin(), data_operands_end());
00228   }
00229   bool data_operands_empty() const {
00230     return data_operands_end() == data_operands_begin();
00231   }
00232   unsigned data_operands_size() const {
00233     return std::distance(data_operands_begin(), data_operands_end());
00234   }
00235 
00236   /// getType - Return the type of the instruction that generated this call site
00237   ///
00238   Type *getType() const { return (*this)->getType(); }
00239 
00240   /// getCaller - Return the caller function for this call site
00241   ///
00242   FunTy *getCaller() const { return (*this)->getParent()->getParent(); }
00243 
00244   /// \brief Tests if this call site must be tail call optimized.  Only a
00245   /// CallInst can be tail call optimized.
00246   bool isMustTailCall() const {
00247     return isCall() && cast<CallInst>(getInstruction())->isMustTailCall();
00248   }
00249 
00250   /// \brief Tests if this call site is marked as a tail call.
00251   bool isTailCall() const {
00252     return isCall() && cast<CallInst>(getInstruction())->isTailCall();
00253   }
00254 
00255 #define CALLSITE_DELEGATE_GETTER(METHOD) \
00256   InstrTy *II = getInstruction();    \
00257   return isCall()                        \
00258     ? cast<CallInst>(II)->METHOD         \
00259     : cast<InvokeInst>(II)->METHOD
00260 
00261 #define CALLSITE_DELEGATE_SETTER(METHOD) \
00262   InstrTy *II = getInstruction();    \
00263   if (isCall())                          \
00264     cast<CallInst>(II)->METHOD;          \
00265   else                                   \
00266     cast<InvokeInst>(II)->METHOD
00267 
00268   unsigned getNumArgOperands() const {
00269     CALLSITE_DELEGATE_GETTER(getNumArgOperands());
00270   }
00271 
00272   ValTy *getArgOperand(unsigned i) const {
00273     CALLSITE_DELEGATE_GETTER(getArgOperand(i));
00274   }
00275 
00276   bool isInlineAsm() const {
00277     if (isCall())
00278       return cast<CallInst>(getInstruction())->isInlineAsm();
00279     return false;
00280   }
00281 
00282   /// getCallingConv/setCallingConv - get or set the calling convention of the
00283   /// call.
00284   CallingConv::ID getCallingConv() const {
00285     CALLSITE_DELEGATE_GETTER(getCallingConv());
00286   }
00287   void setCallingConv(CallingConv::ID CC) {
00288     CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
00289   }
00290 
00291   FunctionType *getFunctionType() const {
00292     CALLSITE_DELEGATE_GETTER(getFunctionType());
00293   }
00294 
00295   void mutateFunctionType(FunctionType *Ty) const {
00296     CALLSITE_DELEGATE_SETTER(mutateFunctionType(Ty));
00297   }
00298 
00299   /// getAttributes/setAttributes - get or set the parameter attributes of
00300   /// the call.
00301   const AttributeSet &getAttributes() const {
00302     CALLSITE_DELEGATE_GETTER(getAttributes());
00303   }
00304   void setAttributes(const AttributeSet &PAL) {
00305     CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
00306   }
00307 
00308   /// \brief Return true if this function has the given attribute.
00309   bool hasFnAttr(Attribute::AttrKind A) const {
00310     CALLSITE_DELEGATE_GETTER(hasFnAttr(A));
00311   }
00312 
00313   /// \brief Return true if this function has the given attribute.
00314   bool hasFnAttr(StringRef A) const {
00315     CALLSITE_DELEGATE_GETTER(hasFnAttr(A));
00316   }
00317 
00318   /// \brief Return true if the call or the callee has the given attribute.
00319   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const {
00320     CALLSITE_DELEGATE_GETTER(paramHasAttr(i, A));
00321   }
00322 
00323   /// \brief Return true if the data operand at index \p i directly or
00324   /// indirectly has the attribute \p A.
00325   ///
00326   /// Normal call or invoke arguments have per operand attributes, as specified
00327   /// in the attribute set attached to this instruction, while operand bundle
00328   /// operands may have some attributes implied by the type of its containing
00329   /// operand bundle.
00330   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const {
00331     CALLSITE_DELEGATE_GETTER(dataOperandHasImpliedAttr(i, A));
00332   }
00333 
00334   /// @brief Extract the alignment for a call or parameter (0=unknown).
00335   uint16_t getParamAlignment(uint16_t i) const {
00336     CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
00337   }
00338 
00339   /// @brief Extract the number of dereferenceable bytes for a call or
00340   /// parameter (0=unknown).
00341   uint64_t getDereferenceableBytes(uint16_t i) const {
00342     CALLSITE_DELEGATE_GETTER(getDereferenceableBytes(i));
00343   }
00344 
00345   /// @brief Extract the number of dereferenceable_or_null bytes for a call or
00346   /// parameter (0=unknown).
00347   uint64_t getDereferenceableOrNullBytes(uint16_t i) const {
00348     CALLSITE_DELEGATE_GETTER(getDereferenceableOrNullBytes(i));
00349   }
00350 
00351   /// @brief Determine if the parameter or return value is marked with NoAlias
00352   /// attribute.
00353   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
00354   bool doesNotAlias(unsigned n) const {
00355     CALLSITE_DELEGATE_GETTER(doesNotAlias(n));
00356   }
00357 
00358   /// \brief Return true if the call should not be treated as a call to a
00359   /// builtin.
00360   bool isNoBuiltin() const {
00361     CALLSITE_DELEGATE_GETTER(isNoBuiltin());
00362   }
00363 
00364   /// @brief Return true if the call should not be inlined.
00365   bool isNoInline() const {
00366     CALLSITE_DELEGATE_GETTER(isNoInline());
00367   }
00368   void setIsNoInline(bool Value = true) {
00369     CALLSITE_DELEGATE_SETTER(setIsNoInline(Value));
00370   }
00371 
00372   /// @brief Determine if the call does not access memory.
00373   bool doesNotAccessMemory() const {
00374     CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
00375   }
00376   void setDoesNotAccessMemory() {
00377     CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory());
00378   }
00379 
00380   /// @brief Determine if the call does not access or only reads memory.
00381   bool onlyReadsMemory() const {
00382     CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
00383   }
00384   void setOnlyReadsMemory() {
00385     CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory());
00386   }
00387 
00388   /// @brief Determine if the call can access memmory only using pointers based
00389   /// on its arguments.
00390   bool onlyAccessesArgMemory() const {
00391     CALLSITE_DELEGATE_GETTER(onlyAccessesArgMemory());
00392   }
00393   void setOnlyAccessesArgMemory() {
00394     CALLSITE_DELEGATE_SETTER(setOnlyAccessesArgMemory());
00395   }
00396 
00397   /// @brief Determine if the call cannot return.
00398   bool doesNotReturn() const {
00399     CALLSITE_DELEGATE_GETTER(doesNotReturn());
00400   }
00401   void setDoesNotReturn() {
00402     CALLSITE_DELEGATE_SETTER(setDoesNotReturn());
00403   }
00404 
00405   /// @brief Determine if the call cannot unwind.
00406   bool doesNotThrow() const {
00407     CALLSITE_DELEGATE_GETTER(doesNotThrow());
00408   }
00409   void setDoesNotThrow() {
00410     CALLSITE_DELEGATE_SETTER(setDoesNotThrow());
00411   }
00412 
00413   unsigned getNumOperandBundles() const {
00414     CALLSITE_DELEGATE_GETTER(getNumOperandBundles());
00415   }
00416 
00417   bool hasOperandBundles() const {
00418     CALLSITE_DELEGATE_GETTER(hasOperandBundles());
00419   }
00420 
00421   unsigned getBundleOperandsStartIndex() const {
00422     CALLSITE_DELEGATE_GETTER(getBundleOperandsStartIndex());
00423   }
00424 
00425   unsigned getBundleOperandsEndIndex() const {
00426     CALLSITE_DELEGATE_GETTER(getBundleOperandsEndIndex());
00427   }
00428 
00429   unsigned getNumTotalBundleOperands() const {
00430     CALLSITE_DELEGATE_GETTER(getNumTotalBundleOperands());
00431   }
00432 
00433   OperandBundleUse getOperandBundleAt(unsigned Index) const {
00434     CALLSITE_DELEGATE_GETTER(getOperandBundleAt(Index));
00435   }
00436 
00437   Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
00438     CALLSITE_DELEGATE_GETTER(getOperandBundle(Name));
00439   }
00440 
00441   Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
00442     CALLSITE_DELEGATE_GETTER(getOperandBundle(ID));
00443   }
00444 
00445   IterTy arg_begin() const {
00446     CALLSITE_DELEGATE_GETTER(arg_begin());
00447   }
00448 
00449   IterTy arg_end() const {
00450     CALLSITE_DELEGATE_GETTER(arg_end());
00451   }
00452 
00453 #undef CALLSITE_DELEGATE_GETTER
00454 #undef CALLSITE_DELEGATE_SETTER
00455 
00456   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
00457     const Instruction *II = getInstruction();
00458     // Since this is actually a getter that "looks like" a setter, don't use the
00459     // above macros to avoid confusion.
00460     if (isCall())
00461       cast<CallInst>(II)->getOperandBundlesAsDefs(Defs);
00462     else
00463       cast<InvokeInst>(II)->getOperandBundlesAsDefs(Defs);
00464   }
00465 
00466   /// @brief Determine whether this data operand is not captured.
00467   bool doesNotCapture(unsigned OpNo) const {
00468     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::NoCapture);
00469   }
00470 
00471   /// @brief Determine whether this argument is passed by value.
00472   bool isByValArgument(unsigned ArgNo) const {
00473     return paramHasAttr(ArgNo + 1, Attribute::ByVal);
00474   }
00475 
00476   /// @brief Determine whether this argument is passed in an alloca.
00477   bool isInAllocaArgument(unsigned ArgNo) const {
00478     return paramHasAttr(ArgNo + 1, Attribute::InAlloca);
00479   }
00480 
00481   /// @brief Determine whether this argument is passed by value or in an alloca.
00482   bool isByValOrInAllocaArgument(unsigned ArgNo) const {
00483     return paramHasAttr(ArgNo + 1, Attribute::ByVal) ||
00484            paramHasAttr(ArgNo + 1, Attribute::InAlloca);
00485   }
00486 
00487   /// @brief Determine if there are is an inalloca argument.  Only the last
00488   /// argument can have the inalloca attribute.
00489   bool hasInAllocaArgument() const {
00490     return paramHasAttr(arg_size(), Attribute::InAlloca);
00491   }
00492 
00493   bool doesNotAccessMemory(unsigned OpNo) const {
00494     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
00495   }
00496 
00497   bool onlyReadsMemory(unsigned OpNo) const {
00498     return dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadOnly) ||
00499            dataOperandHasImpliedAttr(OpNo + 1, Attribute::ReadNone);
00500   }
00501 
00502   /// @brief Return true if the return value is known to be not null.
00503   /// This may be because it has the nonnull attribute, or because at least
00504   /// one byte is dereferenceable and the pointer is in addrspace(0).
00505   bool isReturnNonNull() const {
00506     if (paramHasAttr(0, Attribute::NonNull))
00507       return true;
00508     else if (getDereferenceableBytes(0) > 0 &&
00509              getType()->getPointerAddressSpace() == 0)
00510       return true;
00511 
00512     return false;
00513   }
00514 
00515   /// hasArgument - Returns true if this CallSite passes the given Value* as an
00516   /// argument to the called function.
00517   bool hasArgument(const Value *Arg) const {
00518     for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E;
00519          ++AI)
00520       if (AI->get() == Arg)
00521         return true;
00522     return false;
00523   }
00524 
00525 private:
00526   IterTy getCallee() const {
00527     if (isCall()) // Skip Callee
00528       return cast<CallInst>(getInstruction())->op_end() - 1;
00529     else // Skip BB, BB, Callee
00530       return cast<InvokeInst>(getInstruction())->op_end() - 3;
00531   }
00532 };
00533 
00534 class CallSite : public CallSiteBase<Function, BasicBlock, Value, User, Use,
00535                                      Instruction, CallInst, InvokeInst,
00536                                      User::op_iterator> {
00537 public:
00538   CallSite() {}
00539   CallSite(CallSiteBase B) : CallSiteBase(B) {}
00540   CallSite(CallInst *CI) : CallSiteBase(CI) {}
00541   CallSite(InvokeInst *II) : CallSiteBase(II) {}
00542   explicit CallSite(Instruction *II) : CallSiteBase(II) {}
00543   explicit CallSite(Value *V) : CallSiteBase(V) {}
00544 
00545   bool operator==(const CallSite &CS) const { return I == CS.I; }
00546   bool operator!=(const CallSite &CS) const { return I != CS.I; }
00547   bool operator<(const CallSite &CS) const {
00548     return getInstruction() < CS.getInstruction();
00549   }
00550 
00551 private:
00552   User::op_iterator getCallee() const;
00553 };
00554 
00555 /// ImmutableCallSite - establish a view to a call site for examination
00556 class ImmutableCallSite : public CallSiteBase<> {
00557 public:
00558   ImmutableCallSite() {}
00559   ImmutableCallSite(const CallInst *CI) : CallSiteBase(CI) {}
00560   ImmutableCallSite(const InvokeInst *II) : CallSiteBase(II) {}
00561   explicit ImmutableCallSite(const Instruction *II) : CallSiteBase(II) {}
00562   explicit ImmutableCallSite(const Value *V) : CallSiteBase(V) {}
00563   ImmutableCallSite(CallSite CS) : CallSiteBase(CS.getInstruction()) {}
00564 };
00565 
00566 } // End llvm namespace
00567 
00568 #endif