1//===- CallEvent.h - Wrapper for all function and method calls --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file This file defines CallEvent and its subclasses, which represent path-
10/// sensitive instances of different kinds of function and method calls
11/// (C, C++, and Objective-C).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
16#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Stmt.h"
26#include "clang/AST/Type.h"
27#include "clang/Basic/IdentifierTable.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/IntrusiveRefCntPtr.h"
37#include "llvm/ADT/PointerIntPair.h"
38#include "llvm/ADT/PointerUnion.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Allocator.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/ErrorHandling.h"
46#include <cassert>
47#include <limits>
48#include <optional>
49#include <utility>
50
51namespace clang {
52
53class LocationContext;
54class ProgramPoint;
55class ProgramPointTag;
56class StackFrameContext;
57
58namespace ento {
59
60enum CallEventKind {
61 CE_Function,
62 CE_CXXStaticOperator,
63 CE_CXXMember,
64 CE_CXXMemberOperator,
65 CE_CXXDestructor,
66 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
67 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
68 CE_CXXConstructor,
69 CE_CXXInheritedConstructor,
70 CE_BEG_CXX_CONSTRUCTOR_CALLS = CE_CXXConstructor,
71 CE_END_CXX_CONSTRUCTOR_CALLS = CE_CXXInheritedConstructor,
72 CE_CXXAllocator,
73 CE_CXXDeallocator,
74 CE_BEG_FUNCTION_CALLS = CE_Function,
75 CE_END_FUNCTION_CALLS = CE_CXXDeallocator,
76 CE_Block,
77 CE_ObjCMessage
78};
79
80class CallEvent;
81
82template <typename T = CallEvent>
83class CallEventRef : public IntrusiveRefCntPtr<const T> {
84public:
85 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
86 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
87
88 // The copy assignment operator is defined as deleted pending further
89 // motivation.
90 CallEventRef &operator=(const CallEventRef &) = delete;
91
92 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
93 return this->get()->template cloneWithState<T>(State);
94 }
95
96 // Allow implicit conversions to a superclass type, since CallEventRef
97 // behaves like a pointer-to-const.
98 template <typename SuperT> operator CallEventRef<SuperT>() const {
99 return this->get();
100 }
101};
102
103/// \class RuntimeDefinition
104/// Defines the runtime definition of the called function.
105///
106/// Encapsulates the information we have about which Decl will be used
107/// when the call is executed on the given path. When dealing with dynamic
108/// dispatch, the information is based on DynamicTypeInfo and might not be
109/// precise.
110class RuntimeDefinition {
111 /// The Declaration of the function which could be called at runtime.
112 /// NULL if not available.
113 const Decl *D = nullptr;
114
115 /// The region representing an object (ObjC/C++) on which the method is
116 /// called. With dynamic dispatch, the method definition depends on the
117 /// runtime type of this object. NULL when the DynamicTypeInfo is
118 /// precise.
119 const MemRegion *R = nullptr;
120
121 /// A definition is foreign if it has been imported and newly created by the
122 /// ASTImporter. This can be true only if CTU is enabled.
123 const bool Foreign = false;
124
125public:
126 RuntimeDefinition() = default;
127 RuntimeDefinition(const Decl *InD) : D(InD) {}
128 RuntimeDefinition(const Decl *InD, bool Foreign) : D(InD), Foreign(Foreign) {}
129 RuntimeDefinition(const Decl *InD, const MemRegion *InR) : D(InD), R(InR) {}
130
131 const Decl *getDecl() { return D; }
132 bool isForeign() const { return Foreign; }
133
134 /// Check if the definition we have is precise.
135 /// If not, it is possible that the call dispatches to another definition at
136 /// execution time.
137 bool mayHaveOtherDefinitions() { return R != nullptr; }
138
139 /// When other definitions are possible, returns the region whose runtime type
140 /// determines the method definition.
141 const MemRegion *getDispatchRegion() { return R; }
142};
143
144/// Represents an abstract call to a function or method along a
145/// particular path.
146///
147/// CallEvents are created through the factory methods of CallEventManager.
148///
149/// CallEvents should always be cheap to create and destroy. In order for
150/// CallEventManager to be able to re-use CallEvent-sized memory blocks,
151/// subclasses of CallEvent may not add any data members to the base class.
152/// Use the "Data" and "Location" fields instead.
153class CallEvent {
154public:
155 using Kind = CallEventKind;
156
157private:
158 ProgramStateRef State;
159 const LocationContext *LCtx;
160 llvm::PointerUnion<const Expr *, const Decl *> Origin;
161 CFGBlock::ConstCFGElementRef ElemRef = {nullptr, 0};
162 mutable std::optional<bool> Foreign; // Set by CTU analysis.
163
164protected:
165 // This is user data for subclasses.
166 const void *Data;
167
168 // This is user data for subclasses.
169 // This should come right before RefCount, so that the two fields can be
170 // packed together on LP64 platforms.
171 SourceLocation Location;
172
173private:
174 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
175
176 mutable unsigned RefCount = 0;
177
178 void Retain() const { ++RefCount; }
179 void Release() const;
180
181protected:
182 friend class CallEventManager;
183
184 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx,
185 CFGBlock::ConstCFGElementRef ElemRef)
186 : State(std::move(state)), LCtx(lctx), Origin(E), ElemRef(ElemRef) {}
187
188 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx,
189 CFGBlock::ConstCFGElementRef ElemRef)
190 : State(std::move(state)), LCtx(lctx), Origin(D), ElemRef(ElemRef) {}
191
192 // DO NOT MAKE PUBLIC
193 CallEvent(const CallEvent &Original)
194 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
195 ElemRef(Original.ElemRef), Data(Original.Data),
196 Location(Original.Location) {}
197
198 /// Copies this CallEvent, with vtable intact, into a new block of memory.
199 virtual void cloneTo(void *Dest) const = 0;
200
201 /// Get the value of arbitrary expressions at this point in the path.
202 SVal getSVal(const Stmt *S) const {
203 return getState()->getSVal(Ex: S, LCtx: getLocationContext());
204 }
205
206 using ValueList = SmallVectorImpl<SVal>;
207
208 /// Used to specify non-argument regions that will be invalidated as a
209 /// result of this call.
210 virtual void
211 getExtraInvalidatedValues(ValueList &Values,
212 RegionAndSymbolInvalidationTraits *ETraits) const {}
213
214public:
215 CallEvent &operator=(const CallEvent &) = delete;
216 virtual ~CallEvent() = default;
217
218 /// Returns the kind of call this is.
219 virtual Kind getKind() const = 0;
220 virtual StringRef getKindAsString() const = 0;
221
222 /// Returns the declaration of the function or method that will be
223 /// called. May be null.
224 virtual const Decl *getDecl() const {
225 return Origin.dyn_cast<const Decl *>();
226 }
227
228 bool isForeign() const {
229 assert(Foreign && "Foreign must be set before querying");
230 return *Foreign;
231 }
232 void setForeign(bool B) const { Foreign = B; }
233
234 /// The state in which the call is being evaluated.
235 const ProgramStateRef &getState() const { return State; }
236
237 /// The context in which the call is being evaluated.
238 const LocationContext *getLocationContext() const { return LCtx; }
239
240 const CFGBlock::ConstCFGElementRef &getCFGElementRef() const {
241 return ElemRef;
242 }
243
244 /// Returns the definition of the function or method that will be
245 /// called.
246 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
247
248 /// Returns the expression whose value will be the result of this call.
249 /// May be null.
250 virtual const Expr *getOriginExpr() const {
251 return Origin.dyn_cast<const Expr *>();
252 }
253
254 /// Returns the number of arguments (explicit and implicit).
255 ///
256 /// Note that this may be greater than the number of parameters in the
257 /// callee's declaration, and that it may include arguments not written in
258 /// the source.
259 virtual unsigned getNumArgs() const = 0;
260
261 /// Returns true if the callee is known to be from a system header.
262 bool isInSystemHeader() const {
263 const Decl *D = getDecl();
264 if (!D)
265 return false;
266
267 SourceLocation Loc = D->getLocation();
268 if (Loc.isValid()) {
269 const SourceManager &SM =
270 getState()->getStateManager().getContext().getSourceManager();
271 return SM.isInSystemHeader(Loc: D->getLocation());
272 }
273
274 // Special case for implicitly-declared global operator new/delete.
275 // These should be considered system functions.
276 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
277 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
278
279 return false;
280 }
281
282 /// Returns a source range for the entire call, suitable for
283 /// outputting in diagnostics.
284 virtual SourceRange getSourceRange() const {
285 return getOriginExpr()->getSourceRange();
286 }
287
288 /// Returns the value of a given argument at the time of the call.
289 virtual SVal getArgSVal(unsigned Index) const;
290
291 /// Returns the expression associated with a given argument.
292 /// May be null if this expression does not appear in the source.
293 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
294
295 /// Returns the source range for errors associated with this argument.
296 ///
297 /// May be invalid if the argument is not written in the source.
298 virtual SourceRange getArgSourceRange(unsigned Index) const;
299
300 /// Returns the result type, adjusted for references.
301 QualType getResultType() const;
302
303 /// Returns the return value of the call.
304 ///
305 /// This should only be called if the CallEvent was created using a state in
306 /// which the return value has already been bound to the origin expression.
307 SVal getReturnValue() const;
308
309 /// Returns true if the type of any of the non-null arguments satisfies
310 /// the condition.
311 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
312
313 /// Returns true if any of the arguments appear to represent callbacks.
314 bool hasNonZeroCallbackArg() const;
315
316 /// Returns true if any of the arguments is void*.
317 bool hasVoidPointerToNonConstArg() const;
318
319 /// Returns true if any of the arguments are known to escape to long-
320 /// term storage, even if this method will not modify them.
321 // NOTE: The exact semantics of this are still being defined!
322 // We don't really want a list of hardcoded exceptions in the long run,
323 // but we don't want duplicated lists of known APIs in the short term either.
324 virtual bool argumentsMayEscape() const { return hasNonZeroCallbackArg(); }
325
326 /// Returns true if the callee is an externally-visible function in the
327 /// top-level namespace, such as \c malloc.
328 ///
329 /// You can use this call to determine that a particular function really is
330 /// a library function and not, say, a C++ member function with the same name.
331 ///
332 /// If a name is provided, the function must additionally match the given
333 /// name.
334 ///
335 /// Note that this deliberately excludes C++ library functions in the \c std
336 /// namespace, but will include C library functions accessed through the
337 /// \c std namespace. This also does not check if the function is declared
338 /// as 'extern "C"', or if it uses C++ name mangling.
339 // FIXME: Add a helper for checking namespaces.
340 // FIXME: Move this down to AnyFunctionCall once checkers have more
341 // precise callbacks.
342 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
343
344 /// Returns the name of the callee, if its name is a simple identifier.
345 ///
346 /// Note that this will fail for Objective-C methods, blocks, and C++
347 /// overloaded operators. The former is named by a Selector rather than a
348 /// simple identifier, and the latter two do not have names.
349 // FIXME: Move this down to AnyFunctionCall once checkers have more
350 // precise callbacks.
351 const IdentifierInfo *getCalleeIdentifier() const {
352 const auto *ND = dyn_cast_or_null<NamedDecl>(Val: getDecl());
353 if (!ND)
354 return nullptr;
355 return ND->getIdentifier();
356 }
357
358 /// Returns an appropriate ProgramPoint for this call.
359 ProgramPoint getProgramPoint(bool IsPreVisit = false,
360 const ProgramPointTag *Tag = nullptr) const;
361
362 /// Returns a new state with all argument regions invalidated.
363 ///
364 /// This accepts an alternate state in case some processing has already
365 /// occurred.
366 ProgramStateRef invalidateRegions(unsigned BlockCount,
367 ProgramStateRef Orig = nullptr) const;
368
369 using FrameBindingTy = std::pair<SVal, SVal>;
370 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
371
372 /// Populates the given SmallVector with the bindings in the callee's stack
373 /// frame at the start of this call.
374 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
375 BindingsTy &Bindings) const = 0;
376
377 /// Returns a copy of this CallEvent, but using the given state.
378 template <typename T>
379 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
380
381 /// Returns a copy of this CallEvent, but using the given state.
382 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
383 return cloneWithState<CallEvent>(NewState);
384 }
385
386 /// Returns true if this is a statement is a function or method call
387 /// of some kind.
388 static bool isCallStmt(const Stmt *S);
389
390 /// Returns the result type of a function or method declaration.
391 ///
392 /// This will return a null QualType if the result type cannot be determined.
393 static QualType getDeclaredResultType(const Decl *D);
394
395 /// Returns true if the given decl is known to be variadic.
396 ///
397 /// \p D must not be null.
398 static bool isVariadic(const Decl *D);
399
400 /// Returns AnalysisDeclContext for the callee stack frame.
401 /// Currently may fail; returns null on failure.
402 AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
403
404 /// Returns the callee stack frame. That stack frame will only be entered
405 /// during analysis if the call is inlined, but it may still be useful
406 /// in intermediate calculations even if the call isn't inlined.
407 /// May fail; returns null on failure.
408 const StackFrameContext *getCalleeStackFrame(unsigned BlockCount) const;
409
410 /// Returns memory location for a parameter variable within the callee stack
411 /// frame. The behavior is undefined if the block count is different from the
412 /// one that is there when call happens. May fail; returns null on failure.
413 const ParamVarRegion *getParameterLocation(unsigned Index,
414 unsigned BlockCount) const;
415
416 /// Returns true if on the current path, the argument was constructed by
417 /// calling a C++ constructor over it. This is an internal detail of the
418 /// analysis which doesn't necessarily represent the program semantics:
419 /// if we are supposed to construct an argument directly, we may still
420 /// not do that because we don't know how (i.e., construction context is
421 /// unavailable in the CFG or not supported by the analyzer).
422 bool isArgumentConstructedDirectly(unsigned Index) const {
423 // This assumes that the object was not yet removed from the state.
424 return ExprEngine::getObjectUnderConstruction(
425 State: getState(), Item: {getOriginExpr(), Index}, LC: getLocationContext())
426 .has_value();
427 }
428
429 /// Some calls have parameter numbering mismatched from argument numbering.
430 /// This function converts an argument index to the corresponding
431 /// parameter index. Returns std::nullopt is the argument doesn't correspond
432 /// to any parameter variable.
433 virtual std::optional<unsigned>
434 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
435 return ASTArgumentIndex;
436 }
437
438 /// Some call event sub-classes conveniently adjust mismatching AST indices
439 /// to match parameter indices. This function converts an argument index
440 /// as understood by CallEvent to the argument index as understood by the AST.
441 virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
442 return CallArgumentIndex;
443 }
444
445 /// Returns the construction context of the call, if it is a C++ constructor
446 /// call or a call of a function returning a C++ class instance. Otherwise
447 /// return nullptr.
448 const ConstructionContext *getConstructionContext() const;
449
450 /// If the call returns a C++ record type then the region of its return value
451 /// can be retrieved from its construction context.
452 std::optional<SVal> getReturnValueUnderConstruction() const;
453
454 // Returns the CallEvent representing the caller of this function
455 const CallEventRef<> getCaller() const;
456
457 // Returns true if the function was called from a standard library function.
458 // If not or could not get the caller (it may be a top level function)
459 // returns false.
460 bool isCalledFromSystemHeader() const;
461
462 // Iterator access to formal parameters and their types.
463private:
464 struct GetTypeFn {
465 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
466 };
467
468public:
469 /// Return call's formal parameters.
470 ///
471 /// Remember that the number of formal parameters may not match the number
472 /// of arguments for all calls. However, the first parameter will always
473 /// correspond with the argument value returned by \c getArgSVal(0).
474 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
475
476 using param_type_iterator =
477 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
478
479 /// Returns an iterator over the types of the call's formal parameters.
480 ///
481 /// This uses the callee decl found by default name lookup rather than the
482 /// definition because it represents a public interface, and probably has
483 /// more annotations.
484 param_type_iterator param_type_begin() const {
485 return llvm::map_iterator(I: parameters().begin(), F: GetTypeFn());
486 }
487 /// \sa param_type_begin()
488 param_type_iterator param_type_end() const {
489 return llvm::map_iterator(I: parameters().end(), F: GetTypeFn());
490 }
491
492 // For debugging purposes only
493 void dump(raw_ostream &Out) const;
494 void dump() const;
495};
496
497/// Represents a call to any sort of function that might have a
498/// FunctionDecl.
499class AnyFunctionCall : public CallEvent {
500protected:
501 AnyFunctionCall(const Expr *E, ProgramStateRef St,
502 const LocationContext *LCtx,
503 CFGBlock::ConstCFGElementRef ElemRef)
504 : CallEvent(E, St, LCtx, ElemRef) {}
505 AnyFunctionCall(const Decl *D, ProgramStateRef St,
506 const LocationContext *LCtx,
507 CFGBlock::ConstCFGElementRef ElemRef)
508 : CallEvent(D, St, LCtx, ElemRef) {}
509 AnyFunctionCall(const AnyFunctionCall &Other) = default;
510
511public:
512 // This function is overridden by subclasses, but they must return
513 // a FunctionDecl.
514 const FunctionDecl *getDecl() const override {
515 return cast<FunctionDecl>(Val: CallEvent::getDecl());
516 }
517
518 RuntimeDefinition getRuntimeDefinition() const override;
519
520 bool argumentsMayEscape() const override;
521
522 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
523 BindingsTy &Bindings) const override;
524
525 ArrayRef<ParmVarDecl *> parameters() const override;
526
527 static bool classof(const CallEvent *CA) {
528 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
529 CA->getKind() <= CE_END_FUNCTION_CALLS;
530 }
531};
532
533/// Represents a C function or static C++ member function call.
534///
535/// Example: \c fun()
536class SimpleFunctionCall : public AnyFunctionCall {
537 friend class CallEventManager;
538
539protected:
540 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
541 const LocationContext *LCtx,
542 CFGBlock::ConstCFGElementRef ElemRef)
543 : AnyFunctionCall(CE, St, LCtx, ElemRef) {}
544 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
545
546 void cloneTo(void *Dest) const override {
547 new (Dest) SimpleFunctionCall(*this);
548 }
549
550public:
551 const CallExpr *getOriginExpr() const override {
552 return cast<CallExpr>(Val: AnyFunctionCall::getOriginExpr());
553 }
554
555 const FunctionDecl *getDecl() const override;
556
557 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
558
559 const Expr *getArgExpr(unsigned Index) const override {
560 return getOriginExpr()->getArg(Arg: Index);
561 }
562
563 Kind getKind() const override { return CE_Function; }
564 StringRef getKindAsString() const override { return "SimpleFunctionCall"; }
565
566 static bool classof(const CallEvent *CA) {
567 return CA->getKind() == CE_Function;
568 }
569};
570
571/// Represents a call to a block.
572///
573/// Example: <tt>^{ statement-body }()</tt>
574class BlockCall : public CallEvent {
575 friend class CallEventManager;
576
577protected:
578 BlockCall(const CallExpr *CE, ProgramStateRef St, const LocationContext *LCtx,
579 CFGBlock::ConstCFGElementRef ElemRef)
580 : CallEvent(CE, St, LCtx, ElemRef) {}
581 BlockCall(const BlockCall &Other) = default;
582
583 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
584
585 void getExtraInvalidatedValues(
586 ValueList &Values,
587 RegionAndSymbolInvalidationTraits *ETraits) const override;
588
589public:
590 const CallExpr *getOriginExpr() const override {
591 return cast<CallExpr>(Val: CallEvent::getOriginExpr());
592 }
593
594 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
595
596 const Expr *getArgExpr(unsigned Index) const override {
597 return getOriginExpr()->getArg(Arg: Index);
598 }
599
600 /// Returns the region associated with this instance of the block.
601 ///
602 /// This may be NULL if the block's origin is unknown.
603 const BlockDataRegion *getBlockRegion() const;
604
605 const BlockDecl *getDecl() const override {
606 const BlockDataRegion *BR = getBlockRegion();
607 if (!BR)
608 return nullptr;
609 return BR->getDecl();
610 }
611
612 bool isConversionFromLambda() const {
613 const BlockDecl *BD = getDecl();
614 if (!BD)
615 return false;
616
617 return BD->isConversionFromLambda();
618 }
619
620 /// For a block converted from a C++ lambda, returns the block
621 /// VarRegion for the variable holding the captured C++ lambda record.
622 const VarRegion *getRegionStoringCapturedLambda() const {
623 assert(isConversionFromLambda());
624 const BlockDataRegion *BR = getBlockRegion();
625 assert(BR && "Block converted from lambda must have a block region");
626
627 auto ReferencedVars = BR->referenced_vars();
628 assert(!ReferencedVars.empty());
629 return ReferencedVars.begin().getCapturedRegion();
630 }
631
632 RuntimeDefinition getRuntimeDefinition() const override {
633 if (!isConversionFromLambda())
634 return RuntimeDefinition(getDecl());
635
636 // Clang converts lambdas to blocks with an implicit user-defined
637 // conversion operator method on the lambda record that looks (roughly)
638 // like:
639 //
640 // typedef R(^block_type)(P1, P2, ...);
641 // operator block_type() const {
642 // auto Lambda = *this;
643 // return ^(P1 p1, P2 p2, ...){
644 // /* return Lambda(p1, p2, ...); */
645 // };
646 // }
647 //
648 // Here R is the return type of the lambda and P1, P2, ... are
649 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
650 // that is initialized to a copy of the lambda.
651 //
652 // Sema leaves the body of a lambda-converted block empty (it is
653 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
654 // the block body and analyze the operator() method on the captured lambda.
655 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
656 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
657 CXXMethodDecl *LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
658
659 return RuntimeDefinition(LambdaCallOperator);
660 }
661
662 bool argumentsMayEscape() const override { return true; }
663
664 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
665 BindingsTy &Bindings) const override;
666
667 ArrayRef<ParmVarDecl *> parameters() const override;
668
669 Kind getKind() const override { return CE_Block; }
670 StringRef getKindAsString() const override { return "BlockCall"; }
671
672 static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; }
673};
674
675/// Represents a non-static C++ member function call, no matter how
676/// it is written.
677class CXXInstanceCall : public AnyFunctionCall {
678protected:
679 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
680 const LocationContext *LCtx,
681 CFGBlock::ConstCFGElementRef ElemRef)
682 : AnyFunctionCall(CE, St, LCtx, ElemRef) {}
683 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
684 const LocationContext *LCtx,
685 CFGBlock::ConstCFGElementRef ElemRef)
686 : AnyFunctionCall(D, St, LCtx, ElemRef) {}
687 CXXInstanceCall(const CXXInstanceCall &Other) = default;
688
689 void getExtraInvalidatedValues(
690 ValueList &Values,
691 RegionAndSymbolInvalidationTraits *ETraits) const override;
692
693public:
694 /// Returns the expression representing the implicit 'this' object.
695 virtual const Expr *getCXXThisExpr() const { return nullptr; }
696
697 /// Returns the value of the implicit 'this' object.
698 virtual SVal getCXXThisVal() const;
699
700 const FunctionDecl *getDecl() const override;
701
702 RuntimeDefinition getRuntimeDefinition() const override;
703
704 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
705 BindingsTy &Bindings) const override;
706
707 static bool classof(const CallEvent *CA) {
708 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
709 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
710 }
711};
712
713/// Represents a static C++ operator call.
714///
715/// "A" in this example.
716/// However, "B" and "C" are represented by SimpleFunctionCall.
717/// \code
718/// struct S {
719/// int pad;
720/// static void operator()(int x, int y);
721/// };
722/// S s{10};
723/// void (*fptr)(int, int) = &S::operator();
724///
725/// s(1, 2); // A
726/// S::operator()(1, 2); // B
727/// fptr(1, 2); // C
728/// \endcode
729class CXXStaticOperatorCall : public SimpleFunctionCall {
730 friend class CallEventManager;
731
732protected:
733 CXXStaticOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
734 const LocationContext *LCtx,
735 CFGBlock::ConstCFGElementRef ElemRef)
736 : SimpleFunctionCall(CE, St, LCtx, ElemRef) {}
737 CXXStaticOperatorCall(const CXXStaticOperatorCall &Other) = default;
738
739 void cloneTo(void *Dest) const override {
740 new (Dest) CXXStaticOperatorCall(*this);
741 }
742
743public:
744 const CXXOperatorCallExpr *getOriginExpr() const override {
745 return cast<CXXOperatorCallExpr>(Val: SimpleFunctionCall::getOriginExpr());
746 }
747
748 unsigned getNumArgs() const override {
749 // Ignore the object parameter that is not used for static member functions.
750 assert(getOriginExpr()->getNumArgs() > 0);
751 return getOriginExpr()->getNumArgs() - 1;
752 }
753
754 const Expr *getArgExpr(unsigned Index) const override {
755 // Ignore the object parameter that is not used for static member functions.
756 return getOriginExpr()->getArg(Index + 1);
757 }
758
759 std::optional<unsigned>
760 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
761 // Ignore the object parameter that is not used for static member functions.
762 if (ASTArgumentIndex == 0)
763 return std::nullopt;
764 return ASTArgumentIndex - 1;
765 }
766
767 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
768 // Account for the object parameter for the static member function.
769 return CallArgumentIndex + 1;
770 }
771
772 OverloadedOperatorKind getOverloadedOperator() const {
773 return getOriginExpr()->getOperator();
774 }
775
776 Kind getKind() const override { return CE_CXXStaticOperator; }
777 StringRef getKindAsString() const override { return "CXXStaticOperatorCall"; }
778
779 static bool classof(const CallEvent *CA) {
780 return CA->getKind() == CE_CXXStaticOperator;
781 }
782};
783
784/// Represents a non-static C++ member function call.
785///
786/// Example: \c obj.fun()
787class CXXMemberCall : public CXXInstanceCall {
788 friend class CallEventManager;
789
790protected:
791 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
792 const LocationContext *LCtx,
793 CFGBlock::ConstCFGElementRef ElemRef)
794 : CXXInstanceCall(CE, St, LCtx, ElemRef) {}
795 CXXMemberCall(const CXXMemberCall &Other) = default;
796
797 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
798
799public:
800 const CXXMemberCallExpr *getOriginExpr() const override {
801 return cast<CXXMemberCallExpr>(Val: CXXInstanceCall::getOriginExpr());
802 }
803
804 unsigned getNumArgs() const override {
805 if (const CallExpr *CE = getOriginExpr())
806 return CE->getNumArgs();
807 return 0;
808 }
809
810 const Expr *getArgExpr(unsigned Index) const override {
811 return getOriginExpr()->getArg(Index);
812 }
813
814 const Expr *getCXXThisExpr() const override;
815
816 RuntimeDefinition getRuntimeDefinition() const override;
817
818 Kind getKind() const override { return CE_CXXMember; }
819 StringRef getKindAsString() const override { return "CXXMemberCall"; }
820
821 static bool classof(const CallEvent *CA) {
822 return CA->getKind() == CE_CXXMember;
823 }
824};
825
826/// Represents a C++ overloaded operator call where the operator is
827/// implemented as a non-static member function.
828///
829/// Example: <tt>iter + 1</tt>
830class CXXMemberOperatorCall : public CXXInstanceCall {
831 friend class CallEventManager;
832
833protected:
834 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
835 const LocationContext *LCtx,
836 CFGBlock::ConstCFGElementRef ElemRef)
837 : CXXInstanceCall(CE, St, LCtx, ElemRef) {}
838 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
839
840 void cloneTo(void *Dest) const override {
841 new (Dest) CXXMemberOperatorCall(*this);
842 }
843
844public:
845 const CXXOperatorCallExpr *getOriginExpr() const override {
846 return cast<CXXOperatorCallExpr>(Val: CXXInstanceCall::getOriginExpr());
847 }
848
849 unsigned getNumArgs() const override {
850 return getOriginExpr()->getNumArgs() - 1;
851 }
852
853 const Expr *getArgExpr(unsigned Index) const override {
854 return getOriginExpr()->getArg(Index + 1);
855 }
856
857 const Expr *getCXXThisExpr() const override;
858
859 Kind getKind() const override { return CE_CXXMemberOperator; }
860 StringRef getKindAsString() const override { return "CXXMemberOperatorCall"; }
861
862 static bool classof(const CallEvent *CA) {
863 return CA->getKind() == CE_CXXMemberOperator;
864 }
865
866 std::optional<unsigned>
867 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
868 // For member operator calls argument 0 on the expression corresponds
869 // to implicit this-parameter on the declaration.
870 return (ASTArgumentIndex > 0)
871 ? std::optional<unsigned>(ASTArgumentIndex - 1)
872 : std::nullopt;
873 }
874
875 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
876 // For member operator calls argument 0 on the expression corresponds
877 // to implicit this-parameter on the declaration.
878 return CallArgumentIndex + 1;
879 }
880
881 OverloadedOperatorKind getOverloadedOperator() const {
882 return getOriginExpr()->getOperator();
883 }
884};
885
886/// Represents an implicit call to a C++ destructor.
887///
888/// This can occur at the end of a scope (for automatic objects), at the end
889/// of a full-expression (for temporaries), or as part of a delete.
890class CXXDestructorCall : public CXXInstanceCall {
891 friend class CallEventManager;
892
893protected:
894 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
895
896 /// Creates an implicit destructor.
897 ///
898 /// \param DD The destructor that will be called.
899 /// \param Trigger The statement whose completion causes this destructor call.
900 /// \param Target The object region to be destructed.
901 /// \param St The path-sensitive state at this point in the program.
902 /// \param LCtx The location context at this point in the program.
903 /// \param ElemRef The reference to this destructor in the CFG.
904 ///
905 /// FIXME: Eventually we want to drop \param Target and deduce it from
906 /// \param ElemRef. To do that we need to migrate the logic for target
907 /// region lookup from ExprEngine::ProcessImplicitDtor() and make it
908 /// independent from ExprEngine.
909 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
910 const MemRegion *Target, bool IsBaseDestructor,
911 ProgramStateRef St, const LocationContext *LCtx,
912 CFGBlock::ConstCFGElementRef ElemRef)
913 : CXXInstanceCall(DD, St, LCtx, ElemRef) {
914 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
915 Location = Trigger->getEndLoc();
916 }
917
918 CXXDestructorCall(const CXXDestructorCall &Other) = default;
919
920 void cloneTo(void *Dest) const override {
921 new (Dest) CXXDestructorCall(*this);
922 }
923
924public:
925 SourceRange getSourceRange() const override { return Location; }
926 unsigned getNumArgs() const override { return 0; }
927
928 RuntimeDefinition getRuntimeDefinition() const override;
929
930 /// Returns the value of the implicit 'this' object.
931 SVal getCXXThisVal() const override;
932
933 /// Returns true if this is a call to a base class destructor.
934 bool isBaseDestructor() const {
935 return DtorDataTy::getFromOpaqueValue(V: Data).getInt();
936 }
937
938 Kind getKind() const override { return CE_CXXDestructor; }
939 StringRef getKindAsString() const override { return "CXXDestructorCall"; }
940
941 static bool classof(const CallEvent *CA) {
942 return CA->getKind() == CE_CXXDestructor;
943 }
944};
945
946/// Represents any constructor invocation. This includes regular constructors
947/// and inherited constructors.
948class AnyCXXConstructorCall : public AnyFunctionCall {
949protected:
950 AnyCXXConstructorCall(const Expr *E, const MemRegion *Target,
951 ProgramStateRef St, const LocationContext *LCtx,
952 CFGBlock::ConstCFGElementRef ElemRef)
953 : AnyFunctionCall(E, St, LCtx, ElemRef) {
954 assert(E && (isa<CXXConstructExpr>(E) || isa<CXXInheritedCtorInitExpr>(E)));
955 // Target may be null when the region is unknown.
956 Data = Target;
957 }
958
959 void getExtraInvalidatedValues(
960 ValueList &Values,
961 RegionAndSymbolInvalidationTraits *ETraits) const override;
962
963 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
964 BindingsTy &Bindings) const override;
965
966public:
967 /// Returns the value of the implicit 'this' object.
968 SVal getCXXThisVal() const;
969
970 static bool classof(const CallEvent *Call) {
971 return Call->getKind() >= CE_BEG_CXX_CONSTRUCTOR_CALLS &&
972 Call->getKind() <= CE_END_CXX_CONSTRUCTOR_CALLS;
973 }
974};
975
976/// Represents a call to a C++ constructor.
977///
978/// Example: \c T(1)
979class CXXConstructorCall : public AnyCXXConstructorCall {
980 friend class CallEventManager;
981
982protected:
983 /// Creates a constructor call.
984 ///
985 /// \param CE The constructor expression as written in the source.
986 /// \param Target The region where the object should be constructed. If NULL,
987 /// a new symbolic region will be used.
988 /// \param St The path-sensitive state at this point in the program.
989 /// \param LCtx The location context at this point in the program.
990 /// \param ElemRef The reference to this constructor in the CFG.
991 ///
992 /// FIXME: Eventually we want to drop \param Target and deduce it from
993 /// \param ElemRef.
994 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
995 ProgramStateRef St, const LocationContext *LCtx,
996 CFGBlock::ConstCFGElementRef ElemRef)
997 : AnyCXXConstructorCall(CE, Target, St, LCtx, ElemRef) {}
998
999 CXXConstructorCall(const CXXConstructorCall &Other) = default;
1000
1001 void cloneTo(void *Dest) const override {
1002 new (Dest) CXXConstructorCall(*this);
1003 }
1004
1005public:
1006 const CXXConstructExpr *getOriginExpr() const override {
1007 return cast<CXXConstructExpr>(Val: AnyFunctionCall::getOriginExpr());
1008 }
1009
1010 const CXXConstructorDecl *getDecl() const override {
1011 return getOriginExpr()->getConstructor();
1012 }
1013
1014 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
1015
1016 const Expr *getArgExpr(unsigned Index) const override {
1017 return getOriginExpr()->getArg(Arg: Index);
1018 }
1019
1020 Kind getKind() const override { return CE_CXXConstructor; }
1021 StringRef getKindAsString() const override { return "CXXConstructorCall"; }
1022
1023 static bool classof(const CallEvent *CA) {
1024 return CA->getKind() == CE_CXXConstructor;
1025 }
1026};
1027
1028/// Represents a call to a C++ inherited constructor.
1029///
1030/// Example: \c class T : public S { using S::S; }; T(1);
1031///
1032// Note, it is difficult to model the parameters. This is one of the reasons
1033// why we skip analysis of inheriting constructors as top-level functions.
1034// CXXInheritedCtorInitExpr doesn't take arguments and doesn't model parameter
1035// initialization because there is none: the arguments in the outer
1036// CXXConstructExpr directly initialize the parameters of the base class
1037// constructor, and no copies are made. (Making a copy of the parameter is
1038// incorrect, at least if it's done in an observable way.) The derived class
1039// constructor doesn't even exist in the formal model.
1040/// E.g., in:
1041///
1042/// struct X { X *p = this; ~X() {} };
1043/// struct A { A(X x) : b(x.p == &x) {} bool b; };
1044/// struct B : A { using A::A; };
1045/// B b = X{};
1046///
1047/// ... b.b is initialized to true.
1048class CXXInheritedConstructorCall : public AnyCXXConstructorCall {
1049 friend class CallEventManager;
1050
1051protected:
1052 CXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *CE,
1053 const MemRegion *Target, ProgramStateRef St,
1054 const LocationContext *LCtx,
1055 CFGBlock::ConstCFGElementRef ElemRef)
1056 : AnyCXXConstructorCall(CE, Target, St, LCtx, ElemRef) {}
1057
1058 CXXInheritedConstructorCall(const CXXInheritedConstructorCall &Other) =
1059 default;
1060
1061 void cloneTo(void *Dest) const override {
1062 new (Dest) CXXInheritedConstructorCall(*this);
1063 }
1064
1065public:
1066 const CXXInheritedCtorInitExpr *getOriginExpr() const override {
1067 return cast<CXXInheritedCtorInitExpr>(Val: AnyFunctionCall::getOriginExpr());
1068 }
1069
1070 const CXXConstructorDecl *getDecl() const override {
1071 return getOriginExpr()->getConstructor();
1072 }
1073
1074 /// Obtain the stack frame of the inheriting constructor. Argument expressions
1075 /// can be found on the call site of that stack frame.
1076 const StackFrameContext *getInheritingStackFrame() const;
1077
1078 /// Obtain the CXXConstructExpr for the sub-class that inherited the current
1079 /// constructor (possibly indirectly). It's the statement that contains
1080 /// argument expressions.
1081 const CXXConstructExpr *getInheritingConstructor() const {
1082 return cast<CXXConstructExpr>(Val: getInheritingStackFrame()->getCallSite());
1083 }
1084
1085 unsigned getNumArgs() const override {
1086 return getInheritingConstructor()->getNumArgs();
1087 }
1088
1089 const Expr *getArgExpr(unsigned Index) const override {
1090 return getInheritingConstructor()->getArg(Arg: Index);
1091 }
1092
1093 SVal getArgSVal(unsigned Index) const override {
1094 return getState()->getSVal(
1095 getArgExpr(Index),
1096 getInheritingStackFrame()->getParent()->getStackFrame());
1097 }
1098
1099 Kind getKind() const override { return CE_CXXInheritedConstructor; }
1100 StringRef getKindAsString() const override {
1101 return "CXXInheritedConstructorCall";
1102 }
1103
1104 static bool classof(const CallEvent *CA) {
1105 return CA->getKind() == CE_CXXInheritedConstructor;
1106 }
1107};
1108
1109/// Represents the memory allocation call in a C++ new-expression.
1110///
1111/// This is a call to "operator new".
1112class CXXAllocatorCall : public AnyFunctionCall {
1113 friend class CallEventManager;
1114
1115protected:
1116 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
1117 const LocationContext *LCtx,
1118 CFGBlock::ConstCFGElementRef ElemRef)
1119 : AnyFunctionCall(E, St, LCtx, ElemRef) {}
1120 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
1121
1122 void cloneTo(void *Dest) const override {
1123 new (Dest) CXXAllocatorCall(*this);
1124 }
1125
1126public:
1127 const CXXNewExpr *getOriginExpr() const override {
1128 return cast<CXXNewExpr>(Val: AnyFunctionCall::getOriginExpr());
1129 }
1130
1131 const FunctionDecl *getDecl() const override {
1132 return getOriginExpr()->getOperatorNew();
1133 }
1134
1135 SVal getObjectUnderConstruction() const {
1136 return *ExprEngine::getObjectUnderConstruction(State: getState(), Item: getOriginExpr(),
1137 LC: getLocationContext());
1138 }
1139
1140 /// Number of non-placement arguments to the call. It is equal to 2 for
1141 /// C++17 aligned operator new() calls that have alignment implicitly
1142 /// passed as the second argument, and to 1 for other operator new() calls.
1143 unsigned getNumImplicitArgs() const {
1144 return getOriginExpr()->passAlignment() ? 2 : 1;
1145 }
1146
1147 unsigned getNumArgs() const override {
1148 return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
1149 }
1150
1151 bool isArray() const { return getOriginExpr()->isArray(); }
1152
1153 std::optional<const clang::Expr *> getArraySizeExpr() const {
1154 return getOriginExpr()->getArraySize();
1155 }
1156
1157 SVal getArraySizeVal() const {
1158 assert(isArray() && "The allocator call doesn't allocate and array!");
1159
1160 return getState()->getSVal(*getArraySizeExpr(), getLocationContext());
1161 }
1162
1163 const Expr *getArgExpr(unsigned Index) const override {
1164 // The first argument of an allocator call is the size of the allocation.
1165 if (Index < getNumImplicitArgs())
1166 return nullptr;
1167 return getOriginExpr()->getPlacementArg(I: Index - getNumImplicitArgs());
1168 }
1169
1170 /// Number of placement arguments to the operator new() call. For example,
1171 /// standard std::nothrow operator new and standard placement new both have
1172 /// 1 implicit argument (size) and 1 placement argument, while regular
1173 /// operator new() has 1 implicit argument and 0 placement arguments.
1174 const Expr *getPlacementArgExpr(unsigned Index) const {
1175 return getOriginExpr()->getPlacementArg(I: Index);
1176 }
1177
1178 Kind getKind() const override { return CE_CXXAllocator; }
1179 StringRef getKindAsString() const override { return "CXXAllocatorCall"; }
1180
1181 static bool classof(const CallEvent *CE) {
1182 return CE->getKind() == CE_CXXAllocator;
1183 }
1184};
1185
1186/// Represents the memory deallocation call in a C++ delete-expression.
1187///
1188/// This is a call to "operator delete".
1189// FIXME: CXXDeleteExpr isn't present for custom delete operators, or even for
1190// some those that are in the standard library, like the no-throw or align_val
1191// versions.
1192// Some pointers:
1193// http://lists.llvm.org/pipermail/cfe-dev/2020-April/065080.html
1194// clang/test/Analysis/cxx-dynamic-memory-analysis-order.cpp
1195// clang/unittests/StaticAnalyzer/CallEventTest.cpp
1196class CXXDeallocatorCall : public AnyFunctionCall {
1197 friend class CallEventManager;
1198
1199protected:
1200 CXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef St,
1201 const LocationContext *LCtx,
1202 CFGBlock::ConstCFGElementRef ElemRef)
1203 : AnyFunctionCall(E, St, LCtx, ElemRef) {}
1204 CXXDeallocatorCall(const CXXDeallocatorCall &Other) = default;
1205
1206 void cloneTo(void *Dest) const override {
1207 new (Dest) CXXDeallocatorCall(*this);
1208 }
1209
1210public:
1211 const CXXDeleteExpr *getOriginExpr() const override {
1212 return cast<CXXDeleteExpr>(Val: AnyFunctionCall::getOriginExpr());
1213 }
1214
1215 const FunctionDecl *getDecl() const override {
1216 return getOriginExpr()->getOperatorDelete();
1217 }
1218
1219 unsigned getNumArgs() const override { return getDecl()->getNumParams(); }
1220
1221 const Expr *getArgExpr(unsigned Index) const override {
1222 // CXXDeleteExpr's only have a single argument.
1223 return getOriginExpr()->getArgument();
1224 }
1225
1226 Kind getKind() const override { return CE_CXXDeallocator; }
1227 StringRef getKindAsString() const override { return "CXXDeallocatorCall"; }
1228
1229 static bool classof(const CallEvent *CE) {
1230 return CE->getKind() == CE_CXXDeallocator;
1231 }
1232};
1233
1234/// Represents the ways an Objective-C message send can occur.
1235//
1236// Note to maintainers: OCM_Message should always be last, since it does not
1237// need to fit in the Data field's low bits.
1238enum ObjCMessageKind { OCM_PropertyAccess, OCM_Subscript, OCM_Message };
1239
1240/// Represents any expression that calls an Objective-C method.
1241///
1242/// This includes all of the kinds listed in ObjCMessageKind.
1243class ObjCMethodCall : public CallEvent {
1244 friend class CallEventManager;
1245
1246 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
1247
1248protected:
1249 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
1250 const LocationContext *LCtx,
1251 CFGBlock::ConstCFGElementRef ElemRef)
1252 : CallEvent(Msg, St, LCtx, ElemRef) {
1253 Data = nullptr;
1254 }
1255
1256 ObjCMethodCall(const ObjCMethodCall &Other) = default;
1257
1258 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
1259
1260 void getExtraInvalidatedValues(
1261 ValueList &Values,
1262 RegionAndSymbolInvalidationTraits *ETraits) const override;
1263
1264 /// Check if the selector may have multiple definitions (may have overrides).
1265 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
1266 Selector Sel) const;
1267
1268public:
1269 const ObjCMessageExpr *getOriginExpr() const override {
1270 return cast<ObjCMessageExpr>(Val: CallEvent::getOriginExpr());
1271 }
1272
1273 const ObjCMethodDecl *getDecl() const override {
1274 return getOriginExpr()->getMethodDecl();
1275 }
1276
1277 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
1278
1279 const Expr *getArgExpr(unsigned Index) const override {
1280 return getOriginExpr()->getArg(Arg: Index);
1281 }
1282
1283 bool isInstanceMessage() const {
1284 return getOriginExpr()->isInstanceMessage();
1285 }
1286
1287 ObjCMethodFamily getMethodFamily() const {
1288 return getOriginExpr()->getMethodFamily();
1289 }
1290
1291 Selector getSelector() const { return getOriginExpr()->getSelector(); }
1292
1293 SourceRange getSourceRange() const override;
1294
1295 /// Returns the value of the receiver at the time of this call.
1296 SVal getReceiverSVal() const;
1297
1298 /// Get the interface for the receiver.
1299 ///
1300 /// This works whether this is an instance message or a class message.
1301 /// However, it currently just uses the static type of the receiver.
1302 const ObjCInterfaceDecl *getReceiverInterface() const {
1303 return getOriginExpr()->getReceiverInterface();
1304 }
1305
1306 /// Checks if the receiver refers to 'self' or 'super'.
1307 bool isReceiverSelfOrSuper() const;
1308
1309 /// Returns how the message was written in the source (property access,
1310 /// subscript, or explicit message send).
1311 ObjCMessageKind getMessageKind() const;
1312
1313 /// Returns true if this property access or subscript is a setter (has the
1314 /// form of an assignment).
1315 bool isSetter() const {
1316 switch (getMessageKind()) {
1317 case OCM_Message:
1318 llvm_unreachable("This is not a pseudo-object access!");
1319 case OCM_PropertyAccess:
1320 return getNumArgs() > 0;
1321 case OCM_Subscript:
1322 return getNumArgs() > 1;
1323 }
1324 llvm_unreachable("Unknown message kind");
1325 }
1326
1327 // Returns the property accessed by this method, either explicitly via
1328 // property syntax or implicitly via a getter or setter method. Returns
1329 // nullptr if the call is not a prooperty access.
1330 const ObjCPropertyDecl *getAccessedProperty() const;
1331
1332 RuntimeDefinition getRuntimeDefinition() const override;
1333
1334 bool argumentsMayEscape() const override;
1335
1336 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1337 BindingsTy &Bindings) const override;
1338
1339 ArrayRef<ParmVarDecl *> parameters() const override;
1340
1341 Kind getKind() const override { return CE_ObjCMessage; }
1342 StringRef getKindAsString() const override { return "ObjCMethodCall"; }
1343
1344 static bool classof(const CallEvent *CA) {
1345 return CA->getKind() == CE_ObjCMessage;
1346 }
1347};
1348
1349/// Manages the lifetime of CallEvent objects.
1350///
1351/// CallEventManager provides a way to create arbitrary CallEvents "on the
1352/// stack" as if they were value objects by keeping a cache of CallEvent-sized
1353/// memory blocks. The CallEvents created by CallEventManager are only valid
1354/// for the lifetime of the OwnedCallEvent that holds them; right now these
1355/// objects cannot be copied and ownership cannot be transferred.
1356class CallEventManager {
1357 friend class CallEvent;
1358
1359 llvm::BumpPtrAllocator &Alloc;
1360 SmallVector<void *, 8> Cache;
1361
1362 using CallEventTemplateTy = SimpleFunctionCall;
1363
1364 void reclaim(const void *Memory) {
1365 Cache.push_back(Elt: const_cast<void *>(Memory));
1366 }
1367
1368 /// Returns memory that can be initialized as a CallEvent.
1369 void *allocate() {
1370 if (Cache.empty())
1371 return Alloc.Allocate<CallEventTemplateTy>();
1372 else
1373 return Cache.pop_back_val();
1374 }
1375
1376 template <typename T, typename Arg>
1377 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx,
1378 CFGBlock::ConstCFGElementRef ElemRef) {
1379 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1380 "CallEvent subclasses are not all the same size");
1381 return new (allocate()) T(A, St, LCtx, ElemRef);
1382 }
1383
1384 template <typename T, typename Arg1, typename Arg2>
1385 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx,
1386 CFGBlock::ConstCFGElementRef ElemRef) {
1387 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1388 "CallEvent subclasses are not all the same size");
1389 return new (allocate()) T(A1, A2, St, LCtx, ElemRef);
1390 }
1391
1392 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1393 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1394 const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef) {
1395 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1396 "CallEvent subclasses are not all the same size");
1397 return new (allocate()) T(A1, A2, A3, St, LCtx, ElemRef);
1398 }
1399
1400 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1401 typename Arg4>
1402 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1403 const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef) {
1404 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1405 "CallEvent subclasses are not all the same size");
1406 return new (allocate()) T(A1, A2, A3, A4, St, LCtx, ElemRef);
1407 }
1408
1409public:
1410 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1411
1412 /// Gets an outside caller given a callee context.
1413 CallEventRef<> getCaller(const StackFrameContext *CalleeCtx,
1414 ProgramStateRef State);
1415
1416 /// Gets a call event for a function call, Objective-C method call,
1417 /// a 'new', or a 'delete' call.
1418 CallEventRef<> getCall(const Stmt *S, ProgramStateRef State,
1419 const LocationContext *LC,
1420 CFGBlock::ConstCFGElementRef ElemRef);
1421
1422 CallEventRef<> getSimpleCall(const CallExpr *E, ProgramStateRef State,
1423 const LocationContext *LCtx,
1424 CFGBlock::ConstCFGElementRef ElemRef);
1425
1426 CallEventRef<ObjCMethodCall>
1427 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1428 const LocationContext *LCtx,
1429 CFGBlock::ConstCFGElementRef ElemRef) {
1430 return create<ObjCMethodCall>(A: E, St: State, LCtx, ElemRef);
1431 }
1432
1433 CallEventRef<CXXConstructorCall>
1434 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1435 ProgramStateRef State, const LocationContext *LCtx,
1436 CFGBlock::ConstCFGElementRef ElemRef) {
1437 return create<CXXConstructorCall>(A1: E, A2: Target, St: State, LCtx, ElemRef);
1438 }
1439
1440 CallEventRef<CXXInheritedConstructorCall>
1441 getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E,
1442 const MemRegion *Target, ProgramStateRef State,
1443 const LocationContext *LCtx,
1444 CFGBlock::ConstCFGElementRef ElemRef) {
1445 return create<CXXInheritedConstructorCall>(A1: E, A2: Target, St: State, LCtx, ElemRef);
1446 }
1447
1448 CallEventRef<CXXDestructorCall>
1449 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1450 const MemRegion *Target, bool IsBase,
1451 ProgramStateRef State, const LocationContext *LCtx,
1452 CFGBlock::ConstCFGElementRef ElemRef) {
1453 return create<CXXDestructorCall>(A1: DD, A2: Trigger, A3: Target, A4: IsBase, St: State, LCtx,
1454 ElemRef);
1455 }
1456
1457 CallEventRef<CXXAllocatorCall>
1458 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1459 const LocationContext *LCtx,
1460 CFGBlock::ConstCFGElementRef ElemRef) {
1461 return create<CXXAllocatorCall>(A: E, St: State, LCtx, ElemRef);
1462 }
1463
1464 CallEventRef<CXXDeallocatorCall>
1465 getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State,
1466 const LocationContext *LCtx,
1467 CFGBlock::ConstCFGElementRef ElemRef) {
1468 return create<CXXDeallocatorCall>(A: E, St: State, LCtx, ElemRef);
1469 }
1470};
1471
1472template <typename T>
1473CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1474 assert(isa<T>(*this) && "Cloning to unrelated type");
1475 static_assert(sizeof(T) == sizeof(CallEvent),
1476 "Subclasses may not add fields");
1477
1478 if (NewState == State)
1479 return cast<T>(this);
1480
1481 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1482 T *Copy = static_cast<T *>(Mgr.allocate());
1483 cloneTo(Dest: Copy);
1484 assert(Copy->getKind() == this->getKind() && "Bad copy");
1485
1486 Copy->State = NewState;
1487 return Copy;
1488}
1489
1490inline void CallEvent::Release() const {
1491 assert(RefCount > 0 && "Reference count is already zero.");
1492 --RefCount;
1493
1494 if (RefCount > 0)
1495 return;
1496
1497 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1498 Mgr.reclaim(Memory: this);
1499
1500 this->~CallEvent();
1501}
1502
1503} // namespace ento
1504
1505} // namespace clang
1506
1507namespace llvm {
1508
1509// Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1510template <class T> struct simplify_type<clang::ento::CallEventRef<T>> {
1511 using SimpleType = const T *;
1512
1513 static SimpleType getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1514 return Val.get();
1515 }
1516};
1517
1518} // namespace llvm
1519
1520#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
1521

source code of clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h