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