clang API Documentation

CallEvent.h
Go to the documentation of this file.
00001 //===- CallEvent.h - Wrapper for all function and method calls ----*- 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 /// \file This file defines CallEvent and its subclasses, which represent path-
00011 /// sensitive instances of different kinds of function and method calls
00012 /// (C, C++, and Objective-C).
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
00017 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
00018 
00019 #include "clang/AST/DeclCXX.h"
00020 #include "clang/AST/ExprCXX.h"
00021 #include "clang/AST/ExprObjC.h"
00022 #include "clang/Analysis/AnalysisContext.h"
00023 #include "clang/Basic/SourceManager.h"
00024 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00025 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
00026 #include "llvm/ADT/PointerIntPair.h"
00027 
00028 namespace clang {
00029 class ProgramPoint;
00030 class ProgramPointTag;
00031 
00032 namespace ento {
00033 
00034 enum CallEventKind {
00035   CE_Function,
00036   CE_CXXMember,
00037   CE_CXXMemberOperator,
00038   CE_CXXDestructor,
00039   CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
00040   CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
00041   CE_CXXConstructor,
00042   CE_CXXAllocator,
00043   CE_BEG_FUNCTION_CALLS = CE_Function,
00044   CE_END_FUNCTION_CALLS = CE_CXXAllocator,
00045   CE_Block,
00046   CE_ObjCMessage
00047 };
00048 
00049 class CallEvent;
00050 class CallEventManager;
00051 
00052 template<typename T = CallEvent>
00053 class CallEventRef : public IntrusiveRefCntPtr<const T> {
00054 public:
00055   CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
00056   CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
00057 
00058   CallEventRef<T> cloneWithState(ProgramStateRef State) const {
00059     return this->get()->template cloneWithState<T>(State);
00060   }
00061 
00062   // Allow implicit conversions to a superclass type, since CallEventRef
00063   // behaves like a pointer-to-const.
00064   template <typename SuperT>
00065   operator CallEventRef<SuperT> () const {
00066     return this->get();
00067   }
00068 };
00069 
00070 /// \class RuntimeDefinition 
00071 /// \brief Defines the runtime definition of the called function.
00072 /// 
00073 /// Encapsulates the information we have about which Decl will be used 
00074 /// when the call is executed on the given path. When dealing with dynamic
00075 /// dispatch, the information is based on DynamicTypeInfo and might not be 
00076 /// precise.
00077 class RuntimeDefinition {
00078   /// The Declaration of the function which could be called at runtime.
00079   /// NULL if not available.
00080   const Decl *D;
00081 
00082   /// The region representing an object (ObjC/C++) on which the method is
00083   /// called. With dynamic dispatch, the method definition depends on the
00084   /// runtime type of this object. NULL when the DynamicTypeInfo is
00085   /// precise.
00086   const MemRegion *R;
00087 
00088 public:
00089   RuntimeDefinition(): D(nullptr), R(nullptr) {}
00090   RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {}
00091   RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
00092   const Decl *getDecl() { return D; }
00093     
00094   /// \brief Check if the definition we have is precise. 
00095   /// If not, it is possible that the call dispatches to another definition at 
00096   /// execution time.
00097   bool mayHaveOtherDefinitions() { return R != nullptr; }
00098   
00099   /// When other definitions are possible, returns the region whose runtime type 
00100   /// determines the method definition.
00101   const MemRegion *getDispatchRegion() { return R; }
00102 };
00103 
00104 /// \brief Represents an abstract call to a function or method along a
00105 /// particular path.
00106 ///
00107 /// CallEvents are created through the factory methods of CallEventManager.
00108 ///
00109 /// CallEvents should always be cheap to create and destroy. In order for
00110 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
00111 /// subclasses of CallEvent may not add any data members to the base class.
00112 /// Use the "Data" and "Location" fields instead.
00113 class CallEvent {
00114 public:
00115   typedef CallEventKind Kind;
00116 
00117 private:
00118   ProgramStateRef State;
00119   const LocationContext *LCtx;
00120   llvm::PointerUnion<const Expr *, const Decl *> Origin;
00121 
00122   void operator=(const CallEvent &) LLVM_DELETED_FUNCTION;
00123 
00124 protected:
00125   // This is user data for subclasses.
00126   const void *Data;
00127 
00128   // This is user data for subclasses.
00129   // This should come right before RefCount, so that the two fields can be
00130   // packed together on LP64 platforms.
00131   SourceLocation Location;
00132 
00133 private:
00134   mutable unsigned RefCount;
00135 
00136   template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
00137   void Retain() const { ++RefCount; }
00138   void Release() const;
00139 
00140 protected:
00141   friend class CallEventManager;
00142 
00143   CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
00144     : State(state), LCtx(lctx), Origin(E), RefCount(0) {}
00145 
00146   CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
00147     : State(state), LCtx(lctx), Origin(D), RefCount(0) {}
00148 
00149   // DO NOT MAKE PUBLIC
00150   CallEvent(const CallEvent &Original)
00151     : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
00152       Data(Original.Data), Location(Original.Location), RefCount(0) {}
00153 
00154   /// Copies this CallEvent, with vtable intact, into a new block of memory.
00155   virtual void cloneTo(void *Dest) const = 0;
00156 
00157   /// \brief Get the value of arbitrary expressions at this point in the path.
00158   SVal getSVal(const Stmt *S) const {
00159     return getState()->getSVal(S, getLocationContext());
00160   }
00161 
00162 
00163   typedef SmallVectorImpl<SVal> ValueList;
00164 
00165   /// \brief Used to specify non-argument regions that will be invalidated as a
00166   /// result of this call.
00167   virtual void getExtraInvalidatedValues(ValueList &Values) const {}
00168 
00169 public:
00170   virtual ~CallEvent() {}
00171 
00172   /// \brief Returns the kind of call this is.
00173   virtual Kind getKind() const = 0;
00174 
00175   /// \brief Returns the declaration of the function or method that will be
00176   /// called. May be null.
00177   virtual const Decl *getDecl() const {
00178     return Origin.dyn_cast<const Decl *>();
00179   }
00180 
00181   /// \brief The state in which the call is being evaluated.
00182   const ProgramStateRef &getState() const {
00183     return State;
00184   }
00185 
00186   /// \brief The context in which the call is being evaluated.
00187   const LocationContext *getLocationContext() const {
00188     return LCtx;
00189   }
00190 
00191   /// \brief Returns the definition of the function or method that will be
00192   /// called.
00193   virtual RuntimeDefinition getRuntimeDefinition() const = 0;
00194 
00195   /// \brief Returns the expression whose value will be the result of this call.
00196   /// May be null.
00197   const Expr *getOriginExpr() const {
00198     return Origin.dyn_cast<const Expr *>();
00199   }
00200 
00201   /// \brief Returns the number of arguments (explicit and implicit).
00202   ///
00203   /// Note that this may be greater than the number of parameters in the
00204   /// callee's declaration, and that it may include arguments not written in
00205   /// the source.
00206   virtual unsigned getNumArgs() const = 0;
00207 
00208   /// \brief Returns true if the callee is known to be from a system header.
00209   bool isInSystemHeader() const {
00210     const Decl *D = getDecl();
00211     if (!D)
00212       return false;
00213 
00214     SourceLocation Loc = D->getLocation();
00215     if (Loc.isValid()) {
00216       const SourceManager &SM =
00217         getState()->getStateManager().getContext().getSourceManager();
00218       return SM.isInSystemHeader(D->getLocation());
00219     }
00220 
00221     // Special case for implicitly-declared global operator new/delete.
00222     // These should be considered system functions.
00223     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
00224       return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
00225 
00226     return false;
00227   }
00228 
00229   /// \brief Returns a source range for the entire call, suitable for
00230   /// outputting in diagnostics.
00231   virtual SourceRange getSourceRange() const {
00232     return getOriginExpr()->getSourceRange();
00233   }
00234 
00235   /// \brief Returns the value of a given argument at the time of the call.
00236   virtual SVal getArgSVal(unsigned Index) const;
00237 
00238   /// \brief Returns the expression associated with a given argument.
00239   /// May be null if this expression does not appear in the source.
00240   virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
00241 
00242   /// \brief Returns the source range for errors associated with this argument.
00243   ///
00244   /// May be invalid if the argument is not written in the source.
00245   virtual SourceRange getArgSourceRange(unsigned Index) const;
00246 
00247   /// \brief Returns the result type, adjusted for references.
00248   QualType getResultType() const;
00249 
00250   /// \brief Returns the return value of the call.
00251   ///
00252   /// This should only be called if the CallEvent was created using a state in
00253   /// which the return value has already been bound to the origin expression.
00254   SVal getReturnValue() const;
00255 
00256   /// \brief Returns true if any of the arguments appear to represent callbacks.
00257   bool hasNonZeroCallbackArg() const;
00258 
00259   /// \brief Returns true if any of the arguments are known to escape to long-
00260   /// term storage, even if this method will not modify them.
00261   // NOTE: The exact semantics of this are still being defined!
00262   // We don't really want a list of hardcoded exceptions in the long run,
00263   // but we don't want duplicated lists of known APIs in the short term either.
00264   virtual bool argumentsMayEscape() const {
00265     return hasNonZeroCallbackArg();
00266   }
00267 
00268   /// \brief Returns true if the callee is an externally-visible function in the
00269   /// top-level namespace, such as \c malloc.
00270   ///
00271   /// You can use this call to determine that a particular function really is
00272   /// a library function and not, say, a C++ member function with the same name.
00273   ///
00274   /// If a name is provided, the function must additionally match the given
00275   /// name.
00276   ///
00277   /// Note that this deliberately excludes C++ library functions in the \c std
00278   /// namespace, but will include C library functions accessed through the
00279   /// \c std namespace. This also does not check if the function is declared
00280   /// as 'extern "C"', or if it uses C++ name mangling.
00281   // FIXME: Add a helper for checking namespaces.
00282   // FIXME: Move this down to AnyFunctionCall once checkers have more
00283   // precise callbacks.
00284   bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
00285 
00286   /// \brief Returns the name of the callee, if its name is a simple identifier.
00287   ///
00288   /// Note that this will fail for Objective-C methods, blocks, and C++
00289   /// overloaded operators. The former is named by a Selector rather than a
00290   /// simple identifier, and the latter two do not have names.
00291   // FIXME: Move this down to AnyFunctionCall once checkers have more
00292   // precise callbacks.
00293   const IdentifierInfo *getCalleeIdentifier() const {
00294     const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl());
00295     if (!ND)
00296       return nullptr;
00297     return ND->getIdentifier();
00298   }
00299 
00300   /// \brief Returns an appropriate ProgramPoint for this call.
00301   ProgramPoint getProgramPoint(bool IsPreVisit = false,
00302                                const ProgramPointTag *Tag = nullptr) const;
00303 
00304   /// \brief Returns a new state with all argument regions invalidated.
00305   ///
00306   /// This accepts an alternate state in case some processing has already
00307   /// occurred.
00308   ProgramStateRef invalidateRegions(unsigned BlockCount,
00309                                     ProgramStateRef Orig = nullptr) const;
00310 
00311   typedef std::pair<Loc, SVal> FrameBindingTy;
00312   typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
00313 
00314   /// Populates the given SmallVector with the bindings in the callee's stack
00315   /// frame at the start of this call.
00316   virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00317                                             BindingsTy &Bindings) const = 0;
00318 
00319   /// Returns a copy of this CallEvent, but using the given state.
00320   template <typename T>
00321   CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
00322 
00323   /// Returns a copy of this CallEvent, but using the given state.
00324   CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
00325     return cloneWithState<CallEvent>(NewState);
00326   }
00327 
00328   /// \brief Returns true if this is a statement is a function or method call
00329   /// of some kind.
00330   static bool isCallStmt(const Stmt *S);
00331 
00332   /// \brief Returns the result type of a function or method declaration.
00333   ///
00334   /// This will return a null QualType if the result type cannot be determined.
00335   static QualType getDeclaredResultType(const Decl *D);
00336 
00337   /// \brief Returns true if the given decl is known to be variadic.
00338   ///
00339   /// \p D must not be null.
00340   static bool isVariadic(const Decl *D);
00341 
00342   // Iterator access to formal parameters and their types.
00343 private:
00344   typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun;
00345 
00346 public:
00347   /// Return call's formal parameters.
00348   ///
00349   /// Remember that the number of formal parameters may not match the number
00350   /// of arguments for all calls. However, the first parameter will always
00351   /// correspond with the argument value returned by \c getArgSVal(0).
00352   virtual ArrayRef<ParmVarDecl*> parameters() const = 0;
00353 
00354   typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, get_type_fun>
00355     param_type_iterator;
00356 
00357   /// Returns an iterator over the types of the call's formal parameters.
00358   ///
00359   /// This uses the callee decl found by default name lookup rather than the
00360   /// definition because it represents a public interface, and probably has
00361   /// more annotations.
00362   param_type_iterator param_type_begin() const {
00363     return llvm::map_iterator(parameters().begin(),
00364                               get_type_fun(&ParmVarDecl::getType));
00365   }
00366   /// \sa param_type_begin()
00367   param_type_iterator param_type_end() const {
00368     return llvm::map_iterator(parameters().end(),
00369                               get_type_fun(&ParmVarDecl::getType));
00370   }
00371 
00372   // For debugging purposes only
00373   void dump(raw_ostream &Out) const;
00374   void dump() const;
00375 };
00376 
00377 
00378 /// \brief Represents a call to any sort of function that might have a
00379 /// FunctionDecl.
00380 class AnyFunctionCall : public CallEvent {
00381 protected:
00382   AnyFunctionCall(const Expr *E, ProgramStateRef St,
00383                   const LocationContext *LCtx)
00384     : CallEvent(E, St, LCtx) {}
00385   AnyFunctionCall(const Decl *D, ProgramStateRef St,
00386                   const LocationContext *LCtx)
00387     : CallEvent(D, St, LCtx) {}
00388   AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
00389 
00390 public:
00391   // This function is overridden by subclasses, but they must return
00392   // a FunctionDecl.
00393   const FunctionDecl *getDecl() const override {
00394     return cast<FunctionDecl>(CallEvent::getDecl());
00395   }
00396 
00397   RuntimeDefinition getRuntimeDefinition() const override {
00398     const FunctionDecl *FD = getDecl();
00399     // Note that the AnalysisDeclContext will have the FunctionDecl with
00400     // the definition (if one exists).
00401     if (FD) {
00402       AnalysisDeclContext *AD =
00403         getLocationContext()->getAnalysisDeclContext()->
00404         getManager()->getContext(FD);
00405       if (AD->getBody())
00406         return RuntimeDefinition(AD->getDecl());
00407     }
00408 
00409     return RuntimeDefinition();
00410   }
00411 
00412   bool argumentsMayEscape() const override;
00413 
00414   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00415                                     BindingsTy &Bindings) const override;
00416 
00417   ArrayRef<ParmVarDecl *> parameters() const override;
00418 
00419   static bool classof(const CallEvent *CA) {
00420     return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
00421            CA->getKind() <= CE_END_FUNCTION_CALLS;
00422   }
00423 };
00424 
00425 /// \brief Represents a C function or static C++ member function call.
00426 ///
00427 /// Example: \c fun()
00428 class SimpleFunctionCall : public AnyFunctionCall {
00429   friend class CallEventManager;
00430 
00431 protected:
00432   SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
00433                      const LocationContext *LCtx)
00434     : AnyFunctionCall(CE, St, LCtx) {}
00435   SimpleFunctionCall(const SimpleFunctionCall &Other)
00436     : AnyFunctionCall(Other) {}
00437   void cloneTo(void *Dest) const override {
00438     new (Dest) SimpleFunctionCall(*this);
00439   }
00440 
00441 public:
00442   virtual const CallExpr *getOriginExpr() const {
00443     return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
00444   }
00445 
00446   const FunctionDecl *getDecl() const override;
00447 
00448   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
00449 
00450   const Expr *getArgExpr(unsigned Index) const override {
00451     return getOriginExpr()->getArg(Index);
00452   }
00453 
00454   Kind getKind() const override { return CE_Function; }
00455 
00456   static bool classof(const CallEvent *CA) {
00457     return CA->getKind() == CE_Function;
00458   }
00459 };
00460 
00461 /// \brief Represents a call to a block.
00462 ///
00463 /// Example: <tt>^{ /* ... */ }()</tt>
00464 class BlockCall : public CallEvent {
00465   friend class CallEventManager;
00466 
00467 protected:
00468   BlockCall(const CallExpr *CE, ProgramStateRef St,
00469             const LocationContext *LCtx)
00470     : CallEvent(CE, St, LCtx) {}
00471 
00472   BlockCall(const BlockCall &Other) : CallEvent(Other) {}
00473   void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
00474 
00475   void getExtraInvalidatedValues(ValueList &Values) const override;
00476 
00477 public:
00478   virtual const CallExpr *getOriginExpr() const {
00479     return cast<CallExpr>(CallEvent::getOriginExpr());
00480   }
00481 
00482   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
00483 
00484   const Expr *getArgExpr(unsigned Index) const override {
00485     return getOriginExpr()->getArg(Index);
00486   }
00487 
00488   /// \brief Returns the region associated with this instance of the block.
00489   ///
00490   /// This may be NULL if the block's origin is unknown.
00491   const BlockDataRegion *getBlockRegion() const;
00492 
00493   const BlockDecl *getDecl() const override {
00494     const BlockDataRegion *BR = getBlockRegion();
00495     if (!BR)
00496       return nullptr;
00497     return BR->getDecl();
00498   }
00499 
00500   RuntimeDefinition getRuntimeDefinition() const override {
00501     return RuntimeDefinition(getDecl());
00502   }
00503 
00504   bool argumentsMayEscape() const override {
00505     return true;
00506   }
00507 
00508   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00509                                     BindingsTy &Bindings) const override;
00510 
00511   ArrayRef<ParmVarDecl*> parameters() const override;
00512 
00513   Kind getKind() const override { return CE_Block; }
00514 
00515   static bool classof(const CallEvent *CA) {
00516     return CA->getKind() == CE_Block;
00517   }
00518 };
00519 
00520 /// \brief Represents a non-static C++ member function call, no matter how
00521 /// it is written.
00522 class CXXInstanceCall : public AnyFunctionCall {
00523 protected:
00524   void getExtraInvalidatedValues(ValueList &Values) const override;
00525 
00526   CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
00527                   const LocationContext *LCtx)
00528     : AnyFunctionCall(CE, St, LCtx) {}
00529   CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
00530                   const LocationContext *LCtx)
00531     : AnyFunctionCall(D, St, LCtx) {}
00532 
00533 
00534   CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
00535 
00536 public:
00537   /// \brief Returns the expression representing the implicit 'this' object.
00538   virtual const Expr *getCXXThisExpr() const { return nullptr; }
00539 
00540   /// \brief Returns the value of the implicit 'this' object.
00541   virtual SVal getCXXThisVal() const;
00542 
00543   const FunctionDecl *getDecl() const override;
00544 
00545   RuntimeDefinition getRuntimeDefinition() const override;
00546 
00547   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00548                                     BindingsTy &Bindings) const override;
00549 
00550   static bool classof(const CallEvent *CA) {
00551     return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
00552            CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
00553   }
00554 };
00555 
00556 /// \brief Represents a non-static C++ member function call.
00557 ///
00558 /// Example: \c obj.fun()
00559 class CXXMemberCall : public CXXInstanceCall {
00560   friend class CallEventManager;
00561 
00562 protected:
00563   CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
00564                 const LocationContext *LCtx)
00565     : CXXInstanceCall(CE, St, LCtx) {}
00566 
00567   CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
00568   void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
00569 
00570 public:
00571   virtual const CXXMemberCallExpr *getOriginExpr() const {
00572     return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
00573   }
00574 
00575   unsigned getNumArgs() const override {
00576     if (const CallExpr *CE = getOriginExpr())
00577       return CE->getNumArgs();
00578     return 0;
00579   }
00580 
00581   const Expr *getArgExpr(unsigned Index) const override {
00582     return getOriginExpr()->getArg(Index);
00583   }
00584 
00585   const Expr *getCXXThisExpr() const override;
00586 
00587   RuntimeDefinition getRuntimeDefinition() const override;
00588 
00589   Kind getKind() const override { return CE_CXXMember; }
00590 
00591   static bool classof(const CallEvent *CA) {
00592     return CA->getKind() == CE_CXXMember;
00593   }
00594 };
00595 
00596 /// \brief Represents a C++ overloaded operator call where the operator is
00597 /// implemented as a non-static member function.
00598 ///
00599 /// Example: <tt>iter + 1</tt>
00600 class CXXMemberOperatorCall : public CXXInstanceCall {
00601   friend class CallEventManager;
00602 
00603 protected:
00604   CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
00605                         const LocationContext *LCtx)
00606     : CXXInstanceCall(CE, St, LCtx) {}
00607 
00608   CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
00609     : CXXInstanceCall(Other) {}
00610   void cloneTo(void *Dest) const override {
00611     new (Dest) CXXMemberOperatorCall(*this);
00612   }
00613 
00614 public:
00615   virtual const CXXOperatorCallExpr *getOriginExpr() const {
00616     return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
00617   }
00618 
00619   unsigned getNumArgs() const override {
00620     return getOriginExpr()->getNumArgs() - 1;
00621   }
00622   const Expr *getArgExpr(unsigned Index) const override {
00623     return getOriginExpr()->getArg(Index + 1);
00624   }
00625 
00626   const Expr *getCXXThisExpr() const override;
00627 
00628   Kind getKind() const override { return CE_CXXMemberOperator; }
00629 
00630   static bool classof(const CallEvent *CA) {
00631     return CA->getKind() == CE_CXXMemberOperator;
00632   }
00633 };
00634 
00635 /// \brief Represents an implicit call to a C++ destructor.
00636 ///
00637 /// This can occur at the end of a scope (for automatic objects), at the end
00638 /// of a full-expression (for temporaries), or as part of a delete.
00639 class CXXDestructorCall : public CXXInstanceCall {
00640   friend class CallEventManager;
00641 
00642 protected:
00643   typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy;
00644 
00645   /// Creates an implicit destructor.
00646   ///
00647   /// \param DD The destructor that will be called.
00648   /// \param Trigger The statement whose completion causes this destructor call.
00649   /// \param Target The object region to be destructed.
00650   /// \param St The path-sensitive state at this point in the program.
00651   /// \param LCtx The location context at this point in the program.
00652   CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
00653                     const MemRegion *Target, bool IsBaseDestructor,
00654                     ProgramStateRef St, const LocationContext *LCtx)
00655     : CXXInstanceCall(DD, St, LCtx) {
00656     Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
00657     Location = Trigger->getLocEnd();
00658   }
00659 
00660   CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
00661   void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
00662 
00663 public:
00664   SourceRange getSourceRange() const override { return Location; }
00665   unsigned getNumArgs() const override { return 0; }
00666 
00667   RuntimeDefinition getRuntimeDefinition() const override;
00668 
00669   /// \brief Returns the value of the implicit 'this' object.
00670   SVal getCXXThisVal() const override;
00671 
00672   /// Returns true if this is a call to a base class destructor.
00673   bool isBaseDestructor() const {
00674     return DtorDataTy::getFromOpaqueValue(Data).getInt();
00675   }
00676 
00677   Kind getKind() const override { return CE_CXXDestructor; }
00678 
00679   static bool classof(const CallEvent *CA) {
00680     return CA->getKind() == CE_CXXDestructor;
00681   }
00682 };
00683 
00684 /// \brief Represents a call to a C++ constructor.
00685 ///
00686 /// Example: \c T(1)
00687 class CXXConstructorCall : public AnyFunctionCall {
00688   friend class CallEventManager;
00689 
00690 protected:
00691   /// Creates a constructor call.
00692   ///
00693   /// \param CE The constructor expression as written in the source.
00694   /// \param Target The region where the object should be constructed. If NULL,
00695   ///               a new symbolic region will be used.
00696   /// \param St The path-sensitive state at this point in the program.
00697   /// \param LCtx The location context at this point in the program.
00698   CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
00699                      ProgramStateRef St, const LocationContext *LCtx)
00700     : AnyFunctionCall(CE, St, LCtx) {
00701     Data = Target;
00702   }
00703 
00704   CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
00705   void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
00706 
00707   void getExtraInvalidatedValues(ValueList &Values) const override;
00708 
00709 public:
00710   virtual const CXXConstructExpr *getOriginExpr() const {
00711     return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
00712   }
00713 
00714   const CXXConstructorDecl *getDecl() const override {
00715     return getOriginExpr()->getConstructor();
00716   }
00717 
00718   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
00719 
00720   const Expr *getArgExpr(unsigned Index) const override {
00721     return getOriginExpr()->getArg(Index);
00722   }
00723 
00724   /// \brief Returns the value of the implicit 'this' object.
00725   SVal getCXXThisVal() const;
00726 
00727   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00728                                     BindingsTy &Bindings) const override;
00729 
00730   Kind getKind() const override { return CE_CXXConstructor; }
00731 
00732   static bool classof(const CallEvent *CA) {
00733     return CA->getKind() == CE_CXXConstructor;
00734   }
00735 };
00736 
00737 /// \brief Represents the memory allocation call in a C++ new-expression.
00738 ///
00739 /// This is a call to "operator new".
00740 class CXXAllocatorCall : public AnyFunctionCall {
00741   friend class CallEventManager;
00742 
00743 protected:
00744   CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
00745                    const LocationContext *LCtx)
00746     : AnyFunctionCall(E, St, LCtx) {}
00747 
00748   CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
00749   void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
00750 
00751 public:
00752   virtual const CXXNewExpr *getOriginExpr() const {
00753     return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
00754   }
00755 
00756   const FunctionDecl *getDecl() const override {
00757     return getOriginExpr()->getOperatorNew();
00758   }
00759 
00760   unsigned getNumArgs() const override {
00761     return getOriginExpr()->getNumPlacementArgs() + 1;
00762   }
00763 
00764   const Expr *getArgExpr(unsigned Index) const override {
00765     // The first argument of an allocator call is the size of the allocation.
00766     if (Index == 0)
00767       return nullptr;
00768     return getOriginExpr()->getPlacementArg(Index - 1);
00769   }
00770 
00771   Kind getKind() const override { return CE_CXXAllocator; }
00772 
00773   static bool classof(const CallEvent *CE) {
00774     return CE->getKind() == CE_CXXAllocator;
00775   }
00776 };
00777 
00778 /// \brief Represents the ways an Objective-C message send can occur.
00779 //
00780 // Note to maintainers: OCM_Message should always be last, since it does not
00781 // need to fit in the Data field's low bits.
00782 enum ObjCMessageKind {
00783   OCM_PropertyAccess,
00784   OCM_Subscript,
00785   OCM_Message
00786 };
00787 
00788 /// \brief Represents any expression that calls an Objective-C method.
00789 ///
00790 /// This includes all of the kinds listed in ObjCMessageKind.
00791 class ObjCMethodCall : public CallEvent {
00792   friend class CallEventManager;
00793 
00794   const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
00795 
00796 protected:
00797   ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
00798                  const LocationContext *LCtx)
00799     : CallEvent(Msg, St, LCtx) {
00800     Data = nullptr;
00801   }
00802 
00803   ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
00804   void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
00805 
00806   void getExtraInvalidatedValues(ValueList &Values) const override;
00807 
00808   /// Check if the selector may have multiple definitions (may have overrides).
00809   virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
00810                                         Selector Sel) const;
00811 
00812 public:
00813   virtual const ObjCMessageExpr *getOriginExpr() const {
00814     return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
00815   }
00816   const ObjCMethodDecl *getDecl() const override {
00817     return getOriginExpr()->getMethodDecl();
00818   }
00819   unsigned getNumArgs() const override {
00820     return getOriginExpr()->getNumArgs();
00821   }
00822   const Expr *getArgExpr(unsigned Index) const override {
00823     return getOriginExpr()->getArg(Index);
00824   }
00825 
00826   bool isInstanceMessage() const {
00827     return getOriginExpr()->isInstanceMessage();
00828   }
00829   ObjCMethodFamily getMethodFamily() const {
00830     return getOriginExpr()->getMethodFamily();
00831   }
00832   Selector getSelector() const {
00833     return getOriginExpr()->getSelector();
00834   }
00835 
00836   SourceRange getSourceRange() const override;
00837 
00838   /// \brief Returns the value of the receiver at the time of this call.
00839   SVal getReceiverSVal() const;
00840 
00841   /// \brief Return the value of 'self' if available.
00842   SVal getSelfSVal() const;
00843 
00844   /// \brief Get the interface for the receiver.
00845   ///
00846   /// This works whether this is an instance message or a class message.
00847   /// However, it currently just uses the static type of the receiver.
00848   const ObjCInterfaceDecl *getReceiverInterface() const {
00849     return getOriginExpr()->getReceiverInterface();
00850   }
00851 
00852   /// \brief Checks if the receiver refers to 'self' or 'super'.
00853   bool isReceiverSelfOrSuper() const;
00854 
00855   /// Returns how the message was written in the source (property access,
00856   /// subscript, or explicit message send).
00857   ObjCMessageKind getMessageKind() const;
00858 
00859   /// Returns true if this property access or subscript is a setter (has the
00860   /// form of an assignment).
00861   bool isSetter() const {
00862     switch (getMessageKind()) {
00863     case OCM_Message:
00864       llvm_unreachable("This is not a pseudo-object access!");
00865     case OCM_PropertyAccess:
00866       return getNumArgs() > 0;
00867     case OCM_Subscript:
00868       return getNumArgs() > 1;
00869     }
00870     llvm_unreachable("Unknown message kind");
00871   }
00872 
00873   RuntimeDefinition getRuntimeDefinition() const override;
00874 
00875   bool argumentsMayEscape() const override;
00876 
00877   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
00878                                     BindingsTy &Bindings) const override;
00879 
00880   ArrayRef<ParmVarDecl*> parameters() const override;
00881 
00882   Kind getKind() const override { return CE_ObjCMessage; }
00883 
00884   static bool classof(const CallEvent *CA) {
00885     return CA->getKind() == CE_ObjCMessage;
00886   }
00887 };
00888 
00889 
00890 /// \brief Manages the lifetime of CallEvent objects.
00891 ///
00892 /// CallEventManager provides a way to create arbitrary CallEvents "on the
00893 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
00894 /// memory blocks. The CallEvents created by CallEventManager are only valid
00895 /// for the lifetime of the OwnedCallEvent that holds them; right now these
00896 /// objects cannot be copied and ownership cannot be transferred.
00897 class CallEventManager {
00898   friend class CallEvent;
00899 
00900   llvm::BumpPtrAllocator &Alloc;
00901   SmallVector<void *, 8> Cache;
00902   typedef SimpleFunctionCall CallEventTemplateTy;
00903 
00904   void reclaim(const void *Memory) {
00905     Cache.push_back(const_cast<void *>(Memory));
00906   }
00907 
00908   /// Returns memory that can be initialized as a CallEvent.
00909   void *allocate() {
00910     if (Cache.empty())
00911       return Alloc.Allocate<CallEventTemplateTy>();
00912     else
00913       return Cache.pop_back_val();
00914   }
00915 
00916   template <typename T, typename Arg>
00917   T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
00918     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
00919                   "CallEvent subclasses are not all the same size");
00920     return new (allocate()) T(A, St, LCtx);
00921   }
00922 
00923   template <typename T, typename Arg1, typename Arg2>
00924   T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
00925     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
00926                   "CallEvent subclasses are not all the same size");
00927     return new (allocate()) T(A1, A2, St, LCtx);
00928   }
00929 
00930   template <typename T, typename Arg1, typename Arg2, typename Arg3>
00931   T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
00932             const LocationContext *LCtx) {
00933     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
00934                   "CallEvent subclasses are not all the same size");
00935     return new (allocate()) T(A1, A2, A3, St, LCtx);
00936   }
00937 
00938   template <typename T, typename Arg1, typename Arg2, typename Arg3,
00939             typename Arg4>
00940   T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
00941             const LocationContext *LCtx) {
00942     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
00943                   "CallEvent subclasses are not all the same size");
00944     return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
00945   }
00946 
00947 public:
00948   CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
00949 
00950 
00951   CallEventRef<>
00952   getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
00953 
00954 
00955   CallEventRef<>
00956   getSimpleCall(const CallExpr *E, ProgramStateRef State,
00957                 const LocationContext *LCtx);
00958 
00959   CallEventRef<ObjCMethodCall>
00960   getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
00961                     const LocationContext *LCtx) {
00962     return create<ObjCMethodCall>(E, State, LCtx);
00963   }
00964 
00965   CallEventRef<CXXConstructorCall>
00966   getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
00967                         ProgramStateRef State, const LocationContext *LCtx) {
00968     return create<CXXConstructorCall>(E, Target, State, LCtx);
00969   }
00970 
00971   CallEventRef<CXXDestructorCall>
00972   getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
00973                        const MemRegion *Target, bool IsBase,
00974                        ProgramStateRef State, const LocationContext *LCtx) {
00975     return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
00976   }
00977 
00978   CallEventRef<CXXAllocatorCall>
00979   getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
00980                       const LocationContext *LCtx) {
00981     return create<CXXAllocatorCall>(E, State, LCtx);
00982   }
00983 };
00984 
00985 
00986 template <typename T>
00987 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
00988   assert(isa<T>(*this) && "Cloning to unrelated type");
00989   static_assert(sizeof(T) == sizeof(CallEvent),
00990                 "Subclasses may not add fields");
00991 
00992   if (NewState == State)
00993     return cast<T>(this);
00994 
00995   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
00996   T *Copy = static_cast<T *>(Mgr.allocate());
00997   cloneTo(Copy);
00998   assert(Copy->getKind() == this->getKind() && "Bad copy");
00999 
01000   Copy->State = NewState;
01001   return Copy;
01002 }
01003 
01004 inline void CallEvent::Release() const {
01005   assert(RefCount > 0 && "Reference count is already zero.");
01006   --RefCount;
01007 
01008   if (RefCount > 0)
01009     return;
01010 
01011   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
01012   Mgr.reclaim(this);
01013 
01014   this->~CallEvent();
01015 }
01016 
01017 } // end namespace ento
01018 } // end namespace clang
01019 
01020 namespace llvm {
01021   // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
01022   template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
01023     typedef const T *SimpleType;
01024 
01025     static SimpleType
01026     getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
01027       return Val.get();
01028     }
01029   };
01030 }
01031 
01032 #endif