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