1 //===- CallEvent.h - Wrapper for all function and method calls ----*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
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"
30 class ProgramPointTag;
39 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
40 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
43 CE_BEG_FUNCTION_CALLS = CE_Function,
44 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
50 class CallEventManager;
52 /// This class represents a description of a function call using the number of
53 /// arguments and the name of the function.
54 class CallDescription {
56 mutable IdentifierInfo *II;
58 unsigned RequiredArgs;
61 const static unsigned NoArgRequirement = ~0;
62 /// \brief Constructs a CallDescription object.
64 /// @param FuncName The name of the function that will be matched.
66 /// @param RequiredArgs The number of arguments that is expected to match a
67 /// call. Omit this parameter to match every occurance of call with a given
68 /// name regardless the number of arguments.
69 CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
70 : FuncName(FuncName), RequiredArgs(RequiredArgs) {}
73 template<typename T = CallEvent>
74 class CallEventRef : public IntrusiveRefCntPtr<const T> {
76 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
77 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
79 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
80 return this->get()->template cloneWithState<T>(State);
83 // Allow implicit conversions to a superclass type, since CallEventRef
84 // behaves like a pointer-to-const.
85 template <typename SuperT>
86 operator CallEventRef<SuperT> () const {
91 /// \class RuntimeDefinition
92 /// \brief Defines the runtime definition of the called function.
94 /// Encapsulates the information we have about which Decl will be used
95 /// when the call is executed on the given path. When dealing with dynamic
96 /// dispatch, the information is based on DynamicTypeInfo and might not be
98 class RuntimeDefinition {
99 /// The Declaration of the function which could be called at runtime.
100 /// NULL if not available.
103 /// The region representing an object (ObjC/C++) on which the method is
104 /// called. With dynamic dispatch, the method definition depends on the
105 /// runtime type of this object. NULL when the DynamicTypeInfo is
110 RuntimeDefinition(): D(nullptr), R(nullptr) {}
111 RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {}
112 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
113 const Decl *getDecl() { return D; }
115 /// \brief Check if the definition we have is precise.
116 /// If not, it is possible that the call dispatches to another definition at
118 bool mayHaveOtherDefinitions() { return R != nullptr; }
120 /// When other definitions are possible, returns the region whose runtime type
121 /// determines the method definition.
122 const MemRegion *getDispatchRegion() { return R; }
125 /// \brief Represents an abstract call to a function or method along a
128 /// CallEvents are created through the factory methods of CallEventManager.
130 /// CallEvents should always be cheap to create and destroy. In order for
131 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
132 /// subclasses of CallEvent may not add any data members to the base class.
133 /// Use the "Data" and "Location" fields instead.
136 typedef CallEventKind Kind;
139 ProgramStateRef State;
140 const LocationContext *LCtx;
141 llvm::PointerUnion<const Expr *, const Decl *> Origin;
143 void operator=(const CallEvent &) = delete;
146 // This is user data for subclasses.
149 // This is user data for subclasses.
150 // This should come right before RefCount, so that the two fields can be
151 // packed together on LP64 platforms.
152 SourceLocation Location;
155 mutable unsigned RefCount;
157 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
158 void Retain() const { ++RefCount; }
159 void Release() const;
162 friend class CallEventManager;
164 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
165 : State(state), LCtx(lctx), Origin(E), RefCount(0) {}
167 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
168 : State(state), LCtx(lctx), Origin(D), RefCount(0) {}
170 // DO NOT MAKE PUBLIC
171 CallEvent(const CallEvent &Original)
172 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
173 Data(Original.Data), Location(Original.Location), RefCount(0) {}
175 /// Copies this CallEvent, with vtable intact, into a new block of memory.
176 virtual void cloneTo(void *Dest) const = 0;
178 /// \brief Get the value of arbitrary expressions at this point in the path.
179 SVal getSVal(const Stmt *S) const {
180 return getState()->getSVal(S, getLocationContext());
184 typedef SmallVectorImpl<SVal> ValueList;
186 /// \brief Used to specify non-argument regions that will be invalidated as a
187 /// result of this call.
188 virtual void getExtraInvalidatedValues(ValueList &Values,
189 RegionAndSymbolInvalidationTraits *ETraits) const {}
192 virtual ~CallEvent() {}
194 /// \brief Returns the kind of call this is.
195 virtual Kind getKind() const = 0;
197 /// \brief Returns the declaration of the function or method that will be
198 /// called. May be null.
199 virtual const Decl *getDecl() const {
200 return Origin.dyn_cast<const Decl *>();
203 /// \brief The state in which the call is being evaluated.
204 const ProgramStateRef &getState() const {
208 /// \brief The context in which the call is being evaluated.
209 const LocationContext *getLocationContext() const {
213 /// \brief Returns the definition of the function or method that will be
215 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
217 /// \brief Returns the expression whose value will be the result of this call.
219 const Expr *getOriginExpr() const {
220 return Origin.dyn_cast<const Expr *>();
223 /// \brief Returns the number of arguments (explicit and implicit).
225 /// Note that this may be greater than the number of parameters in the
226 /// callee's declaration, and that it may include arguments not written in
228 virtual unsigned getNumArgs() const = 0;
230 /// \brief Returns true if the callee is known to be from a system header.
231 bool isInSystemHeader() const {
232 const Decl *D = getDecl();
236 SourceLocation Loc = D->getLocation();
238 const SourceManager &SM =
239 getState()->getStateManager().getContext().getSourceManager();
240 return SM.isInSystemHeader(D->getLocation());
243 // Special case for implicitly-declared global operator new/delete.
244 // These should be considered system functions.
245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
246 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
251 /// \brief Returns true if the CallEvent is a call to a function that matches
252 /// the CallDescription.
254 /// Note that this function is not intended to be used to match Obj-C method
256 bool isCalled(const CallDescription &CD) const;
258 /// \brief Returns a source range for the entire call, suitable for
259 /// outputting in diagnostics.
260 virtual SourceRange getSourceRange() const {
261 return getOriginExpr()->getSourceRange();
264 /// \brief Returns the value of a given argument at the time of the call.
265 virtual SVal getArgSVal(unsigned Index) const;
267 /// \brief Returns the expression associated with a given argument.
268 /// May be null if this expression does not appear in the source.
269 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
271 /// \brief Returns the source range for errors associated with this argument.
273 /// May be invalid if the argument is not written in the source.
274 virtual SourceRange getArgSourceRange(unsigned Index) const;
276 /// \brief Returns the result type, adjusted for references.
277 QualType getResultType() const;
279 /// \brief Returns the return value of the call.
281 /// This should only be called if the CallEvent was created using a state in
282 /// which the return value has already been bound to the origin expression.
283 SVal getReturnValue() const;
285 /// \brief Returns true if the type of any of the non-null arguments satisfies
287 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
289 /// \brief Returns true if any of the arguments appear to represent callbacks.
290 bool hasNonZeroCallbackArg() const;
292 /// \brief Returns true if any of the arguments is void*.
293 bool hasVoidPointerToNonConstArg() const;
295 /// \brief Returns true if any of the arguments are known to escape to long-
296 /// term storage, even if this method will not modify them.
297 // NOTE: The exact semantics of this are still being defined!
298 // We don't really want a list of hardcoded exceptions in the long run,
299 // but we don't want duplicated lists of known APIs in the short term either.
300 virtual bool argumentsMayEscape() const {
301 return hasNonZeroCallbackArg();
304 /// \brief Returns true if the callee is an externally-visible function in the
305 /// top-level namespace, such as \c malloc.
307 /// You can use this call to determine that a particular function really is
308 /// a library function and not, say, a C++ member function with the same name.
310 /// If a name is provided, the function must additionally match the given
313 /// Note that this deliberately excludes C++ library functions in the \c std
314 /// namespace, but will include C library functions accessed through the
315 /// \c std namespace. This also does not check if the function is declared
316 /// as 'extern "C"', or if it uses C++ name mangling.
317 // FIXME: Add a helper for checking namespaces.
318 // FIXME: Move this down to AnyFunctionCall once checkers have more
319 // precise callbacks.
320 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
322 /// \brief Returns the name of the callee, if its name is a simple identifier.
324 /// Note that this will fail for Objective-C methods, blocks, and C++
325 /// overloaded operators. The former is named by a Selector rather than a
326 /// simple identifier, and the latter two do not have names.
327 // FIXME: Move this down to AnyFunctionCall once checkers have more
328 // precise callbacks.
329 const IdentifierInfo *getCalleeIdentifier() const {
330 const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl());
333 return ND->getIdentifier();
336 /// \brief Returns an appropriate ProgramPoint for this call.
337 ProgramPoint getProgramPoint(bool IsPreVisit = false,
338 const ProgramPointTag *Tag = nullptr) const;
340 /// \brief Returns a new state with all argument regions invalidated.
342 /// This accepts an alternate state in case some processing has already
344 ProgramStateRef invalidateRegions(unsigned BlockCount,
345 ProgramStateRef Orig = nullptr) const;
347 typedef std::pair<Loc, SVal> FrameBindingTy;
348 typedef SmallVectorImpl<FrameBindingTy> BindingsTy;
350 /// Populates the given SmallVector with the bindings in the callee's stack
351 /// frame at the start of this call.
352 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
353 BindingsTy &Bindings) const = 0;
355 /// Returns a copy of this CallEvent, but using the given state.
356 template <typename T>
357 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
359 /// Returns a copy of this CallEvent, but using the given state.
360 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
361 return cloneWithState<CallEvent>(NewState);
364 /// \brief Returns true if this is a statement is a function or method call
366 static bool isCallStmt(const Stmt *S);
368 /// \brief Returns the result type of a function or method declaration.
370 /// This will return a null QualType if the result type cannot be determined.
371 static QualType getDeclaredResultType(const Decl *D);
373 /// \brief Returns true if the given decl is known to be variadic.
375 /// \p D must not be null.
376 static bool isVariadic(const Decl *D);
378 // Iterator access to formal parameters and their types.
380 typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun;
383 /// Return call's formal parameters.
385 /// Remember that the number of formal parameters may not match the number
386 /// of arguments for all calls. However, the first parameter will always
387 /// correspond with the argument value returned by \c getArgSVal(0).
388 virtual ArrayRef<ParmVarDecl*> parameters() const = 0;
390 typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, get_type_fun>
393 /// Returns an iterator over the types of the call's formal parameters.
395 /// This uses the callee decl found by default name lookup rather than the
396 /// definition because it represents a public interface, and probably has
397 /// more annotations.
398 param_type_iterator param_type_begin() const {
399 return llvm::map_iterator(parameters().begin(),
400 get_type_fun(&ParmVarDecl::getType));
402 /// \sa param_type_begin()
403 param_type_iterator param_type_end() const {
404 return llvm::map_iterator(parameters().end(),
405 get_type_fun(&ParmVarDecl::getType));
408 // For debugging purposes only
409 void dump(raw_ostream &Out) const;
414 /// \brief Represents a call to any sort of function that might have a
416 class AnyFunctionCall : public CallEvent {
418 AnyFunctionCall(const Expr *E, ProgramStateRef St,
419 const LocationContext *LCtx)
420 : CallEvent(E, St, LCtx) {}
421 AnyFunctionCall(const Decl *D, ProgramStateRef St,
422 const LocationContext *LCtx)
423 : CallEvent(D, St, LCtx) {}
424 AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {}
427 // This function is overridden by subclasses, but they must return
429 const FunctionDecl *getDecl() const override {
430 return cast<FunctionDecl>(CallEvent::getDecl());
433 RuntimeDefinition getRuntimeDefinition() const override {
434 const FunctionDecl *FD = getDecl();
435 // Note that the AnalysisDeclContext will have the FunctionDecl with
436 // the definition (if one exists).
438 AnalysisDeclContext *AD =
439 getLocationContext()->getAnalysisDeclContext()->
440 getManager()->getContext(FD);
442 return RuntimeDefinition(AD->getDecl());
445 return RuntimeDefinition();
448 bool argumentsMayEscape() const override;
450 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
451 BindingsTy &Bindings) const override;
453 ArrayRef<ParmVarDecl *> parameters() const override;
455 static bool classof(const CallEvent *CA) {
456 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
457 CA->getKind() <= CE_END_FUNCTION_CALLS;
461 /// \brief Represents a C function or static C++ member function call.
463 /// Example: \c fun()
464 class SimpleFunctionCall : public AnyFunctionCall {
465 friend class CallEventManager;
468 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
469 const LocationContext *LCtx)
470 : AnyFunctionCall(CE, St, LCtx) {}
471 SimpleFunctionCall(const SimpleFunctionCall &Other)
472 : AnyFunctionCall(Other) {}
473 void cloneTo(void *Dest) const override {
474 new (Dest) SimpleFunctionCall(*this);
478 virtual const CallExpr *getOriginExpr() const {
479 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
482 const FunctionDecl *getDecl() const override;
484 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
486 const Expr *getArgExpr(unsigned Index) const override {
487 return getOriginExpr()->getArg(Index);
490 Kind getKind() const override { return CE_Function; }
492 static bool classof(const CallEvent *CA) {
493 return CA->getKind() == CE_Function;
497 /// \brief Represents a call to a block.
499 /// Example: <tt>^{ /* ... */ }()</tt>
500 class BlockCall : public CallEvent {
501 friend class CallEventManager;
504 BlockCall(const CallExpr *CE, ProgramStateRef St,
505 const LocationContext *LCtx)
506 : CallEvent(CE, St, LCtx) {}
508 BlockCall(const BlockCall &Other) : CallEvent(Other) {}
509 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
511 void getExtraInvalidatedValues(ValueList &Values,
512 RegionAndSymbolInvalidationTraits *ETraits) const override;
515 virtual const CallExpr *getOriginExpr() const {
516 return cast<CallExpr>(CallEvent::getOriginExpr());
519 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
521 const Expr *getArgExpr(unsigned Index) const override {
522 return getOriginExpr()->getArg(Index);
525 /// \brief Returns the region associated with this instance of the block.
527 /// This may be NULL if the block's origin is unknown.
528 const BlockDataRegion *getBlockRegion() const;
530 const BlockDecl *getDecl() const override {
531 const BlockDataRegion *BR = getBlockRegion();
534 return BR->getDecl();
537 bool isConversionFromLambda() const {
538 const BlockDecl *BD = getDecl();
542 return BD->isConversionFromLambda();
545 /// \brief For a block converted from a C++ lambda, returns the block
546 /// VarRegion for the variable holding the captured C++ lambda record.
547 const VarRegion *getRegionStoringCapturedLambda() const {
548 assert(isConversionFromLambda());
549 const BlockDataRegion *BR = getBlockRegion();
550 assert(BR && "Block converted from lambda must have a block region");
552 auto I = BR->referenced_vars_begin();
553 assert(I != BR->referenced_vars_end());
555 return I.getCapturedRegion();
558 RuntimeDefinition getRuntimeDefinition() const override {
559 if (!isConversionFromLambda())
560 return RuntimeDefinition(getDecl());
562 // Clang converts lambdas to blocks with an implicit user-defined
563 // conversion operator method on the lambda record that looks (roughly)
566 // typedef R(^block_type)(P1, P2, ...);
567 // operator block_type() const {
568 // auto Lambda = *this;
569 // return ^(P1 p1, P2 p2, ...){
570 // /* return Lambda(p1, p2, ...); */
574 // Here R is the return type of the lambda and P1, P2, ... are
575 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
576 // that is initialized to a copy of the lambda.
578 // Sema leaves the body of a lambda-converted block empty (it is
579 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
580 // the block body and analyze the operator() method on the captured lambda.
581 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
582 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
583 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
585 return RuntimeDefinition(LambdaCallOperator);
588 bool argumentsMayEscape() const override {
592 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
593 BindingsTy &Bindings) const override;
595 ArrayRef<ParmVarDecl*> parameters() const override;
597 Kind getKind() const override { return CE_Block; }
599 static bool classof(const CallEvent *CA) {
600 return CA->getKind() == CE_Block;
604 /// \brief Represents a non-static C++ member function call, no matter how
606 class CXXInstanceCall : public AnyFunctionCall {
608 void getExtraInvalidatedValues(ValueList &Values,
609 RegionAndSymbolInvalidationTraits *ETraits) const override;
611 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
612 const LocationContext *LCtx)
613 : AnyFunctionCall(CE, St, LCtx) {}
614 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
615 const LocationContext *LCtx)
616 : AnyFunctionCall(D, St, LCtx) {}
619 CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {}
622 /// \brief Returns the expression representing the implicit 'this' object.
623 virtual const Expr *getCXXThisExpr() const { return nullptr; }
625 /// \brief Returns the value of the implicit 'this' object.
626 virtual SVal getCXXThisVal() const;
628 const FunctionDecl *getDecl() const override;
630 RuntimeDefinition getRuntimeDefinition() const override;
632 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
633 BindingsTy &Bindings) const override;
635 static bool classof(const CallEvent *CA) {
636 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
637 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
641 /// \brief Represents a non-static C++ member function call.
643 /// Example: \c obj.fun()
644 class CXXMemberCall : public CXXInstanceCall {
645 friend class CallEventManager;
648 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
649 const LocationContext *LCtx)
650 : CXXInstanceCall(CE, St, LCtx) {}
652 CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
653 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
656 virtual const CXXMemberCallExpr *getOriginExpr() const {
657 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
660 unsigned getNumArgs() const override {
661 if (const CallExpr *CE = getOriginExpr())
662 return CE->getNumArgs();
666 const Expr *getArgExpr(unsigned Index) const override {
667 return getOriginExpr()->getArg(Index);
670 const Expr *getCXXThisExpr() const override;
672 RuntimeDefinition getRuntimeDefinition() const override;
674 Kind getKind() const override { return CE_CXXMember; }
676 static bool classof(const CallEvent *CA) {
677 return CA->getKind() == CE_CXXMember;
681 /// \brief Represents a C++ overloaded operator call where the operator is
682 /// implemented as a non-static member function.
684 /// Example: <tt>iter + 1</tt>
685 class CXXMemberOperatorCall : public CXXInstanceCall {
686 friend class CallEventManager;
689 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
690 const LocationContext *LCtx)
691 : CXXInstanceCall(CE, St, LCtx) {}
693 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
694 : CXXInstanceCall(Other) {}
695 void cloneTo(void *Dest) const override {
696 new (Dest) CXXMemberOperatorCall(*this);
700 virtual const CXXOperatorCallExpr *getOriginExpr() const {
701 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
704 unsigned getNumArgs() const override {
705 return getOriginExpr()->getNumArgs() - 1;
707 const Expr *getArgExpr(unsigned Index) const override {
708 return getOriginExpr()->getArg(Index + 1);
711 const Expr *getCXXThisExpr() const override;
713 Kind getKind() const override { return CE_CXXMemberOperator; }
715 static bool classof(const CallEvent *CA) {
716 return CA->getKind() == CE_CXXMemberOperator;
720 /// \brief Represents an implicit call to a C++ destructor.
722 /// This can occur at the end of a scope (for automatic objects), at the end
723 /// of a full-expression (for temporaries), or as part of a delete.
724 class CXXDestructorCall : public CXXInstanceCall {
725 friend class CallEventManager;
728 typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy;
730 /// Creates an implicit destructor.
732 /// \param DD The destructor that will be called.
733 /// \param Trigger The statement whose completion causes this destructor call.
734 /// \param Target The object region to be destructed.
735 /// \param St The path-sensitive state at this point in the program.
736 /// \param LCtx The location context at this point in the program.
737 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
738 const MemRegion *Target, bool IsBaseDestructor,
739 ProgramStateRef St, const LocationContext *LCtx)
740 : CXXInstanceCall(DD, St, LCtx) {
741 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
742 Location = Trigger->getLocEnd();
745 CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {}
746 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
749 SourceRange getSourceRange() const override { return Location; }
750 unsigned getNumArgs() const override { return 0; }
752 RuntimeDefinition getRuntimeDefinition() const override;
754 /// \brief Returns the value of the implicit 'this' object.
755 SVal getCXXThisVal() const override;
757 /// Returns true if this is a call to a base class destructor.
758 bool isBaseDestructor() const {
759 return DtorDataTy::getFromOpaqueValue(Data).getInt();
762 Kind getKind() const override { return CE_CXXDestructor; }
764 static bool classof(const CallEvent *CA) {
765 return CA->getKind() == CE_CXXDestructor;
769 /// \brief Represents a call to a C++ constructor.
772 class CXXConstructorCall : public AnyFunctionCall {
773 friend class CallEventManager;
776 /// Creates a constructor call.
778 /// \param CE The constructor expression as written in the source.
779 /// \param Target The region where the object should be constructed. If NULL,
780 /// a new symbolic region will be used.
781 /// \param St The path-sensitive state at this point in the program.
782 /// \param LCtx The location context at this point in the program.
783 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
784 ProgramStateRef St, const LocationContext *LCtx)
785 : AnyFunctionCall(CE, St, LCtx) {
789 CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
790 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
792 void getExtraInvalidatedValues(ValueList &Values,
793 RegionAndSymbolInvalidationTraits *ETraits) const override;
796 virtual const CXXConstructExpr *getOriginExpr() const {
797 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
800 const CXXConstructorDecl *getDecl() const override {
801 return getOriginExpr()->getConstructor();
804 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
806 const Expr *getArgExpr(unsigned Index) const override {
807 return getOriginExpr()->getArg(Index);
810 /// \brief Returns the value of the implicit 'this' object.
811 SVal getCXXThisVal() const;
813 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
814 BindingsTy &Bindings) const override;
816 Kind getKind() const override { return CE_CXXConstructor; }
818 static bool classof(const CallEvent *CA) {
819 return CA->getKind() == CE_CXXConstructor;
823 /// \brief Represents the memory allocation call in a C++ new-expression.
825 /// This is a call to "operator new".
826 class CXXAllocatorCall : public AnyFunctionCall {
827 friend class CallEventManager;
830 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
831 const LocationContext *LCtx)
832 : AnyFunctionCall(E, St, LCtx) {}
834 CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
835 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
838 virtual const CXXNewExpr *getOriginExpr() const {
839 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
842 const FunctionDecl *getDecl() const override {
843 return getOriginExpr()->getOperatorNew();
846 unsigned getNumArgs() const override {
847 return getOriginExpr()->getNumPlacementArgs() + 1;
850 const Expr *getArgExpr(unsigned Index) const override {
851 // The first argument of an allocator call is the size of the allocation.
854 return getOriginExpr()->getPlacementArg(Index - 1);
857 Kind getKind() const override { return CE_CXXAllocator; }
859 static bool classof(const CallEvent *CE) {
860 return CE->getKind() == CE_CXXAllocator;
864 /// \brief Represents the ways an Objective-C message send can occur.
866 // Note to maintainers: OCM_Message should always be last, since it does not
867 // need to fit in the Data field's low bits.
868 enum ObjCMessageKind {
874 /// \brief Represents any expression that calls an Objective-C method.
876 /// This includes all of the kinds listed in ObjCMessageKind.
877 class ObjCMethodCall : public CallEvent {
878 friend class CallEventManager;
880 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
883 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
884 const LocationContext *LCtx)
885 : CallEvent(Msg, St, LCtx) {
889 ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
890 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
892 void getExtraInvalidatedValues(ValueList &Values,
893 RegionAndSymbolInvalidationTraits *ETraits) const override;
895 /// Check if the selector may have multiple definitions (may have overrides).
896 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
900 virtual const ObjCMessageExpr *getOriginExpr() const {
901 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
903 const ObjCMethodDecl *getDecl() const override {
904 return getOriginExpr()->getMethodDecl();
906 unsigned getNumArgs() const override {
907 return getOriginExpr()->getNumArgs();
909 const Expr *getArgExpr(unsigned Index) const override {
910 return getOriginExpr()->getArg(Index);
913 bool isInstanceMessage() const {
914 return getOriginExpr()->isInstanceMessage();
916 ObjCMethodFamily getMethodFamily() const {
917 return getOriginExpr()->getMethodFamily();
919 Selector getSelector() const {
920 return getOriginExpr()->getSelector();
923 SourceRange getSourceRange() const override;
925 /// \brief Returns the value of the receiver at the time of this call.
926 SVal getReceiverSVal() const;
928 /// \brief Return the value of 'self' if available.
929 SVal getSelfSVal() const;
931 /// \brief Get the interface for the receiver.
933 /// This works whether this is an instance message or a class message.
934 /// However, it currently just uses the static type of the receiver.
935 const ObjCInterfaceDecl *getReceiverInterface() const {
936 return getOriginExpr()->getReceiverInterface();
939 /// \brief Checks if the receiver refers to 'self' or 'super'.
940 bool isReceiverSelfOrSuper() const;
942 /// Returns how the message was written in the source (property access,
943 /// subscript, or explicit message send).
944 ObjCMessageKind getMessageKind() const;
946 /// Returns true if this property access or subscript is a setter (has the
947 /// form of an assignment).
948 bool isSetter() const {
949 switch (getMessageKind()) {
951 llvm_unreachable("This is not a pseudo-object access!");
952 case OCM_PropertyAccess:
953 return getNumArgs() > 0;
955 return getNumArgs() > 1;
957 llvm_unreachable("Unknown message kind");
960 RuntimeDefinition getRuntimeDefinition() const override;
962 bool argumentsMayEscape() const override;
964 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
965 BindingsTy &Bindings) const override;
967 ArrayRef<ParmVarDecl*> parameters() const override;
969 Kind getKind() const override { return CE_ObjCMessage; }
971 static bool classof(const CallEvent *CA) {
972 return CA->getKind() == CE_ObjCMessage;
977 /// \brief Manages the lifetime of CallEvent objects.
979 /// CallEventManager provides a way to create arbitrary CallEvents "on the
980 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
981 /// memory blocks. The CallEvents created by CallEventManager are only valid
982 /// for the lifetime of the OwnedCallEvent that holds them; right now these
983 /// objects cannot be copied and ownership cannot be transferred.
984 class CallEventManager {
985 friend class CallEvent;
987 llvm::BumpPtrAllocator &Alloc;
988 SmallVector<void *, 8> Cache;
989 typedef SimpleFunctionCall CallEventTemplateTy;
991 void reclaim(const void *Memory) {
992 Cache.push_back(const_cast<void *>(Memory));
995 /// Returns memory that can be initialized as a CallEvent.
998 return Alloc.Allocate<CallEventTemplateTy>();
1000 return Cache.pop_back_val();
1003 template <typename T, typename Arg>
1004 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1005 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1006 "CallEvent subclasses are not all the same size");
1007 return new (allocate()) T(A, St, LCtx);
1010 template <typename T, typename Arg1, typename Arg2>
1011 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1012 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1013 "CallEvent subclasses are not all the same size");
1014 return new (allocate()) T(A1, A2, St, LCtx);
1017 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1018 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1019 const LocationContext *LCtx) {
1020 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1021 "CallEvent subclasses are not all the same size");
1022 return new (allocate()) T(A1, A2, A3, St, LCtx);
1025 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1027 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, 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, A4, St, LCtx);
1035 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1039 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1043 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1044 const LocationContext *LCtx);
1046 CallEventRef<ObjCMethodCall>
1047 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1048 const LocationContext *LCtx) {
1049 return create<ObjCMethodCall>(E, State, LCtx);
1052 CallEventRef<CXXConstructorCall>
1053 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1054 ProgramStateRef State, const LocationContext *LCtx) {
1055 return create<CXXConstructorCall>(E, Target, State, LCtx);
1058 CallEventRef<CXXDestructorCall>
1059 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1060 const MemRegion *Target, bool IsBase,
1061 ProgramStateRef State, const LocationContext *LCtx) {
1062 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1065 CallEventRef<CXXAllocatorCall>
1066 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1067 const LocationContext *LCtx) {
1068 return create<CXXAllocatorCall>(E, State, LCtx);
1073 template <typename T>
1074 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1075 assert(isa<T>(*this) && "Cloning to unrelated type");
1076 static_assert(sizeof(T) == sizeof(CallEvent),
1077 "Subclasses may not add fields");
1079 if (NewState == State)
1080 return cast<T>(this);
1082 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1083 T *Copy = static_cast<T *>(Mgr.allocate());
1085 assert(Copy->getKind() == this->getKind() && "Bad copy");
1087 Copy->State = NewState;
1091 inline void CallEvent::Release() const {
1092 assert(RefCount > 0 && "Reference count is already zero.");
1098 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1104 } // end namespace ento
1105 } // end namespace clang
1108 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1109 template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
1110 typedef const T *SimpleType;
1113 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {