Coverage Report

Created: 2022-07-16 07:03

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