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