clang 24.0.0git
RetainSummaryManager.cpp
Go to the documentation of this file.
1//== RetainSummaryManager.cpp - Summaries for reference counting --*- C++ -*--//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines summaries implementation for retain counting, which
10// implements a reference count checker for Core Foundation, Cocoa
11// and OSObject (on Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
21#include <optional>
22
23using namespace clang;
24using namespace ento;
25
26template <class T>
27constexpr static bool isOneOf() {
28 return false;
29}
30
31/// Helper function to check whether the class is one of the
32/// rest of varargs.
33template <class T, class P, class... ToCompare>
34constexpr static bool isOneOf() {
35 return std::is_same_v<T, P> || isOneOf<T, ToCompare...>();
36}
37
38namespace {
39
40/// Fake attribute class for RC* attributes.
41struct GeneralizedReturnsRetainedAttr {
42 static bool classof(const Attr *A) {
43 if (auto AA = dyn_cast<AnnotateAttr>(A))
44 return AA->getAnnotation() == "rc_ownership_returns_retained";
45 return false;
46 }
47};
48
49struct GeneralizedReturnsNotRetainedAttr {
50 static bool classof(const Attr *A) {
51 if (auto AA = dyn_cast<AnnotateAttr>(A))
52 return AA->getAnnotation() == "rc_ownership_returns_not_retained";
53 return false;
54 }
55};
56
57struct GeneralizedConsumedAttr {
58 static bool classof(const Attr *A) {
59 if (auto AA = dyn_cast<AnnotateAttr>(A))
60 return AA->getAnnotation() == "rc_ownership_consumed";
61 return false;
62 }
63};
64
65}
66
67template <class T>
68std::optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
69 QualType QT) {
70 ObjKind K;
71 if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr,
72 CFReturnsNotRetainedAttr>()) {
73 if (!TrackObjCAndCFObjects)
74 return std::nullopt;
75
76 K = ObjKind::CF;
77 } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
78 NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
79 NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
80
81 if (!TrackObjCAndCFObjects)
82 return std::nullopt;
83
84 if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
85 NSReturnsNotRetainedAttr>() &&
87 return std::nullopt;
88 K = ObjKind::ObjC;
89 } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
90 OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
91 OSReturnsRetainedOnZeroAttr,
92 OSReturnsRetainedOnNonZeroAttr>()) {
93 if (!TrackOSObjects)
94 return std::nullopt;
95 K = ObjKind::OS;
96 } else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr,
97 GeneralizedReturnsRetainedAttr,
98 GeneralizedConsumedAttr>()) {
100 } else {
101 llvm_unreachable("Unexpected attribute");
102 }
103 if (D->hasAttr<T>())
104 return K;
105 return std::nullopt;
106}
107
108template <class T1, class T2, class... Others>
109std::optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
110 QualType QT) {
111 if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT))
112 return Out;
113 return hasAnyEnabledAttrOf<T2, Others...>(D, QT);
114}
115
116const RetainSummary *
117RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
118 // Unique "simple" summaries -- those without ArgEffects.
119 if (OldSumm.isSimple()) {
120 ::llvm::FoldingSetNodeID ID;
121 OldSumm.Profile(ID);
122
123 llvm::FoldingSetInsertToken InsertToken;
124 CachedSummaryNode *N = SimpleSummaries.lookup(ID, InsertToken);
125
126 if (!N) {
127 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
128 new (N) CachedSummaryNode(OldSumm);
129 SimpleSummaries.insert(N, InsertToken);
130 }
131
132 return &N->getValue();
133 }
134
135 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
136 new (Summ) RetainSummary(OldSumm);
137 return Summ;
138}
139
140static bool isSubclass(const Decl *D,
141 StringRef ClassName) {
142 using namespace ast_matchers;
143 DeclarationMatcher SubclassM =
144 cxxRecordDecl(isSameOrDerivedFrom(std::string(ClassName)));
145 return !(match(SubclassM, *D, D->getASTContext()).empty());
146}
147
148static bool isExactClass(const Decl *D, StringRef ClassName) {
149 using namespace ast_matchers;
150 DeclarationMatcher sameClassM = cxxRecordDecl(hasName(ClassName));
151 return !(match(sameClassM, *D, D->getASTContext()).empty());
152}
153
154bool RetainSummaryManager::isOSObjectSubclass(const Decl *D) const {
155 return MayHaveOSObjects && D && isSubclass(D, "OSMetaClassBase") &&
156 !isExactClass(D, "OSMetaClass");
157}
158
159static bool isOSObjectDynamicCast(StringRef S) { return S == "safeMetaCast"; }
160
161static bool isOSObjectRequiredCast(StringRef S) {
162 return S == "requiredMetaCast";
163}
164
165static bool isOSObjectThisCast(StringRef S) {
166 return S == "metaCast";
167}
168
169bool RetainSummaryManager::isOSObjectPtr(QualType QT) const {
170 return isOSObjectSubclass(QT->getPointeeCXXRecordDecl());
171}
172
173bool RetainSummaryManager::isISLObjectRef(QualType Ty) const {
174 return MayHaveISLTypes && StringRef(Ty.getAsString()).starts_with("isl_");
175}
176
177bool RetainSummaryManager::hasISLIdentifiers(const IdentifierTable &Idents) {
178 return llvm::any_of(Idents, [](const auto &Entry) {
179 return Entry.getKey().starts_with("isl_");
180 });
181}
182
183static bool isOSIteratorSubclass(const Decl *D) {
184 return isSubclass(D, "OSIterator");
185}
186
187static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
188 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
189 if (Ann->getAnnotation() == rcAnnotation)
190 return true;
191 }
192 return false;
193}
194
195static bool isRetain(const FunctionDecl *FD, StringRef FName) {
196 return FName.starts_with_insensitive("retain") ||
197 FName.ends_with_insensitive("retain");
198}
199
200static bool isRelease(const FunctionDecl *FD, StringRef FName) {
201 return FName.starts_with_insensitive("release") ||
202 FName.ends_with_insensitive("release");
203}
204
205static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
206 return FName.starts_with_insensitive("autorelease") ||
207 FName.ends_with_insensitive("autorelease");
208}
209
210static bool isMakeCollectable(StringRef FName) {
211 return FName.contains_insensitive("MakeCollectable");
212}
213
214/// A function is OSObject related if it is declared on a subclass
215/// of OSObject, or any of the parameters is a subclass of an OSObject.
216bool RetainSummaryManager::isOSObjectRelated(const CXXMethodDecl *MD) const {
217 if (isOSObjectSubclass(MD->getParent()))
218 return true;
219
220 for (ParmVarDecl *Param : MD->parameters()) {
221 QualType PT = Param->getType()->getPointeeType();
222 if (!PT.isNull())
223 if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
224 if (isOSObjectSubclass(RD))
225 return true;
226 }
227
228 return false;
229}
230
231bool
233 QT = QT.getCanonicalType();
234 const auto *RD = QT->getAsCXXRecordDecl();
235 if (!RD)
236 return false;
237 const IdentifierInfo *II = RD->getIdentifier();
238 if (II && II->getName() == "smart_ptr")
239 if (const auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext()))
240 if (ND->getNameAsString() == "os")
241 return true;
242 return false;
243}
244
245const RetainSummary *
246RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
247 StringRef FName, QualType RetTy) {
248 assert(TrackOSObjects &&
249 "Requesting a summary for an OSObject but OSObjects are not tracked");
250
251 if (RetTy->isPointerType()) {
252 const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
253 if (PD && isOSObjectSubclass(PD)) {
254 if (isOSObjectDynamicCast(FName) || isOSObjectRequiredCast(FName) ||
255 isOSObjectThisCast(FName))
256 return getDefaultSummary();
257
258 // TODO: Add support for the slightly common *Matching(table) idiom.
259 // Cf. IOService::nameMatching() etc. - these function have an unusual
260 // contract of returning at +0 or +1 depending on their last argument.
261 if (FName.ends_with("Matching")) {
262 return getPersistentStopSummary();
263 }
264
265 // All objects returned with functions *not* starting with 'get',
266 // or iterators, are returned at +1.
267 if ((!FName.starts_with("get") && !FName.starts_with("Get")) ||
269 return getOSSummaryCreateRule(FD);
270 } else {
271 return getOSSummaryGetRule(FD);
272 }
273 }
274 }
275
276 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
277 const CXXRecordDecl *Parent = MD->getParent();
278 if (Parent && isOSObjectSubclass(Parent)) {
279 if (FName == "release" || FName == "taggedRelease")
280 return getOSSummaryReleaseRule(FD);
281
282 if (FName == "retain" || FName == "taggedRetain")
283 return getOSSummaryRetainRule(FD);
284
285 if (FName == "free")
286 return getOSSummaryFreeRule(FD);
287
288 if (MD->getOverloadedOperator() == OO_New)
289 return getOSSummaryCreateRule(MD);
290 }
291 }
292
293 return nullptr;
294}
295
296const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
297 const FunctionDecl *FD,
298 StringRef FName,
299 QualType RetTy,
300 const FunctionType *FT,
301 bool &AllowAnnotations) {
302
303 ArgEffects ScratchArgs(AF.getEmptyMap());
304
305 std::string RetTyName = RetTy.getAsString();
306 if (FName == "pthread_create" || FName == "pthread_setspecific") {
307 // It's not uncommon to pass a tracked object into the thread
308 // as 'void *arg', and then release it inside the thread.
309 // FIXME: We could build a much more precise model for these functions.
310 return getPersistentStopSummary();
311 } else if(FName == "NSMakeCollectable") {
312 // Handle: id NSMakeCollectable(CFTypeRef)
313 AllowAnnotations = false;
314 return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
315 : getPersistentStopSummary();
316 } else if (FName == "CMBufferQueueDequeueAndRetain" ||
317 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
318 // These API functions are known to NOT act as a CFRetain wrapper.
319 // They simply make a new object owned by the caller.
320 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
321 ScratchArgs,
322 ArgEffect(DoNothing),
323 ArgEffect(DoNothing));
324 } else if (FName == "CFPlugInInstanceCreate") {
325 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
326 } else if (FName == "IORegistryEntrySearchCFProperty" ||
327 (RetTyName == "CFMutableDictionaryRef" &&
328 (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
329 FName == "IOServiceNameMatching" ||
330 FName == "IORegistryEntryIDMatching" ||
331 FName == "IOOpenFirmwarePathMatching"))) {
332 // Yes, these IOKit functions return CF objects.
333 // They also violate the CF naming convention.
334 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
335 ArgEffect(DoNothing), ArgEffect(DoNothing));
336 } else if (FName == "IOServiceGetMatchingService" ||
337 FName == "IOServiceGetMatchingServices") {
338 // These IOKit functions accept CF objects as arguments.
339 // They also consume them without an appropriate annotation.
340 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
341 return getPersistentSummary(RetEffect::MakeNoRet(),
342 ScratchArgs,
343 ArgEffect(DoNothing), ArgEffect(DoNothing));
344 } else if (FName == "IOServiceAddNotification" ||
345 FName == "IOServiceAddMatchingNotification") {
346 // More IOKit functions suddenly accepting (and even more suddenly,
347 // consuming) CF objects.
348 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
349 return getPersistentSummary(RetEffect::MakeNoRet(),
350 ScratchArgs,
351 ArgEffect(DoNothing), ArgEffect(DoNothing));
352 } else if (FName == "CVPixelBufferCreateWithBytes") {
353 // Eventually this can be improved by recognizing that the pixel
354 // buffer passed to CVPixelBufferCreateWithBytes is released via
355 // a callback and doing full IPA to make sure this is done correctly.
356 // Note that it's passed as a 'void *', so it's hard to annotate.
357 // FIXME: This function also has an out parameter that returns an
358 // allocated object.
359 ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
360 return getPersistentSummary(RetEffect::MakeNoRet(),
361 ScratchArgs,
362 ArgEffect(DoNothing), ArgEffect(DoNothing));
363 } else if (FName == "CGBitmapContextCreateWithData") {
364 // This is similar to the CVPixelBufferCreateWithBytes situation above.
365 // Eventually this can be improved by recognizing that 'releaseInfo'
366 // passed to CGBitmapContextCreateWithData is released via
367 // a callback and doing full IPA to make sure this is done correctly.
368 ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
369 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
370 ArgEffect(DoNothing), ArgEffect(DoNothing));
371 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
372 // Same as CVPixelBufferCreateWithBytes, just more arguments.
373 ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
374 return getPersistentSummary(RetEffect::MakeNoRet(),
375 ScratchArgs,
376 ArgEffect(DoNothing), ArgEffect(DoNothing));
377 } else if (FName == "VTCompressionSessionEncodeFrame" ||
378 FName == "VTCompressionSessionEncodeMultiImageFrame") {
379 // The context argument passed to VTCompressionSessionEncodeFrame() et.al.
380 // is passed to the callback specified when creating the session
381 // (e.g. with VTCompressionSessionCreate()) which can release it.
382 // To account for this possibility, conservatively stop tracking
383 // the context.
384 ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking));
385 return getPersistentSummary(RetEffect::MakeNoRet(),
386 ScratchArgs,
387 ArgEffect(DoNothing), ArgEffect(DoNothing));
388 } else if (FName == "dispatch_set_context" ||
389 FName == "xpc_connection_set_context") {
390 // The analyzer currently doesn't have a good way to reason about
391 // dispatch_set_finalizer_f() which typically cleans up the context.
392 // If we pass a context object that is memory managed, stop tracking it.
393 // Same with xpc_connection_set_finalizer_f().
394 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
395 return getPersistentSummary(RetEffect::MakeNoRet(),
396 ScratchArgs,
397 ArgEffect(DoNothing), ArgEffect(DoNothing));
398 } else if (FName.starts_with("NSLog")) {
399 return getDoNothingSummary();
400 } else if (FName.starts_with("NS") && FName.contains("Insert")) {
401 // Allowlist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
402 // be deallocated by NSMapRemove.
403 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
404 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
405 return getPersistentSummary(RetEffect::MakeNoRet(),
406 ScratchArgs, ArgEffect(DoNothing),
407 ArgEffect(DoNothing));
408 }
409
410 if (RetTy->isPointerType()) {
411
412 // For CoreFoundation ('CF') types.
413 if (cocoa::isRefType(RetTy, "CF", FName)) {
414 if (isRetain(FD, FName)) {
415 // CFRetain isn't supposed to be annotated. However, this may as
416 // well be a user-made "safe" CFRetain function that is incorrectly
417 // annotated as cf_returns_retained due to lack of better options.
418 // We want to ignore such annotation.
419 AllowAnnotations = false;
420
421 return getUnarySummary(FT, IncRef);
422 } else if (isAutorelease(FD, FName)) {
423 // The headers use cf_consumed, but we can fully model CFAutorelease
424 // ourselves.
425 AllowAnnotations = false;
426
427 return getUnarySummary(FT, Autorelease);
428 } else if (isMakeCollectable(FName)) {
429 AllowAnnotations = false;
430 return getUnarySummary(FT, DoNothing);
431 } else {
432 return getCFCreateGetRuleSummary(FD);
433 }
434 }
435
436 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
437 if (cocoa::isRefType(RetTy, "CG", FName) ||
438 cocoa::isRefType(RetTy, "CV", FName)) {
439 if (isRetain(FD, FName))
440 return getUnarySummary(FT, IncRef);
441 else
442 return getCFCreateGetRuleSummary(FD);
443 }
444
445 // For all other CF-style types, use the Create/Get
446 // rule for summaries but don't support Retain functions
447 // with framework-specific prefixes.
449 return getCFCreateGetRuleSummary(FD);
450 }
451
452 if (FD->hasAttr<CFAuditedTransferAttr>()) {
453 return getCFCreateGetRuleSummary(FD);
454 }
455 }
456
457 // Check for release functions, the only kind of functions that we care
458 // about that don't return a pointer type.
459 if (FName.starts_with("CG") || FName.starts_with("CF")) {
460 // Test for 'CGCF'.
461 FName = FName.substr(FName.starts_with("CGCF") ? 4 : 2);
462
463 if (isRelease(FD, FName))
464 return getUnarySummary(FT, DecRef);
465 else {
466 assert(ScratchArgs.isEmpty());
467 // Remaining CoreFoundation and CoreGraphics functions.
468 // We use to assume that they all strictly followed the ownership idiom
469 // and that ownership cannot be transferred. While this is technically
470 // correct, many methods allow a tracked object to escape. For example:
471 //
472 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
473 // CFDictionaryAddValue(y, key, x);
474 // CFRelease(x);
475 // ... it is okay to use 'x' since 'y' has a reference to it
476 //
477 // We handle this and similar cases with the follow heuristic. If the
478 // function name contains "InsertValue", "SetValue", "AddValue",
479 // "AppendValue", or "SetAttribute", then we assume that arguments may
480 // "escape." This means that something else holds on to the object,
481 // allowing it be used even after its local retain count drops to 0.
482 ArgEffectKind E = (FName.contains_insensitive("InsertValue") ||
483 FName.contains_insensitive("AddValue") ||
484 FName.contains_insensitive("SetValue") ||
485 FName.contains_insensitive("AppendValue") ||
486 FName.contains_insensitive("SetAttribute"))
487 ? MayEscape
488 : DoNothing;
489
490 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
491 ArgEffect(DoNothing), ArgEffect(E, ObjKind::CF));
492 }
493 }
494
495 return nullptr;
496}
497
498const RetainSummary *
499RetainSummaryManager::generateSummary(const FunctionDecl *FD,
500 bool &AllowAnnotations) {
501 // We generate "stop" summaries for implicitly defined functions.
502 if (FD->isImplicit())
503 return getPersistentStopSummary();
504
505 const IdentifierInfo *II = FD->getIdentifier();
506
507 StringRef FName = II ? II->getName() : "";
508
509 // Strip away preceding '_'. Doing this here will effect all the checks
510 // down below.
511 FName = FName.substr(FName.find_first_not_of('_'));
512
513 // Inspect the result type. Strip away any typedefs.
514 const auto *FT = FD->getType()->castAs<FunctionType>();
515 QualType RetTy = FT->getReturnType();
516
517 if (TrackOSObjects)
518 if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy))
519 return S;
520
521 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
522 if (!isOSObjectRelated(MD))
523 return getPersistentSummary(RetEffect::MakeNoRet(),
524 ArgEffects(AF.getEmptyMap()),
525 ArgEffect(DoNothing),
526 ArgEffect(StopTracking),
527 ArgEffect(DoNothing));
528
529 if (TrackObjCAndCFObjects)
530 if (const RetainSummary *S =
531 getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations))
532 return S;
533
534 return getDefaultSummary();
535}
536
537const RetainSummary *
538RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
539 // If we don't know what function we're calling, use our default summary.
540 if (!FD)
541 return getDefaultSummary();
542
543 // Look up a summary in our cache of FunctionDecls -> Summaries.
544 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
545 if (I != FuncSummaries.end())
546 return I->second;
547
548 // No summary? Generate one.
549 bool AllowAnnotations = true;
550 const RetainSummary *S = generateSummary(FD, AllowAnnotations);
551
552 // Annotations override defaults.
553 if (AllowAnnotations)
554 updateSummaryFromAnnotations(S, FD);
555
556 FuncSummaries[FD] = S;
557 return S;
558}
559
560//===----------------------------------------------------------------------===//
561// Summary creation for functions (largely uses of Core Foundation).
562//===----------------------------------------------------------------------===//
563
565 switch (E.getKind()) {
566 case DoNothing:
567 case Autorelease:
569 case IncRef:
574 case MayEscape:
575 case StopTracking:
576 case StopTrackingHard:
577 return E.withKind(StopTrackingHard);
578 case DecRef:
581 case Dealloc:
582 return E.withKind(Dealloc);
583 }
584
585 llvm_unreachable("Unknown ArgEffect kind");
586}
587
588const RetainSummary *
589RetainSummaryManager::updateSummaryForNonZeroCallbackArg(const RetainSummary *S,
590 AnyCall &C) {
591 ArgEffect RecEffect = getStopTrackingHardEquivalent(S->getReceiverEffect());
592 ArgEffect DefEffect = getStopTrackingHardEquivalent(S->getDefaultArgEffect());
593
594 ArgEffects ScratchArgs(AF.getEmptyMap());
595 ArgEffects CustomArgEffects = S->getArgEffects();
596 for (ArgEffects::iterator I = CustomArgEffects.begin(),
597 E = CustomArgEffects.end();
598 I != E; ++I) {
599 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
600 if (Translated.getKind() != DefEffect.getKind())
601 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
602 }
603
604 RetEffect RE = RetEffect::MakeNoRetHard();
605
606 // Special cases where the callback argument CANNOT free the return value.
607 // This can generally only happen if we know that the callback will only be
608 // called when the return value is already being deallocated.
609 if (const IdentifierInfo *Name = C.getIdentifier()) {
610 // When the CGBitmapContext is deallocated, the callback here will free
611 // the associated data buffer.
612 // The callback in dispatch_data_create frees the buffer, but not
613 // the data object.
614 if (Name->isStr("CGBitmapContextCreateWithData") ||
615 Name->isStr("dispatch_data_create"))
616 RE = S->getRetEffect();
617 }
618
619 return getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
620}
621
622void RetainSummaryManager::updateSummaryForReceiverUnconsumedSelf(
623 const RetainSummary *&S) {
624
626
627 Template->setReceiverEffect(ArgEffect(DoNothing));
628 Template->setRetEffect(RetEffect::MakeNoRet());
629}
630
631
632void RetainSummaryManager::updateSummaryForArgumentTypes(
633 const AnyCall &C, const RetainSummary *&RS) {
635
636 unsigned parm_idx = 0;
637 for (auto pi = C.param_begin(), pe = C.param_end(); pi != pe;
638 ++pi, ++parm_idx) {
639 QualType QT = (*pi)->getType();
640
641 // Skip already created values.
642 if (RS->getArgEffects().contains(parm_idx))
643 continue;
644
646
647 if (isISLObjectRef(QT)) {
649 } else if (isOSObjectPtr(QT)) {
650 K = ObjKind::OS;
651 } else if (cocoa::isCocoaObjectRef(QT)) {
652 K = ObjKind::ObjC;
653 } else if (coreFoundation::isCFObjectRef(QT)) {
654 K = ObjKind::CF;
655 }
656
657 if (K != ObjKind::AnyObj)
658 Template->addArg(AF, parm_idx,
659 ArgEffect(RS->getDefaultArgEffect().getKind(), K));
660 }
661}
662
663const RetainSummary *
665 bool HasNonZeroCallbackArg,
666 bool IsReceiverUnconsumedSelf,
667 QualType ReceiverType) {
668 const RetainSummary *Summ;
669 switch (C.getKind()) {
675 Summ = getFunctionSummary(cast_or_null<FunctionDecl>(C.getDecl()));
676 break;
677 case AnyCall::Block:
679 // FIXME: These calls are currently unsupported.
680 return getPersistentStopSummary();
681 case AnyCall::ObjCMethod: {
682 const auto *ME = cast_or_null<ObjCMessageExpr>(C.getExpr());
683 if (!ME) {
684 Summ = getMethodSummary(cast<ObjCMethodDecl>(C.getDecl()));
685 } else if (ME->isInstanceMessage()) {
686 Summ = getInstanceMethodSummary(ME, ReceiverType);
687 } else {
688 Summ = getClassMethodSummary(ME);
689 }
690 break;
691 }
692 }
693
694 if (HasNonZeroCallbackArg)
695 Summ = updateSummaryForNonZeroCallbackArg(Summ, C);
696
697 if (IsReceiverUnconsumedSelf)
698 updateSummaryForReceiverUnconsumedSelf(Summ);
699
700 updateSummaryForArgumentTypes(C, Summ);
701
702 assert(Summ && "Unknown call type?");
703 return Summ;
704}
705
706
707const RetainSummary *
708RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
710 return getCFSummaryCreateRule(FD);
711
712 return getCFSummaryGetRule(FD);
713}
714
716 const Decl *FD) {
717 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
718}
719
720std::optional<RetainSummaryManager::BehaviorSummary>
722 bool &hasTrustedImplementationAnnotation) {
723
724 IdentifierInfo *II = FD->getIdentifier();
725 if (!II)
726 return std::nullopt;
727
728 StringRef FName = II->getName();
729 FName = FName.substr(FName.find_first_not_of('_'));
730
731 QualType ResultTy = CE->getCallReturnType(Ctx);
732 if (ResultTy->isObjCIdType()) {
733 if (II->isStr("NSMakeCollectable"))
735 } else if (ResultTy->isPointerType()) {
736 // Handle: (CF|CG|CV)Retain
737 // CFAutorelease
738 // It's okay to be a little sloppy here.
739 if (FName == "CMBufferQueueDequeueAndRetain" ||
740 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
741 // These API functions are known to NOT act as a CFRetain wrapper.
742 // They simply make a new object owned by the caller.
743 return std::nullopt;
744 }
745 if (CE->getNumArgs() == 1 &&
746 (cocoa::isRefType(ResultTy, "CF", FName) ||
747 cocoa::isRefType(ResultTy, "CG", FName) ||
748 cocoa::isRefType(ResultTy, "CV", FName)) &&
749 (isRetain(FD, FName) || isAutorelease(FD, FName) ||
750 isMakeCollectable(FName)))
752
753 // safeMetaCast is called by OSDynamicCast.
754 // We assume that OSDynamicCast is either an identity (cast is OK,
755 // the input was non-zero),
756 // or that it returns zero (when the cast failed, or the input
757 // was zero).
758 if (TrackOSObjects) {
759 if (isOSObjectDynamicCast(FName) && FD->param_size() >= 1) {
761 } else if (isOSObjectRequiredCast(FName) && FD->param_size() >= 1) {
763 } else if (isOSObjectThisCast(FName) && isa<CXXMethodDecl>(FD) &&
764 !cast<CXXMethodDecl>(FD)->isStatic()) {
766 }
767 }
768
769 const FunctionDecl* FDD = FD->getDefinition();
771 hasTrustedImplementationAnnotation = true;
773 }
774 }
775
776 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
777 const CXXRecordDecl *Parent = MD->getParent();
778 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
779 if (FName == "release" || FName == "retain")
781 }
782
783 return std::nullopt;
784}
785
786const RetainSummary *
787RetainSummaryManager::getUnarySummary(const FunctionType* FT,
788 ArgEffectKind AE) {
789
790 // Unary functions have no arg effects by definition.
791 ArgEffects ScratchArgs(AF.getEmptyMap());
792
793 // Verify that this is *really* a unary function. This can
794 // happen if people do weird things.
795 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
796 if (!FTP || FTP->getNumParams() != 1)
797 return getPersistentStopSummary();
798
799 ArgEffect Effect(AE, ObjKind::CF);
800
801 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
802 return getPersistentSummary(RetEffect::MakeNoRet(),
803 ScratchArgs,
805}
806
807const RetainSummary *
808RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
809 return getPersistentSummary(RetEffect::MakeNoRet(),
810 AF.getEmptyMap(),
811 /*ReceiverEff=*/ArgEffect(DoNothing),
812 /*DefaultEff=*/ArgEffect(DoNothing),
813 /*ThisEff=*/ArgEffect(IncRef, ObjKind::OS));
814}
815
816const RetainSummary *
817RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) {
818 return getPersistentSummary(RetEffect::MakeNoRet(),
819 AF.getEmptyMap(),
820 /*ReceiverEff=*/ArgEffect(DoNothing),
821 /*DefaultEff=*/ArgEffect(DoNothing),
822 /*ThisEff=*/ArgEffect(DecRef, ObjKind::OS));
823}
824
825const RetainSummary *
826RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) {
827 return getPersistentSummary(RetEffect::MakeNoRet(),
828 AF.getEmptyMap(),
829 /*ReceiverEff=*/ArgEffect(DoNothing),
830 /*DefaultEff=*/ArgEffect(DoNothing),
831 /*ThisEff=*/ArgEffect(Dealloc, ObjKind::OS));
832}
833
834const RetainSummary *
835RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
836 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
837 AF.getEmptyMap());
838}
839
840const RetainSummary *
841RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
842 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
843 AF.getEmptyMap());
844}
845
846const RetainSummary *
847RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
848 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
849 ArgEffects(AF.getEmptyMap()));
850}
851
852const RetainSummary *
853RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
854 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
855 ArgEffects(AF.getEmptyMap()),
856 ArgEffect(DoNothing), ArgEffect(DoNothing));
857}
858
859
860
861
862//===----------------------------------------------------------------------===//
863// Summary creation for Selectors.
864//===----------------------------------------------------------------------===//
865
866std::optional<RetEffect>
867RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
868 const Decl *D) {
869 if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy))
870 return ObjCAllocRetE;
871
872 if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
873 GeneralizedReturnsRetainedAttr>(D, RetTy))
874 return RetEffect::MakeOwned(*K);
875
876 if (auto K = hasAnyEnabledAttrOf<
877 CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
878 GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
879 NSReturnsAutoreleasedAttr>(D, RetTy))
880 return RetEffect::MakeNotOwned(*K);
881
882 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
883 for (const auto *PD : MD->overridden_methods())
884 if (auto RE = getRetEffectFromAnnotations(RetTy, PD))
885 return RE;
886
887 return std::nullopt;
888}
889
890/// \return Whether the chain of typedefs starting from @c QT
891/// has a typedef with a given name @c Name.
893 StringRef Name) {
894 while (auto *T = QT->getAs<TypedefType>()) {
895 const auto &Context = T->getDecl()->getASTContext();
896 if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name))
897 return true;
898 QT = T->getDecl()->getUnderlyingType();
899 }
900 return false;
901}
902
904 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
905 return FD->getReturnType();
906 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
907 return MD->getReturnType();
908 } else {
909 llvm_unreachable("Unexpected decl");
910 }
911}
912
913bool RetainSummaryManager::applyParamAnnotationEffect(
914 const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD,
916 QualType QT = pd->getType();
917 if (auto K =
918 hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
919 GeneralizedConsumedAttr>(pd, QT)) {
920 Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
921 return true;
922 } else if (auto K = hasAnyEnabledAttrOf<
923 CFReturnsRetainedAttr, OSReturnsRetainedAttr,
924 OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
925 GeneralizedReturnsRetainedAttr>(pd, QT)) {
926
927 // For OSObjects, we try to guess whether the object is created based
928 // on the return value.
929 if (K == ObjKind::OS) {
930 QualType QT = getCallableReturnType(FD);
931
932 bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>();
933 bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>();
934
935 // The usual convention is to create an object on non-zero return, but
936 // it's reverted if the typedef chain has a typedef kern_return_t,
937 // because kReturnSuccess constant is defined as zero.
938 // The convention can be overwritten by custom attributes.
939 bool SuccessOnZero =
940 HasRetainedOnZero ||
941 (hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero);
942 bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
944 if (ShouldSplit && SuccessOnZero) {
946 } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
948 }
949 Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS));
950 }
951
952 // For others:
953 // Do nothing. Retained out parameters will either point to a +1 reference
954 // or NULL, but the way you check for failure differs depending on the
955 // API. Consequently, we don't have a good way to track them yet.
956 return true;
957 } else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr,
958 OSReturnsNotRetainedAttr,
959 GeneralizedReturnsNotRetainedAttr>(
960 pd, QT)) {
961 Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
962 return true;
963 }
964
965 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
966 for (const auto *OD : MD->overridden_methods()) {
967 const ParmVarDecl *OP = OD->parameters()[parm_idx];
968 if (applyParamAnnotationEffect(OP, parm_idx, OD, Template))
969 return true;
970 }
971 }
972
973 return false;
974}
975
976void
977RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
978 const FunctionDecl *FD) {
979 if (!FD)
980 return;
981
982 assert(Summ && "Must have a summary to add annotations to.");
983 RetainSummaryTemplate Template(Summ, *this);
984
985 // Effects on the parameters.
986 unsigned parm_idx = 0;
987 for (auto pi = FD->param_begin(),
988 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx)
989 applyParamAnnotationEffect(*pi, parm_idx, FD, Template);
990
991 QualType RetTy = FD->getReturnType();
992 if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
993 Template->setRetEffect(*RetE);
994
995 if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy))
996 Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS));
997}
998
999void
1000RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1001 const ObjCMethodDecl *MD) {
1002 if (!MD)
1003 return;
1004
1005 assert(Summ && "Must have a valid summary to add annotations to");
1006 RetainSummaryTemplate Template(Summ, *this);
1007
1008 // Effects on the receiver.
1009 if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType()))
1010 Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC));
1011
1012 // Effects on the parameters.
1013 unsigned parm_idx = 0;
1014 for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe;
1015 ++pi, ++parm_idx)
1016 applyParamAnnotationEffect(*pi, parm_idx, MD, Template);
1017
1018 QualType RetTy = MD->getReturnType();
1019 if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1020 Template->setRetEffect(*RetE);
1021}
1022
1023const RetainSummary *
1024RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1025 Selector S, QualType RetTy) {
1026 // Any special effects?
1027 ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC);
1028 RetEffect ResultEff = RetEffect::MakeNoRet();
1029
1030 // Check the method family, and apply any default annotations.
1031 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1032 case OMF_None:
1033 case OMF_initialize:
1035 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1036 // FIXME: Does the non-threaded performSelector family really belong here?
1037 // The selector could be, say, @selector(copy).
1038 if (cocoa::isCocoaObjectRef(RetTy))
1040 else if (coreFoundation::isCFObjectRef(RetTy)) {
1041 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1042 // values for alloc, new, copy, or mutableCopy, so we have to
1043 // double-check with the selector. This is ugly, but there aren't that
1044 // many Objective-C methods that return CF objects, right?
1045 if (MD) {
1046 switch (S.getMethodFamily()) {
1047 case OMF_alloc:
1048 case OMF_new:
1049 case OMF_copy:
1050 case OMF_mutableCopy:
1051 ResultEff = RetEffect::MakeOwned(ObjKind::CF);
1052 break;
1053 default:
1055 break;
1056 }
1057 } else {
1059 }
1060 }
1061 break;
1062 case OMF_init:
1063 ResultEff = ObjCInitRetE;
1064 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
1065 break;
1066 case OMF_alloc:
1067 case OMF_new:
1068 case OMF_copy:
1069 case OMF_mutableCopy:
1070 if (cocoa::isCocoaObjectRef(RetTy))
1071 ResultEff = ObjCAllocRetE;
1072 else if (coreFoundation::isCFObjectRef(RetTy))
1073 ResultEff = RetEffect::MakeOwned(ObjKind::CF);
1074 break;
1075 case OMF_autorelease:
1076 ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC);
1077 break;
1078 case OMF_retain:
1079 ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC);
1080 break;
1081 case OMF_release:
1082 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
1083 break;
1084 case OMF_dealloc:
1085 ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC);
1086 break;
1087 case OMF_self:
1088 // -self is handled specially by the ExprEngine to propagate the receiver.
1089 break;
1090 case OMF_retainCount:
1091 case OMF_finalize:
1092 // These methods don't return objects.
1093 break;
1094 }
1095
1096 // If one of the arguments in the selector has the keyword 'delegate' we
1097 // should stop tracking the reference count for the receiver. This is
1098 // because the reference count is quite possibly handled by a delegate
1099 // method.
1100 if (S.isKeywordSelector()) {
1101 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1102 StringRef Slot = S.getNameForSlot(i);
1103 if (Slot.ends_with_insensitive("delegate")) {
1104 if (ResultEff == ObjCInitRetE)
1105 ResultEff = RetEffect::MakeNoRetHard();
1106 else
1107 ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC);
1108 }
1109 }
1110 }
1111
1112 if (ReceiverEff.getKind() == DoNothing &&
1113 ResultEff.getKind() == RetEffect::NoRet)
1114 return getDefaultSummary();
1115
1116 return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()),
1117 ArgEffect(ReceiverEff), ArgEffect(MayEscape));
1118}
1119
1120const RetainSummary *
1121RetainSummaryManager::getClassMethodSummary(const ObjCMessageExpr *ME) {
1122 assert(!ME->isInstanceMessage());
1123 const ObjCInterfaceDecl *Class = ME->getReceiverInterface();
1124
1125 return getMethodSummary(ME->getSelector(), Class, ME->getMethodDecl(),
1126 ME->getType(), ObjCClassMethodSummaries);
1127}
1128
1129const RetainSummary *RetainSummaryManager::getInstanceMethodSummary(
1130 const ObjCMessageExpr *ME,
1131 QualType ReceiverType) {
1132 const ObjCInterfaceDecl *ReceiverClass = nullptr;
1133
1134 // We do better tracking of the type of the object than the core ExprEngine.
1135 // See if we have its type in our private state.
1136 if (!ReceiverType.isNull())
1137 if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>())
1138 ReceiverClass = PT->getInterfaceDecl();
1139
1140 // If we don't know what kind of object this is, fall back to its static type.
1141 if (!ReceiverClass)
1142 ReceiverClass = ME->getReceiverInterface();
1143
1144 // FIXME: The receiver could be a reference to a class, meaning that
1145 // we should use the class method.
1146 // id x = [NSObject class];
1147 // [x performSelector:... withObject:... afterDelay:...];
1148 Selector S = ME->getSelector();
1149 const ObjCMethodDecl *Method = ME->getMethodDecl();
1150 if (!Method && ReceiverClass)
1151 Method = ReceiverClass->getInstanceMethod(S);
1152
1153 return getMethodSummary(S, ReceiverClass, Method, ME->getType(),
1154 ObjCMethodSummaries);
1155}
1156
1157const RetainSummary *
1158RetainSummaryManager::getMethodSummary(Selector S,
1159 const ObjCInterfaceDecl *ID,
1160 const ObjCMethodDecl *MD, QualType RetTy,
1161 ObjCMethodSummariesTy &CachedSummaries) {
1162
1163 // Objective-C method summaries are only applicable to ObjC and CF objects.
1164 if (!TrackObjCAndCFObjects)
1165 return getDefaultSummary();
1166
1167 // Look up a summary in our summary cache.
1168 const RetainSummary *Summ = CachedSummaries.find(ID, S);
1169
1170 if (!Summ) {
1171 Summ = getStandardMethodSummary(MD, S, RetTy);
1172
1173 // Annotations override defaults.
1174 updateSummaryFromAnnotations(Summ, MD);
1175
1176 // Memoize the summary.
1177 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1178 }
1179
1180 return Summ;
1181}
1182
1183void RetainSummaryManager::InitializeClassMethodSummaries() {
1184 ArgEffects ScratchArgs = AF.getEmptyMap();
1185
1186 // Create the [NSAssertionHandler currentHander] summary.
1187 addClassMethSummary("NSAssertionHandler", "currentHandler",
1188 getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
1189 ScratchArgs));
1190
1191 // Create the [NSAutoreleasePool addObject:] summary.
1192 ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
1193 addClassMethSummary("NSAutoreleasePool", "addObject",
1194 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1195 ArgEffect(DoNothing),
1196 ArgEffect(Autorelease)));
1197}
1198
1199void RetainSummaryManager::InitializeMethodSummaries() {
1200
1201 ArgEffects ScratchArgs = AF.getEmptyMap();
1202 // Create the "init" selector. It just acts as a pass-through for the
1203 // receiver.
1204 const RetainSummary *InitSumm = getPersistentSummary(
1205 ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
1206 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1207
1208 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1209 // claims the receiver and returns a retained object.
1210 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1211 InitSumm);
1212
1213 // The next methods are allocators.
1214 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
1215 ScratchArgs);
1216 const RetainSummary *CFAllocSumm =
1217 getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
1218
1219 // Create the "retain" selector.
1220 RetEffect NoRet = RetEffect::MakeNoRet();
1221 const RetainSummary *Summ = getPersistentSummary(
1222 NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
1223 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1224
1225 // Create the "release" selector.
1226 Summ = getPersistentSummary(NoRet, ScratchArgs,
1227 ArgEffect(DecRef, ObjKind::ObjC));
1228 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1229
1230 // Create the -dealloc summary.
1231 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
1232 ObjKind::ObjC));
1233 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1234
1235 // Create the "autorelease" selector.
1236 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
1237 ObjKind::ObjC));
1238 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1239
1240 // For NSWindow, allocated objects are (initially) self-owned.
1241 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1242 // self-own themselves. However, they only do this once they are displayed.
1243 // Thus, we need to track an NSWindow's display status.
1244 const RetainSummary *NoTrackYet =
1245 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1246 ArgEffect(StopTracking), ArgEffect(StopTracking));
1247
1248 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1249
1250 // For NSPanel (which subclasses NSWindow), allocated objects are not
1251 // self-owned.
1252 // FIXME: For now we don't track NSPanels. object for the same reason
1253 // as for NSWindow objects.
1254 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1255
1256 // For NSNull, objects returned by +null are singletons that ignore
1257 // retain/release semantics. Just don't track them.
1258 addClassMethSummary("NSNull", "null", NoTrackYet);
1259
1260 // Don't track allocated autorelease pools, as it is okay to prematurely
1261 // exit a method.
1262 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1263 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1264 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1265
1266 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1267 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1268 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1269
1270 // Create summaries for CIContext, 'createCGImage' and
1271 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1272 // automatically garbage collected.
1273 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1274 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1275 "format", "colorSpace");
1276 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1277}
1278
1279const RetainSummary *
1280RetainSummaryManager::getMethodSummary(const ObjCMethodDecl *MD) {
1281 const ObjCInterfaceDecl *ID = MD->getClassInterface();
1282 Selector S = MD->getSelector();
1283 QualType ResultTy = MD->getReturnType();
1284
1285 ObjCMethodSummariesTy *CachedSummaries;
1286 if (MD->isInstanceMethod())
1287 CachedSummaries = &ObjCMethodSummaries;
1288 else
1289 CachedSummaries = &ObjCClassMethodSummaries;
1290
1291 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
1292}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static bool isSubclass(const ObjCInterfaceDecl *Class, const IdentifierInfo *II)
static bool isRelease(const FunctionDecl *FD, StringRef FName)
static bool hasTypedefNamed(QualType QT, StringRef Name)
static bool isOSObjectRequiredCast(StringRef S)
static ArgEffect getStopTrackingHardEquivalent(ArgEffect E)
static constexpr bool isOneOf()
static bool isOSIteratorSubclass(const Decl *D)
static QualType getCallableReturnType(const NamedDecl *ND)
static bool isAutorelease(const FunctionDecl *FD, StringRef FName)
static bool isExactClass(const Decl *D, StringRef ClassName)
static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation)
static bool isOSObjectThisCast(StringRef S)
static bool isMakeCollectable(StringRef FName)
static bool isOSObjectDynamicCast(StringRef S)
static bool isRetain(const FunctionDecl *FD, StringRef FName)
An instance of this class corresponds to a call.
Definition AnyCall.h:27
@ Destructor
An implicit C++ destructor call (called implicitly or by operator 'delete')
Definition AnyCall.h:41
@ ObjCMethod
A call to an Objective-C method.
Definition AnyCall.h:34
@ Deallocator
A C++ deallocation function call (operator delete), via C++ delete-expression.
Definition AnyCall.h:54
@ Function
A function, function pointer, or a C++ method call.
Definition AnyCall.h:31
@ Allocator
A C++ allocation function call (operator new), via C++ new-expression.
Definition AnyCall.h:50
@ Constructor
An implicit or explicit C++ constructor call.
Definition AnyCall.h:44
@ InheritedConstructor
A C++ inherited constructor produced by a "using T::T" directive.
Definition AnyCall.h:47
@ Block
A call to an Objective-C block.
Definition AnyCall.h:37
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
bool hasAttr() const
Definition DeclBase.h:586
QualType getType() const
Definition Expr.h:146
Represents a function declaration or definition.
Definition Decl.h:2082
param_iterator param_end()
Definition Decl.h:2960
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
param_iterator param_begin()
Definition Decl.h:2959
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4208
size_t param_size() const
Definition Decl.h:2963
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5650
unsigned getNumParams() const
Definition TypeBase.h:5928
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4846
QualType getReturnType() const
Definition TypeBase.h:5186
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition DeclObjC.h:1072
Selector getSelector() const
Definition ExprObjC.cpp:301
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition ExprObjC.h:1288
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition ExprObjC.cpp:322
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
QualType getReturnType() const
Definition DeclObjC.h:332
ObjCInterfaceDecl * getClassInterface()
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8732
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isKeywordSelector() const
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
unsigned getNumArgs() const
bool isVoidType() const
Definition TypeBase.h:9306
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8917
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9604
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isObjCIdType() const
Definition TypeBase.h:9133
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
QualType getType() const
Definition Decl.h:725
An ArgEffect summarizes the retain count behavior on an argument or receiver to a function or method.
ArgEffect withKind(ArgEffectKind NewK)
ArgEffectKind getKind() const
static RetEffect MakeNotOwned(ObjKind o)
static RetEffect MakeOwned(ObjKind o)
@ NoRet
Indicates that no retain count information is tracked for the return value.
static RetEffect MakeNoRetHard()
bool isTrustedReferenceCountImplementation(const Decl *FD)
std::optional< BehaviorSummary > canEval(const CallExpr *CE, const FunctionDecl *FD, bool &hasTrustedImplementationAnnotation)
static bool isKnownSmartPointer(QualType QT)
const RetainSummary * getSummary(AnyCall C, bool HasNonZeroCallbackArg=false, bool IsReceiverUnconsumedSelf=false, QualType ReceiverType={})
Summary for a function with respect to ownership changes.
ArgEffect getReceiverEffect() const
getReceiverEffect - Returns the effect on the receiver of the call.
RetEffect getRetEffect() const
getRetEffect - Returns the effect on the return value of the call.
bool isSimple() const
A retain summary is simple if it has no ArgEffects other than the default.
void Profile(llvm::FoldingSetNodeID &ID) const
Profile this summary for inclusion in a FoldingSet.
internal::Matcher< Decl > DeclarationMatcher
Types of matchers for the top-level classes in the AST class hierarchy.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
bool isCocoaObjectRef(QualType T)
bool isRefType(QualType RetTy, StringRef Prefix, StringRef Name=StringRef())
bool followsCreateRule(const FunctionDecl *FD)
llvm::ImmutableMap< unsigned, ArgEffect > ArgEffects
ArgEffects summarizes the effects of a function/method call on all of its arguments.
ObjKind
Determines the object kind of a tracked object.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Generalized
Indicates that the tracked object is a generalized object.
@ CF
Indicates that the tracked object is a CF object.
@ AnyObj
Indicates that the tracked object could be a CF or Objective-C object.
@ ObjC
Indicates that the tracked object is an Objective-C object.
@ IncRef
The argument has its reference count increased by 1.
@ UnretainedOutParameter
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +0 v...
@ DoNothing
There is no effect.
@ RetainedOutParameter
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ RetainedOutParameterOnZero
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ MayEscape
The argument is treated as potentially escaping, meaning that even when its reference count hits 0 it...
@ StopTracking
All typestate tracking of the object ceases.
@ Dealloc
The argument is treated as if the referenced object was deallocated.
@ Autorelease
The argument is treated as if an -autorelease message had been sent to the referenced object.
@ RetainedOutParameterOnNonZero
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ DecRef
The argument has its reference count decreased by 1.
@ StopTrackingHard
All typestate tracking of the object ceases.
@ DecRefAndStopTrackingHard
Performs the combined functionality of DecRef and StopTrackingHard.
@ DecRefBridgedTransferred
The argument has its reference count decreased by 1 to model a transferred bridge cast under ARC.
PRESERVE_NONE bool NoRet(InterpState &S)
Definition Interp.h:3428
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
static bool classof(const OMPClause *T)
@ OMF_performSelector
@ OMF_None
No particular method family.
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6259