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