CallEvent.h revision 3f558af01643787d209a133215b0abec81b5fe30
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_CXXMember,
36  CE_CXXMemberOperator,
37  CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
38  CE_END_CXX_INSTANCE_CALLS = CE_CXXMemberOperator,
39  CE_Block,
40  CE_BEG_SIMPLE_CALLS = CE_Function,
41  CE_END_SIMPLE_CALLS = CE_Block,
42  CE_CXXConstructor,
43  CE_CXXDestructor,
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 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 non-static C++ member function call, no matter how
430/// it is written.
431class CXXInstanceCall : public SimpleCall {
432protected:
433  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
434
435  CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
436                  const LocationContext *LCtx)
437    : SimpleCall(CE, St, LCtx) {}
438
439  CXXInstanceCall(const CXXInstanceCall &Other) : SimpleCall(Other) {}
440
441public:
442  /// \brief Returns the expression representing the implicit 'this' object.
443  virtual const Expr *getCXXThisExpr() const = 0;
444
445  /// \brief Returns the value of the implicit 'this' object.
446  SVal getCXXThisVal() const {
447    const Expr *Base = getCXXThisExpr();
448    // FIXME: This doesn't handle an overloaded ->* operator.
449    if (!Base)
450      return UnknownVal();
451    return getSVal(Base);
452  }
453
454  virtual RuntimeDefinition getRuntimeDefinition() const;
455
456  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
457                                            BindingsTy &Bindings) const;
458
459  static bool classof(const CallEvent *CA) {
460    return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
461           CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
462  }
463};
464
465/// \brief Represents a non-static C++ member function call.
466///
467/// Example: \c obj.fun()
468class CXXMemberCall : public CXXInstanceCall {
469  friend class CallEventManager;
470
471protected:
472  CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
473                const LocationContext *LCtx)
474    : CXXInstanceCall(CE, St, LCtx) {}
475
476  CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {}
477  virtual void cloneTo(void *Dest) const { new (Dest) CXXMemberCall(*this); }
478
479public:
480  virtual const CXXMemberCallExpr *getOriginExpr() const {
481    return cast<CXXMemberCallExpr>(SimpleCall::getOriginExpr());
482  }
483
484  virtual const Expr *getCXXThisExpr() const;
485
486  virtual Kind getKind() const { return CE_CXXMember; }
487
488  static bool classof(const CallEvent *CA) {
489    return CA->getKind() == CE_CXXMember;
490  }
491};
492
493/// \brief Represents a C++ overloaded operator call where the operator is
494/// implemented as a non-static member function.
495///
496/// Example: <tt>iter + 1</tt>
497class CXXMemberOperatorCall : public CXXInstanceCall {
498  friend class CallEventManager;
499
500protected:
501  CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
502                        const LocationContext *LCtx)
503    : CXXInstanceCall(CE, St, LCtx) {}
504
505  CXXMemberOperatorCall(const CXXMemberOperatorCall &Other)
506    : CXXInstanceCall(Other) {}
507  virtual void cloneTo(void *Dest) const {
508    new (Dest) CXXMemberOperatorCall(*this);
509  }
510
511public:
512  virtual const CXXOperatorCallExpr *getOriginExpr() const {
513    return cast<CXXOperatorCallExpr>(SimpleCall::getOriginExpr());
514  }
515
516  virtual unsigned getNumArgs() const {
517    return getOriginExpr()->getNumArgs() - 1;
518  }
519  virtual const Expr *getArgExpr(unsigned Index) const {
520    return getOriginExpr()->getArg(Index + 1);
521  }
522
523  virtual const Expr *getCXXThisExpr() const;
524
525  virtual Kind getKind() const { return CE_CXXMemberOperator; }
526
527  static bool classof(const CallEvent *CA) {
528    return CA->getKind() == CE_CXXMemberOperator;
529  }
530};
531
532/// \brief Represents a call to a block.
533///
534/// Example: <tt>^{ /* ... */ }()</tt>
535class BlockCall : public SimpleCall {
536  friend class CallEventManager;
537
538protected:
539  BlockCall(const CallExpr *CE, ProgramStateRef St,
540            const LocationContext *LCtx)
541    : SimpleCall(CE, St, LCtx) {}
542
543  BlockCall(const BlockCall &Other) : SimpleCall(Other) {}
544  virtual void cloneTo(void *Dest) const { new (Dest) BlockCall(*this); }
545
546  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
547
548  virtual QualType getDeclaredResultType() const;
549
550public:
551  /// \brief Returns the region associated with this instance of the block.
552  ///
553  /// This may be NULL if the block's origin is unknown.
554  const BlockDataRegion *getBlockRegion() const;
555
556  /// \brief Gets the declaration of the block.
557  ///
558  /// This is not an override of getDecl() because AnyFunctionCall has already
559  /// assumed that it's a FunctionDecl.
560  const BlockDecl *getBlockDecl() const {
561    const BlockDataRegion *BR = getBlockRegion();
562    if (!BR)
563      return 0;
564    return BR->getDecl();
565  }
566
567  virtual RuntimeDefinition getRuntimeDefinition() const {
568    return RuntimeDefinition(getBlockDecl());
569  }
570
571  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
572                                            BindingsTy &Bindings) const;
573
574  virtual param_iterator param_begin() const;
575  virtual param_iterator param_end() const;
576
577  virtual Kind getKind() const { return CE_Block; }
578
579  static bool classof(const CallEvent *CA) {
580    return CA->getKind() == CE_Block;
581  }
582};
583
584/// \brief Represents a call to a C++ constructor.
585///
586/// Example: \c T(1)
587class CXXConstructorCall : public AnyFunctionCall {
588  friend class CallEventManager;
589
590protected:
591  /// Creates a constructor call.
592  ///
593  /// \param CE The constructor expression as written in the source.
594  /// \param Target The region where the object should be constructed. If NULL,
595  ///               a new symbolic region will be used.
596  /// \param St The path-sensitive state at this point in the program.
597  /// \param LCtx The location context at this point in the program.
598  CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *target,
599                     ProgramStateRef St, const LocationContext *LCtx)
600    : AnyFunctionCall(CE, St, LCtx) {
601    Data = target;
602  }
603
604  CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){}
605  virtual void cloneTo(void *Dest) const { new (Dest) CXXConstructorCall(*this); }
606
607  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
608
609public:
610  virtual const CXXConstructExpr *getOriginExpr() const {
611    return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
612  }
613
614  virtual const CXXConstructorDecl *getDecl() const {
615    return getOriginExpr()->getConstructor();
616  }
617
618  virtual unsigned getNumArgs() const { return getOriginExpr()->getNumArgs(); }
619
620  virtual const Expr *getArgExpr(unsigned Index) const {
621    return getOriginExpr()->getArg(Index);
622  }
623
624  /// \brief Returns the value of the implicit 'this' object.
625  virtual SVal getCXXThisVal() const;
626
627  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
628                                            BindingsTy &Bindings) const;
629
630  virtual Kind getKind() const { return CE_CXXConstructor; }
631
632  static bool classof(const CallEvent *CA) {
633    return CA->getKind() == CE_CXXConstructor;
634  }
635};
636
637/// \brief Represents an implicit call to a C++ destructor.
638///
639/// This can occur at the end of a scope (for automatic objects), at the end
640/// of a full-expression (for temporaries), or as part of a delete.
641class CXXDestructorCall : public AnyFunctionCall {
642  friend class CallEventManager;
643
644protected:
645  /// Creates an implicit destructor.
646  ///
647  /// \param DD The destructor that will be called.
648  /// \param Trigger The statement whose completion causes this destructor call.
649  /// \param Target The object region to be destructed.
650  /// \param St The path-sensitive state at this point in the program.
651  /// \param LCtx The location context at this point in the program.
652  CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
653                    const MemRegion *Target, ProgramStateRef St,
654                    const LocationContext *LCtx)
655    : AnyFunctionCall(DD, St, LCtx) {
656    Data = Target;
657    Location = Trigger->getLocEnd();
658  }
659
660  CXXDestructorCall(const CXXDestructorCall &Other) : AnyFunctionCall(Other) {}
661  virtual void cloneTo(void *Dest) const { new (Dest) CXXDestructorCall(*this); }
662
663  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
664
665public:
666  virtual SourceRange getSourceRange() const { return Location; }
667  virtual unsigned getNumArgs() const { return 0; }
668
669  /// \brief Returns the value of the implicit 'this' object.
670  virtual SVal getCXXThisVal() const;
671
672  virtual RuntimeDefinition getRuntimeDefinition() const;
673
674  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
675                                            BindingsTy &Bindings) const;
676
677  virtual Kind getKind() const { return CE_CXXDestructor; }
678
679  static bool classof(const CallEvent *CA) {
680    return CA->getKind() == CE_CXXDestructor;
681  }
682};
683
684/// \brief Represents the memory allocation call in a C++ new-expression.
685///
686/// This is a call to "operator new".
687class CXXAllocatorCall : public AnyFunctionCall {
688  friend class CallEventManager;
689
690protected:
691  CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
692                   const LocationContext *LCtx)
693    : AnyFunctionCall(E, St, LCtx) {}
694
695  CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {}
696  virtual void cloneTo(void *Dest) const { new (Dest) CXXAllocatorCall(*this); }
697
698public:
699  virtual const CXXNewExpr *getOriginExpr() const {
700    return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
701  }
702
703  virtual const FunctionDecl *getDecl() const {
704    return getOriginExpr()->getOperatorNew();
705  }
706
707  virtual unsigned getNumArgs() const {
708    return getOriginExpr()->getNumPlacementArgs() + 1;
709  }
710
711  virtual const Expr *getArgExpr(unsigned Index) const {
712    // The first argument of an allocator call is the size of the allocation.
713    if (Index == 0)
714      return 0;
715    return getOriginExpr()->getPlacementArg(Index - 1);
716  }
717
718  virtual Kind getKind() const { return CE_CXXAllocator; }
719
720  static bool classof(const CallEvent *CE) {
721    return CE->getKind() == CE_CXXAllocator;
722  }
723};
724
725/// \brief Represents the ways an Objective-C message send can occur.
726//
727// Note to maintainers: OCM_Message should always be last, since it does not
728// need to fit in the Data field's low bits.
729enum ObjCMessageKind {
730  OCM_PropertyAccess,
731  OCM_Subscript,
732  OCM_Message
733};
734
735/// \brief Represents any expression that calls an Objective-C method.
736///
737/// This includes all of the kinds listed in ObjCMessageKind.
738class ObjCMethodCall : public CallEvent {
739  friend class CallEventManager;
740
741  const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
742
743protected:
744  ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
745                 const LocationContext *LCtx)
746    : CallEvent(Msg, St, LCtx) {
747    Data = 0;
748  }
749
750  ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {}
751  virtual void cloneTo(void *Dest) const { new (Dest) ObjCMethodCall(*this); }
752
753  virtual void getExtraInvalidatedRegions(RegionList &Regions) const;
754
755  virtual QualType getDeclaredResultType() const;
756
757  /// Check if the selector may have multiple definitions (may have overrides).
758  virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
759                                        Selector Sel) const;
760
761public:
762  virtual const ObjCMessageExpr *getOriginExpr() const {
763    return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
764  }
765  virtual const ObjCMethodDecl *getDecl() const {
766    return getOriginExpr()->getMethodDecl();
767  }
768  virtual unsigned getNumArgs() const {
769    return getOriginExpr()->getNumArgs();
770  }
771  virtual const Expr *getArgExpr(unsigned Index) const {
772    return getOriginExpr()->getArg(Index);
773  }
774
775  bool isInstanceMessage() const {
776    return getOriginExpr()->isInstanceMessage();
777  }
778  ObjCMethodFamily getMethodFamily() const {
779    return getOriginExpr()->getMethodFamily();
780  }
781  Selector getSelector() const {
782    return getOriginExpr()->getSelector();
783  }
784
785  virtual SourceRange getSourceRange() const;
786
787  /// \brief Returns the value of the receiver at the time of this call.
788  SVal getReceiverSVal() const;
789
790  /// \brief Get the interface for the receiver.
791  ///
792  /// This works whether this is an instance message or a class message.
793  /// However, it currently just uses the static type of the receiver.
794  const ObjCInterfaceDecl *getReceiverInterface() const {
795    return getOriginExpr()->getReceiverInterface();
796  }
797
798  ObjCMessageKind getMessageKind() const;
799
800  bool isSetter() const {
801    switch (getMessageKind()) {
802    case OCM_Message:
803      llvm_unreachable("This is not a pseudo-object access!");
804    case OCM_PropertyAccess:
805      return getNumArgs() > 0;
806    case OCM_Subscript:
807      return getNumArgs() > 1;
808    }
809    llvm_unreachable("Unknown message kind");
810  }
811
812  virtual RuntimeDefinition getRuntimeDefinition() const;
813
814  virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
815                                            BindingsTy &Bindings) const;
816
817  virtual param_iterator param_begin() const;
818  virtual param_iterator param_end() const;
819
820  virtual Kind getKind() const { return CE_ObjCMessage; }
821
822  static bool classof(const CallEvent *CA) {
823    return CA->getKind() == CE_ObjCMessage;
824  }
825};
826
827
828/// \brief Manages the lifetime of CallEvent objects.
829///
830/// CallEventManager provides a way to create arbitrary CallEvents "on the
831/// stack" as if they were value objects by keeping a cache of CallEvent-sized
832/// memory blocks. The CallEvents created by CallEventManager are only valid
833/// for the lifetime of the OwnedCallEvent that holds them; right now these
834/// objects cannot be copied and ownership cannot be transferred.
835class CallEventManager {
836  friend class CallEvent;
837
838  llvm::BumpPtrAllocator &Alloc;
839  SmallVector<void *, 8> Cache;
840
841  void reclaim(const void *Memory) {
842    Cache.push_back(const_cast<void *>(Memory));
843  }
844
845  /// Returns memory that can be initialized as a CallEvent.
846  void *allocate() {
847    if (Cache.empty())
848      return Alloc.Allocate<FunctionCall>();
849    else
850      return Cache.pop_back_val();
851  }
852
853  template <typename T, typename Arg>
854  T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
855    return new (allocate()) T(A, St, LCtx);
856  }
857
858  template <typename T, typename Arg1, typename Arg2>
859  T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
860    return new (allocate()) T(A1, A2, St, LCtx);
861  }
862
863  template <typename T, typename Arg1, typename Arg2, typename Arg3>
864  T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
865            const LocationContext *LCtx) {
866    return new (allocate()) T(A1, A2, A3, St, LCtx);
867  }
868
869public:
870  CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
871
872
873  CallEventRef<>
874  getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
875
876
877  CallEventRef<SimpleCall>
878  getSimpleCall(const CallExpr *E, ProgramStateRef State,
879                const LocationContext *LCtx);
880
881  CallEventRef<ObjCMethodCall>
882  getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
883                    const LocationContext *LCtx) {
884    return create<ObjCMethodCall>(E, State, LCtx);
885  }
886
887  CallEventRef<CXXConstructorCall>
888  getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
889                        ProgramStateRef State, const LocationContext *LCtx) {
890    return create<CXXConstructorCall>(E, Target, State, LCtx);
891  }
892
893  CallEventRef<CXXDestructorCall>
894  getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
895                       const MemRegion *Target, ProgramStateRef State,
896                       const LocationContext *LCtx) {
897    return create<CXXDestructorCall>(DD, Trigger, Target, State, LCtx);
898  }
899
900  CallEventRef<CXXAllocatorCall>
901  getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
902                      const LocationContext *LCtx) {
903    return create<CXXAllocatorCall>(E, State, LCtx);
904  }
905};
906
907
908template <typename T>
909CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
910  assert(isa<T>(*this) && "Cloning to unrelated type");
911  assert(sizeof(T) == sizeof(CallEvent) && "Subclasses may not add fields");
912
913  if (NewState == State)
914    return cast<T>(this);
915
916  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
917  T *Copy = static_cast<T *>(Mgr.allocate());
918  cloneTo(Copy);
919  assert(Copy->getKind() == this->getKind() && "Bad copy");
920
921  Copy->State = NewState;
922  return Copy;
923}
924
925inline void CallEvent::Release() const {
926  assert(RefCount > 0 && "Reference count is already zero.");
927  --RefCount;
928
929  if (RefCount > 0)
930    return;
931
932  CallEventManager &Mgr = State->getStateManager().getCallEventManager();
933  Mgr.reclaim(this);
934
935  this->~CallEvent();
936}
937
938} // end namespace ento
939} // end namespace clang
940
941namespace llvm {
942  // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
943  template<class T> struct simplify_type< clang::ento::CallEventRef<T> > {
944    typedef const T *SimpleType;
945
946    static SimpleType
947    getSimplifiedValue(const clang::ento::CallEventRef<T>& Val) {
948      return Val.getPtr();
949    }
950  };
951}
952
953#endif
954