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