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