blob: d1d68fc45fc7c1fd5497ecda8811ff193144190c [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
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//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000018#include "clang/Analysis/PathSensitive/ValueState.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000027#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000028#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000029#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000030#include <ostream>
Ted Kremeneka8503952008-04-18 04:55:01 +000031#include <sstream>
Ted Kremenek827f93b2008-03-06 00:08:09 +000032
33using namespace clang;
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000034using llvm::CStrInCStrNoCase;
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
Ted Kremenek7d421f32008-04-09 23:49:11 +000036//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +000037// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +000038//===----------------------------------------------------------------------===//
39
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +000040static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +000041 IdentifierInfo* II = &Ctx.Idents.get(name);
42 return Ctx.Selectors.getSelector(0, &II);
43}
44
Ted Kremenek0e344d42008-05-06 00:30:21 +000045static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
46 IdentifierInfo* II = &Ctx.Idents.get(name);
47 return Ctx.Selectors.getSelector(1, &II);
48}
49
Ted Kremenek272aa852008-06-25 21:21:56 +000050//===----------------------------------------------------------------------===//
51// Type querying functions.
52//===----------------------------------------------------------------------===//
53
Ted Kremenek62820d82008-05-07 20:06:41 +000054static bool isCFRefType(QualType T) {
55
56 if (!T->isPointerType())
57 return false;
58
Ted Kremenek272aa852008-06-25 21:21:56 +000059 // Check the typedef for the name "CF" and the substring "Ref".
Ted Kremenek62820d82008-05-07 20:06:41 +000060 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
61
62 if (!TD)
63 return false;
64
65 const char* TDName = TD->getDecl()->getIdentifier()->getName();
66 assert (TDName);
67
68 if (TDName[0] != 'C' || TDName[1] != 'F')
69 return false;
70
71 if (strstr(TDName, "Ref") == 0)
72 return false;
73
74 return true;
75}
76
Ted Kremenek4c5378c2008-07-15 16:50:12 +000077static bool isCGRefType(QualType T) {
78
79 if (!T->isPointerType())
80 return false;
81
82 // Check the typedef for the name "CG" and the substring "Ref".
83 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
84
85 if (!TD)
86 return false;
87
88 const char* TDName = TD->getDecl()->getIdentifier()->getName();
89 assert (TDName);
90
91 if (TDName[0] != 'C' || TDName[1] != 'G')
92 return false;
93
94 if (strstr(TDName, "Ref") == 0)
95 return false;
96
97 return true;
98}
99
Ted Kremenek62820d82008-05-07 20:06:41 +0000100static bool isNSType(QualType T) {
101
102 if (!T->isPointerType())
103 return false;
104
105 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
106
107 if (!OT)
108 return false;
109
110 const char* ClsName = OT->getDecl()->getIdentifier()->getName();
111 assert (ClsName);
112
113 if (ClsName[0] != 'N' || ClsName[1] != 'S')
114 return false;
115
116 return true;
117}
118
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000119//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000120// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000121//===----------------------------------------------------------------------===//
122
Ted Kremenek272aa852008-06-25 21:21:56 +0000123namespace {
124/// ArgEffect is used to summarize a function/method call's effect on a
125/// particular argument.
Ted Kremenekede40b72008-07-09 18:11:16 +0000126enum ArgEffect { IncRef, DecRef, DoNothing, DoNothingByRef,
127 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-06-25 21:21:56 +0000128
129/// ArgEffects summarizes the effects of a function/method call on all of
130/// its arguments.
131typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000132}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000133
Ted Kremeneka7338b42008-03-11 06:39:11 +0000134namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000135template <> struct FoldingSetTrait<ArgEffects> {
136 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
137 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
138 ID.AddInteger(I->first);
139 ID.AddInteger((unsigned) I->second);
140 }
141 }
142};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000143} // end llvm namespace
144
145namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000146
147/// RetEffect is used to summarize a function/method call's behavior with
148/// respect to its return value.
149class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000150public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000151 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
152 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek272aa852008-06-25 21:21:56 +0000153
Ted Kremeneka7338b42008-03-11 06:39:11 +0000154private:
155 unsigned Data;
Ted Kremenek272aa852008-06-25 21:21:56 +0000156 RetEffect(Kind k, unsigned D = 0) { Data = (D << 3) | (unsigned) k; }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000157
Ted Kremeneka7338b42008-03-11 06:39:11 +0000158public:
Ted Kremenek272aa852008-06-25 21:21:56 +0000159
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000160 Kind getKind() const { return (Kind) (Data & 0x7); }
Ted Kremenek272aa852008-06-25 21:21:56 +0000161
162 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000163 assert(getKind() == Alias);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000164 return Data >> 3;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000165 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000166
Ted Kremenek272aa852008-06-25 21:21:56 +0000167 static RetEffect MakeAlias(unsigned Idx) {
168 return RetEffect(Alias, Idx);
169 }
170 static RetEffect MakeReceiverAlias() {
171 return RetEffect(ReceiverAlias);
172 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000173 static RetEffect MakeOwned(bool isAllocated = false) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000174 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol);
175 }
176 static RetEffect MakeNotOwned() {
177 return RetEffect(NotOwnedSymbol);
178 }
179 static RetEffect MakeNoRet() {
180 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000181 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000182
Ted Kremenek272aa852008-06-25 21:21:56 +0000183 operator Kind() const {
184 return getKind();
185 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000186
Ted Kremenek272aa852008-06-25 21:21:56 +0000187 void Profile(llvm::FoldingSetNodeID& ID) const {
188 ID.AddInteger(Data);
189 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000190};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000191
Ted Kremenek272aa852008-06-25 21:21:56 +0000192
193class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000194 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
195 /// specifies the argument (starting from 0). This can be sparsely
196 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000197 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000198
199 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
200 /// do not have an entry in Args.
201 ArgEffect DefaultArgEffect;
202
Ted Kremenek272aa852008-06-25 21:21:56 +0000203 /// Receiver - If this summary applies to an Objective-C message expression,
204 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000205 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000206
207 /// Ret - The effect on the return value. Used to indicate if the
208 /// function/method call returns a new tracked symbol, returns an
209 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000210 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000211
Ted Kremenekf2717b02008-07-18 17:24:20 +0000212 /// EndPath - Indicates that execution of this method/function should
213 /// terminate the simulation of a path.
214 bool EndPath;
215
Ted Kremeneka7338b42008-03-11 06:39:11 +0000216public:
217
Ted Kremenekbcaff792008-05-06 15:44:25 +0000218 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000219 ArgEffect ReceiverEff, bool endpath = false)
220 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
221 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000222
Ted Kremenek272aa852008-06-25 21:21:56 +0000223 /// getArg - Return the argument effect on the argument specified by
224 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000225 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000226
Ted Kremenekae855d42008-04-24 17:22:33 +0000227 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000228 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000229
230 // If Args is present, it is likely to contain only 1 element.
231 // Just do a linear search. Do it from the back because functions with
232 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000233 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000234 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
235 I!=E; ++I) {
236
237 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000238 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000239
240 if (idx == I->first)
241 return I->second;
242 }
243
Ted Kremenekbcaff792008-05-06 15:44:25 +0000244 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000245 }
246
Ted Kremenek272aa852008-06-25 21:21:56 +0000247 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000248 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000249 return Ret;
250 }
251
Ted Kremenekf2717b02008-07-18 17:24:20 +0000252 /// isEndPath - Returns true if executing the given method/function should
253 /// terminate the path.
254 bool isEndPath() const { return EndPath; }
255
Ted Kremenek272aa852008-06-25 21:21:56 +0000256 /// getReceiverEffect - Returns the effect on the receiver of the call.
257 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000258 ArgEffect getReceiverEffect() const {
259 return Receiver;
260 }
261
Ted Kremenek2719e982008-06-17 02:43:46 +0000262 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000263
Ted Kremenek2719e982008-06-17 02:43:46 +0000264 ExprIterator begin_args() const { return Args->begin(); }
265 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000266
Ted Kremenek266d8b62008-05-06 02:26:56 +0000267 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000268 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000269 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000271 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000272 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000273 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000274 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275 }
276
277 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000278 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000279 }
280};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000281} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282
Ted Kremenek272aa852008-06-25 21:21:56 +0000283//===----------------------------------------------------------------------===//
284// Data structures for constructing summaries.
285//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000286
Ted Kremenek272aa852008-06-25 21:21:56 +0000287namespace {
288class VISIBILITY_HIDDEN ObjCSummaryKey {
289 IdentifierInfo* II;
290 Selector S;
291public:
292 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
293 : II(ii), S(s) {}
294
295 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
296 : II(d ? d->getIdentifier() : 0), S(s) {}
297
298 ObjCSummaryKey(Selector s)
299 : II(0), S(s) {}
300
301 IdentifierInfo* getIdentifier() const { return II; }
302 Selector getSelector() const { return S; }
303};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000304}
305
306namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000307template <> struct DenseMapInfo<ObjCSummaryKey> {
308 static inline ObjCSummaryKey getEmptyKey() {
309 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
310 DenseMapInfo<Selector>::getEmptyKey());
311 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000312
Ted Kremenek272aa852008-06-25 21:21:56 +0000313 static inline ObjCSummaryKey getTombstoneKey() {
314 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
315 DenseMapInfo<Selector>::getTombstoneKey());
316 }
317
318 static unsigned getHashValue(const ObjCSummaryKey &V) {
319 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
320 & 0x88888888)
321 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
322 & 0x55555555);
323 }
324
325 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
326 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
327 RHS.getIdentifier()) &&
328 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
329 RHS.getSelector());
330 }
331
332 static bool isPod() {
333 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
334 DenseMapInfo<Selector>::isPod();
335 }
336};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000337} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000338
Ted Kremenek84f010c2008-06-23 23:30:29 +0000339namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000340class VISIBILITY_HIDDEN ObjCSummaryCache {
341 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
342 MapTy M;
343public:
344 ObjCSummaryCache() {}
345
346 typedef MapTy::iterator iterator;
347
348 iterator find(ObjCInterfaceDecl* D, Selector S) {
349
350 // Do a lookup with the (D,S) pair. If we find a match return
351 // the iterator.
352 ObjCSummaryKey K(D, S);
353 MapTy::iterator I = M.find(K);
354
355 if (I != M.end() || !D)
356 return I;
357
358 // Walk the super chain. If we find a hit with a parent, we'll end
359 // up returning that summary. We actually allow that key (null,S), as
360 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
361 // generate initial summaries without having to worry about NSObject
362 // being declared.
363 // FIXME: We may change this at some point.
364 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
365 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
366 break;
367
368 if (!C)
369 return I;
370 }
371
372 // Cache the summary with original key to make the next lookup faster
373 // and return the iterator.
374 M[K] = I->second;
375 return I;
376 }
377
378
379 iterator find(Expr* Receiver, Selector S) {
380 return find(getReceiverDecl(Receiver), S);
381 }
382
383 iterator find(IdentifierInfo* II, Selector S) {
384 // FIXME: Class method lookup. Right now we dont' have a good way
385 // of going between IdentifierInfo* and the class hierarchy.
386 iterator I = M.find(ObjCSummaryKey(II, S));
387 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
388 }
389
390 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
391
392 const PointerType* PT = E->getType()->getAsPointerType();
393 if (!PT) return 0;
394
395 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
396 if (!OI) return 0;
397
398 return OI ? OI->getDecl() : 0;
399 }
400
401 iterator end() { return M.end(); }
402
403 RetainSummary*& operator[](ObjCMessageExpr* ME) {
404
405 Selector S = ME->getSelector();
406
407 if (Expr* Receiver = ME->getReceiver()) {
408 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
409 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
410 }
411
412 return M[ObjCSummaryKey(ME->getClassName(), S)];
413 }
414
415 RetainSummary*& operator[](ObjCSummaryKey K) {
416 return M[K];
417 }
418
419 RetainSummary*& operator[](Selector S) {
420 return M[ ObjCSummaryKey(S) ];
421 }
422};
423} // end anonymous namespace
424
425//===----------------------------------------------------------------------===//
426// Data structures for managing collections of summaries.
427//===----------------------------------------------------------------------===//
428
429namespace {
430class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000431
432 //==-----------------------------------------------------------------==//
433 // Typedefs.
434 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000435
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000436 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
437 ArgEffectsSetTy;
438
439 typedef llvm::FoldingSet<RetainSummary>
440 SummarySetTy;
441
442 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
443 FuncSummariesTy;
444
Ted Kremenek84f010c2008-06-23 23:30:29 +0000445 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000446
447 //==-----------------------------------------------------------------==//
448 // Data.
449 //==-----------------------------------------------------------------==//
450
Ted Kremenek272aa852008-06-25 21:21:56 +0000451 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000452 ASTContext& Ctx;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000453
Ted Kremenek272aa852008-06-25 21:21:56 +0000454 /// NSWindowII - An IdentifierInfo* representing the identifier "NSWindow."
455 IdentifierInfo* NSWindowII;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000456
457 /// NSPanelII - An IdentifierInfo* representing the identifier "NSPanel."
458 IdentifierInfo* NSPanelII;
Ted Kremenek272aa852008-06-25 21:21:56 +0000459
Ted Kremenekf2717b02008-07-18 17:24:20 +0000460 /// NSAssertionHandlerII - An IdentifierInfo* representing the identifier
461 // "NSAssertionHandler".
462 IdentifierInfo* NSAssertionHandlerII;
463
Ted Kremenekede40b72008-07-09 18:11:16 +0000464 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
465 /// "CFDictionaryCreate".
466 IdentifierInfo* CFDictionaryCreateII;
467
Ted Kremenek272aa852008-06-25 21:21:56 +0000468 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000469 const bool GCEnabled;
470
Ted Kremenek272aa852008-06-25 21:21:56 +0000471 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000472 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000473
Ted Kremenek272aa852008-06-25 21:21:56 +0000474 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000475 FuncSummariesTy FuncSummaries;
476
Ted Kremenek272aa852008-06-25 21:21:56 +0000477 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
478 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000479 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000480
Ted Kremenek272aa852008-06-25 21:21:56 +0000481 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000482 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000483
Ted Kremenek272aa852008-06-25 21:21:56 +0000484 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000485 ArgEffectsSetTy ArgEffectsSet;
486
Ted Kremenek272aa852008-06-25 21:21:56 +0000487 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
488 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000489 llvm::BumpPtrAllocator BPAlloc;
490
Ted Kremenek272aa852008-06-25 21:21:56 +0000491 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000492 ArgEffects ScratchArgs;
493
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000494 RetainSummary* StopSummary;
495
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000496 //==-----------------------------------------------------------------==//
497 // Methods.
498 //==-----------------------------------------------------------------==//
499
Ted Kremenek272aa852008-06-25 21:21:56 +0000500 /// getArgEffects - Returns a persistent ArgEffects object based on the
501 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000502 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000503
Ted Kremenek562c1302008-05-05 16:51:50 +0000504 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000505 RetainSummary* getUnarySummary(FunctionDecl* FD, UnaryFuncKind func);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000506
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000507 RetainSummary* getNSSummary(FunctionDecl* FD, const char* FName);
508 RetainSummary* getCFSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000509 RetainSummary* getCGSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000510
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000511 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
512 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000513 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000514
Ted Kremenek266d8b62008-05-06 02:26:56 +0000515 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000516 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000517 ArgEffect DefaultEff = MayEscape,
518 bool isEndPath = false);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000519
Ted Kremenek0e344d42008-05-06 00:30:21 +0000520
Ted Kremenek266d8b62008-05-06 02:26:56 +0000521 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000522 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000523 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000524 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000525 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000526
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000527
Ted Kremenekbcaff792008-05-06 15:44:25 +0000528 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000529 if (StopSummary)
530 return StopSummary;
531
532 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
533 StopTracking, StopTracking);
534
535 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000536 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000537
Ted Kremenek272aa852008-06-25 21:21:56 +0000538 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000539
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000540 void InitializeClassMethodSummaries();
541 void InitializeMethodSummaries();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000542
543 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
544 RetainSummary* Summ) {
545 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
546 }
547
Ted Kremenek272aa852008-06-25 21:21:56 +0000548 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
549 ObjCClassMethodSummaries[S] = Summ;
550 }
551
552 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
553 ObjCMethodSummaries[S] = Summ;
554 }
555
556 void addNSWindowMethSummary(Selector S, RetainSummary *Summ) {
557 ObjCMethodSummaries[ObjCSummaryKey(NSWindowII, S)] = Summ;
558 }
559
Ted Kremeneke44927e2008-07-01 17:21:27 +0000560 void addNSPanelMethSummary(Selector S, RetainSummary *Summ) {
561 ObjCMethodSummaries[ObjCSummaryKey(NSPanelII, S)] = Summ;
562 }
563
Ted Kremenekf2717b02008-07-18 17:24:20 +0000564 void addPanicSummary(IdentifierInfo* ClsII, Selector S) {
565 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
566 DoNothing, DoNothing, true);
567
568 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
569 }
570
Ted Kremeneka7338b42008-03-11 06:39:11 +0000571public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000572
573 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000574 : Ctx(ctx),
575 NSWindowII(&ctx.Idents.get("NSWindow")),
576 NSPanelII(&ctx.Idents.get("NSPanel")),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000577 NSAssertionHandlerII(&ctx.Idents.get("NSAssertionHandler")),
Ted Kremenekede40b72008-07-09 18:11:16 +0000578 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000579 GCEnabled(gcenabled), StopSummary(0) {
580
581 InitializeClassMethodSummaries();
582 InitializeMethodSummaries();
583 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000584
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000586
Ted Kremenekd13c1872008-06-24 03:56:45 +0000587 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000588 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000589 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000590
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000591 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000592};
593
594} // end anonymous namespace
595
596//===----------------------------------------------------------------------===//
597// Implementation of checker data structures.
598//===----------------------------------------------------------------------===//
599
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000600RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000601
602 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
603 // mitigating the need to do explicit cleanup of the
604 // Argument-Effect summaries.
605
Ted Kremenek42ea0322008-05-05 23:55:01 +0000606 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
607 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000608 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000609}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000610
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000611ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremenekae855d42008-04-24 17:22:33 +0000613 if (ScratchArgs.empty())
614 return NULL;
615
616 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000617 llvm::FoldingSetNodeID profile;
618 profile.Add(ScratchArgs);
619 void* InsertPos;
620
Ted Kremenekae855d42008-04-24 17:22:33 +0000621 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000622 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000623 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000624
Ted Kremenekae855d42008-04-24 17:22:33 +0000625 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000626 ScratchArgs.clear();
627 return &E->getValue();
628 }
629
630 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000631 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000632
633 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000634 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000635
636 ScratchArgs.clear();
637 return &E->getValue();
638}
639
Ted Kremenek266d8b62008-05-06 02:26:56 +0000640RetainSummary*
641RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000642 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000643 ArgEffect DefaultEff,
644 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000645
Ted Kremenekae855d42008-04-24 17:22:33 +0000646 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000647 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000648 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
649 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000650
Ted Kremenekae855d42008-04-24 17:22:33 +0000651 // Look up the uniqued summary, or create one if it doesn't exist.
652 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000653 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000654
655 if (Summ)
656 return Summ;
657
Ted Kremenekae855d42008-04-24 17:22:33 +0000658 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000659 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000660 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000661 SummarySet.InsertNode(Summ, InsertPos);
662
663 return Summ;
664}
665
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000666//===----------------------------------------------------------------------===//
667// Summary creation for functions (largely uses of Core Foundation).
668//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000669
Ted Kremenekd13c1872008-06-24 03:56:45 +0000670RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000671
672 SourceLocation Loc = FD->getLocation();
673
674 if (!Loc.isFileID())
675 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000676
Ted Kremenekae855d42008-04-24 17:22:33 +0000677 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000678 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000679
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000680 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000681 return I->second;
682
683 // No summary. Generate one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000684 const char* FName = FD->getIdentifier()->getName();
685
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000686 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000687
Ted Kremenek62820d82008-05-07 20:06:41 +0000688 FunctionType* FT = dyn_cast<FunctionType>(FD->getType());
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000689
690 do {
691 if (FT) {
692
693 QualType T = FT->getResultType();
694
695 if (isCFRefType(T)) {
696 S = getCFSummary(FD, FName);
697 break;
698 }
699
700 if (isCGRefType(T)) {
701 S = getCGSummary(FD, FName );
702 break;
703 }
704 }
705
706 if (FName[0] == 'C' && FName[1] == 'F')
707 S = getCFSummary(FD, FName);
708 else if (FName[0] == 'N' && FName[1] == 'S')
709 S = getNSSummary(FD, FName);
710 }
711 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000712
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000713 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000714 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000715}
716
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000717RetainSummary* RetainSummaryManager::getNSSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000718 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000719 FName += 2;
720
721 if (strcmp(FName, "MakeCollectable") == 0)
722 return getUnarySummary(FD, cfmakecollectable);
723
724 return 0;
725}
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000726
727static bool isRetain(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000728 const char* loc = strstr(FName, "Retain");
729 return loc && loc[sizeof("Retain")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000730}
731
732static bool isRelease(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000733 const char* loc = strstr(FName, "Release");
734 return loc && loc[sizeof("Release")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000735}
736
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000737RetainSummary* RetainSummaryManager::getCFSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000738 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000739
Ted Kremenek62820d82008-05-07 20:06:41 +0000740 if (FName[0] == 'C' && FName[1] == 'F')
741 FName += 2;
Ted Kremenek562c1302008-05-05 16:51:50 +0000742
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000743 if (isRetain(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000744 return getUnarySummary(FD, cfretain);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000745
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000746 if (isRelease(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000747 return getUnarySummary(FD, cfrelease);
Ted Kremenekede40b72008-07-09 18:11:16 +0000748
Ted Kremenek562c1302008-05-05 16:51:50 +0000749 if (strcmp(FName, "MakeCollectable") == 0)
750 return getUnarySummary(FD, cfmakecollectable);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000751
752 return getCFCreateGetRuleSummary(FD, FName);
753}
754
755RetainSummary* RetainSummaryManager::getCGSummary(FunctionDecl* FD,
756 const char* FName) {
757
758 if (FName[0] == 'C' && FName[1] == 'G')
759 FName += 2;
760
761 if (isRelease(FD, FName))
762 return getUnarySummary(FD, cfrelease);
763
764 if (isRetain(FD, FName))
765 return getUnarySummary(FD, cfretain);
766
767 return getCFCreateGetRuleSummary(FD, FName);
768}
769
770RetainSummary*
771RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
772 const char* FName) {
773
Ted Kremenek562c1302008-05-05 16:51:50 +0000774 if (strstr(FName, "Create") || strstr(FName, "Copy"))
775 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000776
Ted Kremenek562c1302008-05-05 16:51:50 +0000777 if (strstr(FName, "Get"))
778 return getCFSummaryGetRule(FD);
779
780 return 0;
781}
782
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000783RetainSummary*
784RetainSummaryManager::getUnarySummary(FunctionDecl* FD, UnaryFuncKind func) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000785
786 FunctionTypeProto* FT =
787 dyn_cast<FunctionTypeProto>(FD->getType().getTypePtr());
788
Ted Kremenek562c1302008-05-05 16:51:50 +0000789 if (FT) {
790
791 if (FT->getNumArgs() != 1)
792 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000793
Ted Kremenek562c1302008-05-05 16:51:50 +0000794 TypedefType* ArgT = dyn_cast<TypedefType>(FT->getArgType(0).getTypePtr());
795
796 if (!ArgT)
797 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000798
Ted Kremenek562c1302008-05-05 16:51:50 +0000799 if (!ArgT->isPointerType())
800 return NULL;
801 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000802
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000803 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000804
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000805 switch (func) {
806 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000807 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000808 return getPersistentSummary(RetEffect::MakeAlias(0),
809 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000810 }
811
812 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000813 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000814 return getPersistentSummary(RetEffect::MakeNoRet(),
815 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000816 }
817
818 case cfmakecollectable: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000819 if (GCEnabled)
820 ScratchArgs.push_back(std::make_pair(0, DecRef));
821
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000822 return getPersistentSummary(RetEffect::MakeAlias(0),
823 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000824 }
825
826 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000827 assert (false && "Not a supported unary function.");
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000828 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000829}
830
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000831RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000832
Ted Kremenek62820d82008-05-07 20:06:41 +0000833 FunctionType* FT =
834 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenek562c1302008-05-05 16:51:50 +0000835
836 if (FT && !isCFRefType(FT->getResultType()))
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000837 return getPersistentSummary(RetEffect::MakeNoRet());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000838
Ted Kremenekae855d42008-04-24 17:22:33 +0000839 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000840
841 if (FD->getIdentifier() == CFDictionaryCreateII) {
842 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
843 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
844 }
845
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000846 return getPersistentSummary(RetEffect::MakeOwned(true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847}
848
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000849RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000850
Ted Kremenek62820d82008-05-07 20:06:41 +0000851 FunctionType* FT =
852 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenekd4244d42008-04-11 20:11:19 +0000853
Ted Kremenek562c1302008-05-05 16:51:50 +0000854 if (FT) {
855 QualType RetTy = FT->getResultType();
Ted Kremenekd4244d42008-04-11 20:11:19 +0000856
Ted Kremenek562c1302008-05-05 16:51:50 +0000857 // FIXME: For now we assume that all pointer types returned are referenced
858 // counted. Since this is the "Get" rule, we assume non-ownership, which
859 // works fine for things that are not reference counted. We do this because
860 // some generic data structures return "void*". We need something better
861 // in the future.
862
863 if (!isCFRefType(RetTy) && !RetTy->isPointerType())
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000864 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek562c1302008-05-05 16:51:50 +0000865 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000866
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000867 // FIXME: Add special-cases for functions that retain/release. For now
868 // just handle the default case.
869
Ted Kremenekae855d42008-04-24 17:22:33 +0000870 assert (ScratchArgs.empty());
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000871 return getPersistentSummary(RetEffect::MakeNotOwned(), DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000872}
873
Ted Kremeneka7338b42008-03-11 06:39:11 +0000874//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000875// Summary creation for Selectors.
876//===----------------------------------------------------------------------===//
877
Ted Kremenekbcaff792008-05-06 15:44:25 +0000878RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000879RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +0000880 assert(ScratchArgs.empty());
881
882 RetainSummary* Summ =
Ted Kremenek0e344d42008-05-06 00:30:21 +0000883 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek42ea0322008-05-05 23:55:01 +0000884
Ted Kremenek272aa852008-06-25 21:21:56 +0000885 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000886 return Summ;
887}
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000888
Ted Kremenek272aa852008-06-25 21:21:56 +0000889
Ted Kremenekbcaff792008-05-06 15:44:25 +0000890RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000891RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
892 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000893
894 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000895
Ted Kremenek272aa852008-06-25 21:21:56 +0000896 // Look up a summary in our summary cache.
897 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000898
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000899 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +0000900 return I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000901
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000902 if (!ME->getType()->isPointerType())
903 return 0;
904
Ted Kremenek42ea0322008-05-05 23:55:01 +0000905 // "initXXX": pass-through for receiver.
906
907 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000908 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +0000909
Ted Kremenek988c4472008-06-02 17:14:13 +0000910 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek272aa852008-06-25 21:21:56 +0000911 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000912
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000913 // "copyXXX", "createXXX", "newXXX": allocators.
Ted Kremenek42ea0322008-05-05 23:55:01 +0000914
Ted Kremenek5496f6d2008-05-07 04:25:59 +0000915 if (!isNSType(ME->getReceiver()->getType()))
916 return 0;
917
Ted Kremenek62820d82008-05-07 20:06:41 +0000918 if (CStrInCStrNoCase(s, "create") || CStrInCStrNoCase(s, "copy") ||
919 CStrInCStrNoCase(s, "new")) {
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000920
921 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000922 : RetEffect::MakeOwned(true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000923
924 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +0000925 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000926 return Summ;
927 }
Ted Kremenekbcaff792008-05-06 15:44:25 +0000928
Ted Kremenek42ea0322008-05-05 23:55:01 +0000929 return 0;
930}
931
Ted Kremeneka7722b72008-05-06 21:26:51 +0000932RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000933RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
934 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +0000935
Ted Kremenek272aa852008-06-25 21:21:56 +0000936 // FIXME: Eventually we should properly do class method summaries, but
937 // it requires us being able to walk the type hierarchy. Unfortunately,
938 // we cannot do this with just an IdentifierInfo* for the class name.
939
Ted Kremeneka7722b72008-05-06 21:26:51 +0000940 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +0000941 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000942
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000943 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +0000944 return I->second;
945
Ted Kremenek4c479322008-05-06 23:07:13 +0000946 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +0000947}
948
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000949void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +0000950
951 assert (ScratchArgs.empty());
952
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000953 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
954 : RetEffect::MakeOwned(true);
955
Ted Kremenek0e344d42008-05-06 00:30:21 +0000956 RetainSummary* Summ = getPersistentSummary(E);
957
Ted Kremenek272aa852008-06-25 21:21:56 +0000958 // Create the summaries for "alloc", "new", and "allocWithZone:" for
959 // NSObject and its derivatives.
960 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
961 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
962 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000963
964 // Create the [NSAssertionHandler currentHander] summary.
965 addClsMethSummary(NSAssertionHandlerII,
Ted Kremenek1ebce742008-07-18 18:14:26 +0000966 GetNullarySelector("currentHandler", Ctx),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000967 getPersistentSummary(RetEffect::MakeNotOwned()));
Ted Kremenek0e344d42008-05-06 00:30:21 +0000968}
969
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000970void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000971
972 assert (ScratchArgs.empty());
973
Ted Kremeneka7722b72008-05-06 21:26:51 +0000974 // Create the "init" selector. It just acts as a pass-through for the
975 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +0000976 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
977 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000978
979 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000980 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
981 : RetEffect::MakeOwned(true);
982
Ted Kremeneke44927e2008-07-01 17:21:27 +0000983 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000984
985 // Create the "copy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000986 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000987
988 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000989 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000990
991 // Create the "retain" selector.
992 E = RetEffect::MakeReceiverAlias();
993 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000994 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000995
996 // Create the "release" selector.
997 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000998 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +0000999
1000 // Create the "drain" selector.
1001 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001002 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001003
1004 // Create the "autorelease" selector.
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001005 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001006 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1007
1008 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001009 // For NSPanel (which subclasses NSWindow), allocated objects are not
1010 // self-owned.
1011
1012 RetainSummary *NSWindowSumm =
1013 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek272aa852008-06-25 21:21:56 +00001014
1015 // Create the "initWithContentRect:styleMask:backing:defer:" selector.
Ted Kremenek6fbecac2008-07-18 17:39:56 +00001016 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek272aa852008-06-25 21:21:56 +00001017 II.push_back(&Ctx.Idents.get("initWithContentRect"));
1018 II.push_back(&Ctx.Idents.get("styleMask"));
1019 II.push_back(&Ctx.Idents.get("backing"));
1020 II.push_back(&Ctx.Idents.get("defer"));
1021 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001022 addNSWindowMethSummary(S, NSWindowSumm);
1023 addNSPanelMethSummary(S, InitSumm);
1024
Ted Kremenek272aa852008-06-25 21:21:56 +00001025 // Create the "initWithContentRect:styleMask:backing:defer:screen:" selector.
1026 II.push_back(&Ctx.Idents.get("screen"));
1027 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001028 addNSWindowMethSummary(S, NSWindowSumm);
1029 addNSPanelMethSummary(S, InitSumm);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001030
1031 // Create NSAssertionHandler summaries.
1032 II.clear();
1033 II.push_back(&Ctx.Idents.get("handleFailureInFunction"));
1034 II.push_back(&Ctx.Idents.get("file"));
1035 II.push_back(&Ctx.Idents.get("lineNumber"));
1036 II.push_back(&Ctx.Idents.get("description"));
1037 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
1038 addPanicSummary(NSAssertionHandlerII, S);
1039
1040 II.clear();
1041 II.push_back(&Ctx.Idents.get("handleFailureInMethod"));
Ted Kremenek65259c92008-07-24 18:47:16 +00001042 II.push_back(&Ctx.Idents.get("object"));
Ted Kremenekf2717b02008-07-18 17:24:20 +00001043 II.push_back(&Ctx.Idents.get("file"));
1044 II.push_back(&Ctx.Idents.get("lineNumber"));
1045 II.push_back(&Ctx.Idents.get("description"));
1046 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
1047 addPanicSummary(NSAssertionHandlerII, S);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001048}
1049
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001050//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001051// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001052//===----------------------------------------------------------------------===//
1053
Ted Kremeneka7338b42008-03-11 06:39:11 +00001054namespace {
1055
Ted Kremenek7d421f32008-04-09 23:49:11 +00001056class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001057public:
Ted Kremenek0d721572008-03-11 17:48:22 +00001058
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001059 enum Kind {
1060 Owned = 0, // Owning reference.
1061 NotOwned, // Reference is not owned by still valid (not freed).
1062 Released, // Object has been released.
1063 ReturnedOwned, // Returned object passes ownership to caller.
1064 ReturnedNotOwned, // Return object does not pass ownership to caller.
1065 ErrorUseAfterRelease, // Object used after released.
1066 ErrorReleaseNotOwned, // Release of an object that was not owned.
1067 ErrorLeak // A memory leak due to excessive reference counts.
1068 };
Ted Kremenek0d721572008-03-11 17:48:22 +00001069
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001070private:
1071
1072 Kind kind;
1073 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001074 QualType T;
1075
1076 RefVal(Kind k, unsigned cnt, QualType t) : kind(k), Cnt(cnt), T(t) {}
1077 RefVal(Kind k, unsigned cnt = 0) : kind(k), Cnt(cnt) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001078
1079public:
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001080
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001081 Kind getKind() const { return kind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001082
Ted Kremenek272aa852008-06-25 21:21:56 +00001083 unsigned getCount() const { return Cnt; }
1084 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001085
1086 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001087
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001088 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1089
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001090 static bool isLeak(Kind k) { return k == ErrorLeak; }
1091
Ted Kremenekffefc352008-04-11 22:25:11 +00001092 bool isOwned() const {
1093 return getKind() == Owned;
1094 }
1095
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001096 bool isNotOwned() const {
1097 return getKind() == NotOwned;
1098 }
1099
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001100 bool isReturnedOwned() const {
1101 return getKind() == ReturnedOwned;
1102 }
1103
1104 bool isReturnedNotOwned() const {
1105 return getKind() == ReturnedNotOwned;
1106 }
1107
1108 bool isNonLeakError() const {
1109 Kind k = getKind();
1110 return isError(k) && !isLeak(k);
1111 }
1112
1113 // State creation: normal state.
1114
Ted Kremenek272aa852008-06-25 21:21:56 +00001115 static RefVal makeOwned(QualType t, unsigned Count = 1) {
1116 return RefVal(Owned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001117 }
1118
Ted Kremenek272aa852008-06-25 21:21:56 +00001119 static RefVal makeNotOwned(QualType t, unsigned Count = 0) {
1120 return RefVal(NotOwned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001121 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001122
1123 static RefVal makeReturnedOwned(unsigned Count) {
1124 return RefVal(ReturnedOwned, Count);
1125 }
1126
1127 static RefVal makeReturnedNotOwned() {
1128 return RefVal(ReturnedNotOwned);
1129 }
1130
1131 // State creation: errors.
Ted Kremenek272aa852008-06-25 21:21:56 +00001132
1133#if 0
Ted Kremenek9363fd92008-05-05 17:53:17 +00001134 static RefVal makeLeak(unsigned Count) { return RefVal(ErrorLeak, Count); }
Ted Kremenek0d721572008-03-11 17:48:22 +00001135 static RefVal makeReleased() { return RefVal(Released); }
1136 static RefVal makeUseAfterRelease() { return RefVal(ErrorUseAfterRelease); }
1137 static RefVal makeReleaseNotOwned() { return RefVal(ErrorReleaseNotOwned); }
Ted Kremenek272aa852008-06-25 21:21:56 +00001138#endif
1139
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001140 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001141
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001142 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001143 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001144 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001145
Ted Kremenek272aa852008-06-25 21:21:56 +00001146 RefVal operator-(size_t i) const {
1147 return RefVal(getKind(), getCount() - i, getType());
1148 }
1149
1150 RefVal operator+(size_t i) const {
1151 return RefVal(getKind(), getCount() + i, getType());
1152 }
1153
1154 RefVal operator^(Kind k) const {
1155 return RefVal(k, getCount(), getType());
1156 }
1157
1158
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001159 void Profile(llvm::FoldingSetNodeID& ID) const {
1160 ID.AddInteger((unsigned) kind);
1161 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001162 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001163 }
1164
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001165 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001166};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001167
1168void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001169 if (!T.isNull())
1170 Out << "Tracked Type:" << T.getAsString() << '\n';
1171
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001172 switch (getKind()) {
1173 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001174 case Owned: {
1175 Out << "Owned";
1176 unsigned cnt = getCount();
1177 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001178 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001179 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001180
Ted Kremenekc4f81022008-04-10 23:09:18 +00001181 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001182 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001183 unsigned cnt = getCount();
1184 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001185 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001186 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001187
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001188 case ReturnedOwned: {
1189 Out << "ReturnedOwned";
1190 unsigned cnt = getCount();
1191 if (cnt) Out << " (+ " << cnt << ")";
1192 break;
1193 }
1194
1195 case ReturnedNotOwned: {
1196 Out << "ReturnedNotOwned";
1197 unsigned cnt = getCount();
1198 if (cnt) Out << " (+ " << cnt << ")";
1199 break;
1200 }
1201
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001202 case Released:
1203 Out << "Released";
1204 break;
1205
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001206 case ErrorLeak:
1207 Out << "Leaked";
1208 break;
1209
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001210 case ErrorUseAfterRelease:
1211 Out << "Use-After-Release [ERROR]";
1212 break;
1213
1214 case ErrorReleaseNotOwned:
1215 Out << "Release of Not-Owned [ERROR]";
1216 break;
1217 }
1218}
Ted Kremenek0d721572008-03-11 17:48:22 +00001219
Ted Kremenek7aef4842008-04-16 20:40:59 +00001220//===----------------------------------------------------------------------===//
1221// Transfer functions.
1222//===----------------------------------------------------------------------===//
1223
Ted Kremenek7d421f32008-04-09 23:49:11 +00001224class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001225public:
Ted Kremenek272aa852008-06-25 21:21:56 +00001226 // Type definitions.
Ted Kremenek0d721572008-03-11 17:48:22 +00001227 typedef llvm::ImmutableMap<SymbolID, RefVal> RefBindings;
Ted Kremenek272aa852008-06-25 21:21:56 +00001228
Ted Kremeneka7338b42008-03-11 06:39:11 +00001229 typedef RefBindings::Factory RefBFactoryTy;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001230
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001231 typedef llvm::DenseMap<GRExprEngine::NodeTy*,std::pair<Expr*, SymbolID> >
1232 ReleasesNotOwnedTy;
1233
1234 typedef ReleasesNotOwnedTy UseAfterReleasesTy;
1235
1236 typedef llvm::DenseMap<GRExprEngine::NodeTy*, std::vector<SymbolID>*>
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001237 LeaksTy;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001238
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001239 class BindingsPrinter : public ValueState::CheckerStatePrinter {
1240 public:
1241 virtual void PrintCheckerState(std::ostream& Out, void* State,
1242 const char* nl, const char* sep);
1243 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001244
1245private:
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001246 // Instance variables.
1247
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001248 RetainSummaryManager Summaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001249 const LangOptions& LOpts;
1250 RefBFactoryTy RefBFactory;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001251
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001252 UseAfterReleasesTy UseAfterReleases;
1253 ReleasesNotOwnedTy ReleasesNotOwned;
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001254 LeaksTy Leaks;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001255
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001256 BindingsPrinter Printer;
1257
Ted Kremenek1feab292008-04-16 04:28:53 +00001258 Selector RetainSelector;
1259 Selector ReleaseSelector;
Ted Kremenek3281a1f2008-05-01 02:18:37 +00001260 Selector AutoreleaseSelector;
Ted Kremenek1feab292008-04-16 04:28:53 +00001261
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001262public:
1263
Ted Kremenekf22f8682008-07-10 22:03:41 +00001264 static RefBindings GetRefBindings(const ValueState& StImpl) {
1265 return RefBindings((const RefBindings::TreeTy*) StImpl.CheckerState);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001266 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001267
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001268private:
1269
Ted Kremeneka7338b42008-03-11 06:39:11 +00001270 static void SetRefBindings(ValueState& StImpl, RefBindings B) {
1271 StImpl.CheckerState = B.getRoot();
1272 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001273
Ted Kremeneka7338b42008-03-11 06:39:11 +00001274 RefBindings Remove(RefBindings B, SymbolID sym) {
1275 return RefBFactory.Remove(B, sym);
1276 }
1277
Ted Kremenek0d721572008-03-11 17:48:22 +00001278 RefBindings Update(RefBindings B, SymbolID sym, RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001279 RefVal::Kind& hasErr);
1280
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001281 void ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1282 GRStmtNodeBuilder<ValueState>& Builder,
1283 Expr* NodeExpr, Expr* ErrorExpr,
1284 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001285 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001286 RefVal::Kind hasErr, SymbolID Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001287
Ted Kremenekf22f8682008-07-10 22:03:41 +00001288 const ValueState* HandleSymbolDeath(ValueStateManager& VMgr,
1289 const ValueState* St,
1290 SymbolID sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001291
Ted Kremenekf22f8682008-07-10 22:03:41 +00001292 const ValueState* NukeBinding(ValueStateManager& VMgr, const ValueState* St,
1293 SymbolID sid);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001294
1295public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001296
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001297 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001298 : Summaries(Ctx, gcenabled),
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001299 LOpts(lopts),
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +00001300 RetainSelector(GetNullarySelector("retain", Ctx)),
1301 ReleaseSelector(GetNullarySelector("release", Ctx)),
1302 AutoreleaseSelector(GetNullarySelector("autorelease", Ctx)) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001303
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001304 virtual ~CFRefCount() {
1305 for (LeaksTy::iterator I = Leaks.begin(), E = Leaks.end(); I!=E; ++I)
1306 delete I->second;
1307 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00001308
1309 virtual void RegisterChecks(GRExprEngine& Eng);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001310
1311 virtual ValueState::CheckerStatePrinter* getCheckerStatePrinter() {
1312 return &Printer;
1313 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001314
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001315 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001316 const LangOptions& getLangOptions() const { return LOpts; }
1317
Ted Kremeneka7338b42008-03-11 06:39:11 +00001318 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001319
1320 void EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1321 GRExprEngine& Eng,
1322 GRStmtNodeBuilder<ValueState>& Builder,
1323 Expr* Ex,
1324 Expr* Receiver,
1325 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001326 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001327 ExplodedNode<ValueState>* Pred);
1328
Ted Kremeneka7338b42008-03-11 06:39:11 +00001329 virtual void EvalCall(ExplodedNodeSet<ValueState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001330 GRExprEngine& Eng,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001331 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek0a6a80b2008-04-23 20:12:28 +00001332 CallExpr* CE, RVal L,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001333 ExplodedNode<ValueState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001334
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001335
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001336 virtual void EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1337 GRExprEngine& Engine,
1338 GRStmtNodeBuilder<ValueState>& Builder,
1339 ObjCMessageExpr* ME,
1340 ExplodedNode<ValueState>* Pred);
1341
1342 bool EvalObjCMessageExprAux(ExplodedNodeSet<ValueState>& Dst,
1343 GRExprEngine& Engine,
1344 GRStmtNodeBuilder<ValueState>& Builder,
1345 ObjCMessageExpr* ME,
1346 ExplodedNode<ValueState>* Pred);
1347
Ted Kremenek7aef4842008-04-16 20:40:59 +00001348 // Stores.
1349
1350 virtual void EvalStore(ExplodedNodeSet<ValueState>& Dst,
1351 GRExprEngine& Engine,
1352 GRStmtNodeBuilder<ValueState>& Builder,
1353 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001354 const ValueState* St, RVal TargetLV, RVal Val);
Ted Kremenekffefc352008-04-11 22:25:11 +00001355 // End-of-path.
1356
1357 virtual void EvalEndPath(GRExprEngine& Engine,
1358 GREndPathNodeBuilder<ValueState>& Builder);
1359
Ted Kremenek541db372008-04-24 23:57:27 +00001360 virtual void EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1361 GRExprEngine& Engine,
1362 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001363 ExplodedNode<ValueState>* Pred,
1364 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001365 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001366 const ValueStateManager::DeadSymbolsTy& Dead);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001367 // Return statements.
1368
1369 virtual void EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1370 GRExprEngine& Engine,
1371 GRStmtNodeBuilder<ValueState>& Builder,
1372 ReturnStmt* S,
1373 ExplodedNode<ValueState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001374
1375 // Assumptions.
1376
Ted Kremenek76d31662008-07-17 23:33:10 +00001377 virtual const ValueState* EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001378 const ValueState* St, RVal Cond,
1379 bool Assumption, bool& isFeasible);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001380
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001381 // Error iterators.
1382
1383 typedef UseAfterReleasesTy::iterator use_after_iterator;
1384 typedef ReleasesNotOwnedTy::iterator bad_release_iterator;
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001385 typedef LeaksTy::iterator leaks_iterator;
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001386
Ted Kremenek7d421f32008-04-09 23:49:11 +00001387 use_after_iterator use_after_begin() { return UseAfterReleases.begin(); }
1388 use_after_iterator use_after_end() { return UseAfterReleases.end(); }
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001389
Ted Kremenek7d421f32008-04-09 23:49:11 +00001390 bad_release_iterator bad_release_begin() { return ReleasesNotOwned.begin(); }
1391 bad_release_iterator bad_release_end() { return ReleasesNotOwned.end(); }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001392
1393 leaks_iterator leaks_begin() { return Leaks.begin(); }
1394 leaks_iterator leaks_end() { return Leaks.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001395};
1396
1397} // end anonymous namespace
1398
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001399
Ted Kremenek7d421f32008-04-09 23:49:11 +00001400
1401
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001402void CFRefCount::BindingsPrinter::PrintCheckerState(std::ostream& Out,
1403 void* State, const char* nl,
1404 const char* sep) {
1405 RefBindings B((RefBindings::TreeTy*) State);
1406
1407 if (State)
1408 Out << sep << nl;
1409
1410 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1411 Out << (*I).first << " : ";
1412 (*I).second.print(Out);
1413 Out << nl;
1414 }
1415}
1416
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001417static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001418 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001419}
1420
Ted Kremenek266d8b62008-05-06 02:26:56 +00001421static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1422 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001423}
1424
Ted Kremenek227c5372008-05-06 02:41:27 +00001425static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1426 return Summ ? Summ->getReceiverEffect() : DoNothing;
1427}
1428
Ted Kremenekf2717b02008-07-18 17:24:20 +00001429static inline bool IsEndPath(RetainSummary* Summ) {
1430 return Summ ? Summ->isEndPath() : false;
1431}
1432
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001433void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1434 GRStmtNodeBuilder<ValueState>& Builder,
1435 Expr* NodeExpr, Expr* ErrorExpr,
1436 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001437 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001438 RefVal::Kind hasErr, SymbolID Sym) {
Ted Kremenek1feab292008-04-16 04:28:53 +00001439 Builder.BuildSinks = true;
1440 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
1441
1442 if (!N) return;
1443
1444 switch (hasErr) {
1445 default: assert(false);
1446 case RefVal::ErrorUseAfterRelease:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001447 UseAfterReleases[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001448 break;
1449
1450 case RefVal::ErrorReleaseNotOwned:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001451 ReleasesNotOwned[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001452 break;
1453 }
1454}
1455
Ted Kremenek272aa852008-06-25 21:21:56 +00001456/// GetReturnType - Used to get the return type of a message expression or
1457/// function call with the intention of affixing that type to a tracked symbol.
1458/// While the the return type can be queried directly from RetEx, when
1459/// invoking class methods we augment to the return type to be that of
1460/// a pointer to the class (as opposed it just being id).
1461static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1462
1463 QualType RetTy = RetE->getType();
1464
1465 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001466 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001467 if (!PT)
1468 return RetTy;
1469
1470 // If RetEx is not a message expression just return its type.
1471 // If RetEx is a message expression, return its types if it is something
1472 /// more specific than id.
1473
1474 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1475
1476 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1477 return RetTy;
1478
1479 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1480
1481 // At this point we know the return type of the message expression is id.
1482 // If we have an ObjCInterceDecl, we know this is a call to a class method
1483 // whose type we can resolve. In such cases, promote the return type to
1484 // Class*.
1485 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1486}
1487
1488
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001489void CFRefCount::EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1490 GRExprEngine& Eng,
1491 GRStmtNodeBuilder<ValueState>& Builder,
1492 Expr* Ex,
1493 Expr* Receiver,
1494 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001495 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001496 ExplodedNode<ValueState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001497
Ted Kremeneka7338b42008-03-11 06:39:11 +00001498 // Get the state.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001499 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001500 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00001501
1502 // Evaluate the effect of the arguments.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001503 ValueState StVals = *St;
Ted Kremenek1feab292008-04-16 04:28:53 +00001504 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001505 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001506 Expr* ErrorExpr = NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001507 SymbolID ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001508
Ted Kremenek2719e982008-06-17 02:43:46 +00001509 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001510
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001511 RVal V = StateMgr.GetRVal(St, *I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001512
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001513 if (isa<lval::SymbolVal>(V)) {
1514 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
Ted Kremenek455dd862008-04-11 20:23:24 +00001515 RefBindings B = GetRefBindings(StVals);
1516
Ted Kremenek6064a362008-07-07 16:21:19 +00001517 if (RefBindings::data_type* T = B.lookup(Sym)) {
1518 B = Update(B, Sym, *T, GetArgE(Summ, idx), hasErr);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001519 SetRefBindings(StVals, B);
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001520
Ted Kremenek1feab292008-04-16 04:28:53 +00001521 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001522 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001523 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001524 break;
1525 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001526 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001527 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001528 else if (isa<LVal>(V)) {
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001529#if 0
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001530 // Nuke all arguments passed by reference.
Ted Kremenek455dd862008-04-11 20:23:24 +00001531 StateMgr.Unbind(StVals, cast<LVal>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001532#else
Ted Kremenekede40b72008-07-09 18:11:16 +00001533 if (lval::DeclVal* DV = dyn_cast<lval::DeclVal>(&V)) {
1534
1535 if (GetArgE(Summ, idx) == DoNothingByRef)
1536 continue;
1537
1538 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001539
1540 // FIXME: Either this logic should also be replicated in GRSimpleVals
1541 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001542
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001543 // FIXME: We can have collisions on the conjured symbol if the
1544 // expression *I also creates conjured symbols. We probably want
1545 // to identify conjured symbols by an expression pair: the enclosing
1546 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001547 // disambiguate conjured symbols.
1548
1549 // Is the invalidated variable something that we were tracking?
1550 RVal X = StateMgr.GetRVal(&StVals, *DV);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001551
Ted Kremenekede40b72008-07-09 18:11:16 +00001552 if (isa<lval::SymbolVal>(X)) {
1553 SymbolID Sym = cast<lval::SymbolVal>(X).getSymbol();
1554 SetRefBindings(StVals,RefBFactory.Remove(GetRefBindings(StVals),Sym));
1555 }
1556
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001557 // Set the value of the variable to be a conjured symbol.
1558 unsigned Count = Builder.getCurrentBlockCount();
1559 SymbolID NewSym = Eng.getSymbolManager().getConjuredSymbol(*I, Count);
1560
Ted Kremenekf22f8682008-07-10 22:03:41 +00001561 StateMgr.SetRVal(StVals, *DV,
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001562 LVal::IsLValType(DV->getDecl()->getType())
1563 ? cast<RVal>(lval::SymbolVal(NewSym))
1564 : cast<RVal>(nonlval::SymbolVal(NewSym)));
1565 }
1566 else {
1567 // Nuke all other arguments passed by reference.
1568 StateMgr.Unbind(StVals, cast<LVal>(V));
1569 }
1570#endif
Ted Kremeneke4924202008-04-11 20:51:02 +00001571 }
Ted Kremenekbe621292008-04-22 21:39:21 +00001572 else if (isa<nonlval::LValAsInteger>(V))
1573 StateMgr.Unbind(StVals, cast<nonlval::LValAsInteger>(V).getLVal());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001574 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001575
Ted Kremenek272aa852008-06-25 21:21:56 +00001576 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001577 if (!ErrorExpr && Receiver) {
1578 RVal V = StateMgr.GetRVal(St, Receiver);
1579
1580 if (isa<lval::SymbolVal>(V)) {
1581 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1582 RefBindings B = GetRefBindings(StVals);
1583
Ted Kremenek6064a362008-07-07 16:21:19 +00001584 if (const RefVal* T = B.lookup(Sym)) {
1585 B = Update(B, Sym, *T, GetReceiverE(Summ), hasErr);
Ted Kremenek227c5372008-05-06 02:41:27 +00001586 SetRefBindings(StVals, B);
1587
1588 if (hasErr) {
1589 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001590 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001591 }
1592 }
1593 }
1594 }
1595
Ted Kremenek272aa852008-06-25 21:21:56 +00001596 // Get the persistent state.
Ted Kremenek1feab292008-04-16 04:28:53 +00001597 St = StateMgr.getPersistentState(StVals);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001598
Ted Kremenek272aa852008-06-25 21:21:56 +00001599 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001600 if (hasErr) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001601 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001602 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001603 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001604 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001605
Ted Kremenekf2717b02008-07-18 17:24:20 +00001606 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001607 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001608
1609 switch (RE.getKind()) {
1610 default:
1611 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001612
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001613 case RetEffect::NoRet:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001614
Ted Kremenek455dd862008-04-11 20:23:24 +00001615 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001616 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1617 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001618
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001619 if (Ex->getType() != Eng.getContext().VoidTy) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001620 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001621 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001622
Ted Kremenek9e2c1ea2008-05-09 23:45:33 +00001623 RVal X = LVal::IsLValType(Ex->getType())
1624 ? cast<RVal>(lval::SymbolVal(Sym))
1625 : cast<RVal>(nonlval::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001626
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001627 St = StateMgr.SetRVal(St, Ex, X, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001628 }
1629
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001630 break;
1631
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001632 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001633 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001634 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001635 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek2719e982008-06-17 02:43:46 +00001636 RVal V = StateMgr.GetRVal(St, *(arg_beg+idx));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001637 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001638 break;
1639 }
1640
Ted Kremenek227c5372008-05-06 02:41:27 +00001641 case RetEffect::ReceiverAlias: {
1642 assert (Receiver);
1643 RVal V = StateMgr.GetRVal(St, Receiver);
1644 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
1645 break;
1646 }
1647
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001648 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001649 case RetEffect::OwnedSymbol: {
1650 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001651 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001652 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001653
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001654 ValueState StImpl = *St;
1655 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001656 SetRefBindings(StImpl, RefBFactory.Add(B, Sym, RefVal::makeOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001657
1658 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001659 Ex, lval::SymbolVal(Sym),
1660 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001661
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001662 // FIXME: Add a flag to the checker where allocations are allowed to fail.
1663 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol)
1664 St = StateMgr.AddNE(St, Sym, Eng.getBasicVals().getZeroWithPtrWidth());
1665
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001666 break;
1667 }
1668
1669 case RetEffect::NotOwnedSymbol: {
1670 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001671 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001672 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001673
1674 ValueState StImpl = *St;
1675 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001676 SetRefBindings(StImpl, RefBFactory.Add(B, Sym,
1677 RefVal::makeNotOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001678
1679 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001680 Ex, lval::SymbolVal(Sym),
1681 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001682
1683 break;
1684 }
1685 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001686
Ted Kremenekf2717b02008-07-18 17:24:20 +00001687 // Is this a sink?
1688 if (IsEndPath(Summ))
1689 Builder.MakeSinkNode(Dst, Ex, Pred, St);
1690 else
1691 Builder.MakeNode(Dst, Ex, Pred, St);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001692}
1693
1694
1695void CFRefCount::EvalCall(ExplodedNodeSet<ValueState>& Dst,
1696 GRExprEngine& Eng,
1697 GRStmtNodeBuilder<ValueState>& Builder,
1698 CallExpr* CE, RVal L,
1699 ExplodedNode<ValueState>* Pred) {
1700
1701
1702 RetainSummary* Summ = NULL;
1703
1704 // Get the summary.
1705
1706 if (isa<lval::FuncVal>(L)) {
1707 lval::FuncVal FV = cast<lval::FuncVal>(L);
1708 FunctionDecl* FD = FV.getDecl();
Ted Kremenekd13c1872008-06-24 03:56:45 +00001709 Summ = Summaries.getSummary(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001710 }
1711
1712 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1713 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001714}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001715
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001716
1717void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1718 GRExprEngine& Eng,
1719 GRStmtNodeBuilder<ValueState>& Builder,
1720 ObjCMessageExpr* ME,
1721 ExplodedNode<ValueState>* Pred) {
1722
Ted Kremenek926abf22008-05-06 04:20:12 +00001723 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001724
Ted Kremenek272aa852008-06-25 21:21:56 +00001725 if (Expr* Receiver = ME->getReceiver()) {
1726 // We need the type-information of the tracked receiver object
1727 // Retrieve it from the state.
1728 ObjCInterfaceDecl* ID = 0;
1729
1730 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1731 // a chain of lookups.
Ted Kremenekf22f8682008-07-10 22:03:41 +00001732 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek272aa852008-06-25 21:21:56 +00001733 RVal V = Eng.getStateManager().GetRVal(St, Receiver );
1734
1735 if (isa<lval::SymbolVal>(V)) {
1736 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1737
Ted Kremenek6064a362008-07-07 16:21:19 +00001738 if (const RefVal* T = GetRefBindings(*St).lookup(Sym)) {
1739 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001740
1741 if (const PointerType* PT = Ty->getAsPointerType()) {
1742 QualType PointeeTy = PT->getPointeeType();
1743
1744 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1745 ID = IT->getDecl();
1746 }
1747 }
1748 }
1749
1750 Summ = Summaries.getMethodSummary(ME, ID);
1751 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001752 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001753 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1754 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001755
Ted Kremenek926abf22008-05-06 04:20:12 +00001756 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1757 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001758}
Ted Kremenek926abf22008-05-06 04:20:12 +00001759
Ted Kremenek7aef4842008-04-16 20:40:59 +00001760// Stores.
1761
1762void CFRefCount::EvalStore(ExplodedNodeSet<ValueState>& Dst,
1763 GRExprEngine& Eng,
1764 GRStmtNodeBuilder<ValueState>& Builder,
1765 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001766 const ValueState* St, RVal TargetLV, RVal Val) {
Ted Kremenek7aef4842008-04-16 20:40:59 +00001767
1768 // Check if we have a binding for "Val" and if we are storing it to something
1769 // we don't understand or otherwise the value "escapes" the function.
1770
1771 if (!isa<lval::SymbolVal>(Val))
1772 return;
1773
1774 // Are we storing to something that causes the value to "escape"?
1775
1776 bool escapes = false;
1777
1778 if (!isa<lval::DeclVal>(TargetLV))
1779 escapes = true;
1780 else
1781 escapes = cast<lval::DeclVal>(TargetLV).getDecl()->hasGlobalStorage();
1782
1783 if (!escapes)
1784 return;
1785
1786 SymbolID Sym = cast<lval::SymbolVal>(Val).getSymbol();
Ted Kremenek7aef4842008-04-16 20:40:59 +00001787
Ted Kremenek6064a362008-07-07 16:21:19 +00001788 if (!GetRefBindings(*St).lookup(Sym))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001789 return;
1790
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001791 // Nuke the binding.
1792 St = NukeBinding(Eng.getStateManager(), St, Sym);
Ted Kremenek7aef4842008-04-16 20:40:59 +00001793
1794 // Hand of the remaining logic to the parent implementation.
1795 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, St, TargetLV, Val);
1796}
1797
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001798
Ted Kremenekf22f8682008-07-10 22:03:41 +00001799const ValueState* CFRefCount::NukeBinding(ValueStateManager& VMgr,
1800 const ValueState* St,
1801 SymbolID sid) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001802 ValueState StImpl = *St;
1803 RefBindings B = GetRefBindings(StImpl);
1804 StImpl.CheckerState = RefBFactory.Remove(B, sid).getRoot();
1805 return VMgr.getPersistentState(StImpl);
1806}
1807
Ted Kremenekffefc352008-04-11 22:25:11 +00001808// End-of-path.
1809
Ted Kremenekf22f8682008-07-10 22:03:41 +00001810const ValueState* CFRefCount::HandleSymbolDeath(ValueStateManager& VMgr,
1811 const ValueState* St, SymbolID sid,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001812 RefVal V, bool& hasLeak) {
1813
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001814 hasLeak = V.isOwned() ||
1815 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001816
1817 if (!hasLeak)
1818 return NukeBinding(VMgr, St, sid);
1819
1820 RefBindings B = GetRefBindings(*St);
Ted Kremenek272aa852008-06-25 21:21:56 +00001821 ValueState StImpl = *St;
1822 StImpl.CheckerState = RefBFactory.Add(B, sid, V^RefVal::ErrorLeak).getRoot();
Ted Kremenek9363fd92008-05-05 17:53:17 +00001823
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001824 return VMgr.getPersistentState(StImpl);
1825}
1826
1827void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Ted Kremenekffefc352008-04-11 22:25:11 +00001828 GREndPathNodeBuilder<ValueState>& Builder) {
1829
Ted Kremenekf22f8682008-07-10 22:03:41 +00001830 const ValueState* St = Builder.getState();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001831 RefBindings B = GetRefBindings(*St);
Ted Kremenekffefc352008-04-11 22:25:11 +00001832
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001833 llvm::SmallVector<SymbolID, 10> Leaked;
Ted Kremenekffefc352008-04-11 22:25:11 +00001834
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001835 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1836 bool hasLeak = false;
Ted Kremenekffefc352008-04-11 22:25:11 +00001837
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001838 St = HandleSymbolDeath(Eng.getStateManager(), St,
1839 (*I).first, (*I).second, hasLeak);
1840
1841 if (hasLeak) Leaked.push_back((*I).first);
1842 }
Ted Kremenek541db372008-04-24 23:57:27 +00001843
1844 if (Leaked.empty())
1845 return;
1846
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001847 ExplodedNode<ValueState>* N = Builder.MakeNode(St);
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001848
Ted Kremenek541db372008-04-24 23:57:27 +00001849 if (!N)
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001850 return;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001851
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001852 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1853 assert (!LeaksAtNode);
1854 LeaksAtNode = new std::vector<SymbolID>();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001855
1856 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1857 E = Leaked.end(); I != E; ++I)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001858 (*LeaksAtNode).push_back(*I);
Ted Kremenekffefc352008-04-11 22:25:11 +00001859}
1860
Ted Kremenek541db372008-04-24 23:57:27 +00001861// Dead symbols.
1862
1863void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1864 GRExprEngine& Eng,
1865 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001866 ExplodedNode<ValueState>* Pred,
1867 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001868 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001869 const ValueStateManager::DeadSymbolsTy& Dead) {
Ted Kremenekac91ce92008-04-25 01:25:15 +00001870
Ted Kremenek541db372008-04-24 23:57:27 +00001871 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
1872
1873 RefBindings B = GetRefBindings(*St);
1874 llvm::SmallVector<SymbolID, 10> Leaked;
1875
1876 for (ValueStateManager::DeadSymbolsTy::const_iterator
1877 I=Dead.begin(), E=Dead.end(); I!=E; ++I) {
1878
Ted Kremenek6064a362008-07-07 16:21:19 +00001879 const RefVal* T = B.lookup(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001880
1881 if (!T)
1882 continue;
1883
1884 bool hasLeak = false;
1885
Ted Kremenek6064a362008-07-07 16:21:19 +00001886 St = HandleSymbolDeath(Eng.getStateManager(), St, *I, *T, hasLeak);
Ted Kremenek541db372008-04-24 23:57:27 +00001887
Ted Kremenek6064a362008-07-07 16:21:19 +00001888 if (hasLeak)
1889 Leaked.push_back(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001890 }
1891
1892 if (Leaked.empty())
1893 return;
1894
1895 ExplodedNode<ValueState>* N = Builder.MakeNode(Dst, S, Pred, St);
1896
1897 if (!N)
1898 return;
1899
1900 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1901 assert (!LeaksAtNode);
1902 LeaksAtNode = new std::vector<SymbolID>();
1903
1904 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1905 E = Leaked.end(); I != E; ++I)
1906 (*LeaksAtNode).push_back(*I);
1907}
1908
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001909 // Return statements.
1910
1911void CFRefCount::EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1912 GRExprEngine& Eng,
1913 GRStmtNodeBuilder<ValueState>& Builder,
1914 ReturnStmt* S,
1915 ExplodedNode<ValueState>* Pred) {
1916
1917 Expr* RetE = S->getRetValue();
1918 if (!RetE) return;
1919
1920 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001921 const ValueState* St = Builder.GetState(Pred);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001922 RVal V = StateMgr.GetRVal(St, RetE);
1923
1924 if (!isa<lval::SymbolVal>(V))
1925 return;
1926
1927 // Get the reference count binding (if any).
1928 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1929 RefBindings B = GetRefBindings(*St);
Ted Kremenek6064a362008-07-07 16:21:19 +00001930 const RefVal* T = B.lookup(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001931
1932 if (!T)
1933 return;
1934
1935 // Change the reference count.
1936
Ted Kremenek6064a362008-07-07 16:21:19 +00001937 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001938
1939 switch (X.getKind()) {
1940
1941 case RefVal::Owned: {
1942 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001943 assert (cnt > 0);
1944 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001945 break;
1946 }
1947
1948 case RefVal::NotOwned: {
1949 unsigned cnt = X.getCount();
1950 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1951 : RefVal::makeReturnedNotOwned();
1952 break;
1953 }
1954
1955 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001956 return;
1957 }
1958
1959 // Update the binding.
1960
1961 ValueState StImpl = *St;
1962 StImpl.CheckerState = RefBFactory.Add(B, Sym, X).getRoot();
1963 Builder.MakeNode(Dst, S, Pred, StateMgr.getPersistentState(StImpl));
1964}
1965
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001966// Assumptions.
1967
Ted Kremenek76d31662008-07-17 23:33:10 +00001968const ValueState* CFRefCount::EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001969 const ValueState* St,
1970 RVal Cond, bool Assumption,
1971 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001972
1973 // FIXME: We may add to the interface of EvalAssume the list of symbols
1974 // whose assumptions have changed. For now we just iterate through the
1975 // bindings and check if any of the tracked symbols are NULL. This isn't
1976 // too bad since the number of symbols we will track in practice are
1977 // probably small and EvalAssume is only called at branches and a few
1978 // other places.
1979
1980 RefBindings B = GetRefBindings(*St);
1981
1982 if (B.isEmpty())
1983 return St;
1984
1985 bool changed = false;
1986
1987 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1988
1989 // Check if the symbol is null (or equal to any constant).
1990 // If this is the case, stop tracking the symbol.
1991
1992 if (St->getSymVal(I.getKey())) {
1993 changed = true;
1994 B = RefBFactory.Remove(B, I.getKey());
1995 }
1996 }
1997
1998 if (!changed)
1999 return St;
2000
2001 ValueState StImpl = *St;
2002 StImpl.CheckerState = B.getRoot();
Ted Kremenek76d31662008-07-17 23:33:10 +00002003 return VMgr.getPersistentState(StImpl);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002004}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002005
2006CFRefCount::RefBindings CFRefCount::Update(RefBindings B, SymbolID sym,
Ted Kremenek0d721572008-03-11 17:48:22 +00002007 RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00002008 RefVal::Kind& hasErr) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00002009
Ted Kremenek0d721572008-03-11 17:48:22 +00002010 // FIXME: This dispatch can potentially be sped up by unifiying it into
2011 // a single switch statement. Opt for simplicity for now.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002012
Ted Kremenek0d721572008-03-11 17:48:22 +00002013 switch (E) {
2014 default:
2015 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002016
2017 case MayEscape:
2018 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002019 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002020 break;
2021 }
2022
2023 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002024
Ted Kremenekede40b72008-07-09 18:11:16 +00002025 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002026 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002027 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002028 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002029 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002030 break;
2031 }
2032
Ted Kremenek0d721572008-03-11 17:48:22 +00002033 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002034
Ted Kremenek4e1d22f2008-07-01 00:01:02 +00002035 case Autorelease:
Ted Kremenek227c5372008-05-06 02:41:27 +00002036 case StopTracking:
2037 return RefBFactory.Remove(B, sym);
2038
Ted Kremenek0d721572008-03-11 17:48:22 +00002039 case IncRef:
2040 switch (V.getKind()) {
2041 default:
2042 assert(false);
2043
2044 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002045 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002046 V = V + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002047 break;
2048
2049 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002050 if (isGCEnabled())
Ted Kremenek272aa852008-06-25 21:21:56 +00002051 V = V ^ RefVal::Owned;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002052 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002053 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002054 hasErr = V.getKind();
2055 }
2056
Ted Kremenek0d721572008-03-11 17:48:22 +00002057 break;
2058 }
2059
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002060 break;
2061
Ted Kremenek272aa852008-06-25 21:21:56 +00002062 case SelfOwn:
2063 V = V ^ RefVal::NotOwned;
2064
Ted Kremenek0d721572008-03-11 17:48:22 +00002065 case DecRef:
2066 switch (V.getKind()) {
2067 default:
2068 assert (false);
2069
Ted Kremenek272aa852008-06-25 21:21:56 +00002070 case RefVal::Owned:
2071 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek0d721572008-03-11 17:48:22 +00002072 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002073
Ted Kremenek272aa852008-06-25 21:21:56 +00002074 case RefVal::NotOwned:
2075 if (V.getCount() > 0)
2076 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002077 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002078 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002079 hasErr = V.getKind();
Ted Kremenekc4f81022008-04-10 23:09:18 +00002080 }
2081
Ted Kremenek0d721572008-03-11 17:48:22 +00002082 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002083
2084 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002085 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002086 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002087 break;
2088 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002089
2090 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002091 }
2092
2093 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002094}
2095
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002096
2097//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002098// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002099//===----------------------------------------------------------------------===//
2100
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002101namespace {
2102
2103 //===-------------===//
2104 // Bug Descriptions. //
2105 //===-------------===//
2106
Ted Kremeneke3769852008-04-18 20:54:29 +00002107 class VISIBILITY_HIDDEN CFRefBug : public BugTypeCacheLocation {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002108 protected:
2109 CFRefCount& TF;
2110
2111 public:
2112 CFRefBug(CFRefCount& tf) : TF(tf) {}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002113
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002114 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002115 const CFRefCount& getTF() const { return TF; }
2116
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002117 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002118 };
2119
2120 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2121 public:
2122 UseAfterRelease(CFRefCount& tf) : CFRefBug(tf) {}
2123
2124 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002125 return "Use-After-Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002126 }
2127 virtual const char* getDescription() const {
Ted Kremeneka8503952008-04-18 04:55:01 +00002128 return "Reference-counted object is used"
2129 " after it is released.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002130 }
2131
2132 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002133 };
2134
2135 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2136 public:
2137 BadRelease(CFRefCount& tf) : CFRefBug(tf) {}
2138
2139 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002140 return "Bad Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002141 }
2142 virtual const char* getDescription() const {
2143 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002144 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002145 "The object is not owned at this point by the caller.";
2146 }
2147
2148 virtual void EmitWarnings(BugReporter& BR);
2149 };
2150
2151 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2152 public:
2153 Leak(CFRefCount& tf) : CFRefBug(tf) {}
2154
2155 virtual const char* getName() const {
Ted Kremenekb3a44e72008-05-06 18:11:36 +00002156
2157 if (getTF().isGCEnabled())
2158 return "Memory Leak (GC)";
2159
2160 if (getTF().getLangOptions().getGCMode() == LangOptions::HybridGC)
2161 return "Memory Leak (Hybrid MM, non-GC)";
2162
2163 assert (getTF().getLangOptions().getGCMode() == LangOptions::NonGC);
2164 return "Memory Leak";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002165 }
2166
2167 virtual const char* getDescription() const {
Ted Kremeneka8503952008-04-18 04:55:01 +00002168 return "Object leaked.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002169 }
2170
2171 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002172 virtual void GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002173 virtual bool isLeak() const { return true; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002174 virtual bool isCached(BugReport& R);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002175 };
2176
2177 //===---------===//
2178 // Bug Reports. //
2179 //===---------===//
2180
2181 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2182 SymbolID Sym;
2183 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002184 CFRefReport(CFRefBug& D, ExplodedNode<ValueState> *n, SymbolID sym)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002185 : RangedBugReport(D, n), Sym(sym) {}
2186
2187 virtual ~CFRefReport() {}
2188
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002189 CFRefBug& getBugType() {
2190 return (CFRefBug&) RangedBugReport::getBugType();
2191 }
2192 const CFRefBug& getBugType() const {
2193 return (const CFRefBug&) RangedBugReport::getBugType();
2194 }
2195
2196 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2197 const SourceRange*& end) {
2198
Ted Kremenek198cae02008-05-02 20:53:50 +00002199 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002200 RangedBugReport::getRanges(BR, beg, end);
2201 else {
2202 beg = 0;
2203 end = 0;
2204 }
2205 }
2206
Ted Kremenekd7e26782008-05-16 18:33:44 +00002207 SymbolID getSymbol() const { return Sym; }
2208
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002209 virtual PathDiagnosticPiece* getEndPath(BugReporter& BR,
2210 ExplodedNode<ValueState>* N);
2211
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002212 virtual std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002213
2214 virtual PathDiagnosticPiece* VisitNode(ExplodedNode<ValueState>* N,
2215 ExplodedNode<ValueState>* PrevN,
2216 ExplodedGraph<ValueState>& G,
2217 BugReporter& BR);
2218 };
2219
2220
2221} // end anonymous namespace
2222
2223void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002224 Eng.Register(new UseAfterRelease(*this));
2225 Eng.Register(new BadRelease(*this));
2226 Eng.Register(new Leak(*this));
2227}
2228
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002229
2230static const char* Msgs[] = {
2231 "Code is compiled in garbage collection only mode" // GC only
2232 " (the bug occurs with garbage collection enabled).",
2233
2234 "Code is compiled without garbage collection.", // No GC.
2235
2236 "Code is compiled for use with and without garbage collection (GC)."
2237 " The bug occurs with GC enabled.", // Hybrid, with GC.
2238
2239 "Code is compiled for use with and without garbage collection (GC)."
2240 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2241};
2242
2243std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2244 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2245
2246 switch (TF.getLangOptions().getGCMode()) {
2247 default:
2248 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002249
2250 case LangOptions::GCOnly:
2251 assert (TF.isGCEnabled());
2252 return std::make_pair(&Msgs[0], &Msgs[0]+1);
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002253
2254 case LangOptions::NonGC:
2255 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002256 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2257
2258 case LangOptions::HybridGC:
2259 if (TF.isGCEnabled())
2260 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2261 else
2262 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2263 }
2264}
2265
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002266PathDiagnosticPiece* CFRefReport::VisitNode(ExplodedNode<ValueState>* N,
2267 ExplodedNode<ValueState>* PrevN,
2268 ExplodedGraph<ValueState>& G,
2269 BugReporter& BR) {
2270
2271 // Check if the type state has changed.
2272
Ted Kremenekf22f8682008-07-10 22:03:41 +00002273 const ValueState* PrevSt = PrevN->getState();
2274 const ValueState* CurrSt = N->getState();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002275
2276 CFRefCount::RefBindings PrevB = CFRefCount::GetRefBindings(*PrevSt);
2277 CFRefCount::RefBindings CurrB = CFRefCount::GetRefBindings(*CurrSt);
2278
Ted Kremenek6064a362008-07-07 16:21:19 +00002279 const RefVal* PrevT = PrevB.lookup(Sym);
2280 const RefVal* CurrT = CurrB.lookup(Sym);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002281
Ted Kremeneka8503952008-04-18 04:55:01 +00002282 if (!CurrT)
2283 return NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002284
Ted Kremeneka8503952008-04-18 04:55:01 +00002285 const char* Msg = NULL;
Ted Kremenek6064a362008-07-07 16:21:19 +00002286 const RefVal& CurrV = *CurrB.lookup(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002287
Ted Kremeneka8503952008-04-18 04:55:01 +00002288 if (!PrevT) {
2289
Ted Kremenek9363fd92008-05-05 17:53:17 +00002290 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2291
2292 if (CurrV.isOwned()) {
2293
2294 if (isa<CallExpr>(S))
2295 Msg = "Function call returns an object with a +1 retain count"
2296 " (owning reference).";
2297 else {
2298 assert (isa<ObjCMessageExpr>(S));
2299 Msg = "Method returns an object with a +1 retain count"
2300 " (owning reference).";
2301 }
2302 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002303 else {
2304 assert (CurrV.isNotOwned());
Ted Kremenek9363fd92008-05-05 17:53:17 +00002305
2306 if (isa<CallExpr>(S))
2307 Msg = "Function call returns an object with a +0 retain count"
2308 " (non-owning reference).";
2309 else {
2310 assert (isa<ObjCMessageExpr>(S));
2311 Msg = "Method returns an object with a +0 retain count"
2312 " (non-owning reference).";
2313 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002314 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002315
Ted Kremeneka8503952008-04-18 04:55:01 +00002316 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2317 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2318
2319 if (Expr* Exp = dyn_cast<Expr>(S))
2320 P->addRange(Exp->getSourceRange());
2321
2322 return P;
2323 }
2324
Ted Kremenek6064a362008-07-07 16:21:19 +00002325 // Determine if the typestate has changed.
2326 RefVal PrevV = *PrevB.lookup(Sym);
Ted Kremeneka8503952008-04-18 04:55:01 +00002327
2328 if (PrevV == CurrV)
2329 return NULL;
2330
2331 // The typestate has changed.
2332
2333 std::ostringstream os;
2334
2335 switch (CurrV.getKind()) {
2336 case RefVal::Owned:
2337 case RefVal::NotOwned:
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002338
2339 if (PrevV.getCount() == CurrV.getCount())
2340 return 0;
Ted Kremeneka8503952008-04-18 04:55:01 +00002341
2342 if (PrevV.getCount() > CurrV.getCount())
2343 os << "Reference count decremented.";
2344 else
2345 os << "Reference count incremented.";
2346
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002347 if (unsigned Count = CurrV.getCount()) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002348
2349 os << " Object has +" << Count;
Ted Kremenek752b5842008-04-18 05:32:44 +00002350
Ted Kremenek9363fd92008-05-05 17:53:17 +00002351 if (Count > 1)
2352 os << " retain counts.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002353 else
Ted Kremenek9363fd92008-05-05 17:53:17 +00002354 os << " retain count.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002355 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002356
2357 Msg = os.str().c_str();
2358
2359 break;
2360
2361 case RefVal::Released:
2362 Msg = "Object released.";
2363 break;
2364
2365 case RefVal::ReturnedOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002366 Msg = "Object returned to caller as owning reference (single retain count"
2367 " transferred to caller).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002368 break;
2369
2370 case RefVal::ReturnedNotOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002371 Msg = "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremeneka8503952008-04-18 04:55:01 +00002372 break;
2373
2374 default:
2375 return NULL;
2376 }
2377
2378 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2379 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2380 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2381
2382 // Add the range by scanning the children of the statement for any bindings
2383 // to Sym.
2384
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002385 ValueStateManager& VSM = cast<GRBugReporter>(BR).getStateManager();
Ted Kremeneka8503952008-04-18 04:55:01 +00002386
2387 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2388 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
2389 RVal X = VSM.GetRVal(CurrSt, Exp);
2390
2391 if (lval::SymbolVal* SV = dyn_cast<lval::SymbolVal>(&X))
2392 if (SV->getSymbol() == Sym) {
2393 P->addRange(Exp->getSourceRange()); break;
2394 }
2395 }
2396
2397 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002398}
2399
Ted Kremenekd7e26782008-05-16 18:33:44 +00002400static std::pair<ExplodedNode<ValueState>*,VarDecl*>
2401GetAllocationSite(ExplodedNode<ValueState>* N, SymbolID Sym) {
2402
2403 typedef CFRefCount::RefBindings RefBindings;
2404 ExplodedNode<ValueState>* Last = N;
2405
2406 // Find the first node that referred to the tracked symbol. We also
2407 // try and find the first VarDecl the value was stored to.
2408
2409 VarDecl* FirstDecl = 0;
2410
2411 while (N) {
Ted Kremenekf22f8682008-07-10 22:03:41 +00002412 const ValueState* St = N->getState();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002413 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002414
Ted Kremenek6064a362008-07-07 16:21:19 +00002415 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002416 break;
2417
2418 VarDecl* VD = 0;
2419
2420 // Determine if there is an LVal binding to the symbol.
2421 for (ValueState::vb_iterator I=St->vb_begin(), E=St->vb_end(); I!=E; ++I) {
2422 if (!isa<lval::SymbolVal>(I->second) // Is the value a symbol?
2423 || cast<lval::SymbolVal>(I->second).getSymbol() != Sym)
2424 continue;
2425
2426 if (VD) { // Multiple decls map to this symbol.
2427 VD = 0;
2428 break;
2429 }
2430
2431 VD = I->first;
2432 }
2433
2434 if (VD) FirstDecl = VD;
2435
2436 Last = N;
2437 N = N->pred_empty() ? NULL : *(N->pred_begin());
2438 }
2439
2440 return std::make_pair(Last, FirstDecl);
2441}
Ted Kremenek4c479322008-05-06 23:07:13 +00002442
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002443PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& BR,
Ted Kremenekea794e92008-05-05 18:50:19 +00002444 ExplodedNode<ValueState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002445
2446 // Tell the BugReporter to report cases when the tracked symbol is
2447 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002448 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002449
2450 if (!getBugType().isLeak())
Ted Kremenekea794e92008-05-05 18:50:19 +00002451 return RangedBugReport::getEndPath(BR, EndN);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002452
Ted Kremenek9363fd92008-05-05 17:53:17 +00002453 typedef CFRefCount::RefBindings RefBindings;
2454
2455 // Get the retain count.
Ted Kremenek9363fd92008-05-05 17:53:17 +00002456
Ted Kremenek6064a362008-07-07 16:21:19 +00002457 unsigned long RetCount =
2458 CFRefCount::GetRefBindings(*EndN->getState()).lookup(Sym)->getCount();
2459
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002460 // We are a leak. Walk up the graph to get to the first node where the
Ted Kremenekd7e26782008-05-16 18:33:44 +00002461 // symbol appeared, and also get the first VarDecl that tracked object
2462 // is stored to.
2463
2464 ExplodedNode<ValueState>* AllocNode = 0;
Ted Kremenek198cae02008-05-02 20:53:50 +00002465 VarDecl* FirstDecl = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002466 llvm::tie(AllocNode, FirstDecl) = GetAllocationSite(EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002467
Ted Kremenekd7e26782008-05-16 18:33:44 +00002468 // Get the allocate site.
2469 assert (AllocNode);
2470 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002471
Ted Kremenekea794e92008-05-05 18:50:19 +00002472 SourceManager& SMgr = BR.getContext().getSourceManager();
2473 unsigned AllocLine = SMgr.getLogicalLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002474
Ted Kremenekea794e92008-05-05 18:50:19 +00002475 // Get the leak site. We may have multiple ExplodedNodes (one with the
2476 // leak) that occur on the same line number; if the node with the leak
2477 // has any immediate predecessor nodes with the same line number, find
2478 // any transitive-successors that have a different statement and use that
2479 // line number instead. This avoids emiting a diagnostic like:
2480 //
2481 // // 'y' is leaked.
2482 // int x = foo(y);
2483 //
2484 // instead we want:
2485 //
2486 // int x = foo(y);
2487 // // 'y' is leaked.
2488
2489 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2490 assert (S);
2491 unsigned EndLine = SMgr.getLogicalLineNumber(S->getLocStart());
2492
2493 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2494 // it occur on the same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002495
2496 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremenekea794e92008-05-05 18:50:19 +00002497
2498 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremenek4c479322008-05-06 23:07:13 +00002499 ExplodedNode<ValueState> *Pred = *(EndN->pred_begin());
2500 ProgramPoint PredPos = Pred->getLocation();
Ted Kremenekea794e92008-05-05 18:50:19 +00002501
Ted Kremenek4c479322008-05-06 23:07:13 +00002502 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremenekea794e92008-05-05 18:50:19 +00002503
Ted Kremenek4c479322008-05-06 23:07:13 +00002504 Stmt* SPred = PredPS->getStmt();
Ted Kremenekea794e92008-05-05 18:50:19 +00002505
2506 // Predecessor at same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002507 if (SMgr.getLogicalLineNumber(SPred->getLocStart()) != EndLine) {
2508 Hint = PathDiagnosticPiece::Below;
2509 S = SPred;
2510 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002511 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002512
2513 // Generate the diagnostic.
Ted Kremenek4c479322008-05-06 23:07:13 +00002514 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002515 std::ostringstream os;
Ted Kremenek198cae02008-05-02 20:53:50 +00002516
Ted Kremenekea794e92008-05-05 18:50:19 +00002517 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002518
2519 if (FirstDecl)
2520 os << " and stored into '" << FirstDecl->getName() << '\'';
2521
Ted Kremenek9363fd92008-05-05 17:53:17 +00002522 os << " is no longer referenced after this point and has a retain count of +"
2523 << RetCount << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002524
Ted Kremenek4c479322008-05-06 23:07:13 +00002525 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002526}
2527
Ted Kremenek7d421f32008-04-09 23:49:11 +00002528void UseAfterRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002529
Ted Kremenek7d421f32008-04-09 23:49:11 +00002530 for (CFRefCount::use_after_iterator I = TF.use_after_begin(),
2531 E = TF.use_after_end(); I != E; ++I) {
2532
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002533 CFRefReport report(*this, I->first, I->second.second);
2534 report.addRange(I->second.first->getSourceRange());
Ted Kremenek270ab7d2008-04-18 01:56:37 +00002535 BR.EmitWarning(report);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002536 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00002537}
2538
2539void BadRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002540
Ted Kremenek7d421f32008-04-09 23:49:11 +00002541 for (CFRefCount::bad_release_iterator I = TF.bad_release_begin(),
2542 E = TF.bad_release_end(); I != E; ++I) {
2543
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002544 CFRefReport report(*this, I->first, I->second.second);
2545 report.addRange(I->second.first->getSourceRange());
2546 BR.EmitWarning(report);
Ted Kremenek7d421f32008-04-09 23:49:11 +00002547 }
2548}
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002549
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002550void Leak::EmitWarnings(BugReporter& BR) {
2551
2552 for (CFRefCount::leaks_iterator I = TF.leaks_begin(),
2553 E = TF.leaks_end(); I != E; ++I) {
2554
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002555 std::vector<SymbolID>& SymV = *(I->second);
2556 unsigned n = SymV.size();
2557
2558 for (unsigned i = 0; i < n; ++i) {
2559 CFRefReport report(*this, I->first, SymV[i]);
2560 BR.EmitWarning(report);
2561 }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002562 }
2563}
2564
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002565void Leak::GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes) {
2566 for (CFRefCount::leaks_iterator I=TF.leaks_begin(), E=TF.leaks_end();
2567 I!=E; ++I)
2568 Nodes.push_back(I->first);
2569}
2570
Ted Kremenekd7e26782008-05-16 18:33:44 +00002571bool Leak::isCached(BugReport& R) {
2572
2573 // Most bug reports are cached at the location where they occured.
2574 // With leaks, we want to unique them by the location where they were
2575 // allocated, and only report only a single path.
2576
2577 SymbolID Sym = static_cast<CFRefReport&>(R).getSymbol();
2578
2579 ExplodedNode<ValueState>* AllocNode =
2580 GetAllocationSite(R.getEndNode(), Sym).first;
2581
2582 if (!AllocNode)
2583 return false;
2584
2585 return BugTypeCacheLocation::isCached(AllocNode->getLocation());
2586}
2587
Ted Kremeneka7338b42008-03-11 06:39:11 +00002588//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002589// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002590//===----------------------------------------------------------------------===//
2591
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002592GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2593 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002594 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002595}