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