Home | History | Annotate | Download | only in PathSensitive
      1 //===- CallEvent.h - Wrapper for all function and method calls ----*- C++ -*--//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 /// \file This file defines CallEvent and its subclasses, which represent path-
     11 /// sensitive instances of different kinds of function and method calls
     12 /// (C, C++, and Objective-C).
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
     17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
     18 
     19 #include "clang/AST/DeclCXX.h"
     20 #include "clang/AST/ExprCXX.h"
     21 #include "clang/AST/ExprObjC.h"
     22 #include "clang/Analysis/AnalysisContext.h"
     23 #include "clang/Basic/SourceManager.h"
     24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
     25 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
     26 #include "llvm/ADT/PointerIntPair.h"
     27 #include <utility>
     28 
     29 namespace clang {
     30 class ProgramPoint;
     31 class ProgramPointTag;
     32 
     33 namespace ento {
     34 
     35 enum CallEventKind {
     36   CE_Function,
     37   CE_CXXMember,
     38   CE_CXXMemberOperator,
     39   CE_CXXDestructor,
     40   CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
     41   CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
     42   CE_CXXConstructor,
     43   CE_CXXAllocator,
     44   CE_BEG_FUNCTION_CALLS = CE_Function,
     45   CE_END_FUNCTION_CALLS = CE_CXXAllocator,
     46   CE_Block,
     47   CE_ObjCMessage
     48 };
     49 
     50 class CallEvent;
     51 class CallEventManager;
     52 
     53 /// This class represents a description of a function call using the number of
     54 /// arguments and the name of the function.
     55 class CallDescription {
     56   friend CallEvent;
     57   mutable IdentifierInfo *II;
     58   StringRef FuncName;
     59   unsigned RequiredArgs;
     60 
     61 public:
     62   const static unsigned NoArgRequirement = ~0;
     63   /// \brief Constructs a CallDescription object.
     64   ///
     65   /// @param FuncName The name of the function that will be matched.
     66   ///
     67   /// @param RequiredArgs The number of arguments that is expected to match a
     68   /// call. Omit this parameter to match every occurance of call with a given
     69   /// name regardless the number of arguments.
     70   CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
     71       : II(nullptr), FuncName(FuncName), RequiredArgs(RequiredArgs) {}
     72 
     73   /// \brief Get the name of the function that this object matches.
     74   StringRef getFunctionName() const { return FuncName; }
     75 };
     76 
     77 template<typename T = CallEvent>
     78 class CallEventRef : public IntrusiveRefCntPtr<const T> {
     79 public:
     80   CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
     81   CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
     82 
     83   CallEventRef<T> cloneWithState(ProgramStateRef State) const {
     84     return this->get()->template cloneWithState<T>(State);
     85   }
     86 
     87   // Allow implicit conversions to a superclass type, since CallEventRef
     88   // behaves like a pointer-to-const.
     89   template <typename SuperT>
     90   operator CallEventRef<SuperT> () const {
     91     return this->get();
     92   }
     93 };
     94 
     95 /// \class RuntimeDefinition
     96 /// \brief Defines the runtime definition of the called function.
     97 ///
     98 /// Encapsulates the information we have about which Decl will be used
     99 /// when the call is executed on the given path. When dealing with dynamic
    100 /// dispatch, the information is based on DynamicTypeInfo and might not be
    101 /// precise.
    102 class RuntimeDefinition {
    103   /// The Declaration of the function which could be called at runtime.
    104   /// NULL if not available.
    105   const Decl *D;
    106 
    107   /// The region representing an object (ObjC/C++) on which the method is
    108   /// called. With dynamic dispatch, the method definition depends on the
    109   /// runtime type of this object. NULL when the DynamicTypeInfo is
    110   /// precise.
    111   const MemRegion *R;
    112 
    113 public:
    114   RuntimeDefinition(): D(nullptr), R(nullptr) {}
    115   RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {}
    116   RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
    117   const Decl *getDecl() { return D; }
    118 
    119   /// \brief Check if the definition we have is precise.
    120   /// If not, it is possible that the call dispatches to another definition at
    121   /// execution time.
    122   bool mayHaveOtherDefinitions() { return R != nullptr; }
    123 
    124   /// When other definitions are possible, returns the region whose runtime type
    125   /// determines the method definition.
    126   const MemRegion *getDispatchRegion() { return R; }
    127 };
    128 
    129 /// \brief Represents an abstract call to a function or method along a
    130 /// particular path.
    131 ///
    132 /// CallEvents are created through the factory methods of CallEventManager.
    133 ///
    134 /// CallEvents should always be cheap to create and destroy. In order for
    135 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
    136 /// subclasses of CallEvent may not add any data members to the base class.
    137 /// Use the "Data" and "Location" fields instead.
    138 class CallEvent {
    139 public:
    140   typedef CallEventKind Kind;
    141 
    142 private:
    143   ProgramStateRef State;
    144   const LocationContext *LCtx;
    145   llvm::PointerUnion<const Expr *, const Decl *> Origin;
    146 
    147   void operator=(const CallEvent &) = delete;
    148 
    149 protected:
    150   // This is user data for subclasses.
    151   const void *Data;
    152 
    153   // This is user data for subclasses.
    154   // This should come right before RefCount, so that the two fields can be
    155   // packed together on LP64 platforms.
    156   SourceLocation Location;
    157 
    158 private:
    159   mutable unsigned RefCount;
    160 
    161   template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
    162   void Retain() const { ++RefCount; }
    163   void Release() const;
    164 
    165 protected:
    166   friend class CallEventManager;
    167 
    168   CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
    169       : State(std::move(state)), LCtx(lctx), Origin(E), RefCount(0) {}
    170 
    171   CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
    172       : State(std::move(state)), LCtx(lctx), Origin(D), RefCount(0) {}
    173 
    174   // DO NOT MAKE PUBLIC
    175   CallEvent(const CallEvent &Original)
    176     : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
    177       Data(Original.Data), Location(Original.Location), RefCount(0) {}
    178 
    179   /// Copies this CallEvent, with vtable intact, into a new block of memory.
    180   virtual void cloneTo(void *Dest) const = 0;
    181 
    182   /// \brief Get the value of arbitrary expressions at this point in the path.
    183   SVal getSVal(const Stmt *S) const {
    184     return getState()->getSVal(S, getLocationContext());
    185   }
    186 
    187 
    188   typedef SmallVectorImpl<SVal> ValueList;
    189 
    190   /// \brief Used to specify non-argument regions that will be invalidated as a
    191   /// result of this call.
    192   virtual void getExtraInvalidatedValues(ValueList &Values,
    193                  RegionAndSymbolInvalidationTraits *ETraits) const {}
    194 
    195 public:
    196   virtual ~CallEvent() {}
    197 
    198   /// \brief Returns the kind of call this is.
    199   virtual Kind getKind() const = 0;
    200 
    201   /// \brief Returns the declaration of the function or method that will be
    202   /// called. May be null.
    203   virtual const Decl *getDecl() const {
    204     return Origin.dyn_cast<const Decl *>();
    205   }
    206 
    207   /// \brief The state in which the call is being evaluated.
    208   const ProgramStateRef &getState() const {
    209     return State;
    210   }
    211 
    212   /// \brief The context in which the call is being evaluated.
    213   const LocationContext *getLocationContext() const {
    214     return LCtx;
    215   }
    216 
    217   /// \brief Returns the definition of the function or method that will be
    218   /// called.
    219   virtual RuntimeDefinition getRuntimeDefinition() const = 0;
    220 
    221   /// \brief Returns the expression whose value will be the result of this call.
    222   /// May be null.
    223   const Expr *getOriginExpr() const {
    224     return Origin.dyn_cast<const Expr *>();
    225   }
    226 
    227   /// \brief Returns the number of arguments (explicit and implicit).
    228   ///
    229   /// Note that this may be greater than the number of parameters in the
    230   /// callee's declaration, and that it may include arguments not written in
    231   /// the source.
    232   virtual unsigned getNumArgs() const = 0;
    233 
    234   /// \brief Returns true if the callee is known to be from a system header.
    235   bool isInSystemHeader() const {
    236     const Decl *D = getDecl();
    237     if (!D)
    238       return false;
    239 
    240     SourceLocation Loc = D->getLocation();
    241     if (Loc.isValid()) {
    242       const SourceManager &SM =
    243         getState()->getStateManager().getContext().getSourceManager();
    244       return SM.isInSystemHeader(D->getLocation());
    245     }
    246 
    247     // Special case for implicitly-declared global operator new/delete.
    248     // These should be considered system functions.
    249     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
    250       return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
    251 
    252     return false;
    253   }
    254 
    255   /// \brief Returns true if the CallEvent is a call to a function that matches
    256   /// the CallDescription.
    257   ///
    258   /// Note that this function is not intended to be used to match Obj-C method
    259   /// calls.
    260   bool isCalled(const CallDescription &CD) const;
    261 
    262   /// \brief Returns a source range for the entire call, suitable for
    263   /// outputting in diagnostics.
    264   virtual SourceRange getSourceRange() const {
    265     return getOriginExpr()->getSourceRange();
    266   }
    267 
    268   /// \brief Returns the value of a given argument at the time of the call.
    269   virtual SVal getArgSVal(unsigned Index) const;
    270 
    271   /// \brief Returns the expression associated with a given argument.
    272   /// May be null if this expression does not appear in the source.
    273   virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
    274 
    275   /// \brief Returns the source range for errors associated with this argument.
    276   ///
    277   /// May be invalid if the argument is not written in the source.
    278   virtual SourceRange getArgSourceRange(unsigned Index) const;
    279 
    280   /// \brief Returns the result type, adjusted for references.
    281   QualType getResultType() const;
    282 
    283   /// \brief Returns the return value of the call.
    284   ///
    285   /// This should only be called if the CallEvent was created using a state in
    286   /// which the return value has already been bound to the origin expression.
    287   SVal getReturnValue() const;
    288 
    289   /// \brief Returns true if the type of any of the non-null arguments satisfies
    290   /// the condition.
    291   bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
    292 
    293   /// \brief Returns true if any of the arguments appear to represent callbacks.
    294   bool hasNonZeroCallbackArg() const;
    295 
    296   /// \brief Returns true if any of the arguments is void*.
    297   bool hasVoidPointerToNonConstArg() const;
    298 
    299   /// \brief Returns true if any of the arguments are known to escape to long-
    300   /// term storage, even if this method will not modify them.
    301   // NOTE: The exact semantics of this are still being defined!
    302   // We don't really want a list of hardcoded exceptions in the long run,
    303   // but we don't want duplicated lists of known APIs in the short term either.
    304   virtual bool argumentsMayEscape() const {
    305     return hasNonZeroCallbackArg();
    306   }
    307 
    308   /// \brief Returns true if the callee is an externally-visible function in the
    309   /// top-level namespace, such as \c malloc.
    310   ///
    311   /// You can use this call to determine that a particular function really is
    312   /// a library function and not, say, a C++ member function with the same name.
    313   ///
    314   /// If a name is provided, the function must additionally match the given
    315   /// name.
    316   ///
    317   /// Note that this deliberately excludes C++ library functions in the \c std
    318   /// namespace, but will include C library functions accessed through the
    319   /// \c std namespace. This also does not check if the function is declared
    320   /// as 'extern "C"', or if it uses C++ name mangling.
    321   // FIXME: Add a helper for checking namespaces.
    322   // FIXME: Move this down to AnyFunctionCall once checkers have more
    323   // precise callbacks.
    324   bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
    325 
    326   /// \brief Returns the name of the callee, if its name is a simple identifier.
    327   ///
    328   /// Note that this will fail for Objective-C methods, blocks, and C++
    329   /// overloaded operators. The former is named by a Selector rather than a
    330   /// simple identifier, and the latter two do not have names.
    331   // FIXME: Move this down to AnyFunctionCall once checkers have more
    332   // precise callbacks.
    333   const IdentifierInfo *getCalleeIdentifier() const {
    334     const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl());
    335     if (!ND)
    336       return nullptr;
    337     return ND->getIdentifier();
    338   }
    339 
    340   /// \brief Returns an appropriate ProgramPoint for this call.
    341   ProgramPoint getProgramPoint(bool IsPreVisit = false,
    342                                const ProgramPointTag *Tag = nullptr) const;
    343 
    344   /// \brief Returns a new state with all argument regions invalidated.
    345   ///
    346   /// This accepts an alternate state in case some processing has already
    347   /// occurred.
    348   ProgramStateRef invalidateRegions(unsigned BlockCount,
    349                                     ProgramStateRef Orig = nullptr) const;
    350 
    351   typedef std::pair<Loc, SVal> FrameBindingTy;
    352   typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
    353 
    354   /// Populates the given SmallVector with the bindings in the callee's stack
    355   /// frame at the start of this call.
    356   virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    357                                             BindingsTy &Bindings) const = 0;
    358 
    359   /// Returns a copy of this CallEvent, but using the given state.
    360   template <typename T>
    361   CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
    362 
    363   /// Returns a copy of this CallEvent, but using the given state.
    364   CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
    365     return cloneWithState<CallEvent>(NewState);
    366   }
    367 
    368   /// \brief Returns true if this is a statement is a function or method call
    369   /// of some kind.
    370   static bool isCallStmt(const Stmt *S);
    371 
    372   /// \brief Returns the result type of a function or method declaration.
    373   ///
    374   /// This will return a null QualType if the result type cannot be determined.
    375   static QualType getDeclaredResultType(const Decl *D);
    376 
    377   /// \brief Returns true if the given decl is known to be variadic.
    378   ///
    379   /// \p D must not be null.
    380   static bool isVariadic(const Decl *D);
    381 
    382   // Iterator access to formal parameters and their types.
    383 private:
    384   typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun;
    385 
    386 public:
    387   /// Return call's formal parameters.
    388   ///
    389   /// Remember that the number of formal parameters may not match the number
    390   /// of arguments for all calls. However, the first parameter will always
    391   /// correspond with the argument value returned by \c getArgSVal(0).
    392   virtual ArrayRef<ParmVarDecl*> parameters() const = 0;
    393 
    394   typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, get_type_fun>
    395     param_type_iterator;
    396 
    397   /// Returns an iterator over the types of the call's formal parameters.
    398   ///
    399   /// This uses the callee decl found by default name lookup rather than the
    400   /// definition because it represents a public interface, and probably has
    401   /// more annotations.
    402   param_type_iterator param_type_begin() const {
    403     return llvm::map_iterator(parameters().begin(),
    404                               get_type_fun(&ParmVarDecl::getType));
    405   }
    406   /// \sa param_type_begin()
    407   param_type_iterator param_type_end() const {
    408     return llvm::map_iterator(parameters().end(),
    409                               get_type_fun(&ParmVarDecl::getType));
    410   }
    411 
    412   // For debugging purposes only
    413   void dump(raw_ostream &Out) const;
    414   void dump() const;
    415 };
    416 
    417 
    418 /// \brief Represents a call to any sort of function that might have a
    419 /// FunctionDecl.
    420 class AnyFunctionCall : public CallEvent {
    421 protected:
    422   AnyFunctionCall(const Expr *E, ProgramStateRef St,
    423                   const LocationContext *LCtx)
    424     : CallEvent(E, St, LCtx) {}
    425   AnyFunctionCall(const Decl *D, ProgramStateRef St,
    426                   const LocationContext *LCtx)
    427     : CallEvent(D, St, LCtx) {}
    428   AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
    429 
    430 public:
    431   // This function is overridden by subclasses, but they must return
    432   // a FunctionDecl.
    433   const FunctionDecl *getDecl() const override {
    434     return cast<FunctionDecl>(CallEvent::getDecl());
    435   }
    436 
    437   RuntimeDefinition getRuntimeDefinition() const override {
    438     const FunctionDecl *FD = getDecl();
    439     // Note that the AnalysisDeclContext will have the FunctionDecl with
    440     // the definition (if one exists).
    441     if (FD) {
    442       AnalysisDeclContext *AD =
    443         getLocationContext()->getAnalysisDeclContext()->
    444         getManager()->getContext(FD);
    445       if (AD->getBody())
    446         return RuntimeDefinition(AD->getDecl());
    447     }
    448 
    449     return RuntimeDefinition();
    450   }
    451 
    452   bool argumentsMayEscape() const override;
    453 
    454   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    455                                     BindingsTy &Bindings) const override;
    456 
    457   ArrayRef<ParmVarDecl *> parameters() const override;
    458 
    459   static bool classof(const CallEvent *CA) {
    460     return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
    461            CA->getKind() <= CE_END_FUNCTION_CALLS;
    462   }
    463 };
    464 
    465 /// \brief Represents a C function or static C++ member function call.
    466 ///
    467 /// Example: \c fun()
    468 class SimpleFunctionCall : public AnyFunctionCall {
    469   friend class CallEventManager;
    470 
    471 protected:
    472   SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
    473                      const LocationContext *LCtx)
    474     : AnyFunctionCall(CE, St, LCtx) {}
    475   SimpleFunctionCall(const SimpleFunctionCall &Other)
    476     : AnyFunctionCall(Other) {}
    477   void cloneTo(void *Dest) const override {
    478     new (Dest) SimpleFunctionCall(*this);
    479   }
    480 
    481 public:
    482   virtual const CallExpr *getOriginExpr() const {
    483     return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
    484   }
    485 
    486   const FunctionDecl *getDecl() const override;
    487 
    488   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
    489 
    490   const Expr *getArgExpr(unsigned Index) const override {
    491     return getOriginExpr()->getArg(Index);
    492   }
    493 
    494   Kind getKind() const override { return CE_Function; }
    495 
    496   static bool classof(const CallEvent *CA) {
    497     return CA->getKind() == CE_Function;
    498   }
    499 };
    500 
    501 /// \brief Represents a call to a block.
    502 ///
    503 /// Example: <tt>^{ /* ... */ }()</tt>
    504 class BlockCall : public CallEvent {
    505   friend class CallEventManager;
    506 
    507 protected:
    508   BlockCall(const CallExpr *CE, ProgramStateRef St,
    509             const LocationContext *LCtx)
    510     : CallEvent(CE, St, LCtx) {}
    511 
    512   BlockCall(const BlockCall &Other) : CallEvent(Other) {}
    513   void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
    514 
    515   void getExtraInvalidatedValues(ValueList &Values,
    516          RegionAndSymbolInvalidationTraits *ETraits) const override;
    517 
    518 public:
    519   virtual const CallExpr *getOriginExpr() const {
    520     return cast<CallExpr>(CallEvent::getOriginExpr());
    521   }
    522 
    523   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
    524 
    525   const Expr *getArgExpr(unsigned Index) const override {
    526     return getOriginExpr()->getArg(Index);
    527   }
    528 
    529   /// \brief Returns the region associated with this instance of the block.
    530   ///
    531   /// This may be NULL if the block's origin is unknown.
    532   const BlockDataRegion *getBlockRegion() const;
    533 
    534   const BlockDecl *getDecl() const override {
    535     const BlockDataRegion *BR = getBlockRegion();
    536     if (!BR)
    537       return nullptr;
    538     return BR->getDecl();
    539   }
    540 
    541   bool isConversionFromLambda() const {
    542     const BlockDecl *BD = getDecl();
    543     if (!BD)
    544       return false;
    545 
    546     return BD->isConversionFromLambda();
    547   }
    548 
    549   /// \brief For a block converted from a C++ lambda, returns the block
    550   /// VarRegion for the variable holding the captured C++ lambda record.
    551   const VarRegion *getRegionStoringCapturedLambda() const {
    552     assert(isConversionFromLambda());
    553     const BlockDataRegion *BR = getBlockRegion();
    554     assert(BR && "Block converted from lambda must have a block region");
    555 
    556     auto I = BR->referenced_vars_begin();
    557     assert(I != BR->referenced_vars_end());
    558 
    559     return I.getCapturedRegion();
    560   }
    561 
    562   RuntimeDefinition getRuntimeDefinition() const override {
    563     if (!isConversionFromLambda())
    564       return RuntimeDefinition(getDecl());
    565 
    566     // Clang converts lambdas to blocks with an implicit user-defined
    567     // conversion operator method on the lambda record that looks (roughly)
    568     // like:
    569     //
    570     // typedef R(^block_type)(P1, P2, ...);
    571     // operator block_type() const {
    572     //   auto Lambda = *this;
    573     //   return ^(P1 p1, P2 p2, ...){
    574     //     /* return Lambda(p1, p2, ...); */
    575     //   };
    576     // }
    577     //
    578     // Here R is the return type of the lambda and P1, P2, ... are
    579     // its parameter types. 'Lambda' is a fake VarDecl captured by the block
    580     // that is initialized to a copy of the lambda.
    581     //
    582     // Sema leaves the body of a lambda-converted block empty (it is
    583     // produced by CodeGen), so we can't analyze it directly. Instead, we skip
    584     // the block body and analyze the operator() method on the captured lambda.
    585     const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
    586     const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
    587     CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
    588 
    589     return RuntimeDefinition(LambdaCallOperator);
    590   }
    591 
    592   bool argumentsMayEscape() const override {
    593     return true;
    594   }
    595 
    596   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    597                                     BindingsTy &Bindings) const override;
    598 
    599   ArrayRef<ParmVarDecl*> parameters() const override;
    600 
    601   Kind getKind() const override { return CE_Block; }
    602 
    603   static bool classof(const CallEvent *CA) {
    604     return CA->getKind() == CE_Block;
    605   }
    606 };
    607 
    608 /// \brief Represents a non-static C++ member function call, no matter how
    609 /// it is written.
    610 class CXXInstanceCall : public AnyFunctionCall {
    611 protected:
    612   void getExtraInvalidatedValues(ValueList &Values,
    613          RegionAndSymbolInvalidationTraits *ETraits) const override;
    614 
    615   CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
    616                   const LocationContext *LCtx)
    617     : AnyFunctionCall(CE, St, LCtx) {}
    618   CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
    619                   const LocationContext *LCtx)
    620     : AnyFunctionCall(D, St, LCtx) {}
    621 
    622 
    623   CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
    624 
    625 public:
    626   /// \brief Returns the expression representing the implicit 'this' object.
    627   virtual const Expr *getCXXThisExpr() const { return nullptr; }
    628 
    629   /// \brief Returns the value of the implicit 'this' object.
    630   virtual SVal getCXXThisVal() const;
    631 
    632   const FunctionDecl *getDecl() const override;
    633 
    634   RuntimeDefinition getRuntimeDefinition() const override;
    635 
    636   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    637                                     BindingsTy &Bindings) const override;
    638 
    639   static bool classof(const CallEvent *CA) {
    640     return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
    641            CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
    642   }
    643 };
    644 
    645 /// \brief Represents a non-static C++ member function call.
    646 ///
    647 /// Example: \c obj.fun()
    648 class CXXMemberCall : public CXXInstanceCall {
    649   friend class CallEventManager;
    650 
    651 protected:
    652   CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
    653                 const LocationContext *LCtx)
    654     : CXXInstanceCall(CE, St, LCtx) {}
    655 
    656   CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
    657   void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
    658 
    659 public:
    660   virtual const CXXMemberCallExpr *getOriginExpr() const {
    661     return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
    662   }
    663 
    664   unsigned getNumArgs() const override {
    665     if (const CallExpr *CE = getOriginExpr())
    666       return CE->getNumArgs();
    667     return 0;
    668   }
    669 
    670   const Expr *getArgExpr(unsigned Index) const override {
    671     return getOriginExpr()->getArg(Index);
    672   }
    673 
    674   const Expr *getCXXThisExpr() const override;
    675 
    676   RuntimeDefinition getRuntimeDefinition() const override;
    677 
    678   Kind getKind() const override { return CE_CXXMember; }
    679 
    680   static bool classof(const CallEvent *CA) {
    681     return CA->getKind() == CE_CXXMember;
    682   }
    683 };
    684 
    685 /// \brief Represents a C++ overloaded operator call where the operator is
    686 /// implemented as a non-static member function.
    687 ///
    688 /// Example: <tt>iter + 1</tt>
    689 class CXXMemberOperatorCall : public CXXInstanceCall {
    690   friend class CallEventManager;
    691 
    692 protected:
    693   CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
    694                         const LocationContext *LCtx)
    695     : CXXInstanceCall(CE, St, LCtx) {}
    696 
    697   CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
    698     : CXXInstanceCall(Other) {}
    699   void cloneTo(void *Dest) const override {
    700     new (Dest) CXXMemberOperatorCall(*this);
    701   }
    702 
    703 public:
    704   virtual const CXXOperatorCallExpr *getOriginExpr() const {
    705     return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
    706   }
    707 
    708   unsigned getNumArgs() const override {
    709     return getOriginExpr()->getNumArgs() - 1;
    710   }
    711   const Expr *getArgExpr(unsigned Index) const override {
    712     return getOriginExpr()->getArg(Index + 1);
    713   }
    714 
    715   const Expr *getCXXThisExpr() const override;
    716 
    717   Kind getKind() const override { return CE_CXXMemberOperator; }
    718 
    719   static bool classof(const CallEvent *CA) {
    720     return CA->getKind() == CE_CXXMemberOperator;
    721   }
    722 };
    723 
    724 /// \brief Represents an implicit call to a C++ destructor.
    725 ///
    726 /// This can occur at the end of a scope (for automatic objects), at the end
    727 /// of a full-expression (for temporaries), or as part of a delete.
    728 class CXXDestructorCall : public CXXInstanceCall {
    729   friend class CallEventManager;
    730 
    731 protected:
    732   typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy;
    733 
    734   /// Creates an implicit destructor.
    735   ///
    736   /// \param DD The destructor that will be called.
    737   /// \param Trigger The statement whose completion causes this destructor call.
    738   /// \param Target The object region to be destructed.
    739   /// \param St The path-sensitive state at this point in the program.
    740   /// \param LCtx The location context at this point in the program.
    741   CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
    742                     const MemRegion *Target, bool IsBaseDestructor,
    743                     ProgramStateRef St, const LocationContext *LCtx)
    744     : CXXInstanceCall(DD, St, LCtx) {
    745     Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
    746     Location = Trigger->getLocEnd();
    747   }
    748 
    749   CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
    750   void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
    751 
    752 public:
    753   SourceRange getSourceRange() const override { return Location; }
    754   unsigned getNumArgs() const override { return 0; }
    755 
    756   RuntimeDefinition getRuntimeDefinition() const override;
    757 
    758   /// \brief Returns the value of the implicit 'this' object.
    759   SVal getCXXThisVal() const override;
    760 
    761   /// Returns true if this is a call to a base class destructor.
    762   bool isBaseDestructor() const {
    763     return DtorDataTy::getFromOpaqueValue(Data).getInt();
    764   }
    765 
    766   Kind getKind() const override { return CE_CXXDestructor; }
    767 
    768   static bool classof(const CallEvent *CA) {
    769     return CA->getKind() == CE_CXXDestructor;
    770   }
    771 };
    772 
    773 /// \brief Represents a call to a C++ constructor.
    774 ///
    775 /// Example: \c T(1)
    776 class CXXConstructorCall : public AnyFunctionCall {
    777   friend class CallEventManager;
    778 
    779 protected:
    780   /// Creates a constructor call.
    781   ///
    782   /// \param CE The constructor expression as written in the source.
    783   /// \param Target The region where the object should be constructed. If NULL,
    784   ///               a new symbolic region will be used.
    785   /// \param St The path-sensitive state at this point in the program.
    786   /// \param LCtx The location context at this point in the program.
    787   CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
    788                      ProgramStateRef St, const LocationContext *LCtx)
    789     : AnyFunctionCall(CE, St, LCtx) {
    790     Data = Target;
    791   }
    792 
    793   CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
    794   void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
    795 
    796   void getExtraInvalidatedValues(ValueList &Values,
    797          RegionAndSymbolInvalidationTraits *ETraits) const override;
    798 
    799 public:
    800   virtual const CXXConstructExpr *getOriginExpr() const {
    801     return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
    802   }
    803 
    804   const CXXConstructorDecl *getDecl() const override {
    805     return getOriginExpr()->getConstructor();
    806   }
    807 
    808   unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
    809 
    810   const Expr *getArgExpr(unsigned Index) const override {
    811     return getOriginExpr()->getArg(Index);
    812   }
    813 
    814   /// \brief Returns the value of the implicit 'this' object.
    815   SVal getCXXThisVal() const;
    816 
    817   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    818                                     BindingsTy &Bindings) const override;
    819 
    820   Kind getKind() const override { return CE_CXXConstructor; }
    821 
    822   static bool classof(const CallEvent *CA) {
    823     return CA->getKind() == CE_CXXConstructor;
    824   }
    825 };
    826 
    827 /// \brief Represents the memory allocation call in a C++ new-expression.
    828 ///
    829 /// This is a call to "operator new".
    830 class CXXAllocatorCall : public AnyFunctionCall {
    831   friend class CallEventManager;
    832 
    833 protected:
    834   CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
    835                    const LocationContext *LCtx)
    836     : AnyFunctionCall(E, St, LCtx) {}
    837 
    838   CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
    839   void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
    840 
    841 public:
    842   virtual const CXXNewExpr *getOriginExpr() const {
    843     return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
    844   }
    845 
    846   const FunctionDecl *getDecl() const override {
    847     return getOriginExpr()->getOperatorNew();
    848   }
    849 
    850   unsigned getNumArgs() const override {
    851     return getOriginExpr()->getNumPlacementArgs() + 1;
    852   }
    853 
    854   const Expr *getArgExpr(unsigned Index) const override {
    855     // The first argument of an allocator call is the size of the allocation.
    856     if (Index == 0)
    857       return nullptr;
    858     return getOriginExpr()->getPlacementArg(Index - 1);
    859   }
    860 
    861   Kind getKind() const override { return CE_CXXAllocator; }
    862 
    863   static bool classof(const CallEvent *CE) {
    864     return CE->getKind() == CE_CXXAllocator;
    865   }
    866 };
    867 
    868 /// \brief Represents the ways an Objective-C message send can occur.
    869 //
    870 // Note to maintainers: OCM_Message should always be last, since it does not
    871 // need to fit in the Data field's low bits.
    872 enum ObjCMessageKind {
    873   OCM_PropertyAccess,
    874   OCM_Subscript,
    875   OCM_Message
    876 };
    877 
    878 /// \brief Represents any expression that calls an Objective-C method.
    879 ///
    880 /// This includes all of the kinds listed in ObjCMessageKind.
    881 class ObjCMethodCall : public CallEvent {
    882   friend class CallEventManager;
    883 
    884   const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
    885 
    886 protected:
    887   ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
    888                  const LocationContext *LCtx)
    889     : CallEvent(Msg, St, LCtx) {
    890     Data = nullptr;
    891   }
    892 
    893   ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
    894   void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
    895 
    896   void getExtraInvalidatedValues(ValueList &Values,
    897          RegionAndSymbolInvalidationTraits *ETraits) const override;
    898 
    899   /// Check if the selector may have multiple definitions (may have overrides).
    900   virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
    901                                         Selector Sel) const;
    902 
    903 public:
    904   virtual const ObjCMessageExpr *getOriginExpr() const {
    905     return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
    906   }
    907   const ObjCMethodDecl *getDecl() const override {
    908     return getOriginExpr()->getMethodDecl();
    909   }
    910   unsigned getNumArgs() const override {
    911     return getOriginExpr()->getNumArgs();
    912   }
    913   const Expr *getArgExpr(unsigned Index) const override {
    914     return getOriginExpr()->getArg(Index);
    915   }
    916 
    917   bool isInstanceMessage() const {
    918     return getOriginExpr()->isInstanceMessage();
    919   }
    920   ObjCMethodFamily getMethodFamily() const {
    921     return getOriginExpr()->getMethodFamily();
    922   }
    923   Selector getSelector() const {
    924     return getOriginExpr()->getSelector();
    925   }
    926 
    927   SourceRange getSourceRange() const override;
    928 
    929   /// \brief Returns the value of the receiver at the time of this call.
    930   SVal getReceiverSVal() const;
    931 
    932   /// \brief Return the value of 'self' if available.
    933   SVal getSelfSVal() const;
    934 
    935   /// \brief Get the interface for the receiver.
    936   ///
    937   /// This works whether this is an instance message or a class message.
    938   /// However, it currently just uses the static type of the receiver.
    939   const ObjCInterfaceDecl *getReceiverInterface() const {
    940     return getOriginExpr()->getReceiverInterface();
    941   }
    942 
    943   /// \brief Checks if the receiver refers to 'self' or 'super'.
    944   bool isReceiverSelfOrSuper() const;
    945 
    946   /// Returns how the message was written in the source (property access,
    947   /// subscript, or explicit message send).
    948   ObjCMessageKind getMessageKind() const;
    949 
    950   /// Returns true if this property access or subscript is a setter (has the
    951   /// form of an assignment).
    952   bool isSetter() const {
    953     switch (getMessageKind()) {
    954     case OCM_Message:
    955       llvm_unreachable("This is not a pseudo-object access!");
    956     case OCM_PropertyAccess:
    957       return getNumArgs() > 0;
    958     case OCM_Subscript:
    959       return getNumArgs() > 1;
    960     }
    961     llvm_unreachable("Unknown message kind");
    962   }
    963 
    964   // Returns the property accessed by this method, either explicitly via
    965   // property syntax or implicitly via a getter or setter method. Returns
    966   // nullptr if the call is not a prooperty access.
    967   const ObjCPropertyDecl *getAccessedProperty() const;
    968 
    969   RuntimeDefinition getRuntimeDefinition() const override;
    970 
    971   bool argumentsMayEscape() const override;
    972 
    973   void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
    974                                     BindingsTy &Bindings) const override;
    975 
    976   ArrayRef<ParmVarDecl*> parameters() const override;
    977 
    978   Kind getKind() const override { return CE_ObjCMessage; }
    979 
    980   static bool classof(const CallEvent *CA) {
    981     return CA->getKind() == CE_ObjCMessage;
    982   }
    983 };
    984 
    985 
    986 /// \brief Manages the lifetime of CallEvent objects.
    987 ///
    988 /// CallEventManager provides a way to create arbitrary CallEvents "on the
    989 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
    990 /// memory blocks. The CallEvents created by CallEventManager are only valid
    991 /// for the lifetime of the OwnedCallEvent that holds them; right now these
    992 /// objects cannot be copied and ownership cannot be transferred.
    993 class CallEventManager {
    994   friend class CallEvent;
    995 
    996   llvm::BumpPtrAllocator &Alloc;
    997   SmallVector<void *, 8> Cache;
    998   typedef SimpleFunctionCall CallEventTemplateTy;
    999 
   1000   void reclaim(const void *Memory) {
   1001     Cache.push_back(const_cast<void *>(Memory));
   1002   }
   1003 
   1004   /// Returns memory that can be initialized as a CallEvent.
   1005   void *allocate() {
   1006     if (Cache.empty())
   1007       return Alloc.Allocate<CallEventTemplateTy>();
   1008     else
   1009       return Cache.pop_back_val();
   1010   }
   1011 
   1012   template <typename T, typename Arg>
   1013   T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
   1014     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
   1015                   "CallEvent subclasses are not all the same size");
   1016     return new (allocate()) T(A, St, LCtx);
   1017   }
   1018 
   1019   template <typename T, typename Arg1, typename Arg2>
   1020   T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
   1021     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
   1022                   "CallEvent subclasses are not all the same size");
   1023     return new (allocate()) T(A1, A2, St, LCtx);
   1024   }
   1025 
   1026   template <typename T, typename Arg1, typename Arg2, typename Arg3>
   1027   T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
   1028             const LocationContext *LCtx) {
   1029     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
   1030                   "CallEvent subclasses are not all the same size");
   1031     return new (allocate()) T(A1, A2, A3, St, LCtx);
   1032   }
   1033 
   1034   template <typename T, typename Arg1, typename Arg2, typename Arg3,
   1035             typename Arg4>
   1036   T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
   1037             const LocationContext *LCtx) {
   1038     static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
   1039                   "CallEvent subclasses are not all the same size");
   1040     return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
   1041   }
   1042 
   1043 public:
   1044   CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
   1045 
   1046 
   1047   CallEventRef<>
   1048   getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
   1049 
   1050 
   1051   CallEventRef<>
   1052   getSimpleCall(const CallExpr *E, ProgramStateRef State,
   1053                 const LocationContext *LCtx);
   1054 
   1055   CallEventRef<ObjCMethodCall>
   1056   getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
   1057                     const LocationContext *LCtx) {
   1058     return create<ObjCMethodCall>(E, State, LCtx);
   1059   }
   1060 
   1061   CallEventRef<CXXConstructorCall>
   1062   getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
   1063                         ProgramStateRef State, const LocationContext *LCtx) {
   1064     return create<CXXConstructorCall>(E, Target, State, LCtx);
   1065   }
   1066 
   1067   CallEventRef<CXXDestructorCall>
   1068   getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
   1069                        const MemRegion *Target, bool IsBase,
   1070                        ProgramStateRef State, const LocationContext *LCtx) {
   1071     return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
   1072   }
   1073 
   1074   CallEventRef<CXXAllocatorCall>
   1075   getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
   1076                       const LocationContext *LCtx) {
   1077     return create<CXXAllocatorCall>(E, State, LCtx);
   1078   }
   1079 };
   1080 
   1081 
   1082 template <typename T>
   1083 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
   1084   assert(isa<T>(*this) && "Cloning to unrelated type");
   1085   static_assert(sizeof(T) == sizeof(CallEvent),
   1086                 "Subclasses may not add fields");
   1087 
   1088   if (NewState == State)
   1089     return cast<T>(this);
   1090 
   1091   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
   1092   T *Copy = static_cast<T *>(Mgr.allocate());
   1093   cloneTo(Copy);
   1094   assert(Copy->getKind() == this->getKind() && "Bad copy");
   1095 
   1096   Copy->State = NewState;
   1097   return Copy;
   1098 }
   1099 
   1100 inline void CallEvent::Release() const {
   1101   assert(RefCount > 0 && "Reference count is already zero.");
   1102   --RefCount;
   1103 
   1104   if (RefCount > 0)
   1105     return;
   1106 
   1107   CallEventManager &Mgr = State->getStateManager().getCallEventManager();
   1108   Mgr.reclaim(this);
   1109 
   1110   this->~CallEvent();
   1111 }
   1112 
   1113 } // end namespace ento
   1114 } // end namespace clang
   1115 
   1116 namespace llvm {
   1117   // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
   1118   template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
   1119     typedef const T *SimpleType;
   1120 
   1121     static SimpleType
   1122     getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
   1123       return Val.get();
   1124     }
   1125   };
   1126 }
   1127 
   1128 #endif
   1129