RetainCountChecker.cpp revision 81f01c62d74601303069682ce12210eb0368c8e7
1f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
2f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
3f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//                     The LLVM Compiler Infrastructure
4f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
5f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// This file is distributed under the University of Illinois Open Source
6f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// License. See LICENSE.TXT for details.
7f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
8f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
9f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
10f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//  This file defines the methods for RetainCountChecker, which implements
11f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
13f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
14f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
15f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "ClangSACheckers.h"
16f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/AST/DeclObjC.h"
17f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/AST/DeclCXX.h"
18f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/Basic/LangOptions.h"
19f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/Basic/SourceManager.h"
20f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/AST/ParentMap.h"
22f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/Checker.h"
23f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/CheckerManager.h"
24f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
26f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
27f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
28f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
30f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/DenseMap.h"
31f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/FoldingSet.h"
32f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/ImmutableList.h"
33f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/ImmutableMap.h"
34f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/SmallString.h"
35f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/STLExtras.h"
36f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "llvm/ADT/StringExtras.h"
37f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <cstdarg>
38f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
39f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgusing namespace clang;
40f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgusing namespace ento;
41f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgusing llvm::StrInStrNoCase;
42f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
43f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgnamespace {
44f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// Wrapper around different kinds of node builder, so that helper functions
45f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// can have a common interface.
46f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgclass GenericNodeBuilderRefCount {
47f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  CheckerContext *C;
48f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  const ProgramPointTag *tag;
49f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgpublic:
50f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  GenericNodeBuilderRefCount(CheckerContext &c,
51f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                             const ProgramPointTag *t = 0)
52f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  : C(&c), tag(t){}
53f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
54f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
55f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                         bool MarkAsSink = false) {
56f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org    return C->addTransition(state, Pred, tag, MarkAsSink);
57f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  }
58f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org};
59f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org} // end anonymous namespace
60f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
61f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
62f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// Primitives used for constructing summaries for function/method calls.
63f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
64f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
65f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// ArgEffect is used to summarize a function/method call's effect on a
66f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// particular argument.
67f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgenum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
68f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                 DecRefBridgedTransfered,
69f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                 DecRefAndStopTracking, DecRefMsgAndStopTracking,
70f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                 IncRefMsg, IncRef, MakeCollectable, MayEscape,
71f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org                 NewAutoreleasePool, StopTracking };
72f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
73f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgnamespace llvm {
74f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtemplate <> struct FoldingSetTrait<ArgEffect> {
75f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
76f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  ID.AddInteger((unsigned) X);
77f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
78f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org};
79f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org} // end llvm namespace
80f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
81f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// ArgEffects summarizes the effects of a function/method call on all of
82f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/// its arguments.
83f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtypedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
84f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
85f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgnamespace {
86f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
87f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org///  RetEffect is used to summarize a function/method call's behavior with
88f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org///  respect to its return value.
89f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgclass RetEffect {
90f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgpublic:
91f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
92f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org              NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
93f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org              OwnedWhenTrackedReceiver };
94f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
95f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  enum ObjKind { CF, ObjC, AnyObj };
96f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
97f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgprivate:
98f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  Kind K;
99f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  ObjKind O;
100f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
101f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
102f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
103f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgpublic:
104f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  Kind getKind() const { return K; }
105f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
106f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  ObjKind getObjKind() const { return O; }
107f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
108f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  bool isOwned() const {
109f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org    return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
110f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org           K == OwnedWhenTrackedReceiver;
111f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  }
112f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
113f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  bool operator==(const RetEffect &Other) const {
114f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org    return K == Other.K && O == Other.O;
115f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  }
116f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
117f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  static RetEffect MakeOwnedWhenTrackedReceiver() {
118    return RetEffect(OwnedWhenTrackedReceiver, ObjC);
119  }
120
121  static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
122    return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
123  }
124  static RetEffect MakeNotOwned(ObjKind o) {
125    return RetEffect(NotOwnedSymbol, o);
126  }
127  static RetEffect MakeGCNotOwned() {
128    return RetEffect(GCNotOwnedSymbol, ObjC);
129  }
130  static RetEffect MakeARCNotOwned() {
131    return RetEffect(ARCNotOwnedSymbol, ObjC);
132  }
133  static RetEffect MakeNoRet() {
134    return RetEffect(NoRet);
135  }
136
137  void Profile(llvm::FoldingSetNodeID& ID) const {
138    ID.AddInteger((unsigned) K);
139    ID.AddInteger((unsigned) O);
140  }
141};
142
143//===----------------------------------------------------------------------===//
144// Reference-counting logic (typestate + counts).
145//===----------------------------------------------------------------------===//
146
147class RefVal {
148public:
149  enum Kind {
150    Owned = 0, // Owning reference.
151    NotOwned,  // Reference is not owned by still valid (not freed).
152    Released,  // Object has been released.
153    ReturnedOwned, // Returned object passes ownership to caller.
154    ReturnedNotOwned, // Return object does not pass ownership to caller.
155    ERROR_START,
156    ErrorDeallocNotOwned, // -dealloc called on non-owned object.
157    ErrorDeallocGC, // Calling -dealloc with GC enabled.
158    ErrorUseAfterRelease, // Object used after released.
159    ErrorReleaseNotOwned, // Release of an object that was not owned.
160    ERROR_LEAK_START,
161    ErrorLeak,  // A memory leak due to excessive reference counts.
162    ErrorLeakReturned, // A memory leak due to the returning method not having
163                       // the correct naming conventions.
164    ErrorGCLeakReturned,
165    ErrorOverAutorelease,
166    ErrorReturnedNotOwned
167  };
168
169private:
170  Kind kind;
171  RetEffect::ObjKind okind;
172  unsigned Cnt;
173  unsigned ACnt;
174  QualType T;
175
176  RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
177  : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
178
179public:
180  Kind getKind() const { return kind; }
181
182  RetEffect::ObjKind getObjKind() const { return okind; }
183
184  unsigned getCount() const { return Cnt; }
185  unsigned getAutoreleaseCount() const { return ACnt; }
186  unsigned getCombinedCounts() const { return Cnt + ACnt; }
187  void clearCounts() { Cnt = 0; ACnt = 0; }
188  void setCount(unsigned i) { Cnt = i; }
189  void setAutoreleaseCount(unsigned i) { ACnt = i; }
190
191  QualType getType() const { return T; }
192
193  bool isOwned() const {
194    return getKind() == Owned;
195  }
196
197  bool isNotOwned() const {
198    return getKind() == NotOwned;
199  }
200
201  bool isReturnedOwned() const {
202    return getKind() == ReturnedOwned;
203  }
204
205  bool isReturnedNotOwned() const {
206    return getKind() == ReturnedNotOwned;
207  }
208
209  static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
210                          unsigned Count = 1) {
211    return RefVal(Owned, o, Count, 0, t);
212  }
213
214  static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
215                             unsigned Count = 0) {
216    return RefVal(NotOwned, o, Count, 0, t);
217  }
218
219  // Comparison, profiling, and pretty-printing.
220
221  bool operator==(const RefVal& X) const {
222    return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
223  }
224
225  RefVal operator-(size_t i) const {
226    return RefVal(getKind(), getObjKind(), getCount() - i,
227                  getAutoreleaseCount(), getType());
228  }
229
230  RefVal operator+(size_t i) const {
231    return RefVal(getKind(), getObjKind(), getCount() + i,
232                  getAutoreleaseCount(), getType());
233  }
234
235  RefVal operator^(Kind k) const {
236    return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
237                  getType());
238  }
239
240  RefVal autorelease() const {
241    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
242                  getType());
243  }
244
245  void Profile(llvm::FoldingSetNodeID& ID) const {
246    ID.AddInteger((unsigned) kind);
247    ID.AddInteger(Cnt);
248    ID.AddInteger(ACnt);
249    ID.Add(T);
250  }
251
252  void print(raw_ostream &Out) const;
253};
254
255void RefVal::print(raw_ostream &Out) const {
256  if (!T.isNull())
257    Out << "Tracked " << T.getAsString() << '/';
258
259  switch (getKind()) {
260    default: llvm_unreachable("Invalid RefVal kind");
261    case Owned: {
262      Out << "Owned";
263      unsigned cnt = getCount();
264      if (cnt) Out << " (+ " << cnt << ")";
265      break;
266    }
267
268    case NotOwned: {
269      Out << "NotOwned";
270      unsigned cnt = getCount();
271      if (cnt) Out << " (+ " << cnt << ")";
272      break;
273    }
274
275    case ReturnedOwned: {
276      Out << "ReturnedOwned";
277      unsigned cnt = getCount();
278      if (cnt) Out << " (+ " << cnt << ")";
279      break;
280    }
281
282    case ReturnedNotOwned: {
283      Out << "ReturnedNotOwned";
284      unsigned cnt = getCount();
285      if (cnt) Out << " (+ " << cnt << ")";
286      break;
287    }
288
289    case Released:
290      Out << "Released";
291      break;
292
293    case ErrorDeallocGC:
294      Out << "-dealloc (GC)";
295      break;
296
297    case ErrorDeallocNotOwned:
298      Out << "-dealloc (not-owned)";
299      break;
300
301    case ErrorLeak:
302      Out << "Leaked";
303      break;
304
305    case ErrorLeakReturned:
306      Out << "Leaked (Bad naming)";
307      break;
308
309    case ErrorGCLeakReturned:
310      Out << "Leaked (GC-ed at return)";
311      break;
312
313    case ErrorUseAfterRelease:
314      Out << "Use-After-Release [ERROR]";
315      break;
316
317    case ErrorReleaseNotOwned:
318      Out << "Release of Not-Owned [ERROR]";
319      break;
320
321    case RefVal::ErrorOverAutorelease:
322      Out << "Over autoreleased";
323      break;
324
325    case RefVal::ErrorReturnedNotOwned:
326      Out << "Non-owned object returned instead of owned";
327      break;
328  }
329
330  if (ACnt) {
331    Out << " [ARC +" << ACnt << ']';
332  }
333}
334} //end anonymous namespace
335
336//===----------------------------------------------------------------------===//
337// RefBindings - State used to track object reference counts.
338//===----------------------------------------------------------------------===//
339
340typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
341
342namespace clang {
343namespace ento {
344template<>
345struct ProgramStateTrait<RefBindings>
346  : public ProgramStatePartialTrait<RefBindings> {
347  static void *GDMIndex() {
348    static int RefBIndex = 0;
349    return &RefBIndex;
350  }
351};
352}
353}
354
355static inline const RefVal *getRefBinding(ProgramStateRef State,
356                                          SymbolRef Sym) {
357  return State->get<RefBindings>(Sym);
358}
359
360static inline ProgramStateRef setRefBinding(ProgramStateRef State,
361                                            SymbolRef Sym, RefVal Val) {
362  return State->set<RefBindings>(Sym, Val);
363}
364
365static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
366  return State->remove<RefBindings>(Sym);
367}
368
369//===----------------------------------------------------------------------===//
370// Function/Method behavior summaries.
371//===----------------------------------------------------------------------===//
372
373namespace {
374class RetainSummary {
375  /// Args - a map of (index, ArgEffect) pairs, where index
376  ///  specifies the argument (starting from 0).  This can be sparsely
377  ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
378  ArgEffects Args;
379
380  /// DefaultArgEffect - The default ArgEffect to apply to arguments that
381  ///  do not have an entry in Args.
382  ArgEffect DefaultArgEffect;
383
384  /// Receiver - If this summary applies to an Objective-C message expression,
385  ///  this is the effect applied to the state of the receiver.
386  ArgEffect Receiver;
387
388  /// Ret - The effect on the return value.  Used to indicate if the
389  ///  function/method call returns a new tracked symbol.
390  RetEffect Ret;
391
392public:
393  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
394                ArgEffect ReceiverEff)
395    : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
396
397  /// getArg - Return the argument effect on the argument specified by
398  ///  idx (starting from 0).
399  ArgEffect getArg(unsigned idx) const {
400    if (const ArgEffect *AE = Args.lookup(idx))
401      return *AE;
402
403    return DefaultArgEffect;
404  }
405
406  void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
407    Args = af.add(Args, idx, e);
408  }
409
410  /// setDefaultArgEffect - Set the default argument effect.
411  void setDefaultArgEffect(ArgEffect E) {
412    DefaultArgEffect = E;
413  }
414
415  /// getRetEffect - Returns the effect on the return value of the call.
416  RetEffect getRetEffect() const { return Ret; }
417
418  /// setRetEffect - Set the effect of the return value of the call.
419  void setRetEffect(RetEffect E) { Ret = E; }
420
421
422  /// Sets the effect on the receiver of the message.
423  void setReceiverEffect(ArgEffect e) { Receiver = e; }
424
425  /// getReceiverEffect - Returns the effect on the receiver of the call.
426  ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
427  ArgEffect getReceiverEffect() const { return Receiver; }
428
429  /// Test if two retain summaries are identical. Note that merely equivalent
430  /// summaries are not necessarily identical (for example, if an explicit
431  /// argument effect matches the default effect).
432  bool operator==(const RetainSummary &Other) const {
433    return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
434           Receiver == Other.Receiver && Ret == Other.Ret;
435  }
436
437  /// Profile this summary for inclusion in a FoldingSet.
438  void Profile(llvm::FoldingSetNodeID& ID) const {
439    ID.Add(Args);
440    ID.Add(DefaultArgEffect);
441    ID.Add(Receiver);
442    ID.Add(Ret);
443  }
444
445  /// A retain summary is simple if it has no ArgEffects other than the default.
446  bool isSimple() const {
447    return Args.isEmpty();
448  }
449
450private:
451  ArgEffects getArgEffects() const { return Args; }
452  ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
453
454  friend class RetainSummaryManager;
455};
456} // end anonymous namespace
457
458//===----------------------------------------------------------------------===//
459// Data structures for constructing summaries.
460//===----------------------------------------------------------------------===//
461
462namespace {
463class ObjCSummaryKey {
464  IdentifierInfo* II;
465  Selector S;
466public:
467  ObjCSummaryKey(IdentifierInfo* ii, Selector s)
468    : II(ii), S(s) {}
469
470  ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
471    : II(d ? d->getIdentifier() : 0), S(s) {}
472
473  ObjCSummaryKey(Selector s)
474    : II(0), S(s) {}
475
476  IdentifierInfo *getIdentifier() const { return II; }
477  Selector getSelector() const { return S; }
478};
479}
480
481namespace llvm {
482template <> struct DenseMapInfo<ObjCSummaryKey> {
483  static inline ObjCSummaryKey getEmptyKey() {
484    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
485                          DenseMapInfo<Selector>::getEmptyKey());
486  }
487
488  static inline ObjCSummaryKey getTombstoneKey() {
489    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
490                          DenseMapInfo<Selector>::getTombstoneKey());
491  }
492
493  static unsigned getHashValue(const ObjCSummaryKey &V) {
494    typedef std::pair<IdentifierInfo*, Selector> PairTy;
495    return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
496                                                     V.getSelector()));
497  }
498
499  static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
500    return LHS.getIdentifier() == RHS.getIdentifier() &&
501           LHS.getSelector() == RHS.getSelector();
502  }
503
504};
505template <>
506struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
507} // end llvm namespace
508
509namespace {
510class ObjCSummaryCache {
511  typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
512  MapTy M;
513public:
514  ObjCSummaryCache() {}
515
516  const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
517    // Do a lookup with the (D,S) pair.  If we find a match return
518    // the iterator.
519    ObjCSummaryKey K(D, S);
520    MapTy::iterator I = M.find(K);
521
522    if (I != M.end())
523      return I->second;
524    if (!D)
525      return NULL;
526
527    // Walk the super chain.  If we find a hit with a parent, we'll end
528    // up returning that summary.  We actually allow that key (null,S), as
529    // we cache summaries for the null ObjCInterfaceDecl* to allow us to
530    // generate initial summaries without having to worry about NSObject
531    // being declared.
532    // FIXME: We may change this at some point.
533    for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
534      if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
535        break;
536
537      if (!C)
538        return NULL;
539    }
540
541    // Cache the summary with original key to make the next lookup faster
542    // and return the iterator.
543    const RetainSummary *Summ = I->second;
544    M[K] = Summ;
545    return Summ;
546  }
547
548  const RetainSummary *find(IdentifierInfo* II, Selector S) {
549    // FIXME: Class method lookup.  Right now we dont' have a good way
550    // of going between IdentifierInfo* and the class hierarchy.
551    MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
552
553    if (I == M.end())
554      I = M.find(ObjCSummaryKey(S));
555
556    return I == M.end() ? NULL : I->second;
557  }
558
559  const RetainSummary *& operator[](ObjCSummaryKey K) {
560    return M[K];
561  }
562
563  const RetainSummary *& operator[](Selector S) {
564    return M[ ObjCSummaryKey(S) ];
565  }
566};
567} // end anonymous namespace
568
569//===----------------------------------------------------------------------===//
570// Data structures for managing collections of summaries.
571//===----------------------------------------------------------------------===//
572
573namespace {
574class RetainSummaryManager {
575
576  //==-----------------------------------------------------------------==//
577  //  Typedefs.
578  //==-----------------------------------------------------------------==//
579
580  typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
581          FuncSummariesTy;
582
583  typedef ObjCSummaryCache ObjCMethodSummariesTy;
584
585  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
586
587  //==-----------------------------------------------------------------==//
588  //  Data.
589  //==-----------------------------------------------------------------==//
590
591  /// Ctx - The ASTContext object for the analyzed ASTs.
592  ASTContext &Ctx;
593
594  /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
595  const bool GCEnabled;
596
597  /// Records whether or not the analyzed code runs in ARC mode.
598  const bool ARCEnabled;
599
600  /// FuncSummaries - A map from FunctionDecls to summaries.
601  FuncSummariesTy FuncSummaries;
602
603  /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
604  ///  to summaries.
605  ObjCMethodSummariesTy ObjCClassMethodSummaries;
606
607  /// ObjCMethodSummaries - A map from selectors to summaries.
608  ObjCMethodSummariesTy ObjCMethodSummaries;
609
610  /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
611  ///  and all other data used by the checker.
612  llvm::BumpPtrAllocator BPAlloc;
613
614  /// AF - A factory for ArgEffects objects.
615  ArgEffects::Factory AF;
616
617  /// ScratchArgs - A holding buffer for construct ArgEffects.
618  ArgEffects ScratchArgs;
619
620  /// ObjCAllocRetE - Default return effect for methods returning Objective-C
621  ///  objects.
622  RetEffect ObjCAllocRetE;
623
624  /// ObjCInitRetE - Default return effect for init methods returning
625  ///   Objective-C objects.
626  RetEffect ObjCInitRetE;
627
628  /// SimpleSummaries - Used for uniquing summaries that don't have special
629  /// effects.
630  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
631
632  //==-----------------------------------------------------------------==//
633  //  Methods.
634  //==-----------------------------------------------------------------==//
635
636  /// getArgEffects - Returns a persistent ArgEffects object based on the
637  ///  data in ScratchArgs.
638  ArgEffects getArgEffects();
639
640  enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
641
642  const RetainSummary *getUnarySummary(const FunctionType* FT,
643                                       UnaryFuncKind func);
644
645  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
646  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
647  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
648
649  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
650
651  const RetainSummary *getPersistentSummary(RetEffect RetEff,
652                                            ArgEffect ReceiverEff = DoNothing,
653                                            ArgEffect DefaultEff = MayEscape) {
654    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
655    return getPersistentSummary(Summ);
656  }
657
658  const RetainSummary *getDoNothingSummary() {
659    return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
660  }
661
662  const RetainSummary *getDefaultSummary() {
663    return getPersistentSummary(RetEffect::MakeNoRet(),
664                                DoNothing, MayEscape);
665  }
666
667  const RetainSummary *getPersistentStopSummary() {
668    return getPersistentSummary(RetEffect::MakeNoRet(),
669                                StopTracking, StopTracking);
670  }
671
672  void InitializeClassMethodSummaries();
673  void InitializeMethodSummaries();
674private:
675  void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
676    ObjCClassMethodSummaries[S] = Summ;
677  }
678
679  void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
680    ObjCMethodSummaries[S] = Summ;
681  }
682
683  void addClassMethSummary(const char* Cls, const char* name,
684                           const RetainSummary *Summ, bool isNullary = true) {
685    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
686    Selector S = isNullary ? GetNullarySelector(name, Ctx)
687                           : GetUnarySelector(name, Ctx);
688    ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
689  }
690
691  void addInstMethSummary(const char* Cls, const char* nullaryName,
692                          const RetainSummary *Summ) {
693    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
694    Selector S = GetNullarySelector(nullaryName, Ctx);
695    ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
696  }
697
698  Selector generateSelector(va_list argp) {
699    SmallVector<IdentifierInfo*, 10> II;
700
701    while (const char* s = va_arg(argp, const char*))
702      II.push_back(&Ctx.Idents.get(s));
703
704    return Ctx.Selectors.getSelector(II.size(), &II[0]);
705  }
706
707  void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
708                        const RetainSummary * Summ, va_list argp) {
709    Selector S = generateSelector(argp);
710    Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
711  }
712
713  void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
714    va_list argp;
715    va_start(argp, Summ);
716    addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
717    va_end(argp);
718  }
719
720  void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
721    va_list argp;
722    va_start(argp, Summ);
723    addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
724    va_end(argp);
725  }
726
727  void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
728    va_list argp;
729    va_start(argp, Summ);
730    addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
731    va_end(argp);
732  }
733
734public:
735
736  RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
737   : Ctx(ctx),
738     GCEnabled(gcenabled),
739     ARCEnabled(usesARC),
740     AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
741     ObjCAllocRetE(gcenabled
742                    ? RetEffect::MakeGCNotOwned()
743                    : (usesARC ? RetEffect::MakeARCNotOwned()
744                               : RetEffect::MakeOwned(RetEffect::ObjC, true))),
745     ObjCInitRetE(gcenabled
746                    ? RetEffect::MakeGCNotOwned()
747                    : (usesARC ? RetEffect::MakeARCNotOwned()
748                               : RetEffect::MakeOwnedWhenTrackedReceiver())) {
749    InitializeClassMethodSummaries();
750    InitializeMethodSummaries();
751  }
752
753  const RetainSummary *getSummary(const CallEvent &Call,
754                                  ProgramStateRef State = 0);
755
756  const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
757
758  const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
759                                        const ObjCMethodDecl *MD,
760                                        QualType RetTy,
761                                        ObjCMethodSummariesTy &CachedSummaries);
762
763  const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
764                                                ProgramStateRef State);
765
766  const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
767    assert(!M.isInstanceMessage());
768    const ObjCInterfaceDecl *Class = M.getReceiverInterface();
769
770    return getMethodSummary(M.getSelector(), Class, M.getDecl(),
771                            M.getResultType(), ObjCClassMethodSummaries);
772  }
773
774  /// getMethodSummary - This version of getMethodSummary is used to query
775  ///  the summary for the current method being analyzed.
776  const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
777    const ObjCInterfaceDecl *ID = MD->getClassInterface();
778    Selector S = MD->getSelector();
779    QualType ResultTy = MD->getResultType();
780
781    ObjCMethodSummariesTy *CachedSummaries;
782    if (MD->isInstanceMethod())
783      CachedSummaries = &ObjCMethodSummaries;
784    else
785      CachedSummaries = &ObjCClassMethodSummaries;
786
787    return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
788  }
789
790  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
791                                                Selector S, QualType RetTy);
792
793  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
794                                    const ObjCMethodDecl *MD);
795
796  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
797                                    const FunctionDecl *FD);
798
799  void updateSummaryForCall(const RetainSummary *&Summ,
800                            const CallEvent &Call);
801
802  bool isGCEnabled() const { return GCEnabled; }
803
804  bool isARCEnabled() const { return ARCEnabled; }
805
806  bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
807
808  RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
809
810  friend class RetainSummaryTemplate;
811};
812
813// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
814// summaries. If a function or method looks like it has a default summary, but
815// it has annotations, the annotations are added to the stack-based template
816// and then copied into managed memory.
817class RetainSummaryTemplate {
818  RetainSummaryManager &Manager;
819  const RetainSummary *&RealSummary;
820  RetainSummary ScratchSummary;
821  bool Accessed;
822public:
823  RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
824    : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
825
826  ~RetainSummaryTemplate() {
827    if (Accessed)
828      RealSummary = Manager.getPersistentSummary(ScratchSummary);
829  }
830
831  RetainSummary &operator*() {
832    Accessed = true;
833    return ScratchSummary;
834  }
835
836  RetainSummary *operator->() {
837    Accessed = true;
838    return &ScratchSummary;
839  }
840};
841
842} // end anonymous namespace
843
844//===----------------------------------------------------------------------===//
845// Implementation of checker data structures.
846//===----------------------------------------------------------------------===//
847
848ArgEffects RetainSummaryManager::getArgEffects() {
849  ArgEffects AE = ScratchArgs;
850  ScratchArgs = AF.getEmptyMap();
851  return AE;
852}
853
854const RetainSummary *
855RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
856  // Unique "simple" summaries -- those without ArgEffects.
857  if (OldSumm.isSimple()) {
858    llvm::FoldingSetNodeID ID;
859    OldSumm.Profile(ID);
860
861    void *Pos;
862    CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
863
864    if (!N) {
865      N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
866      new (N) CachedSummaryNode(OldSumm);
867      SimpleSummaries.InsertNode(N, Pos);
868    }
869
870    return &N->getValue();
871  }
872
873  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
874  new (Summ) RetainSummary(OldSumm);
875  return Summ;
876}
877
878//===----------------------------------------------------------------------===//
879// Summary creation for functions (largely uses of Core Foundation).
880//===----------------------------------------------------------------------===//
881
882static bool isRetain(const FunctionDecl *FD, StringRef FName) {
883  return FName.endswith("Retain");
884}
885
886static bool isRelease(const FunctionDecl *FD, StringRef FName) {
887  return FName.endswith("Release");
888}
889
890static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
891  // FIXME: Remove FunctionDecl parameter.
892  // FIXME: Is it really okay if MakeCollectable isn't a suffix?
893  return FName.find("MakeCollectable") != StringRef::npos;
894}
895
896static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
897  switch (E) {
898  case DoNothing:
899  case Autorelease:
900  case DecRefBridgedTransfered:
901  case IncRef:
902  case IncRefMsg:
903  case MakeCollectable:
904  case MayEscape:
905  case NewAutoreleasePool:
906  case StopTracking:
907    return StopTracking;
908  case DecRef:
909  case DecRefAndStopTracking:
910    return DecRefAndStopTracking;
911  case DecRefMsg:
912  case DecRefMsgAndStopTracking:
913    return DecRefMsgAndStopTracking;
914  case Dealloc:
915    return Dealloc;
916  }
917
918  llvm_unreachable("Unknown ArgEffect kind");
919}
920
921void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
922                                                const CallEvent &Call) {
923  if (Call.hasNonZeroCallbackArg()) {
924    ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
925    ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
926
927    ArgEffects CustomArgEffects = S->getArgEffects();
928    for (ArgEffects::iterator I = CustomArgEffects.begin(),
929                              E = CustomArgEffects.end();
930         I != E; ++I) {
931      ArgEffect Translated = getStopTrackingEquivalent(I->second);
932      if (Translated != DefEffect)
933        ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
934    }
935
936    RetEffect RE = RetEffect::MakeNoRet();
937
938    // Special cases where the callback argument CANNOT free the return value.
939    // This can generally only happen if we know that the callback will only be
940    // called when the return value is already being deallocated.
941    if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
942      IdentifierInfo *Name = FC->getDecl()->getIdentifier();
943
944      // This callback frees the associated buffer.
945      if (Name->isStr("CGBitmapContextCreateWithData"))
946        RE = S->getRetEffect();
947    }
948
949    S = getPersistentSummary(RE, RecEffect, DefEffect);
950  }
951}
952
953const RetainSummary *
954RetainSummaryManager::getSummary(const CallEvent &Call,
955                                 ProgramStateRef State) {
956  const RetainSummary *Summ;
957  switch (Call.getKind()) {
958  case CE_Function:
959    Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
960    break;
961  case CE_CXXMember:
962  case CE_CXXMemberOperator:
963  case CE_Block:
964  case CE_CXXConstructor:
965  case CE_CXXDestructor:
966  case CE_CXXAllocator:
967    // FIXME: These calls are currently unsupported.
968    return getPersistentStopSummary();
969  case CE_ObjCMessage: {
970    const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
971    if (Msg.isInstanceMessage())
972      Summ = getInstanceMethodSummary(Msg, State);
973    else
974      Summ = getClassMethodSummary(Msg);
975    break;
976  }
977  }
978
979  updateSummaryForCall(Summ, Call);
980
981  assert(Summ && "Unknown call type?");
982  return Summ;
983}
984
985const RetainSummary *
986RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
987  // If we don't know what function we're calling, use our default summary.
988  if (!FD)
989    return getDefaultSummary();
990
991  // Look up a summary in our cache of FunctionDecls -> Summaries.
992  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
993  if (I != FuncSummaries.end())
994    return I->second;
995
996  // No summary?  Generate one.
997  const RetainSummary *S = 0;
998  bool AllowAnnotations = true;
999
1000  do {
1001    // We generate "stop" summaries for implicitly defined functions.
1002    if (FD->isImplicit()) {
1003      S = getPersistentStopSummary();
1004      break;
1005    }
1006
1007    // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1008    // function's type.
1009    const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1010    const IdentifierInfo *II = FD->getIdentifier();
1011    if (!II)
1012      break;
1013
1014    StringRef FName = II->getName();
1015
1016    // Strip away preceding '_'.  Doing this here will effect all the checks
1017    // down below.
1018    FName = FName.substr(FName.find_first_not_of('_'));
1019
1020    // Inspect the result type.
1021    QualType RetTy = FT->getResultType();
1022
1023    // FIXME: This should all be refactored into a chain of "summary lookup"
1024    //  filters.
1025    assert(ScratchArgs.isEmpty());
1026
1027    if (FName == "pthread_create" || FName == "pthread_setspecific") {
1028      // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1029      // This will be addressed better with IPA.
1030      S = getPersistentStopSummary();
1031    } else if (FName == "NSMakeCollectable") {
1032      // Handle: id NSMakeCollectable(CFTypeRef)
1033      S = (RetTy->isObjCIdType())
1034          ? getUnarySummary(FT, cfmakecollectable)
1035          : getPersistentStopSummary();
1036      // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1037      // but we can fully model NSMakeCollectable ourselves.
1038      AllowAnnotations = false;
1039    } else if (FName == "IOBSDNameMatching" ||
1040               FName == "IOServiceMatching" ||
1041               FName == "IOServiceNameMatching" ||
1042               FName == "IORegistryEntrySearchCFProperty" ||
1043               FName == "IORegistryEntryIDMatching" ||
1044               FName == "IOOpenFirmwarePathMatching") {
1045      // Part of <rdar://problem/6961230>. (IOKit)
1046      // This should be addressed using a API table.
1047      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1048                               DoNothing, DoNothing);
1049    } else if (FName == "IOServiceGetMatchingService" ||
1050               FName == "IOServiceGetMatchingServices") {
1051      // FIXES: <rdar://problem/6326900>
1052      // This should be addressed using a API table.  This strcmp is also
1053      // a little gross, but there is no need to super optimize here.
1054      ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1055      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1056    } else if (FName == "IOServiceAddNotification" ||
1057               FName == "IOServiceAddMatchingNotification") {
1058      // Part of <rdar://problem/6961230>. (IOKit)
1059      // This should be addressed using a API table.
1060      ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1061      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1062    } else if (FName == "CVPixelBufferCreateWithBytes") {
1063      // FIXES: <rdar://problem/7283567>
1064      // Eventually this can be improved by recognizing that the pixel
1065      // buffer passed to CVPixelBufferCreateWithBytes is released via
1066      // a callback and doing full IPA to make sure this is done correctly.
1067      // FIXME: This function has an out parameter that returns an
1068      // allocated object.
1069      ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1070      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1071    } else if (FName == "CGBitmapContextCreateWithData") {
1072      // FIXES: <rdar://problem/7358899>
1073      // Eventually this can be improved by recognizing that 'releaseInfo'
1074      // passed to CGBitmapContextCreateWithData is released via
1075      // a callback and doing full IPA to make sure this is done correctly.
1076      ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1077      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1078                               DoNothing, DoNothing);
1079    } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1080      // FIXES: <rdar://problem/7283567>
1081      // Eventually this can be improved by recognizing that the pixel
1082      // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1083      // via a callback and doing full IPA to make sure this is done
1084      // correctly.
1085      ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1086      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1087    } else if (FName == "dispatch_set_context") {
1088      // <rdar://problem/11059275> - The analyzer currently doesn't have
1089      // a good way to reason about the finalizer function for libdispatch.
1090      // If we pass a context object that is memory managed, stop tracking it.
1091      // FIXME: this hack should possibly go away once we can handle
1092      // libdispatch finalizers.
1093      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1094      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1095    } else if (FName.startswith("NSLog")) {
1096      S = getDoNothingSummary();
1097    } else if (FName.startswith("NS") &&
1098                (FName.find("Insert") != StringRef::npos)) {
1099      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1100      // be deallocated by NSMapRemove. (radar://11152419)
1101      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1102      ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1103      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1104    }
1105
1106    // Did we get a summary?
1107    if (S)
1108      break;
1109
1110    // Enable this code once the semantics of NSDeallocateObject are resolved
1111    // for GC.  <rdar://problem/6619988>
1112#if 0
1113    // Handle: NSDeallocateObject(id anObject);
1114    // This method does allow 'nil' (although we don't check it now).
1115    if (strcmp(FName, "NSDeallocateObject") == 0) {
1116      return RetTy == Ctx.VoidTy
1117        ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1118        : getPersistentStopSummary();
1119    }
1120#endif
1121
1122    if (RetTy->isPointerType()) {
1123      // For CoreFoundation ('CF') types.
1124      if (cocoa::isRefType(RetTy, "CF", FName)) {
1125        if (isRetain(FD, FName))
1126          S = getUnarySummary(FT, cfretain);
1127        else if (isMakeCollectable(FD, FName))
1128          S = getUnarySummary(FT, cfmakecollectable);
1129        else
1130          S = getCFCreateGetRuleSummary(FD);
1131
1132        break;
1133      }
1134
1135      // For CoreGraphics ('CG') types.
1136      if (cocoa::isRefType(RetTy, "CG", FName)) {
1137        if (isRetain(FD, FName))
1138          S = getUnarySummary(FT, cfretain);
1139        else
1140          S = getCFCreateGetRuleSummary(FD);
1141
1142        break;
1143      }
1144
1145      // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1146      if (cocoa::isRefType(RetTy, "DADisk") ||
1147          cocoa::isRefType(RetTy, "DADissenter") ||
1148          cocoa::isRefType(RetTy, "DASessionRef")) {
1149        S = getCFCreateGetRuleSummary(FD);
1150        break;
1151      }
1152
1153      break;
1154    }
1155
1156    // Check for release functions, the only kind of functions that we care
1157    // about that don't return a pointer type.
1158    if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1159      // Test for 'CGCF'.
1160      FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1161
1162      if (isRelease(FD, FName))
1163        S = getUnarySummary(FT, cfrelease);
1164      else {
1165        assert (ScratchArgs.isEmpty());
1166        // Remaining CoreFoundation and CoreGraphics functions.
1167        // We use to assume that they all strictly followed the ownership idiom
1168        // and that ownership cannot be transferred.  While this is technically
1169        // correct, many methods allow a tracked object to escape.  For example:
1170        //
1171        //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1172        //   CFDictionaryAddValue(y, key, x);
1173        //   CFRelease(x);
1174        //   ... it is okay to use 'x' since 'y' has a reference to it
1175        //
1176        // We handle this and similar cases with the follow heuristic.  If the
1177        // function name contains "InsertValue", "SetValue", "AddValue",
1178        // "AppendValue", or "SetAttribute", then we assume that arguments may
1179        // "escape."  This means that something else holds on to the object,
1180        // allowing it be used even after its local retain count drops to 0.
1181        ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1182                       StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1183                       StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1184                       StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1185                       StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1186                      ? MayEscape : DoNothing;
1187
1188        S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1189      }
1190    }
1191  }
1192  while (0);
1193
1194  // If we got all the way here without any luck, use a default summary.
1195  if (!S)
1196    S = getDefaultSummary();
1197
1198  // Annotations override defaults.
1199  if (AllowAnnotations)
1200    updateSummaryFromAnnotations(S, FD);
1201
1202  FuncSummaries[FD] = S;
1203  return S;
1204}
1205
1206const RetainSummary *
1207RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1208  if (coreFoundation::followsCreateRule(FD))
1209    return getCFSummaryCreateRule(FD);
1210
1211  return getCFSummaryGetRule(FD);
1212}
1213
1214const RetainSummary *
1215RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1216                                      UnaryFuncKind func) {
1217
1218  // Sanity check that this is *really* a unary function.  This can
1219  // happen if people do weird things.
1220  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1221  if (!FTP || FTP->getNumArgs() != 1)
1222    return getPersistentStopSummary();
1223
1224  assert (ScratchArgs.isEmpty());
1225
1226  ArgEffect Effect;
1227  switch (func) {
1228    case cfretain: Effect = IncRef; break;
1229    case cfrelease: Effect = DecRef; break;
1230    case cfmakecollectable: Effect = MakeCollectable; break;
1231  }
1232
1233  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1234  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1235}
1236
1237const RetainSummary *
1238RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1239  assert (ScratchArgs.isEmpty());
1240
1241  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1242}
1243
1244const RetainSummary *
1245RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1246  assert (ScratchArgs.isEmpty());
1247  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1248                              DoNothing, DoNothing);
1249}
1250
1251//===----------------------------------------------------------------------===//
1252// Summary creation for Selectors.
1253//===----------------------------------------------------------------------===//
1254
1255void
1256RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1257                                                   const FunctionDecl *FD) {
1258  if (!FD)
1259    return;
1260
1261  assert(Summ && "Must have a summary to add annotations to.");
1262  RetainSummaryTemplate Template(Summ, *this);
1263
1264  // Effects on the parameters.
1265  unsigned parm_idx = 0;
1266  for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1267         pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1268    const ParmVarDecl *pd = *pi;
1269    if (pd->getAttr<NSConsumedAttr>()) {
1270      if (!GCEnabled) {
1271        Template->addArg(AF, parm_idx, DecRef);
1272      }
1273    } else if (pd->getAttr<CFConsumedAttr>()) {
1274      Template->addArg(AF, parm_idx, DecRef);
1275    }
1276  }
1277
1278  QualType RetTy = FD->getResultType();
1279
1280  // Determine if there is a special return effect for this method.
1281  if (cocoa::isCocoaObjectRef(RetTy)) {
1282    if (FD->getAttr<NSReturnsRetainedAttr>()) {
1283      Template->setRetEffect(ObjCAllocRetE);
1284    }
1285    else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1286      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1287    }
1288    else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
1289      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1290    }
1291    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1292      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1293    }
1294  } else if (RetTy->getAs<PointerType>()) {
1295    if (FD->getAttr<CFReturnsRetainedAttr>()) {
1296      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1297    }
1298    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1299      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1300    }
1301  }
1302}
1303
1304void
1305RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1306                                                   const ObjCMethodDecl *MD) {
1307  if (!MD)
1308    return;
1309
1310  assert(Summ && "Must have a valid summary to add annotations to");
1311  RetainSummaryTemplate Template(Summ, *this);
1312  bool isTrackedLoc = false;
1313
1314  // Effects on the receiver.
1315  if (MD->getAttr<NSConsumesSelfAttr>()) {
1316    if (!GCEnabled)
1317      Template->setReceiverEffect(DecRefMsg);
1318  }
1319
1320  // Effects on the parameters.
1321  unsigned parm_idx = 0;
1322  for (ObjCMethodDecl::param_const_iterator
1323         pi=MD->param_begin(), pe=MD->param_end();
1324       pi != pe; ++pi, ++parm_idx) {
1325    const ParmVarDecl *pd = *pi;
1326    if (pd->getAttr<NSConsumedAttr>()) {
1327      if (!GCEnabled)
1328        Template->addArg(AF, parm_idx, DecRef);
1329    }
1330    else if(pd->getAttr<CFConsumedAttr>()) {
1331      Template->addArg(AF, parm_idx, DecRef);
1332    }
1333  }
1334
1335  // Determine if there is a special return effect for this method.
1336  if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1337    if (MD->getAttr<NSReturnsRetainedAttr>()) {
1338      Template->setRetEffect(ObjCAllocRetE);
1339      return;
1340    }
1341    if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
1342      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1343      return;
1344    }
1345
1346    isTrackedLoc = true;
1347  } else {
1348    isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1349  }
1350
1351  if (isTrackedLoc) {
1352    if (MD->getAttr<CFReturnsRetainedAttr>())
1353      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1354    else if (MD->getAttr<CFReturnsNotRetainedAttr>())
1355      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1356  }
1357}
1358
1359const RetainSummary *
1360RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1361                                               Selector S, QualType RetTy) {
1362
1363  if (MD) {
1364    // Scan the method decl for 'void*' arguments.  These should be treated
1365    // as 'StopTracking' because they are often used with delegates.
1366    // Delegates are a frequent form of false positives with the retain
1367    // count checker.
1368    unsigned i = 0;
1369    for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
1370         E = MD->param_end(); I != E; ++I, ++i)
1371      if (const ParmVarDecl *PD = *I) {
1372        QualType Ty = Ctx.getCanonicalType(PD->getType());
1373        if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
1374          ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
1375      }
1376  }
1377
1378  // Any special effects?
1379  ArgEffect ReceiverEff = DoNothing;
1380  RetEffect ResultEff = RetEffect::MakeNoRet();
1381
1382  // Check the method family, and apply any default annotations.
1383  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1384    case OMF_None:
1385    case OMF_performSelector:
1386      // Assume all Objective-C methods follow Cocoa Memory Management rules.
1387      // FIXME: Does the non-threaded performSelector family really belong here?
1388      // The selector could be, say, @selector(copy).
1389      if (cocoa::isCocoaObjectRef(RetTy))
1390        ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1391      else if (coreFoundation::isCFObjectRef(RetTy)) {
1392        // ObjCMethodDecl currently doesn't consider CF objects as valid return
1393        // values for alloc, new, copy, or mutableCopy, so we have to
1394        // double-check with the selector. This is ugly, but there aren't that
1395        // many Objective-C methods that return CF objects, right?
1396        if (MD) {
1397          switch (S.getMethodFamily()) {
1398          case OMF_alloc:
1399          case OMF_new:
1400          case OMF_copy:
1401          case OMF_mutableCopy:
1402            ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1403            break;
1404          default:
1405            ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1406            break;
1407          }
1408        } else {
1409          ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1410        }
1411      }
1412      break;
1413    case OMF_init:
1414      ResultEff = ObjCInitRetE;
1415      ReceiverEff = DecRefMsg;
1416      break;
1417    case OMF_alloc:
1418    case OMF_new:
1419    case OMF_copy:
1420    case OMF_mutableCopy:
1421      if (cocoa::isCocoaObjectRef(RetTy))
1422        ResultEff = ObjCAllocRetE;
1423      else if (coreFoundation::isCFObjectRef(RetTy))
1424        ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1425      break;
1426    case OMF_autorelease:
1427      ReceiverEff = Autorelease;
1428      break;
1429    case OMF_retain:
1430      ReceiverEff = IncRefMsg;
1431      break;
1432    case OMF_release:
1433      ReceiverEff = DecRefMsg;
1434      break;
1435    case OMF_dealloc:
1436      ReceiverEff = Dealloc;
1437      break;
1438    case OMF_self:
1439      // -self is handled specially by the ExprEngine to propagate the receiver.
1440      break;
1441    case OMF_retainCount:
1442    case OMF_finalize:
1443      // These methods don't return objects.
1444      break;
1445  }
1446
1447  // If one of the arguments in the selector has the keyword 'delegate' we
1448  // should stop tracking the reference count for the receiver.  This is
1449  // because the reference count is quite possibly handled by a delegate
1450  // method.
1451  if (S.isKeywordSelector()) {
1452    for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1453      StringRef Slot = S.getNameForSlot(i);
1454      if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1455        if (ResultEff == ObjCInitRetE)
1456          ResultEff = RetEffect::MakeNoRet();
1457        else
1458          ReceiverEff = StopTracking;
1459      }
1460    }
1461  }
1462
1463  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1464      ResultEff.getKind() == RetEffect::NoRet)
1465    return getDefaultSummary();
1466
1467  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1468}
1469
1470const RetainSummary *
1471RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1472                                               ProgramStateRef State) {
1473  const ObjCInterfaceDecl *ReceiverClass = 0;
1474
1475  // We do better tracking of the type of the object than the core ExprEngine.
1476  // See if we have its type in our private state.
1477  // FIXME: Eventually replace the use of state->get<RefBindings> with
1478  // a generic API for reasoning about the Objective-C types of symbolic
1479  // objects.
1480  SVal ReceiverV = Msg.getReceiverSVal();
1481  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1482    if (const RefVal *T = getRefBinding(State, Sym))
1483      if (const ObjCObjectPointerType *PT =
1484            T->getType()->getAs<ObjCObjectPointerType>())
1485        ReceiverClass = PT->getInterfaceDecl();
1486
1487  // If we don't know what kind of object this is, fall back to its static type.
1488  if (!ReceiverClass)
1489    ReceiverClass = Msg.getReceiverInterface();
1490
1491  // FIXME: The receiver could be a reference to a class, meaning that
1492  //  we should use the class method.
1493  // id x = [NSObject class];
1494  // [x performSelector:... withObject:... afterDelay:...];
1495  Selector S = Msg.getSelector();
1496  const ObjCMethodDecl *Method = Msg.getDecl();
1497  if (!Method && ReceiverClass)
1498    Method = ReceiverClass->getInstanceMethod(S);
1499
1500  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1501                          ObjCMethodSummaries);
1502}
1503
1504const RetainSummary *
1505RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1506                                       const ObjCMethodDecl *MD, QualType RetTy,
1507                                       ObjCMethodSummariesTy &CachedSummaries) {
1508
1509  // Look up a summary in our summary cache.
1510  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1511
1512  if (!Summ) {
1513    Summ = getStandardMethodSummary(MD, S, RetTy);
1514
1515    // Annotations override defaults.
1516    updateSummaryFromAnnotations(Summ, MD);
1517
1518    // Memoize the summary.
1519    CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1520  }
1521
1522  return Summ;
1523}
1524
1525void RetainSummaryManager::InitializeClassMethodSummaries() {
1526  assert(ScratchArgs.isEmpty());
1527  // Create the [NSAssertionHandler currentHander] summary.
1528  addClassMethSummary("NSAssertionHandler", "currentHandler",
1529                getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1530
1531  // Create the [NSAutoreleasePool addObject:] summary.
1532  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1533  addClassMethSummary("NSAutoreleasePool", "addObject",
1534                      getPersistentSummary(RetEffect::MakeNoRet(),
1535                                           DoNothing, Autorelease));
1536}
1537
1538void RetainSummaryManager::InitializeMethodSummaries() {
1539
1540  assert (ScratchArgs.isEmpty());
1541
1542  // Create the "init" selector.  It just acts as a pass-through for the
1543  // receiver.
1544  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1545  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1546
1547  // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1548  // claims the receiver and returns a retained object.
1549  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1550                         InitSumm);
1551
1552  // The next methods are allocators.
1553  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1554  const RetainSummary *CFAllocSumm =
1555    getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1556
1557  // Create the "retain" selector.
1558  RetEffect NoRet = RetEffect::MakeNoRet();
1559  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1560  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1561
1562  // Create the "release" selector.
1563  Summ = getPersistentSummary(NoRet, DecRefMsg);
1564  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1565
1566  // Create the "drain" selector.
1567  Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
1568  addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
1569
1570  // Create the -dealloc summary.
1571  Summ = getPersistentSummary(NoRet, Dealloc);
1572  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1573
1574  // Create the "autorelease" selector.
1575  Summ = getPersistentSummary(NoRet, Autorelease);
1576  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1577
1578  // Specially handle NSAutoreleasePool.
1579  addInstMethSummary("NSAutoreleasePool", "init",
1580                     getPersistentSummary(NoRet, NewAutoreleasePool));
1581
1582  // For NSWindow, allocated objects are (initially) self-owned.
1583  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1584  //  self-own themselves.  However, they only do this once they are displayed.
1585  //  Thus, we need to track an NSWindow's display status.
1586  //  This is tracked in <rdar://problem/6062711>.
1587  //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1588  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1589                                                   StopTracking,
1590                                                   StopTracking);
1591
1592  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1593
1594#if 0
1595  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1596                     "styleMask", "backing", "defer", NULL);
1597
1598  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1599                     "styleMask", "backing", "defer", "screen", NULL);
1600#endif
1601
1602  // For NSPanel (which subclasses NSWindow), allocated objects are not
1603  //  self-owned.
1604  // FIXME: For now we don't track NSPanels. object for the same reason
1605  //   as for NSWindow objects.
1606  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1607
1608#if 0
1609  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1610                     "styleMask", "backing", "defer", NULL);
1611
1612  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1613                     "styleMask", "backing", "defer", "screen", NULL);
1614#endif
1615
1616  // Don't track allocated autorelease pools yet, as it is okay to prematurely
1617  // exit a method.
1618  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1619  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1620
1621  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1622  addInstMethSummary("QCRenderer", AllocSumm,
1623                     "createSnapshotImageOfType", NULL);
1624  addInstMethSummary("QCView", AllocSumm,
1625                     "createSnapshotImageOfType", NULL);
1626
1627  // Create summaries for CIContext, 'createCGImage' and
1628  // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1629  // automatically garbage collected.
1630  addInstMethSummary("CIContext", CFAllocSumm,
1631                     "createCGImage", "fromRect", NULL);
1632  addInstMethSummary("CIContext", CFAllocSumm,
1633                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
1634  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1635           "info", NULL);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Error reporting.
1640//===----------------------------------------------------------------------===//
1641namespace {
1642  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1643    SummaryLogTy;
1644
1645  //===-------------===//
1646  // Bug Descriptions. //
1647  //===-------------===//
1648
1649  class CFRefBug : public BugType {
1650  protected:
1651    CFRefBug(StringRef name)
1652    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
1653  public:
1654
1655    // FIXME: Eventually remove.
1656    virtual const char *getDescription() const = 0;
1657
1658    virtual bool isLeak() const { return false; }
1659  };
1660
1661  class UseAfterRelease : public CFRefBug {
1662  public:
1663    UseAfterRelease() : CFRefBug("Use-after-release") {}
1664
1665    const char *getDescription() const {
1666      return "Reference-counted object is used after it is released";
1667    }
1668  };
1669
1670  class BadRelease : public CFRefBug {
1671  public:
1672    BadRelease() : CFRefBug("Bad release") {}
1673
1674    const char *getDescription() const {
1675      return "Incorrect decrement of the reference count of an object that is "
1676             "not owned at this point by the caller";
1677    }
1678  };
1679
1680  class DeallocGC : public CFRefBug {
1681  public:
1682    DeallocGC()
1683    : CFRefBug("-dealloc called while using garbage collection") {}
1684
1685    const char *getDescription() const {
1686      return "-dealloc called while using garbage collection";
1687    }
1688  };
1689
1690  class DeallocNotOwned : public CFRefBug {
1691  public:
1692    DeallocNotOwned()
1693    : CFRefBug("-dealloc sent to non-exclusively owned object") {}
1694
1695    const char *getDescription() const {
1696      return "-dealloc sent to object that may be referenced elsewhere";
1697    }
1698  };
1699
1700  class OverAutorelease : public CFRefBug {
1701  public:
1702    OverAutorelease()
1703    : CFRefBug("Object sent -autorelease too many times") {}
1704
1705    const char *getDescription() const {
1706      return "Object sent -autorelease too many times";
1707    }
1708  };
1709
1710  class ReturnedNotOwnedForOwned : public CFRefBug {
1711  public:
1712    ReturnedNotOwnedForOwned()
1713    : CFRefBug("Method should return an owned object") {}
1714
1715    const char *getDescription() const {
1716      return "Object with a +0 retain count returned to caller where a +1 "
1717             "(owning) retain count is expected";
1718    }
1719  };
1720
1721  class Leak : public CFRefBug {
1722  public:
1723    Leak(StringRef name)
1724    : CFRefBug(name) {
1725      // Leaks should not be reported if they are post-dominated by a sink.
1726      setSuppressOnSink(true);
1727    }
1728
1729    const char *getDescription() const { return ""; }
1730
1731    bool isLeak() const { return true; }
1732  };
1733
1734  //===---------===//
1735  // Bug Reports.  //
1736  //===---------===//
1737
1738  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1739  protected:
1740    SymbolRef Sym;
1741    const SummaryLogTy &SummaryLog;
1742    bool GCEnabled;
1743
1744  public:
1745    CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1746       : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1747
1748    virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1749      static int x = 0;
1750      ID.AddPointer(&x);
1751      ID.AddPointer(Sym);
1752    }
1753
1754    virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1755                                           const ExplodedNode *PrevN,
1756                                           BugReporterContext &BRC,
1757                                           BugReport &BR);
1758
1759    virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1760                                            const ExplodedNode *N,
1761                                            BugReport &BR);
1762  };
1763
1764  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1765  public:
1766    CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1767                           const SummaryLogTy &log)
1768       : CFRefReportVisitor(sym, GCEnabled, log) {}
1769
1770    PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1771                                    const ExplodedNode *N,
1772                                    BugReport &BR);
1773
1774    virtual BugReporterVisitor *clone() const {
1775      // The curiously-recurring template pattern only works for one level of
1776      // subclassing. Rather than make a new template base for
1777      // CFRefReportVisitor, we simply override clone() to do the right thing.
1778      // This could be trouble someday if BugReporterVisitorImpl is ever
1779      // used for something else besides a convenient implementation of clone().
1780      return new CFRefLeakReportVisitor(*this);
1781    }
1782  };
1783
1784  class CFRefReport : public BugReport {
1785    void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1786
1787  public:
1788    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1789                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1790                bool registerVisitor = true)
1791      : BugReport(D, D.getDescription(), n) {
1792      if (registerVisitor)
1793        addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1794      addGCModeDescription(LOpts, GCEnabled);
1795    }
1796
1797    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1798                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1799                StringRef endText)
1800      : BugReport(D, D.getDescription(), endText, n) {
1801      addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1802      addGCModeDescription(LOpts, GCEnabled);
1803    }
1804
1805    virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
1806      const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1807      if (!BugTy.isLeak())
1808        return BugReport::getRanges();
1809      else
1810        return std::make_pair(ranges_iterator(), ranges_iterator());
1811    }
1812  };
1813
1814  class CFRefLeakReport : public CFRefReport {
1815    const MemRegion* AllocBinding;
1816
1817  public:
1818    CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1819                    const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1820                    CheckerContext &Ctx);
1821
1822    PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1823      assert(Location.isValid());
1824      return Location;
1825    }
1826  };
1827} // end anonymous namespace
1828
1829void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1830                                       bool GCEnabled) {
1831  const char *GCModeDescription = 0;
1832
1833  switch (LOpts.getGC()) {
1834  case LangOptions::GCOnly:
1835    assert(GCEnabled);
1836    GCModeDescription = "Code is compiled to only use garbage collection";
1837    break;
1838
1839  case LangOptions::NonGC:
1840    assert(!GCEnabled);
1841    GCModeDescription = "Code is compiled to use reference counts";
1842    break;
1843
1844  case LangOptions::HybridGC:
1845    if (GCEnabled) {
1846      GCModeDescription = "Code is compiled to use either garbage collection "
1847                          "(GC) or reference counts (non-GC).  The bug occurs "
1848                          "with GC enabled";
1849      break;
1850    } else {
1851      GCModeDescription = "Code is compiled to use either garbage collection "
1852                          "(GC) or reference counts (non-GC).  The bug occurs "
1853                          "in non-GC mode";
1854      break;
1855    }
1856  }
1857
1858  assert(GCModeDescription && "invalid/unknown GC mode");
1859  addExtraText(GCModeDescription);
1860}
1861
1862// FIXME: This should be a method on SmallVector.
1863static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
1864                            ArgEffect X) {
1865  for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1866       I!=E; ++I)
1867    if (*I == X) return true;
1868
1869  return false;
1870}
1871
1872static bool isNumericLiteralExpression(const Expr *E) {
1873  // FIXME: This set of cases was copied from SemaExprObjC.
1874  return isa<IntegerLiteral>(E) ||
1875         isa<CharacterLiteral>(E) ||
1876         isa<FloatingLiteral>(E) ||
1877         isa<ObjCBoolLiteralExpr>(E) ||
1878         isa<CXXBoolLiteralExpr>(E);
1879}
1880
1881PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1882                                                   const ExplodedNode *PrevN,
1883                                                   BugReporterContext &BRC,
1884                                                   BugReport &BR) {
1885  // FIXME: We will eventually need to handle non-statement-based events
1886  // (__attribute__((cleanup))).
1887  if (!isa<StmtPoint>(N->getLocation()))
1888    return NULL;
1889
1890  // Check if the type state has changed.
1891  ProgramStateRef PrevSt = PrevN->getState();
1892  ProgramStateRef CurrSt = N->getState();
1893  const LocationContext *LCtx = N->getLocationContext();
1894
1895  const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1896  if (!CurrT) return NULL;
1897
1898  const RefVal &CurrV = *CurrT;
1899  const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1900
1901  // Create a string buffer to constain all the useful things we want
1902  // to tell the user.
1903  std::string sbuf;
1904  llvm::raw_string_ostream os(sbuf);
1905
1906  // This is the allocation site since the previous node had no bindings
1907  // for this symbol.
1908  if (!PrevT) {
1909    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1910
1911    if (isa<ObjCArrayLiteral>(S)) {
1912      os << "NSArray literal is an object with a +0 retain count";
1913    }
1914    else if (isa<ObjCDictionaryLiteral>(S)) {
1915      os << "NSDictionary literal is an object with a +0 retain count";
1916    }
1917    else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1918      if (isNumericLiteralExpression(BL->getSubExpr()))
1919        os << "NSNumber literal is an object with a +0 retain count";
1920      else {
1921        const ObjCInterfaceDecl *BoxClass = 0;
1922        if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1923          BoxClass = Method->getClassInterface();
1924
1925        // We should always be able to find the boxing class interface,
1926        // but consider this future-proofing.
1927        if (BoxClass)
1928          os << *BoxClass << " b";
1929        else
1930          os << "B";
1931
1932        os << "oxed expression produces an object with a +0 retain count";
1933      }
1934    }
1935    else {
1936      if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1937        // Get the name of the callee (if it is available).
1938        SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1939        if (const FunctionDecl *FD = X.getAsFunctionDecl())
1940          os << "Call to function '" << *FD << '\'';
1941        else
1942          os << "function call";
1943      }
1944      else {
1945        assert(isa<ObjCMessageExpr>(S));
1946        CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1947        CallEventRef<ObjCMethodCall> Call
1948          = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1949
1950        switch (Call->getMessageKind()) {
1951        case OCM_Message:
1952          os << "Method";
1953          break;
1954        case OCM_PropertyAccess:
1955          os << "Property";
1956          break;
1957        case OCM_Subscript:
1958          os << "Subscript";
1959          break;
1960        }
1961      }
1962
1963      if (CurrV.getObjKind() == RetEffect::CF) {
1964        os << " returns a Core Foundation object with a ";
1965      }
1966      else {
1967        assert (CurrV.getObjKind() == RetEffect::ObjC);
1968        os << " returns an Objective-C object with a ";
1969      }
1970
1971      if (CurrV.isOwned()) {
1972        os << "+1 retain count";
1973
1974        if (GCEnabled) {
1975          assert(CurrV.getObjKind() == RetEffect::CF);
1976          os << ".  "
1977          "Core Foundation objects are not automatically garbage collected.";
1978        }
1979      }
1980      else {
1981        assert (CurrV.isNotOwned());
1982        os << "+0 retain count";
1983      }
1984    }
1985
1986    PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1987                                  N->getLocationContext());
1988    return new PathDiagnosticEventPiece(Pos, os.str());
1989  }
1990
1991  // Gather up the effects that were performed on the object at this
1992  // program point
1993  SmallVector<ArgEffect, 2> AEffects;
1994
1995  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1996  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
1997    // We only have summaries attached to nodes after evaluating CallExpr and
1998    // ObjCMessageExprs.
1999    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2000
2001    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2002      // Iterate through the parameter expressions and see if the symbol
2003      // was ever passed as an argument.
2004      unsigned i = 0;
2005
2006      for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2007           AI!=AE; ++AI, ++i) {
2008
2009        // Retrieve the value of the argument.  Is it the symbol
2010        // we are interested in?
2011        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2012          continue;
2013
2014        // We have an argument.  Get the effect!
2015        AEffects.push_back(Summ->getArg(i));
2016      }
2017    }
2018    else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2019      if (const Expr *receiver = ME->getInstanceReceiver())
2020        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2021              .getAsLocSymbol() == Sym) {
2022          // The symbol we are tracking is the receiver.
2023          AEffects.push_back(Summ->getReceiverEffect());
2024        }
2025    }
2026  }
2027
2028  do {
2029    // Get the previous type state.
2030    RefVal PrevV = *PrevT;
2031
2032    // Specially handle -dealloc.
2033    if (!GCEnabled && contains(AEffects, Dealloc)) {
2034      // Determine if the object's reference count was pushed to zero.
2035      assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2036      // We may not have transitioned to 'release' if we hit an error.
2037      // This case is handled elsewhere.
2038      if (CurrV.getKind() == RefVal::Released) {
2039        assert(CurrV.getCombinedCounts() == 0);
2040        os << "Object released by directly sending the '-dealloc' message";
2041        break;
2042      }
2043    }
2044
2045    // Specially handle CFMakeCollectable and friends.
2046    if (contains(AEffects, MakeCollectable)) {
2047      // Get the name of the function.
2048      const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2049      SVal X =
2050        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2051      const FunctionDecl *FD = X.getAsFunctionDecl();
2052
2053      if (GCEnabled) {
2054        // Determine if the object's reference count was pushed to zero.
2055        assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2056
2057        os << "In GC mode a call to '" << *FD
2058        <<  "' decrements an object's retain count and registers the "
2059        "object with the garbage collector. ";
2060
2061        if (CurrV.getKind() == RefVal::Released) {
2062          assert(CurrV.getCount() == 0);
2063          os << "Since it now has a 0 retain count the object can be "
2064          "automatically collected by the garbage collector.";
2065        }
2066        else
2067          os << "An object must have a 0 retain count to be garbage collected. "
2068          "After this call its retain count is +" << CurrV.getCount()
2069          << '.';
2070      }
2071      else
2072        os << "When GC is not enabled a call to '" << *FD
2073        << "' has no effect on its argument.";
2074
2075      // Nothing more to say.
2076      break;
2077    }
2078
2079    // Determine if the typestate has changed.
2080    if (!(PrevV == CurrV))
2081      switch (CurrV.getKind()) {
2082        case RefVal::Owned:
2083        case RefVal::NotOwned:
2084
2085          if (PrevV.getCount() == CurrV.getCount()) {
2086            // Did an autorelease message get sent?
2087            if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2088              return 0;
2089
2090            assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2091            os << "Object sent -autorelease message";
2092            break;
2093          }
2094
2095          if (PrevV.getCount() > CurrV.getCount())
2096            os << "Reference count decremented.";
2097          else
2098            os << "Reference count incremented.";
2099
2100          if (unsigned Count = CurrV.getCount())
2101            os << " The object now has a +" << Count << " retain count.";
2102
2103          if (PrevV.getKind() == RefVal::Released) {
2104            assert(GCEnabled && CurrV.getCount() > 0);
2105            os << " The object is not eligible for garbage collection until "
2106                  "the retain count reaches 0 again.";
2107          }
2108
2109          break;
2110
2111        case RefVal::Released:
2112          os << "Object released.";
2113          break;
2114
2115        case RefVal::ReturnedOwned:
2116          // Autoreleases can be applied after marking a node ReturnedOwned.
2117          if (CurrV.getAutoreleaseCount())
2118            return NULL;
2119
2120          os << "Object returned to caller as an owning reference (single "
2121                "retain count transferred to caller)";
2122          break;
2123
2124        case RefVal::ReturnedNotOwned:
2125          os << "Object returned to caller with a +0 retain count";
2126          break;
2127
2128        default:
2129          return NULL;
2130      }
2131
2132    // Emit any remaining diagnostics for the argument effects (if any).
2133    for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2134         E=AEffects.end(); I != E; ++I) {
2135
2136      // A bunch of things have alternate behavior under GC.
2137      if (GCEnabled)
2138        switch (*I) {
2139          default: break;
2140          case Autorelease:
2141            os << "In GC mode an 'autorelease' has no effect.";
2142            continue;
2143          case IncRefMsg:
2144            os << "In GC mode the 'retain' message has no effect.";
2145            continue;
2146          case DecRefMsg:
2147            os << "In GC mode the 'release' message has no effect.";
2148            continue;
2149        }
2150    }
2151  } while (0);
2152
2153  if (os.str().empty())
2154    return 0; // We have nothing to say!
2155
2156  const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2157  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2158                                N->getLocationContext());
2159  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2160
2161  // Add the range by scanning the children of the statement for any bindings
2162  // to Sym.
2163  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2164       I!=E; ++I)
2165    if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2166      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2167        P->addRange(Exp->getSourceRange());
2168        break;
2169      }
2170
2171  return P;
2172}
2173
2174// Find the first node in the current function context that referred to the
2175// tracked symbol and the memory location that value was stored to. Note, the
2176// value is only reported if the allocation occurred in the same function as
2177// the leak.
2178static std::pair<const ExplodedNode*,const MemRegion*>
2179GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2180                  SymbolRef Sym) {
2181  const ExplodedNode *Last = N;
2182  const MemRegion* FirstBinding = 0;
2183  const LocationContext *LeakContext = N->getLocationContext();
2184
2185  while (N) {
2186    ProgramStateRef St = N->getState();
2187
2188    if (!getRefBinding(St, Sym))
2189      break;
2190
2191    StoreManager::FindUniqueBinding FB(Sym);
2192    StateMgr.iterBindings(St, FB);
2193    if (FB) FirstBinding = FB.getRegion();
2194
2195    // Allocation node, is the last node in the current context in which the
2196    // symbol was tracked.
2197    if (N->getLocationContext() == LeakContext)
2198      Last = N;
2199
2200    N = N->pred_empty() ? NULL : *(N->pred_begin());
2201  }
2202
2203  // If allocation happened in a function different from the leak node context,
2204  // do not report the binding.
2205  if (N->getLocationContext() != LeakContext) {
2206    FirstBinding = 0;
2207  }
2208
2209  return std::make_pair(Last, FirstBinding);
2210}
2211
2212PathDiagnosticPiece*
2213CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2214                               const ExplodedNode *EndN,
2215                               BugReport &BR) {
2216  BR.markInteresting(Sym);
2217  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2218}
2219
2220PathDiagnosticPiece*
2221CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2222                                   const ExplodedNode *EndN,
2223                                   BugReport &BR) {
2224
2225  // Tell the BugReporterContext to report cases when the tracked symbol is
2226  // assigned to different variables, etc.
2227  BR.markInteresting(Sym);
2228
2229  // We are reporting a leak.  Walk up the graph to get to the first node where
2230  // the symbol appeared, and also get the first VarDecl that tracked object
2231  // is stored to.
2232  const ExplodedNode *AllocNode = 0;
2233  const MemRegion* FirstBinding = 0;
2234
2235  llvm::tie(AllocNode, FirstBinding) =
2236    GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2237
2238  SourceManager& SM = BRC.getSourceManager();
2239
2240  // Compute an actual location for the leak.  Sometimes a leak doesn't
2241  // occur at an actual statement (e.g., transition between blocks; end
2242  // of function) so we need to walk the graph and compute a real location.
2243  const ExplodedNode *LeakN = EndN;
2244  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2245
2246  std::string sbuf;
2247  llvm::raw_string_ostream os(sbuf);
2248
2249  os << "Object leaked: ";
2250
2251  if (FirstBinding) {
2252    os << "object allocated and stored into '"
2253       << FirstBinding->getString() << '\'';
2254  }
2255  else
2256    os << "allocated object";
2257
2258  // Get the retain count.
2259  const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2260
2261  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2262    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2263    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2264    // to the caller for NS objects.
2265    const Decl *D = &EndN->getCodeDecl();
2266    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2267      os << " is returned from a method whose name ('"
2268         << MD->getSelector().getAsString()
2269         << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2270            "  This violates the naming convention rules"
2271            " given in the Memory Management Guide for Cocoa";
2272    }
2273    else {
2274      const FunctionDecl *FD = cast<FunctionDecl>(D);
2275      os << " is returned from a function whose name ('"
2276         << *FD
2277         << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2278            " convention rules given in the Memory Management Guide for Core"
2279            " Foundation";
2280    }
2281  }
2282  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2283    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2284    os << " and returned from method '" << MD.getSelector().getAsString()
2285       << "' is potentially leaked when using garbage collection.  Callers "
2286          "of this method do not expect a returned object with a +1 retain "
2287          "count since they expect the object to be managed by the garbage "
2288          "collector";
2289  }
2290  else
2291    os << " is not referenced later in this execution path and has a retain "
2292          "count of +" << RV->getCount();
2293
2294  return new PathDiagnosticEventPiece(L, os.str());
2295}
2296
2297CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2298                                 bool GCEnabled, const SummaryLogTy &Log,
2299                                 ExplodedNode *n, SymbolRef sym,
2300                                 CheckerContext &Ctx)
2301: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2302
2303  // Most bug reports are cached at the location where they occurred.
2304  // With leaks, we want to unique them by the location where they were
2305  // allocated, and only report a single path.  To do this, we need to find
2306  // the allocation site of a piece of tracked memory, which we do via a
2307  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2308  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2309  // that all ancestor nodes that represent the allocation site have the
2310  // same SourceLocation.
2311  const ExplodedNode *AllocNode = 0;
2312
2313  const SourceManager& SMgr = Ctx.getSourceManager();
2314
2315  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2316    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2317
2318  // Get the SourceLocation for the allocation site.
2319  // FIXME: This will crash the analyzer if an allocation comes from an
2320  // implicit call. (Currently there are no such allocations in Cocoa, though.)
2321  const Stmt *AllocStmt;
2322  ProgramPoint P = AllocNode->getLocation();
2323  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2324    AllocStmt = Exit->getCalleeContext()->getCallSite();
2325  else
2326    AllocStmt = cast<PostStmt>(P).getStmt();
2327  assert(AllocStmt && "All allocations must come from explicit calls");
2328  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2329                                                  n->getLocationContext());
2330  // Fill in the description of the bug.
2331  Description.clear();
2332  llvm::raw_string_ostream os(Description);
2333  os << "Potential leak ";
2334  if (GCEnabled)
2335    os << "(when using garbage collection) ";
2336  os << "of an object";
2337
2338  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2339  if (AllocBinding)
2340    os << " stored into '" << AllocBinding->getString() << '\'';
2341
2342  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2343}
2344
2345//===----------------------------------------------------------------------===//
2346// Main checker logic.
2347//===----------------------------------------------------------------------===//
2348
2349namespace {
2350class RetainCountChecker
2351  : public Checker< check::Bind,
2352                    check::DeadSymbols,
2353                    check::EndAnalysis,
2354                    check::EndPath,
2355                    check::PostStmt<BlockExpr>,
2356                    check::PostStmt<CastExpr>,
2357                    check::PostStmt<ObjCArrayLiteral>,
2358                    check::PostStmt<ObjCDictionaryLiteral>,
2359                    check::PostStmt<ObjCBoxedExpr>,
2360                    check::PostCall,
2361                    check::PreStmt<ReturnStmt>,
2362                    check::RegionChanges,
2363                    eval::Assume,
2364                    eval::Call > {
2365  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2366  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2367  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2368  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2369  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2370
2371  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2372
2373  // This map is only used to ensure proper deletion of any allocated tags.
2374  mutable SymbolTagMap DeadSymbolTags;
2375
2376  mutable OwningPtr<RetainSummaryManager> Summaries;
2377  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2378  mutable SummaryLogTy SummaryLog;
2379  mutable bool ShouldResetSummaryLog;
2380
2381public:
2382  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2383
2384  virtual ~RetainCountChecker() {
2385    DeleteContainerSeconds(DeadSymbolTags);
2386  }
2387
2388  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2389                        ExprEngine &Eng) const {
2390    // FIXME: This is a hack to make sure the summary log gets cleared between
2391    // analyses of different code bodies.
2392    //
2393    // Why is this necessary? Because a checker's lifetime is tied to a
2394    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2395    // Once in a blue moon, a new ExplodedNode will have the same address as an
2396    // old one with an associated summary, and the bug report visitor gets very
2397    // confused. (To make things worse, the summary lifetime is currently also
2398    // tied to a code body, so we get a crash instead of incorrect results.)
2399    //
2400    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2401    // changes, things will start going wrong again. Really the lifetime of this
2402    // log needs to be tied to either the specific nodes in it or the entire
2403    // ExplodedGraph, not to a specific part of the code being analyzed.
2404    //
2405    // (Also, having stateful local data means that the same checker can't be
2406    // used from multiple threads, but a lot of checkers have incorrect
2407    // assumptions about that anyway. So that wasn't a priority at the time of
2408    // this fix.)
2409    //
2410    // This happens at the end of analysis, but bug reports are emitted /after/
2411    // this point. So we can't just clear the summary log now. Instead, we mark
2412    // that the next time we access the summary log, it should be cleared.
2413
2414    // If we never reset the summary log during /this/ code body analysis,
2415    // there were no new summaries. There might still have been summaries from
2416    // the /last/ analysis, so clear them out to make sure the bug report
2417    // visitors don't get confused.
2418    if (ShouldResetSummaryLog)
2419      SummaryLog.clear();
2420
2421    ShouldResetSummaryLog = !SummaryLog.empty();
2422  }
2423
2424  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2425                                     bool GCEnabled) const {
2426    if (GCEnabled) {
2427      if (!leakWithinFunctionGC)
2428        leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2429                                             "garbage collection"));
2430      return leakWithinFunctionGC.get();
2431    } else {
2432      if (!leakWithinFunction) {
2433        if (LOpts.getGC() == LangOptions::HybridGC) {
2434          leakWithinFunction.reset(new Leak("Leak of object when not using "
2435                                            "garbage collection (GC) in "
2436                                            "dual GC/non-GC code"));
2437        } else {
2438          leakWithinFunction.reset(new Leak("Leak"));
2439        }
2440      }
2441      return leakWithinFunction.get();
2442    }
2443  }
2444
2445  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2446    if (GCEnabled) {
2447      if (!leakAtReturnGC)
2448        leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2449                                      "garbage collection"));
2450      return leakAtReturnGC.get();
2451    } else {
2452      if (!leakAtReturn) {
2453        if (LOpts.getGC() == LangOptions::HybridGC) {
2454          leakAtReturn.reset(new Leak("Leak of returned object when not using "
2455                                      "garbage collection (GC) in dual "
2456                                      "GC/non-GC code"));
2457        } else {
2458          leakAtReturn.reset(new Leak("Leak of returned object"));
2459        }
2460      }
2461      return leakAtReturn.get();
2462    }
2463  }
2464
2465  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2466                                          bool GCEnabled) const {
2467    // FIXME: We don't support ARC being turned on and off during one analysis.
2468    // (nor, for that matter, do we support changing ASTContexts)
2469    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2470    if (GCEnabled) {
2471      if (!SummariesGC)
2472        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2473      else
2474        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2475      return *SummariesGC;
2476    } else {
2477      if (!Summaries)
2478        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2479      else
2480        assert(Summaries->isARCEnabled() == ARCEnabled);
2481      return *Summaries;
2482    }
2483  }
2484
2485  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2486    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2487  }
2488
2489  void printState(raw_ostream &Out, ProgramStateRef State,
2490                  const char *NL, const char *Sep) const;
2491
2492  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2493  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2494  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2495
2496  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2497  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2498  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2499
2500  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2501
2502  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2503                    CheckerContext &C) const;
2504
2505  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2506
2507  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2508                                 bool Assumption) const;
2509
2510  ProgramStateRef
2511  checkRegionChanges(ProgramStateRef state,
2512                     const StoreManager::InvalidatedSymbols *invalidated,
2513                     ArrayRef<const MemRegion *> ExplicitRegions,
2514                     ArrayRef<const MemRegion *> Regions,
2515                     const CallEvent *Call) const;
2516
2517  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2518    return true;
2519  }
2520
2521  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2522  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2523                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2524                                SymbolRef Sym, ProgramStateRef state) const;
2525
2526  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2527  void checkEndPath(CheckerContext &C) const;
2528
2529  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2530                                   RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2531                                   CheckerContext &C) const;
2532
2533  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2534                           RefVal::Kind ErrorKind, SymbolRef Sym,
2535                           CheckerContext &C) const;
2536
2537  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2538
2539  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2540
2541  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2542                                    SymbolRef sid, RefVal V,
2543                                    SmallVectorImpl<SymbolRef> &Leaked) const;
2544
2545  std::pair<ExplodedNode *, ProgramStateRef >
2546  handleAutoreleaseCounts(ProgramStateRef state,
2547                          GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
2548                          CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
2549
2550  ExplodedNode *processLeaks(ProgramStateRef state,
2551                             SmallVectorImpl<SymbolRef> &Leaked,
2552                             GenericNodeBuilderRefCount &Builder,
2553                             CheckerContext &Ctx,
2554                             ExplodedNode *Pred = 0) const;
2555};
2556} // end anonymous namespace
2557
2558namespace {
2559class StopTrackingCallback : public SymbolVisitor {
2560  ProgramStateRef state;
2561public:
2562  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2563  ProgramStateRef getState() const { return state; }
2564
2565  bool VisitSymbol(SymbolRef sym) {
2566    state = state->remove<RefBindings>(sym);
2567    return true;
2568  }
2569};
2570} // end anonymous namespace
2571
2572//===----------------------------------------------------------------------===//
2573// Handle statements that may have an effect on refcounts.
2574//===----------------------------------------------------------------------===//
2575
2576void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2577                                       CheckerContext &C) const {
2578
2579  // Scan the BlockDecRefExprs for any object the retain count checker
2580  // may be tracking.
2581  if (!BE->getBlockDecl()->hasCaptures())
2582    return;
2583
2584  ProgramStateRef state = C.getState();
2585  const BlockDataRegion *R =
2586    cast<BlockDataRegion>(state->getSVal(BE,
2587                                         C.getLocationContext()).getAsRegion());
2588
2589  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2590                                            E = R->referenced_vars_end();
2591
2592  if (I == E)
2593    return;
2594
2595  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2596  // via captured variables, even though captured variables result in a copy
2597  // and in implicit increment/decrement of a retain count.
2598  SmallVector<const MemRegion*, 10> Regions;
2599  const LocationContext *LC = C.getLocationContext();
2600  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2601
2602  for ( ; I != E; ++I) {
2603    const VarRegion *VR = *I;
2604    if (VR->getSuperRegion() == R) {
2605      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2606    }
2607    Regions.push_back(VR);
2608  }
2609
2610  state =
2611    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2612                                    Regions.data() + Regions.size()).getState();
2613  C.addTransition(state);
2614}
2615
2616void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2617                                       CheckerContext &C) const {
2618  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2619  if (!BE)
2620    return;
2621
2622  ArgEffect AE = IncRef;
2623
2624  switch (BE->getBridgeKind()) {
2625    case clang::OBC_Bridge:
2626      // Do nothing.
2627      return;
2628    case clang::OBC_BridgeRetained:
2629      AE = IncRef;
2630      break;
2631    case clang::OBC_BridgeTransfer:
2632      AE = DecRefBridgedTransfered;
2633      break;
2634  }
2635
2636  ProgramStateRef state = C.getState();
2637  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2638  if (!Sym)
2639    return;
2640  const RefVal* T = getRefBinding(state, Sym);
2641  if (!T)
2642    return;
2643
2644  RefVal::Kind hasErr = (RefVal::Kind) 0;
2645  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2646
2647  if (hasErr) {
2648    // FIXME: If we get an error during a bridge cast, should we report it?
2649    // Should we assert that there is no error?
2650    return;
2651  }
2652
2653  C.addTransition(state);
2654}
2655
2656void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2657                                             const Expr *Ex) const {
2658  ProgramStateRef state = C.getState();
2659  const ExplodedNode *pred = C.getPredecessor();
2660  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2661       it != et ; ++it) {
2662    const Stmt *child = *it;
2663    SVal V = state->getSVal(child, pred->getLocationContext());
2664    if (SymbolRef sym = V.getAsSymbol())
2665      if (const RefVal* T = getRefBinding(state, sym)) {
2666        RefVal::Kind hasErr = (RefVal::Kind) 0;
2667        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2668        if (hasErr) {
2669          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2670          return;
2671        }
2672      }
2673  }
2674
2675  // Return the object as autoreleased.
2676  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2677  if (SymbolRef sym =
2678        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2679    QualType ResultTy = Ex->getType();
2680    state = setRefBinding(state, sym,
2681                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2682  }
2683
2684  C.addTransition(state);
2685}
2686
2687void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2688                                       CheckerContext &C) const {
2689  // Apply the 'MayEscape' to all values.
2690  processObjCLiterals(C, AL);
2691}
2692
2693void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2694                                       CheckerContext &C) const {
2695  // Apply the 'MayEscape' to all keys and values.
2696  processObjCLiterals(C, DL);
2697}
2698
2699void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2700                                       CheckerContext &C) const {
2701  const ExplodedNode *Pred = C.getPredecessor();
2702  const LocationContext *LCtx = Pred->getLocationContext();
2703  ProgramStateRef State = Pred->getState();
2704
2705  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2706    QualType ResultTy = Ex->getType();
2707    State = setRefBinding(State, Sym,
2708                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2709  }
2710
2711  C.addTransition(State);
2712}
2713
2714void RetainCountChecker::checkPostCall(const CallEvent &Call,
2715                                       CheckerContext &C) const {
2716  if (C.wasInlined)
2717    return;
2718
2719  RetainSummaryManager &Summaries = getSummaryManager(C);
2720  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2721  checkSummary(*Summ, Call, C);
2722}
2723
2724/// GetReturnType - Used to get the return type of a message expression or
2725///  function call with the intention of affixing that type to a tracked symbol.
2726///  While the return type can be queried directly from RetEx, when
2727///  invoking class methods we augment to the return type to be that of
2728///  a pointer to the class (as opposed it just being id).
2729// FIXME: We may be able to do this with related result types instead.
2730// This function is probably overestimating.
2731static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2732  QualType RetTy = RetE->getType();
2733  // If RetE is not a message expression just return its type.
2734  // If RetE is a message expression, return its types if it is something
2735  /// more specific than id.
2736  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2737    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2738      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2739          PT->isObjCClassType()) {
2740        // At this point we know the return type of the message expression is
2741        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2742        // is a call to a class method whose type we can resolve.  In such
2743        // cases, promote the return type to XXX* (where XXX is the class).
2744        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2745        return !D ? RetTy :
2746                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2747      }
2748
2749  return RetTy;
2750}
2751
2752void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2753                                      const CallEvent &CallOrMsg,
2754                                      CheckerContext &C) const {
2755  ProgramStateRef state = C.getState();
2756
2757  // Evaluate the effect of the arguments.
2758  RefVal::Kind hasErr = (RefVal::Kind) 0;
2759  SourceRange ErrorRange;
2760  SymbolRef ErrorSym = 0;
2761
2762  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2763    SVal V = CallOrMsg.getArgSVal(idx);
2764
2765    if (SymbolRef Sym = V.getAsLocSymbol()) {
2766      if (const RefVal *T = getRefBinding(state, Sym)) {
2767        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2768        if (hasErr) {
2769          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2770          ErrorSym = Sym;
2771          break;
2772        }
2773      }
2774    }
2775  }
2776
2777  // Evaluate the effect on the message receiver.
2778  bool ReceiverIsTracked = false;
2779  if (!hasErr) {
2780    const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2781    if (MsgInvocation) {
2782      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2783        if (const RefVal *T = getRefBinding(state, Sym)) {
2784          ReceiverIsTracked = true;
2785          state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2786                               hasErr, C);
2787          if (hasErr) {
2788            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2789            ErrorSym = Sym;
2790          }
2791        }
2792      }
2793    }
2794  }
2795
2796  // Process any errors.
2797  if (hasErr) {
2798    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2799    return;
2800  }
2801
2802  // Consult the summary for the return value.
2803  RetEffect RE = Summ.getRetEffect();
2804
2805  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2806    if (ReceiverIsTracked)
2807      RE = getSummaryManager(C).getObjAllocRetEffect();
2808    else
2809      RE = RetEffect::MakeNoRet();
2810  }
2811
2812  switch (RE.getKind()) {
2813    default:
2814      llvm_unreachable("Unhandled RetEffect.");
2815
2816    case RetEffect::NoRet:
2817      // No work necessary.
2818      break;
2819
2820    case RetEffect::OwnedAllocatedSymbol:
2821    case RetEffect::OwnedSymbol: {
2822      SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2823                                     C.getLocationContext()).getAsSymbol();
2824      if (!Sym)
2825        break;
2826
2827      // Use the result type from the CallEvent as it automatically adjusts
2828      // for methods/functions that return references.
2829      QualType ResultTy = CallOrMsg.getResultType();
2830      state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2831                                                          ResultTy));
2832
2833      // FIXME: Add a flag to the checker where allocations are assumed to
2834      // *not* fail. (The code below is out-of-date, though.)
2835#if 0
2836      if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2837        bool isFeasible;
2838        state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2839        assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2840      }
2841#endif
2842
2843      break;
2844    }
2845
2846    case RetEffect::GCNotOwnedSymbol:
2847    case RetEffect::ARCNotOwnedSymbol:
2848    case RetEffect::NotOwnedSymbol: {
2849      const Expr *Ex = CallOrMsg.getOriginExpr();
2850      SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
2851      if (!Sym)
2852        break;
2853
2854      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2855      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2856      state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2857                                                             ResultTy));
2858      break;
2859    }
2860  }
2861
2862  // This check is actually necessary; otherwise the statement builder thinks
2863  // we've hit a previously-found path.
2864  // Normally addTransition takes care of this, but we want the node pointer.
2865  ExplodedNode *NewNode;
2866  if (state == C.getState()) {
2867    NewNode = C.getPredecessor();
2868  } else {
2869    NewNode = C.addTransition(state);
2870  }
2871
2872  // Annotate the node with summary we used.
2873  if (NewNode) {
2874    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2875    if (ShouldResetSummaryLog) {
2876      SummaryLog.clear();
2877      ShouldResetSummaryLog = false;
2878    }
2879    SummaryLog[NewNode] = &Summ;
2880  }
2881}
2882
2883
2884ProgramStateRef
2885RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2886                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2887                                 CheckerContext &C) const {
2888  // In GC mode [... release] and [... retain] do nothing.
2889  // In ARC mode they shouldn't exist at all, but we just ignore them.
2890  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2891  if (!IgnoreRetainMsg)
2892    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2893
2894  switch (E) {
2895  default:
2896    break;
2897  case IncRefMsg:
2898    E = IgnoreRetainMsg ? DoNothing : IncRef;
2899    break;
2900  case DecRefMsg:
2901    E = IgnoreRetainMsg ? DoNothing : DecRef;
2902    break;
2903  case DecRefMsgAndStopTracking:
2904    E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2905    break;
2906  case MakeCollectable:
2907    E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2908    break;
2909  case NewAutoreleasePool:
2910    E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2911    break;
2912  }
2913
2914  // Handle all use-after-releases.
2915  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2916    V = V ^ RefVal::ErrorUseAfterRelease;
2917    hasErr = V.getKind();
2918    return setRefBinding(state, sym, V);
2919  }
2920
2921  switch (E) {
2922    case DecRefMsg:
2923    case IncRefMsg:
2924    case MakeCollectable:
2925    case DecRefMsgAndStopTracking:
2926      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2927
2928    case Dealloc:
2929      // Any use of -dealloc in GC is *bad*.
2930      if (C.isObjCGCEnabled()) {
2931        V = V ^ RefVal::ErrorDeallocGC;
2932        hasErr = V.getKind();
2933        break;
2934      }
2935
2936      switch (V.getKind()) {
2937        default:
2938          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2939        case RefVal::Owned:
2940          // The object immediately transitions to the released state.
2941          V = V ^ RefVal::Released;
2942          V.clearCounts();
2943          return setRefBinding(state, sym, V);
2944        case RefVal::NotOwned:
2945          V = V ^ RefVal::ErrorDeallocNotOwned;
2946          hasErr = V.getKind();
2947          break;
2948      }
2949      break;
2950
2951    case NewAutoreleasePool:
2952      assert(!C.isObjCGCEnabled());
2953      return state;
2954
2955    case MayEscape:
2956      if (V.getKind() == RefVal::Owned) {
2957        V = V ^ RefVal::NotOwned;
2958        break;
2959      }
2960
2961      // Fall-through.
2962
2963    case DoNothing:
2964      return state;
2965
2966    case Autorelease:
2967      if (C.isObjCGCEnabled())
2968        return state;
2969      // Update the autorelease counts.
2970      V = V.autorelease();
2971      break;
2972
2973    case StopTracking:
2974      return removeRefBinding(state, sym);
2975
2976    case IncRef:
2977      switch (V.getKind()) {
2978        default:
2979          llvm_unreachable("Invalid RefVal state for a retain.");
2980        case RefVal::Owned:
2981        case RefVal::NotOwned:
2982          V = V + 1;
2983          break;
2984        case RefVal::Released:
2985          // Non-GC cases are handled above.
2986          assert(C.isObjCGCEnabled());
2987          V = (V ^ RefVal::Owned) + 1;
2988          break;
2989      }
2990      break;
2991
2992    case DecRef:
2993    case DecRefBridgedTransfered:
2994    case DecRefAndStopTracking:
2995      switch (V.getKind()) {
2996        default:
2997          // case 'RefVal::Released' handled above.
2998          llvm_unreachable("Invalid RefVal state for a release.");
2999
3000        case RefVal::Owned:
3001          assert(V.getCount() > 0);
3002          if (V.getCount() == 1)
3003            V = V ^ (E == DecRefBridgedTransfered ?
3004                      RefVal::NotOwned : RefVal::Released);
3005          else if (E == DecRefAndStopTracking)
3006            return removeRefBinding(state, sym);
3007
3008          V = V - 1;
3009          break;
3010
3011        case RefVal::NotOwned:
3012          if (V.getCount() > 0) {
3013            if (E == DecRefAndStopTracking)
3014              return removeRefBinding(state, sym);
3015            V = V - 1;
3016          } else {
3017            V = V ^ RefVal::ErrorReleaseNotOwned;
3018            hasErr = V.getKind();
3019          }
3020          break;
3021
3022        case RefVal::Released:
3023          // Non-GC cases are handled above.
3024          assert(C.isObjCGCEnabled());
3025          V = V ^ RefVal::ErrorUseAfterRelease;
3026          hasErr = V.getKind();
3027          break;
3028      }
3029      break;
3030  }
3031  return setRefBinding(state, sym, V);
3032}
3033
3034void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3035                                             SourceRange ErrorRange,
3036                                             RefVal::Kind ErrorKind,
3037                                             SymbolRef Sym,
3038                                             CheckerContext &C) const {
3039  ExplodedNode *N = C.generateSink(St);
3040  if (!N)
3041    return;
3042
3043  CFRefBug *BT;
3044  switch (ErrorKind) {
3045    default:
3046      llvm_unreachable("Unhandled error.");
3047    case RefVal::ErrorUseAfterRelease:
3048      if (!useAfterRelease)
3049        useAfterRelease.reset(new UseAfterRelease());
3050      BT = &*useAfterRelease;
3051      break;
3052    case RefVal::ErrorReleaseNotOwned:
3053      if (!releaseNotOwned)
3054        releaseNotOwned.reset(new BadRelease());
3055      BT = &*releaseNotOwned;
3056      break;
3057    case RefVal::ErrorDeallocGC:
3058      if (!deallocGC)
3059        deallocGC.reset(new DeallocGC());
3060      BT = &*deallocGC;
3061      break;
3062    case RefVal::ErrorDeallocNotOwned:
3063      if (!deallocNotOwned)
3064        deallocNotOwned.reset(new DeallocNotOwned());
3065      BT = &*deallocNotOwned;
3066      break;
3067  }
3068
3069  assert(BT);
3070  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3071                                        C.isObjCGCEnabled(), SummaryLog,
3072                                        N, Sym);
3073  report->addRange(ErrorRange);
3074  C.EmitReport(report);
3075}
3076
3077//===----------------------------------------------------------------------===//
3078// Handle the return values of retain-count-related functions.
3079//===----------------------------------------------------------------------===//
3080
3081bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3082  // Get the callee. We're only interested in simple C functions.
3083  ProgramStateRef state = C.getState();
3084  const FunctionDecl *FD = C.getCalleeDecl(CE);
3085  if (!FD)
3086    return false;
3087
3088  IdentifierInfo *II = FD->getIdentifier();
3089  if (!II)
3090    return false;
3091
3092  // For now, we're only handling the functions that return aliases of their
3093  // arguments: CFRetain and CFMakeCollectable (and their families).
3094  // Eventually we should add other functions we can model entirely,
3095  // such as CFRelease, which don't invalidate their arguments or globals.
3096  if (CE->getNumArgs() != 1)
3097    return false;
3098
3099  // Get the name of the function.
3100  StringRef FName = II->getName();
3101  FName = FName.substr(FName.find_first_not_of('_'));
3102
3103  // See if it's one of the specific functions we know how to eval.
3104  bool canEval = false;
3105
3106  QualType ResultTy = CE->getCallReturnType();
3107  if (ResultTy->isObjCIdType()) {
3108    // Handle: id NSMakeCollectable(CFTypeRef)
3109    canEval = II->isStr("NSMakeCollectable");
3110  } else if (ResultTy->isPointerType()) {
3111    // Handle: (CF|CG)Retain
3112    //         CFMakeCollectable
3113    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3114    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3115        cocoa::isRefType(ResultTy, "CG", FName)) {
3116      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3117    }
3118  }
3119
3120  if (!canEval)
3121    return false;
3122
3123  // Bind the return value.
3124  const LocationContext *LCtx = C.getLocationContext();
3125  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3126  if (RetVal.isUnknown()) {
3127    // If the receiver is unknown, conjure a return value.
3128    SValBuilder &SVB = C.getSValBuilder();
3129    unsigned Count = C.getCurrentBlockCount();
3130    RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
3131  }
3132  state = state->BindExpr(CE, LCtx, RetVal, false);
3133
3134  // FIXME: This should not be necessary, but otherwise the argument seems to be
3135  // considered alive during the next statement.
3136  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3137    // Save the refcount status of the argument.
3138    SymbolRef Sym = RetVal.getAsLocSymbol();
3139    const RefVal *Binding = 0;
3140    if (Sym)
3141      Binding = getRefBinding(state, Sym);
3142
3143    // Invalidate the argument region.
3144    unsigned Count = C.getCurrentBlockCount();
3145    state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
3146
3147    // Restore the refcount status of the argument.
3148    if (Binding)
3149      state = setRefBinding(state, Sym, *Binding);
3150  }
3151
3152  C.addTransition(state);
3153  return true;
3154}
3155
3156//===----------------------------------------------------------------------===//
3157// Handle return statements.
3158//===----------------------------------------------------------------------===//
3159
3160// Return true if the current LocationContext has no caller context.
3161static bool inTopFrame(CheckerContext &C) {
3162  const LocationContext *LC = C.getLocationContext();
3163  return LC->getParent() == 0;
3164}
3165
3166void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3167                                      CheckerContext &C) const {
3168
3169  // Only adjust the reference count if this is the top-level call frame,
3170  // and not the result of inlining.  In the future, we should do
3171  // better checking even for inlined calls, and see if they match
3172  // with their expected semantics (e.g., the method should return a retained
3173  // object, etc.).
3174  if (!inTopFrame(C))
3175    return;
3176
3177  const Expr *RetE = S->getRetValue();
3178  if (!RetE)
3179    return;
3180
3181  ProgramStateRef state = C.getState();
3182  SymbolRef Sym =
3183    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3184  if (!Sym)
3185    return;
3186
3187  // Get the reference count binding (if any).
3188  const RefVal *T = getRefBinding(state, Sym);
3189  if (!T)
3190    return;
3191
3192  // Change the reference count.
3193  RefVal X = *T;
3194
3195  switch (X.getKind()) {
3196    case RefVal::Owned: {
3197      unsigned cnt = X.getCount();
3198      assert(cnt > 0);
3199      X.setCount(cnt - 1);
3200      X = X ^ RefVal::ReturnedOwned;
3201      break;
3202    }
3203
3204    case RefVal::NotOwned: {
3205      unsigned cnt = X.getCount();
3206      if (cnt) {
3207        X.setCount(cnt - 1);
3208        X = X ^ RefVal::ReturnedOwned;
3209      }
3210      else {
3211        X = X ^ RefVal::ReturnedNotOwned;
3212      }
3213      break;
3214    }
3215
3216    default:
3217      return;
3218  }
3219
3220  // Update the binding.
3221  state = setRefBinding(state, Sym, X);
3222  ExplodedNode *Pred = C.addTransition(state);
3223
3224  // At this point we have updated the state properly.
3225  // Everything after this is merely checking to see if the return value has
3226  // been over- or under-retained.
3227
3228  // Did we cache out?
3229  if (!Pred)
3230    return;
3231
3232  // Update the autorelease counts.
3233  static SimpleProgramPointTag
3234         AutoreleaseTag("RetainCountChecker : Autorelease");
3235  GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
3236  llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
3237
3238  // Did we cache out?
3239  if (!Pred)
3240    return;
3241
3242  // Get the updated binding.
3243  T = getRefBinding(state, Sym);
3244  assert(T);
3245  X = *T;
3246
3247  // Consult the summary of the enclosing method.
3248  RetainSummaryManager &Summaries = getSummaryManager(C);
3249  const Decl *CD = &Pred->getCodeDecl();
3250  RetEffect RE = RetEffect::MakeNoRet();
3251
3252  // FIXME: What is the convention for blocks? Is there one?
3253  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3254    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3255    RE = Summ->getRetEffect();
3256  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3257    if (!isa<CXXMethodDecl>(FD)) {
3258      const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3259      RE = Summ->getRetEffect();
3260    }
3261  }
3262
3263  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3264}
3265
3266void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3267                                                  CheckerContext &C,
3268                                                  ExplodedNode *Pred,
3269                                                  RetEffect RE, RefVal X,
3270                                                  SymbolRef Sym,
3271                                              ProgramStateRef state) const {
3272  // Any leaks or other errors?
3273  if (X.isReturnedOwned() && X.getCount() == 0) {
3274    if (RE.getKind() != RetEffect::NoRet) {
3275      bool hasError = false;
3276      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3277        // Things are more complicated with garbage collection.  If the
3278        // returned object is suppose to be an Objective-C object, we have
3279        // a leak (as the caller expects a GC'ed object) because no
3280        // method should return ownership unless it returns a CF object.
3281        hasError = true;
3282        X = X ^ RefVal::ErrorGCLeakReturned;
3283      }
3284      else if (!RE.isOwned()) {
3285        // Either we are using GC and the returned object is a CF type
3286        // or we aren't using GC.  In either case, we expect that the
3287        // enclosing method is expected to return ownership.
3288        hasError = true;
3289        X = X ^ RefVal::ErrorLeakReturned;
3290      }
3291
3292      if (hasError) {
3293        // Generate an error node.
3294        state = setRefBinding(state, Sym, X);
3295
3296        static SimpleProgramPointTag
3297               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3298        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3299        if (N) {
3300          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3301          bool GCEnabled = C.isObjCGCEnabled();
3302          CFRefReport *report =
3303            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3304                                LOpts, GCEnabled, SummaryLog,
3305                                N, Sym, C);
3306          C.EmitReport(report);
3307        }
3308      }
3309    }
3310  } else if (X.isReturnedNotOwned()) {
3311    if (RE.isOwned()) {
3312      // Trying to return a not owned object to a caller expecting an
3313      // owned object.
3314      state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3315
3316      static SimpleProgramPointTag
3317             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3318      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3319      if (N) {
3320        if (!returnNotOwnedForOwned)
3321          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3322
3323        CFRefReport *report =
3324            new CFRefReport(*returnNotOwnedForOwned,
3325                            C.getASTContext().getLangOpts(),
3326                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3327        C.EmitReport(report);
3328      }
3329    }
3330  }
3331}
3332
3333//===----------------------------------------------------------------------===//
3334// Check various ways a symbol can be invalidated.
3335//===----------------------------------------------------------------------===//
3336
3337void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3338                                   CheckerContext &C) const {
3339  // Are we storing to something that causes the value to "escape"?
3340  bool escapes = true;
3341
3342  // A value escapes in three possible cases (this may change):
3343  //
3344  // (1) we are binding to something that is not a memory region.
3345  // (2) we are binding to a memregion that does not have stack storage
3346  // (3) we are binding to a memregion with stack storage that the store
3347  //     does not understand.
3348  ProgramStateRef state = C.getState();
3349
3350  if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3351    escapes = !regionLoc->getRegion()->hasStackStorage();
3352
3353    if (!escapes) {
3354      // To test (3), generate a new state with the binding added.  If it is
3355      // the same state, then it escapes (since the store cannot represent
3356      // the binding).
3357      // Do this only if we know that the store is not supposed to generate the
3358      // same state.
3359      SVal StoredVal = state->getSVal(regionLoc->getRegion());
3360      if (StoredVal != val)
3361        escapes = (state == (state->bindLoc(*regionLoc, val)));
3362    }
3363    if (!escapes) {
3364      // Case 4: We do not currently model what happens when a symbol is
3365      // assigned to a struct field, so be conservative here and let the symbol
3366      // go. TODO: This could definitely be improved upon.
3367      escapes = !isa<VarRegion>(regionLoc->getRegion());
3368    }
3369  }
3370
3371  // If our store can represent the binding and we aren't storing to something
3372  // that doesn't have local storage then just return and have the simulation
3373  // state continue as is.
3374  if (!escapes)
3375      return;
3376
3377  // Otherwise, find all symbols referenced by 'val' that we are tracking
3378  // and stop tracking them.
3379  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3380  C.addTransition(state);
3381}
3382
3383ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3384                                                   SVal Cond,
3385                                                   bool Assumption) const {
3386
3387  // FIXME: We may add to the interface of evalAssume the list of symbols
3388  //  whose assumptions have changed.  For now we just iterate through the
3389  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3390  //  too bad since the number of symbols we will track in practice are
3391  //  probably small and evalAssume is only called at branches and a few
3392  //  other places.
3393  RefBindings B = state->get<RefBindings>();
3394
3395  if (B.isEmpty())
3396    return state;
3397
3398  bool changed = false;
3399  RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3400
3401  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3402    // Check if the symbol is null (or equal to any constant).
3403    // If this is the case, stop tracking the symbol.
3404    if (state->getSymVal(I.getKey())) {
3405      changed = true;
3406      B = RefBFactory.remove(B, I.getKey());
3407    }
3408  }
3409
3410  if (changed)
3411    state = state->set<RefBindings>(B);
3412
3413  return state;
3414}
3415
3416ProgramStateRef
3417RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3418                            const StoreManager::InvalidatedSymbols *invalidated,
3419                                    ArrayRef<const MemRegion *> ExplicitRegions,
3420                                    ArrayRef<const MemRegion *> Regions,
3421                                    const CallEvent *Call) const {
3422  if (!invalidated)
3423    return state;
3424
3425  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3426  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3427       E = ExplicitRegions.end(); I != E; ++I) {
3428    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3429      WhitelistedSymbols.insert(SR->getSymbol());
3430  }
3431
3432  for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3433       E = invalidated->end(); I!=E; ++I) {
3434    SymbolRef sym = *I;
3435    if (WhitelistedSymbols.count(sym))
3436      continue;
3437    // Remove any existing reference-count binding.
3438    state = removeRefBinding(state, sym);
3439  }
3440  return state;
3441}
3442
3443//===----------------------------------------------------------------------===//
3444// Handle dead symbols and end-of-path.
3445//===----------------------------------------------------------------------===//
3446
3447std::pair<ExplodedNode *, ProgramStateRef >
3448RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3449                                            GenericNodeBuilderRefCount Bd,
3450                                            ExplodedNode *Pred,
3451                                            CheckerContext &Ctx,
3452                                            SymbolRef Sym, RefVal V) const {
3453  unsigned ACnt = V.getAutoreleaseCount();
3454
3455  // No autorelease counts?  Nothing to be done.
3456  if (!ACnt)
3457    return std::make_pair(Pred, state);
3458
3459  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3460  unsigned Cnt = V.getCount();
3461
3462  // FIXME: Handle sending 'autorelease' to already released object.
3463
3464  if (V.getKind() == RefVal::ReturnedOwned)
3465    ++Cnt;
3466
3467  if (ACnt <= Cnt) {
3468    if (ACnt == Cnt) {
3469      V.clearCounts();
3470      if (V.getKind() == RefVal::ReturnedOwned)
3471        V = V ^ RefVal::ReturnedNotOwned;
3472      else
3473        V = V ^ RefVal::NotOwned;
3474    } else {
3475      V.setCount(Cnt - ACnt);
3476      V.setAutoreleaseCount(0);
3477    }
3478    state = setRefBinding(state, Sym, V);
3479    ExplodedNode *N = Bd.MakeNode(state, Pred);
3480    if (N == 0)
3481      state = 0;
3482    return std::make_pair(N, state);
3483  }
3484
3485  // Woah!  More autorelease counts then retain counts left.
3486  // Emit hard error.
3487  V = V ^ RefVal::ErrorOverAutorelease;
3488  state = setRefBinding(state, Sym, V);
3489
3490  if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
3491    SmallString<128> sbuf;
3492    llvm::raw_svector_ostream os(sbuf);
3493    os << "Object over-autoreleased: object was sent -autorelease ";
3494    if (V.getAutoreleaseCount() > 1)
3495      os << V.getAutoreleaseCount() << " times ";
3496    os << "but the object has a +" << V.getCount() << " retain count";
3497
3498    if (!overAutorelease)
3499      overAutorelease.reset(new OverAutorelease());
3500
3501    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3502    CFRefReport *report =
3503      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3504                      SummaryLog, N, Sym, os.str());
3505    Ctx.EmitReport(report);
3506  }
3507
3508  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
3509}
3510
3511ProgramStateRef
3512RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3513                                      SymbolRef sid, RefVal V,
3514                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3515  bool hasLeak = false;
3516  if (V.isOwned())
3517    hasLeak = true;
3518  else if (V.isNotOwned() || V.isReturnedOwned())
3519    hasLeak = (V.getCount() > 0);
3520
3521  if (!hasLeak)
3522    return removeRefBinding(state, sid);
3523
3524  Leaked.push_back(sid);
3525  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3526}
3527
3528ExplodedNode *
3529RetainCountChecker::processLeaks(ProgramStateRef state,
3530                                 SmallVectorImpl<SymbolRef> &Leaked,
3531                                 GenericNodeBuilderRefCount &Builder,
3532                                 CheckerContext &Ctx,
3533                                 ExplodedNode *Pred) const {
3534  if (Leaked.empty())
3535    return Pred;
3536
3537  // Generate an intermediate node representing the leak point.
3538  ExplodedNode *N = Builder.MakeNode(state, Pred);
3539
3540  if (N) {
3541    for (SmallVectorImpl<SymbolRef>::iterator
3542         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3543
3544      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3545      bool GCEnabled = Ctx.isObjCGCEnabled();
3546      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3547                          : getLeakAtReturnBug(LOpts, GCEnabled);
3548      assert(BT && "BugType not initialized.");
3549
3550      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3551                                                    SummaryLog, N, *I, Ctx);
3552      Ctx.EmitReport(report);
3553    }
3554  }
3555
3556  return N;
3557}
3558
3559void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
3560  ProgramStateRef state = Ctx.getState();
3561  GenericNodeBuilderRefCount Bd(Ctx);
3562  RefBindings B = state->get<RefBindings>();
3563  ExplodedNode *Pred = Ctx.getPredecessor();
3564
3565  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3566    llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
3567                                                     I->first, I->second);
3568    if (!state)
3569      return;
3570  }
3571
3572  // If the current LocationContext has a parent, don't check for leaks.
3573  // We will do that later.
3574  // FIXME: we should instead check for imbalances of the retain/releases,
3575  // and suggest annotations.
3576  if (Ctx.getLocationContext()->getParent())
3577    return;
3578
3579  B = state->get<RefBindings>();
3580  SmallVector<SymbolRef, 10> Leaked;
3581
3582  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3583    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3584
3585  processLeaks(state, Leaked, Bd, Ctx, Pred);
3586}
3587
3588const ProgramPointTag *
3589RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3590  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3591  if (!tag) {
3592    SmallString<64> buf;
3593    llvm::raw_svector_ostream out(buf);
3594    out << "RetainCountChecker : Dead Symbol : ";
3595    sym->dumpToStream(out);
3596    tag = new SimpleProgramPointTag(out.str());
3597  }
3598  return tag;
3599}
3600
3601void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3602                                          CheckerContext &C) const {
3603  ExplodedNode *Pred = C.getPredecessor();
3604
3605  ProgramStateRef state = C.getState();
3606  RefBindings B = state->get<RefBindings>();
3607
3608  // Update counts from autorelease pools
3609  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3610       E = SymReaper.dead_end(); I != E; ++I) {
3611    SymbolRef Sym = *I;
3612    if (const RefVal *T = B.lookup(Sym)){
3613      // Use the symbol as the tag.
3614      // FIXME: This might not be as unique as we would like.
3615      GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
3616      llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
3617                                                       Sym, *T);
3618      if (!state)
3619        return;
3620    }
3621  }
3622
3623  B = state->get<RefBindings>();
3624  SmallVector<SymbolRef, 10> Leaked;
3625
3626  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3627       E = SymReaper.dead_end(); I != E; ++I) {
3628    if (const RefVal *T = B.lookup(*I))
3629      state = handleSymbolDeath(state, *I, *T, Leaked);
3630  }
3631
3632  {
3633    GenericNodeBuilderRefCount Bd(C, this);
3634    Pred = processLeaks(state, Leaked, Bd, C, Pred);
3635  }
3636
3637  // Did we cache out?
3638  if (!Pred)
3639    return;
3640
3641  // Now generate a new node that nukes the old bindings.
3642  RefBindings::Factory &F = state->get_context<RefBindings>();
3643
3644  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3645       E = SymReaper.dead_end(); I != E; ++I)
3646    B = F.remove(B, *I);
3647
3648  state = state->set<RefBindings>(B);
3649  C.addTransition(state, Pred);
3650}
3651
3652void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3653                                    const char *NL, const char *Sep) const {
3654
3655  RefBindings B = State->get<RefBindings>();
3656
3657  if (!B.isEmpty())
3658    Out << Sep << NL;
3659
3660  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3661    Out << I->first << " : ";
3662    I->second.print(Out);
3663    Out << NL;
3664  }
3665}
3666
3667//===----------------------------------------------------------------------===//
3668// Checker registration.
3669//===----------------------------------------------------------------------===//
3670
3671void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3672  Mgr.registerChecker<RetainCountChecker>();
3673}
3674
3675