Coverage Report

Created: 2022-05-17 06:19

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