1//=======- PtrTypesSemantics.cpp ---------------------------------*- 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#include "PtrTypesSemantics.h"
10#include "ASTUtils.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/CXXInheritance.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "llvm/ADT/StringSet.h"
21#include <optional>
22
23using namespace clang;
24
25namespace {
26
27bool hasPublicMethodInBaseClass(const CXXRecordDecl *R, StringRef NameToMatch) {
28 assert(R);
29 assert(R->hasDefinition());
30
31 for (const CXXMethodDecl *MD : R->methods()) {
32 const auto MethodName = safeGetName(ASTNode: MD);
33 if (MethodName == NameToMatch && MD->getAccess() == AS_public)
34 return true;
35 }
36
37 for (const Decl *D : R->decls()) {
38 const auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D);
39 if (!Shadow || Shadow->getAccess() != AS_public)
40 continue;
41 const auto *MD = dyn_cast<CXXMethodDecl>(Val: Shadow->getTargetDecl());
42 if (MD && safeGetName(ASTNode: MD) == NameToMatch)
43 return true;
44 }
45 return false;
46}
47
48} // namespace
49
50namespace clang {
51
52std::optional<const clang::CXXRecordDecl *>
53hasPublicMethodInBase(const CXXBaseSpecifier *Base, StringRef NameToMatch) {
54 assert(Base);
55
56 const Type *T = Base->getType().getTypePtrOrNull();
57 if (!T)
58 return std::nullopt;
59
60 const CXXRecordDecl *R = T->getAsCXXRecordDecl();
61 if (!R) {
62 auto CT = Base->getType().getCanonicalType();
63 if (auto *TST = dyn_cast<TemplateSpecializationType>(Val&: CT)) {
64 auto TmplName = TST->getTemplateName();
65 if (!TmplName.isNull()) {
66 if (auto *TD = TmplName.getAsTemplateDecl())
67 R = dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl());
68 }
69 }
70 if (!R)
71 return std::nullopt;
72 }
73 if (!R->hasDefinition())
74 return std::nullopt;
75
76 return hasPublicMethodInBaseClass(R, NameToMatch) ? R : nullptr;
77}
78
79static std::optional<bool> hasPublicMethodInHierarchy(const CXXRecordDecl *R,
80 StringRef MethodName) {
81 assert(R);
82
83 R = R->getDefinition();
84 if (!R)
85 return std::nullopt;
86
87 if (hasPublicMethodInBaseClass(R, NameToMatch: MethodName))
88 return true;
89
90 CXXBasePaths Paths;
91 Paths.setOrigin(const_cast<CXXRecordDecl *>(R));
92
93 bool AnyInconclusiveBase = false;
94 const auto hasPublicMethod = [&](const CXXBaseSpecifier *Base,
95 CXXBasePath &) {
96 auto HasMethodInBase = clang::hasPublicMethodInBase(Base, NameToMatch: MethodName);
97 if (!HasMethodInBase) {
98 AnyInconclusiveBase = true;
99 return false;
100 }
101 return (*HasMethodInBase) != nullptr;
102 };
103
104 bool Found = R->lookupInBases(BaseMatches: hasPublicMethod, Paths,
105 /*LookupInDependent =*/true);
106 if (AnyInconclusiveBase)
107 return std::nullopt;
108
109 return Found;
110}
111
112std::optional<bool> isSmartPtrCompatible(const CXXRecordDecl *R,
113 StringRef IncMethodName,
114 StringRef DecMethodName) {
115 assert(R);
116
117 auto HasInc = hasPublicMethodInHierarchy(R, MethodName: IncMethodName);
118 if (!HasInc)
119 return std::nullopt;
120
121 auto HasDec = hasPublicMethodInHierarchy(R, MethodName: DecMethodName);
122 if (!HasDec)
123 return std::nullopt;
124
125 return *HasInc && *HasDec;
126}
127
128std::optional<bool> isRefCountable(const clang::CXXRecordDecl *R) {
129 return isSmartPtrCompatible(R, IncMethodName: "ref", DecMethodName: "deref");
130}
131
132std::optional<bool> isCheckedPtrCapable(const clang::CXXRecordDecl *R) {
133 return isSmartPtrCompatible(R, IncMethodName: "incrementCheckedPtrCount",
134 DecMethodName: "decrementCheckedPtrCount");
135}
136
137std::optional<bool> isBorrowable(const clang::CXXRecordDecl *R) {
138 assert(R);
139 return hasPublicMethodInHierarchy(R, MethodName: "crashIfBorrowed");
140}
141
142bool isBorrow(const clang::CXXRecordDecl *R) {
143 if (!R)
144 return false;
145 return isBorrow(Name: safeGetName(ASTNode: R));
146}
147
148bool isBorrowType(const clang::QualType T) {
149 return isBorrow(R: T->getAsCXXRecordDecl());
150}
151
152QualType pointeeType(QualType T) {
153 while (!T.isNull()) {
154 QualType Pointee = T->getPointeeType();
155 if (Pointee.isNull())
156 break;
157 T = Pointee;
158 }
159 return T;
160}
161
162QualType borrowedType(QualType T) {
163 const auto *Specialization =
164 dyn_cast_or_null<ClassTemplateSpecializationDecl>(
165 Val: T->getAsCXXRecordDecl());
166 if (!Specialization)
167 return QualType();
168 const auto &Args = Specialization->getTemplateArgs();
169 if (!Args.size() || Args[0].getKind() != TemplateArgument::Type)
170 return QualType();
171 return Args[0].getAsType();
172}
173
174static bool hasLifetimeBoundCtor(const clang::CXXRecordDecl *R) {
175 if (!R || !R->hasDefinition())
176 return false;
177 for (const CXXConstructorDecl *Ctor : R->ctors()) {
178 for (const ParmVarDecl *Param : Ctor->parameters()) {
179 if (Param->hasAttr<LifetimeBoundAttr>() ||
180 Param->hasAttr<LifetimeCaptureByAttr>())
181 return true;
182 }
183 }
184 return false;
185}
186
187static bool isStdRangesViewInterface(const clang::CXXRecordDecl *R) {
188 if (!R || !R->getIdentifier() || R->getName() != "view_interface")
189 return false;
190 const auto *NS = dyn_cast<NamespaceDecl>(Val: R->getDeclContext());
191 return NS && NS->getIdentifier() && NS->getName() == "ranges" &&
192 NS->getParent()->isStdNamespace();
193}
194
195static bool derivesFromViewInterface(const clang::CXXRecordDecl *R) {
196 if (!R)
197 return false;
198 R = R->getDefinition();
199 if (!R)
200 return false;
201 if (isStdRangesViewInterface(R))
202 return true;
203 for (const CXXBaseSpecifier &Base : R->bases()) {
204 if (derivesFromViewInterface(R: Base.getType()->getAsCXXRecordDecl()))
205 return true;
206 }
207 return false;
208}
209
210bool isStdView(const clang::CXXRecordDecl *R) {
211 if (!R)
212 return false;
213 if (R->hasAttr<PointerAttr>())
214 return true;
215 static const llvm::StringSet<> StdIterators{
216 "reverse_iterator", "move_iterator", "common_iterator",
217 "counted_iterator", "basic_const_iterator"};
218 if (R->isInStdNamespace() && R->getIdentifier() &&
219 StdIterators.contains(key: R->getName()))
220 return true;
221 if (derivesFromViewInterface(R))
222 return true;
223 if (const auto *Parent = dyn_cast<CXXRecordDecl>(Val: R->getDeclContext()))
224 return isStdView(R: Parent);
225 return false;
226}
227
228bool isView(const clang::QualType T) {
229 if (T->isReferenceType())
230 return true;
231 if (lifetimes::isPointerLikeType(QT: T))
232 return true;
233 auto *Record = T->getAsCXXRecordDecl();
234 if (isStdView(R: Record))
235 return true;
236 return hasLifetimeBoundCtor(R: Record);
237}
238
239bool isRefType(const std::string &Name) {
240 return Name == "Ref" || Name == "RefAllowingPartiallyDestroyed" ||
241 Name == "RefPtr" || Name == "RefPtrAllowingPartiallyDestroyed";
242}
243
244bool isRetainPtrOrOSPtr(const std::string &Name) {
245 return Name == "RetainPtr" || Name == "RetainPtrArc" ||
246 Name == "OSObjectPtr" || Name == "OSObjectPtrArc";
247}
248
249bool isCheckedPtr(const std::string &Name) {
250 return Name == "CheckedPtr" || Name == "CheckedRef";
251}
252
253bool isUniquePtr(const std::string &Name) {
254 return Name == "unique_ptr" || Name == "UniqueRef" || Name == "LazyUniqueRef";
255}
256
257bool isBorrow(const std::string &Name) { return Name == "Borrow"; }
258
259bool isOwnerPtr(const std::string &Name) {
260 return isRefType(Name) || isCheckedPtr(Name) || isRetainPtrOrOSPtr(Name) ||
261 isUniquePtr(Name);
262}
263
264static bool isWeakPtrClass(const std::string &Name) {
265 return Name == "WeakPtr" || Name == "SingleThreadPackedWeakPtr" ||
266 Name == "SingleThreadWeakPtr" || Name == "ThreadSafeWeakPtr" ||
267 Name == "ThreadSafeWeakOrStrongPtr" || Name == "InlineWeakPtr";
268}
269
270bool isSmartPtrClass(const std::string &Name) {
271 return isRefType(Name) || isCheckedPtr(Name) || isRetainPtrOrOSPtr(Name) ||
272 isWeakPtrClass(Name) || Name == "WeakPtrFactory" ||
273 Name == "WeakPtrFactoryWithBitField" || Name == "WeakPtrImplBase" ||
274 Name == "WeakPtrImplBaseSingleThread" ||
275 Name == "ThreadSafeWeakOrStrongPtr" ||
276 Name == "ThreadSafeWeakPtrControlBlock" ||
277 Name == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr";
278}
279
280std::string getConstructorName(const clang::FunctionDecl *F) {
281 if (auto *Ctor = dyn_cast_or_null<CXXConstructorDecl>(Val: F))
282 return safeGetName(ASTNode: Ctor->getParent());
283 return safeGetName(ASTNode: F);
284}
285
286bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
287 assert(F);
288 auto FunctionName = getConstructorName(F);
289 return isRefType(Name: FunctionName) || FunctionName == "adoptRef" ||
290 FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
291 FunctionName == "makeUniqueRefWithoutFastMallocCheck"
292
293 || FunctionName == "String" || FunctionName == "AtomString" ||
294 FunctionName == "UniqueString"
295 // FIXME: Implement as attribute.
296 || FunctionName == "Identifier";
297}
298
299bool isCtorOfCheckedPtr(const clang::FunctionDecl *F) {
300 assert(F);
301 return isCheckedPtr(Name: getConstructorName(F));
302}
303
304bool isCtorOfRetainPtrOrOSPtr(const clang::FunctionDecl *F) {
305 auto FunctionName = getConstructorName(F);
306 return isRetainPtrOrOSPtr(Name: FunctionName) || FunctionName == "adoptNS" ||
307 FunctionName == "adoptNSNullable" || FunctionName == "adoptCF" ||
308 FunctionName == "adoptCFNullable" || FunctionName == "retainPtr" ||
309 FunctionName == "adoptNSArc" || FunctionName == "adoptOSObject" ||
310 FunctionName == "adoptOSObjectArc";
311}
312
313bool isCtorOfSafePtr(const clang::FunctionDecl *F) {
314 return isCtorOfRefCounted(F) || isCtorOfCheckedPtr(F) ||
315 isCtorOfRetainPtrOrOSPtr(F);
316}
317
318bool isStdOrWTFMove(const clang::FunctionDecl *F) {
319 auto FnName = safeGetName(ASTNode: F);
320 auto *Namespace = F->getParent();
321 if (!Namespace)
322 return false;
323 auto *TUDeck = Namespace->getParent();
324 if (!isa_and_nonnull<TranslationUnitDecl>(Val: TUDeck))
325 return false;
326 auto NsName = safeGetName(ASTNode: Namespace);
327 return (NsName == "WTF" || NsName == "std") && FnName == "move";
328}
329
330template <typename Predicate>
331static bool isPtrOfType(const clang::QualType T, Predicate Pred) {
332 QualType type = T;
333 while (!type.isNull()) {
334 if (auto *SpecialT = type->getAs<TemplateSpecializationType>()) {
335 auto *Decl = SpecialT->getTemplateName().getAsTemplateDecl();
336 return Decl && Pred(Decl->getNameAsString());
337 } else if (auto *DTS = type->getAs<DeducedTemplateSpecializationType>()) {
338 auto *Decl = DTS->getTemplateName().getAsTemplateDecl();
339 return Decl && Pred(Decl->getNameAsString());
340 } else if (auto *RD = type->getAs<RecordType>()) {
341 auto *Decl = RD->getDecl();
342 return Decl && Pred(Decl->getNameAsString());
343 } else
344 break;
345 }
346 return false;
347}
348
349bool isRefOrCheckedPtrType(const clang::QualType T) {
350 return isPtrOfType(
351 T, Pred: [](auto Name) { return isRefType(Name) || isCheckedPtr(Name); });
352}
353
354bool isRetainPtrOrOSPtrType(const clang::QualType T) {
355 return isPtrOfType(T, Pred: [](auto Name) { return isRetainPtrOrOSPtr(Name); });
356}
357
358bool isOwnerPtrType(const clang::QualType T) {
359 return isPtrOfType(T, Pred: [](auto Name) { return isOwnerPtr(Name); });
360}
361
362std::optional<bool> isUncounted(const QualType T) {
363 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Val: T)) {
364 if (auto *Decl = Subst->getAssociatedDecl()) {
365 if (isRefType(Name: safeGetName(ASTNode: Decl)))
366 return false;
367 }
368 }
369 return isUncounted(Class: T->getAsCXXRecordDecl());
370}
371
372std::optional<bool> isUnchecked(const QualType T) {
373 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Val: T)) {
374 if (auto *Decl = Subst->getAssociatedDecl()) {
375 if (isCheckedPtr(Name: safeGetName(ASTNode: Decl)))
376 return false;
377 }
378 }
379 return isUnchecked(Class: T->getAsCXXRecordDecl());
380}
381
382void RetainTypeChecker::visitTranslationUnitDecl(
383 const TranslationUnitDecl *TUD) {
384 IsARCEnabled = TUD->getLangOpts().ObjCAutoRefCount;
385 DefaultSynthProperties = TUD->getLangOpts().ObjCDefaultSynthProperties;
386}
387
388void RetainTypeChecker::visitTypedef(const TypedefDecl *TD) {
389 auto QT = TD->getUnderlyingType();
390 if (!QT->isPointerType())
391 return;
392
393 auto PointeeQT = QT->getPointeeType();
394 const RecordType *RT = PointeeQT->getAsCanonical<RecordType>();
395 if (!RT) {
396 if (TD->hasAttr<ObjCBridgeAttr>() || TD->hasAttr<ObjCBridgeMutableAttr>()) {
397 RecordlessTypes.insert(V: TD->getASTContext()
398 .getTypedefType(Keyword: ElaboratedTypeKeyword::None,
399 /*Qualifier=*/std::nullopt, Decl: TD)
400 .getTypePtr());
401 }
402 return;
403 }
404
405 for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
406 if (Redecl->getAttr<ObjCBridgeAttr>() ||
407 Redecl->getAttr<ObjCBridgeMutableAttr>()) {
408 CFPointees.insert(KV: {RT, TD});
409 return;
410 }
411 }
412}
413
414bool RetainTypeChecker::isUnretained(const QualType QT, bool ignoreARC) {
415 if (ento::cocoa::isCocoaObjectRef(T: QT) && (!IsARCEnabled || ignoreARC))
416 return true;
417 if (auto *RT = dyn_cast_or_null<RecordType>(
418 Val: QT.getCanonicalType()->getPointeeType().getTypePtrOrNull()))
419 return CFPointees.contains(Val: RT);
420 return RecordlessTypes.contains(V: QT.getTypePtr());
421}
422
423const TypedefDecl *RetainTypeChecker::getCanonicalDecl(QualType QT) {
424 if (auto *TT = dyn_cast_or_null<TypedefType>(Val: QT.getTypePtrOrNull())) {
425 if (auto *TD = dyn_cast<TypedefDecl>(Val: TT->getDecl()))
426 return TD;
427 }
428 QT = QT.getCanonicalType();
429 auto PointeeQT = QT->getPointeeType();
430 auto *PointeeType = PointeeQT.getTypePtrOrNull();
431 if (!PointeeType)
432 return nullptr;
433 auto *RD = dyn_cast<RecordType>(Val: PointeeType);
434 if (!RD)
435 return nullptr;
436 return CFPointees.lookup(Val: RD);
437}
438
439std::optional<bool> isUncounted(const CXXRecordDecl* Class)
440{
441 // Keep isRefCounted first as it's cheaper.
442 if (!Class || isRefCounted(Class))
443 return false;
444
445 std::optional<bool> IsRefCountable = isRefCountable(R: Class);
446 if (!IsRefCountable)
447 return std::nullopt;
448
449 return (*IsRefCountable);
450}
451
452std::optional<bool> isUnchecked(const CXXRecordDecl *Class) {
453 if (!Class || isCheckedPtr(Class))
454 return false; // Cheaper than below
455 return isCheckedPtrCapable(R: Class);
456}
457
458std::optional<bool> isUncountedPtr(const QualType T) {
459 if (T->isPointerType() || T->isReferenceType()) {
460 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
461 return isUncounted(Class: CXXRD);
462 }
463 return false;
464}
465
466std::optional<bool> isUncheckedPtr(const QualType T) {
467 if (T->isPointerType() || T->isReferenceType()) {
468 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
469 return isUnchecked(Class: CXXRD);
470 }
471 return false;
472}
473
474std::optional<bool> isGetterOfSafePtr(const CXXMethodDecl *M) {
475 assert(M);
476
477 const CXXRecordDecl *calleeMethodsClass = M->getParent();
478 std::string className = safeGetName(ASTNode: calleeMethodsClass);
479 std::string method = safeGetName(ASTNode: M);
480
481 auto OpType = M->getOverloadedOperator();
482 if (isCheckedPtr(Name: className) &&
483 (method == "get" || method == "ptr" || OpType == OO_Star))
484 return true;
485
486 if ((isRefType(Name: className) &&
487 (method == "get" || method == "ptr" || OpType == OO_Star)) ||
488 ((className == "String" || className == "AtomString" ||
489 className == "AtomStringImpl" || className == "UniqueString" ||
490 className == "UniqueStringImpl" || className == "Identifier") &&
491 method == "impl"))
492 return true;
493
494 if (isRetainPtrOrOSPtr(Name: className) && method == "get")
495 return true;
496
497 // Ref<T> -> T conversion
498 // FIXME: Currently allowing any Ref<T> -> whatever cast.
499 if (isRefType(Name: className)) {
500 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
501 QualType QT = maybeRefToRawOperator->getConversionType();
502 const Type *T = QT.getTypePtrOrNull();
503 return T && (T->isPointerType() || T->isReferenceType());
504 }
505 }
506
507 if (isCheckedPtr(Name: className)) {
508 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
509 QualType QT = maybeRefToRawOperator->getConversionType();
510 const Type *T = QT.getTypePtrOrNull();
511 return T && (T->isPointerType() || T->isReferenceType());
512 }
513 }
514
515 if (isRetainPtrOrOSPtr(Name: className)) {
516 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
517 QualType QT = maybeRefToRawOperator->getConversionType();
518 const Type *T = QT.getTypePtrOrNull();
519 return T && (T->isPointerType() || T->isReferenceType() ||
520 T->isObjCObjectPointerType());
521 }
522 }
523 return false;
524}
525
526bool isGetterOfUniquePtr(const CXXMethodDecl *M) {
527 assert(M);
528 if (!isUniquePtr(Name: safeGetName(ASTNode: M->getParent())))
529 return false;
530 auto method = safeGetName(ASTNode: M);
531 if (method == "get" || method == "ptr")
532 return true;
533 if (auto *conversion = dyn_cast<CXXConversionDecl>(Val: M)) {
534 const Type *T = conversion->getConversionType().getTypePtrOrNull();
535 return T && (T->isPointerType() || T->isReferenceType());
536 }
537 return false;
538}
539
540// The object lives until the program exits but a pointer stored in it doesn't
541// keep its pointee alive. A smart pointer keeps its pointee alive only if it
542// can't be reassigned or swapped.
543static bool isImmortalStorageType(QualType T) {
544 if (T.isNull() || T->isPointerType() || T->isReferenceType() ||
545 T->isObjCObjectPointerType())
546 return false;
547 auto Name = safeGetName(ASTNode: T->getAsCXXRecordDecl());
548 if (isSmartPtrClass(Name) || isOwnerPtr(Name))
549 return T.isConstQualified();
550 return true;
551}
552
553/// \returns true if \p R is NeverDestroyed or LazyNeverDestroyed which stores
554/// a non-pointer type.
555static bool isNeverDestroyedOfObject(const CXXRecordDecl *R) {
556 auto *Spec = dyn_cast_or_null<ClassTemplateSpecializationDecl>(Val: R);
557 if (!Spec)
558 return false;
559 auto Name = safeGetName(ASTNode: Spec);
560 if (Name != "NeverDestroyed" && Name != "LazyNeverDestroyed")
561 return false;
562 const auto &Args = Spec->getTemplateArgs();
563 return Args.size() && Args[0].getKind() == TemplateArgument::Type &&
564 isImmortalStorageType(T: Args[0].getAsType());
565}
566
567bool isAccessorOfNeverDestroyed(const CXXMethodDecl *M) {
568 assert(M);
569 if (!isNeverDestroyedOfObject(R: M->getParent()))
570 return false;
571 if (safeGetName(ASTNode: M) == "get" || M->getOverloadedOperator() == OO_Arrow)
572 return true;
573 if (auto *Conversion = dyn_cast<CXXConversionDecl>(Val: M)) {
574 const Type *T = Conversion->getConversionType().getTypePtrOrNull();
575 return T && (T->isPointerType() || T->isReferenceType());
576 }
577 return false;
578}
579
580bool isImmortalVar(const VarDecl *V) {
581 assert(V);
582 if (!V->hasGlobalStorage())
583 return false;
584 QualType T = V->getType();
585 if (V->hasAttr<NoDestroyAttr>() && isImmortalStorageType(T))
586 return true;
587 return isNeverDestroyedOfObject(R: T->getAsCXXRecordDecl());
588}
589
590bool isRefCounted(const CXXRecordDecl *R) {
591 assert(R);
592 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
593 // FIXME: String/AtomString/UniqueString
594 const auto &ClassName = safeGetName(ASTNode: TmplR);
595 return isRefType(Name: ClassName);
596 }
597 return false;
598}
599
600bool isCheckedPtr(const CXXRecordDecl *R) {
601 assert(R);
602 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
603 const auto &ClassName = safeGetName(ASTNode: TmplR);
604 return isCheckedPtr(Name: ClassName);
605 }
606 return false;
607}
608
609bool isRetainPtrOrOSPtr(const CXXRecordDecl *R) {
610 assert(R);
611 if (auto *TmplR = R->getTemplateInstantiationPattern())
612 return isRetainPtrOrOSPtr(Name: safeGetName(ASTNode: TmplR));
613 return false;
614}
615
616bool isWeakPtr(const CXXRecordDecl *R) {
617 assert(R);
618 if (auto *TmplR = R->getTemplateInstantiationPattern())
619 return isWeakPtrClass(Name: safeGetName(ASTNode: TmplR));
620 return false;
621}
622
623bool isSmartPtr(const CXXRecordDecl *R) {
624 assert(R);
625 if (auto *TmplR = R->getTemplateInstantiationPattern())
626 return isSmartPtrClass(Name: safeGetName(ASTNode: TmplR));
627 return false;
628}
629
630enum class WebKitAnnotation : uint8_t {
631 None,
632 PointerConversion,
633 NoDelete,
634};
635
636static WebKitAnnotation annotationType(StringRef Annotation) {
637 if (Annotation == "webkit.pointerconversion")
638 return WebKitAnnotation::PointerConversion;
639 if (Annotation == "webkit.nodelete")
640 return WebKitAnnotation::NoDelete;
641 return WebKitAnnotation::None;
642}
643
644static bool hasAnnotationForFunction(const FunctionDecl *FD,
645 WebKitAnnotation TargetAnnotation) {
646 for (auto *Attr : FD->specific_attrs<AnnotateAttr>()) {
647 if (annotationType(Annotation: Attr->getAnnotation()) == TargetAnnotation)
648 return true;
649 }
650 auto RetType = FD->getReturnType();
651 auto *Type = RetType.getTypePtrOrNull();
652 if (auto *MacroQualified = dyn_cast_or_null<MacroQualifiedType>(Val: Type))
653 Type = MacroQualified->desugar().getTypePtrOrNull();
654 auto *Attr = dyn_cast_or_null<AttributedType>(Val: Type);
655 if (!Attr)
656 return false;
657 auto *AnnotateType = dyn_cast_or_null<AnnotateTypeAttr>(Val: Attr->getAttr());
658 if (!AnnotateType)
659 return false;
660 return annotationType(Annotation: AnnotateType->getAnnotation()) == TargetAnnotation;
661}
662
663bool isPtrConversion(const FunctionDecl *F) {
664 assert(F);
665 if (isCtorOfRefCounted(F))
666 return true;
667
668 // FIXME: check # of params == 1
669 const auto FunctionName = safeGetName(ASTNode: F);
670 if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
671 FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
672 FunctionName == "checkedDowncast" || FunctionName == "bit_cast" ||
673 FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" ||
674 FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" ||
675 FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" ||
676 FunctionName == "dynamic_objc_cast" ||
677 FunctionName == "checked_objc_cast")
678 return true;
679
680 if (hasAnnotationForFunction(FD: F, TargetAnnotation: WebKitAnnotation::PointerConversion))
681 return true;
682
683 return false;
684}
685
686static bool isNoDeleteFunctionDecl(const FunctionDecl *F) {
687 return hasAnnotationForFunction(FD: F, TargetAnnotation: WebKitAnnotation::NoDelete);
688}
689
690bool isNoDeleteFunction(const FunctionDecl *F) {
691 if (llvm::any_of(Range: F->redecls(), P: isNoDeleteFunctionDecl))
692 return true;
693
694 const auto *MD = dyn_cast<CXXMethodDecl>(Val: F);
695 if (!MD || !MD->isVirtual())
696 return false;
697
698 auto Overriders = llvm::to_vector(Range: MD->overridden_methods());
699 while (!Overriders.empty()) {
700 const auto *Fn = Overriders.pop_back_val();
701 llvm::append_range(C&: Overriders, R: Fn->overridden_methods());
702 if (isNoDeleteFunctionDecl(F: Fn))
703 return true;
704 }
705
706 return false;
707}
708
709bool isTrivialBuiltinFunction(const FunctionDecl *F) {
710 if (!F || !F->getDeclName().isIdentifier())
711 return false;
712 auto Name = F->getName();
713 return Name.starts_with(Prefix: "__builtin") || Name == "__libcpp_verbose_abort" ||
714 Name.starts_with(Prefix: "os_log") || Name.starts_with(Prefix: "_os_log");
715}
716
717bool isSingleton(const NamedDecl *F) {
718 assert(F);
719 // FIXME: check # of params == 1
720 if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: F)) {
721 if (!MethodDecl->isStatic())
722 return false;
723 }
724 const auto &NameStr = safeGetName(ASTNode: F);
725 StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef.
726 return Name == "singleton" || Name.ends_with(Suffix: "Singleton");
727}
728
729// We only care about statements so let's use the simple
730// (non-recursive) visitor.
731class TrivialFunctionAnalysisVisitor
732 : public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> {
733 using Base = ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool>;
734
735 // Returns false if at least one child is non-trivial.
736 bool VisitChildren(const Stmt *S) {
737 for (const Stmt *Child : S->children()) {
738 if (Child && !Visit(S: Child))
739 return false;
740 }
741
742 return true;
743 }
744
745 bool canUseCachedResult(bool CachedResult) const {
746 return CachedResult || !CallStack;
747 }
748
749 template <typename StmtOrDecl, typename CheckFunction>
750 bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) {
751 auto CacheIt = Cache.find(S);
752 if (CacheIt != Cache.end() && canUseCachedResult(CachedResult: CacheIt->second))
753 return CacheIt->second;
754
755 // Treat a recursive statement to be trivial until proven otherwise.
756 auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true));
757 if (!IsNew)
758 return RecursiveIt->second;
759
760 bool Result = Function();
761
762 if (!Result) {
763 for (auto &It : RecursiveFn)
764 It.second = false;
765 }
766 RecursiveIt = RecursiveFn.find(S);
767 assert(RecursiveIt != RecursiveFn.end());
768 Result = RecursiveIt->second;
769 RecursiveFn.erase(RecursiveIt);
770 Cache[S] = Result;
771
772 return Result;
773 }
774
775 static bool isTrivialType(QualType Ty) {
776 // T*, T&, or T&& does not delete.
777 if (Ty->isPointerOrReferenceType())
778 return true;
779
780 // Fundamental types (integral, nullptr, etc...) does not delete.
781 if (Ty->isFundamentalType() || Ty->isIntegralOrEnumerationType())
782 return true;
783
784 return false;
785 }
786
787 bool CanTriviallyDestruct(QualType Ty) {
788 if (Ty.isNull())
789 return false;
790
791 // FIXME: Handle a case when there is a local autorelease pool.
792 if (Ty->isObjCObjectPointerType()) {
793 auto Type = Ty.isDestructedType();
794 if (Type == QualType::DK_objc_weak_lifetime || Type == QualType::DK_none)
795 return true;
796 // strong lifetime in ARC could dealloc an object.
797 }
798
799 if (isTrivialType(Ty))
800 return true;
801
802 if (const auto *R = Ty->getAsCXXRecordDecl()) {
803 // C++ trivially destructible classes are fine.
804 if (R->hasDefinition() && R->hasTrivialDestructor())
805 return true;
806
807 if (auto *Dtor = R->getDestructor()) {
808 if (isNoDeleteFunction(F: Dtor))
809 return true;
810 }
811
812 if (FieldWithNonTrivialDtor(Cls: R))
813 return false;
814
815 // For Webkit, side-effects are fine as long as we don't delete objects,
816 // so check recursively.
817 if (const auto *Dtor = R->getDestructor())
818 return IsFunctionTrivial(D: Dtor);
819 }
820
821 // Structs in C are trivial.
822 if (Ty->isRecordType())
823 return true;
824
825 // For arrays it depends on the element type.
826 // FIXME: We should really use ASTContext::getAsArrayType instead.
827 if (const auto *AT = Ty->getAsArrayTypeUnsafe())
828 return CanTriviallyDestruct(Ty: AT->getElementType());
829
830 return false; // Otherwise it's likely not trivial.
831 }
832
833 // The body of an implicit or =default destructor says nothing about what it
834 // does: the calls to the base and member destructors are materialised at
835 // codegen, so the AST holds either no body at all (when the destructor is
836 // never odr-used) or an empty one. Reading the body therefore flips between
837 // blaming every such destructor and clearing every such destructor; ask the
838 // subobjects instead. Closure types depend on this -- their destructor is
839 // always implicit.
840 bool CanTriviallyRunImplicitDtor(const CXXDestructorDecl *Dtor) {
841 const CXXRecordDecl *Cls = Dtor->getParent();
842 if (!Cls->hasDefinition())
843 return false;
844 if (Cls->hasTrivialDestructor())
845 return true;
846 for (const FieldDecl *F : Cls->fields()) {
847 if (!CanTriviallyDestruct(Ty: F->getType()))
848 return false;
849 }
850 for (const CXXBaseSpecifier &B : Cls->bases()) {
851 if (!CanTriviallyDestruct(Ty: B.getType()))
852 return false;
853 }
854 for (const CXXBaseSpecifier &B : Cls->vbases()) {
855 if (!CanTriviallyDestruct(Ty: B.getType()))
856 return false;
857 }
858 return true;
859 }
860
861 bool CanTriviallyConstruct(QualType Ty) {
862 if (Ty.isNull())
863 return false;
864
865 if (isTrivialType(Ty))
866 return true;
867
868 if (const auto *R = Ty->getAsCXXRecordDecl()) {
869 // C++ trivially destructible classes are fine.
870 if (R->hasDefinition() && R->hasTrivialDefaultConstructor())
871 return true;
872 for (auto *Ctor : R->ctors()) {
873 if (Ctor->isDefaultConstructor() && IsFunctionTrivial(D: Ctor))
874 return true;
875 }
876 }
877
878 return false;
879 }
880
881 template <typename CacheTy, typename IsTrivialTypeFn>
882 bool hasNonTrivialField(const CXXRecordDecl *Cls,
883 const FieldDecl **OffendingField, CacheTy &Cache,
884 bool IncludeBases, IsTrivialTypeFn IsTrivialType) {
885 auto CacheIt = Cache.find(Cls);
886 if (CacheIt != Cache.end() && !OffendingField)
887 return CacheIt->second;
888
889 bool Result = ([&] {
890 auto HasNonTrivialField = [&](const CXXRecordDecl *R) {
891 for (const FieldDecl *F : R->fields()) {
892 if (!IsTrivialType(F->getType())) {
893 if (OffendingField)
894 *OffendingField = F;
895 return true;
896 }
897 }
898 return false;
899 };
900
901 if (HasNonTrivialField(Cls))
902 return true;
903
904 if (!IncludeBases || !Cls->hasDefinition())
905 return false;
906
907 CXXBasePaths Paths;
908 Paths.setOrigin(const_cast<CXXRecordDecl *>(Cls));
909 return Cls->lookupInBases(
910 BaseMatches: [&](const CXXBaseSpecifier *B, CXXBasePath &) {
911 auto *T = B->getType().getTypePtrOrNull();
912 if (!T)
913 return false;
914 auto *R = T->getAsCXXRecordDecl();
915 return R && HasNonTrivialField(R);
916 },
917 Paths, /*LookupInDependent =*/true);
918 })();
919
920 Cache[Cls] = Result;
921
922 return Result;
923 }
924
925public:
926 using CacheTy = TrivialFunctionAnalysis::CacheTy;
927
928 TrivialFunctionAnalysisVisitor(CacheTy &Cache,
929 NonTrivialityReason *Reason = nullptr)
930 : Cache(Cache), OffendingStmt(Reason ? &Reason->OffendingStmt : nullptr),
931 CallStack(Reason ? &Reason->CallStack : nullptr) {}
932
933 // Hides ConstStmtVisitor::Visit so that every recursive step in this class
934 // funnels through here. Recursion unwinds innermost-first, so the first
935 // statement recorded is the deepest one that failed -- the code actually
936 // responsible, rather than the enclosing statement that contains it.
937 // Implicit nodes have no location to point at, so they are passed over in
938 // favour of the nearest enclosing node that was actually written.
939 bool Visit(const Stmt *S) {
940 bool Result = Base::Visit(S);
941 if (!Result && OffendingStmt && !*OffendingStmt &&
942 S->getBeginLoc().isValid())
943 *OffendingStmt = S;
944 return Result;
945 }
946
947 bool IsFunctionTrivial(const Decl *D) {
948 if (!CallStack)
949 return IsFunctionTrivialImpl(D);
950
951 const auto *FnDecl = dyn_cast<FunctionDecl>(Val: D);
952 if (!FnDecl)
953 return IsFunctionTrivialImpl(D);
954
955 // CallStack[0, ActiveDepth) mirrors the functions currently being
956 // analyzed. Anything past that was left by a callee whose failure was
957 // tolerated, e.g. one of several candidate default constructors, and is
958 // not part of the chain that explains this call.
959 CallStack->truncate(N: ActiveDepth);
960 size_t Index = ActiveDepth++;
961 CallStack->push_back(Elt: {.Callee: FnDecl, .OffendingStmt: nullptr});
962
963 // Blame is recorded separately for each function, so that every frame
964 // can point at the code within it that leads further down the chain.
965 const Stmt *CalleeOffendingStmt = nullptr;
966 const Stmt **SavedOffendingStmt =
967 std::exchange(obj&: OffendingStmt, new_val: &CalleeOffendingStmt);
968 bool Result = IsFunctionTrivialImpl(D);
969 OffendingStmt = SavedOffendingStmt;
970
971 --ActiveDepth;
972 // On failure, keep this frame along with the frames its body left behind:
973 // together they are the chain from here down to the root cause.
974 if (Result)
975 CallStack->truncate(N: Index);
976 else
977 (*CallStack)[Index].OffendingStmt = CalleeOffendingStmt;
978 return Result;
979 }
980
981 bool IsFunctionTrivialImpl(const Decl *D) {
982 return WithCachedResult(S: D, Function: [&]() {
983 auto *FnDecl = dyn_cast<FunctionDecl>(Val: D);
984 auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: D);
985 auto *CtorDecl = dyn_cast<CXXConstructorDecl>(Val: D);
986 auto *DtorDecl = dyn_cast<CXXDestructorDecl>(Val: D);
987
988 if (FnDecl) {
989 if (isNoDeleteFunction(F: FnDecl))
990 return true;
991 if (MethodDecl && MethodDecl->isVirtual())
992 return false;
993 for (auto *Param : FnDecl->parameters()) {
994 if (!HasTrivialDestructor(VD: Param))
995 return false;
996 }
997 }
998 if (CtorDecl) {
999 for (auto *CtorInit : CtorDecl->inits()) {
1000 if (!Visit(S: CtorInit->getInit()))
1001 return false;
1002 }
1003 }
1004 // An implicit or =default special member has no body of its own to read.
1005 // A constructor is covered by the inits() walk above; a destructor has
1006 // to be decided from its subobjects. The synthesized body is in any case
1007 // absent from the AST until codegen materialises it, which the generic
1008 // null-body check below would otherwise call non-trivial.
1009 if (MethodDecl && !MethodDecl->isUserProvided()) {
1010 if (CtorDecl) {
1011 const CXXRecordDecl *RD = CtorDecl->getParent();
1012 if ((CtorDecl->isDefaultConstructor() &&
1013 RD->hasTrivialDefaultConstructor()) ||
1014 (CtorDecl->isCopyConstructor() &&
1015 RD->hasTrivialCopyConstructor()) ||
1016 (CtorDecl->isMoveConstructor() &&
1017 RD->hasTrivialMoveConstructor()))
1018 return true;
1019 }
1020 if (DtorDecl)
1021 return CanTriviallyRunImplicitDtor(Dtor: DtorDecl);
1022 }
1023 const Stmt *Body = D->getBody();
1024 if (!Body)
1025 return false;
1026 return Visit(S: Body);
1027 });
1028 }
1029
1030 bool HasTrivialDestructor(const VarDecl *VD) {
1031 return WithCachedResult(
1032 S: VD, Function: [&] { return CanTriviallyDestruct(Ty: VD->getType()); });
1033 }
1034
1035 const FieldDecl *FieldWithNonTrivialCtor(const CXXRecordDecl *Cls) {
1036 const FieldDecl *OffendingField = nullptr;
1037 // Base class subobjects are constructed by the base class constructors,
1038 // which appear in the constructor's inits() and are checked there, so
1039 // only look at the fields declared in Cls itself.
1040 hasNonTrivialField(
1041 Cls, OffendingField: &OffendingField, Cache&: FieldCtorCache, /*IncludeBases=*/false,
1042 IsTrivialType: [&](const QualType Ty) { return CanTriviallyConstruct(Ty); });
1043 return OffendingField;
1044 }
1045
1046 const FieldDecl *FieldWithNonTrivialDtor(const CXXRecordDecl *Cls) {
1047 const FieldDecl *OffendingField = nullptr;
1048 hasNonTrivialField(
1049 Cls, OffendingField: &OffendingField, Cache&: FieldDtorCache, /*IncludeBases=*/true,
1050 IsTrivialType: [&](const QualType Ty) { return CanTriviallyDestruct(Ty); });
1051 return OffendingField;
1052 }
1053
1054 bool IsStatementTrivial(const Stmt *S) {
1055 auto CacheIt = Cache.find(Val: S);
1056 if (CacheIt != Cache.end() && canUseCachedResult(CachedResult: CacheIt->second))
1057 return CacheIt->second;
1058 bool Result = Visit(S);
1059 Cache[S] = Result;
1060 return Result;
1061 }
1062
1063 bool VisitStmt(const Stmt *S) {
1064 // All statements are non-trivial unless overriden later.
1065 // Don't even recurse into children by default.
1066 return false;
1067 }
1068
1069 bool VisitAttributedStmt(const AttributedStmt *AS) {
1070 // Ignore attributes.
1071 return Visit(S: AS->getSubStmt());
1072 }
1073
1074 bool VisitCompoundStmt(const CompoundStmt *CS) {
1075 // A compound statement is allowed as long each individual sub-statement
1076 // is trivial.
1077 return WithCachedResult(S: CS, Function: [&]() { return VisitChildren(S: CS); });
1078 }
1079
1080 bool VisitCoroutineBodyStmt(const CoroutineBodyStmt *CBS) {
1081 return WithCachedResult(S: CBS, Function: [&]() { return VisitChildren(S: CBS); });
1082 }
1083
1084 bool VisitReturnStmt(const ReturnStmt *RS) {
1085 // A return statement is allowed as long as the return value is trivial. A
1086 // returned smart-pointer prvalue is special: under guaranteed copy elision
1087 // the temporary *is* the function's return slot, so it is destructed by the
1088 // caller, not here. Hence we may ignore that temporary's destructor.
1089 if (auto *RV = RS->getRetValue())
1090 return visitReturnValueElidingTemp(Arg: RV);
1091 return true;
1092 }
1093
1094 bool VisitDeclStmt(const DeclStmt *DS) {
1095 for (auto &Decl : DS->decls()) {
1096 // FIXME: Handle DecompositionDecls.
1097 if (auto *VD = dyn_cast<VarDecl>(Val: Decl)) {
1098 if (!HasTrivialDestructor(VD))
1099 return false;
1100 }
1101 }
1102 return VisitChildren(S: DS);
1103 }
1104 bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(S: DS); }
1105 bool VisitIfStmt(const IfStmt *IS) {
1106 return WithCachedResult(S: IS, Function: [&]() { return VisitChildren(S: IS); });
1107 }
1108 bool VisitForStmt(const ForStmt *FS) {
1109 return WithCachedResult(S: FS, Function: [&]() { return VisitChildren(S: FS); });
1110 }
1111 bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) {
1112 return WithCachedResult(S: FS, Function: [&]() { return VisitChildren(S: FS); });
1113 }
1114 bool VisitWhileStmt(const WhileStmt *WS) {
1115 return WithCachedResult(S: WS, Function: [&]() { return VisitChildren(S: WS); });
1116 }
1117 bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(S: SS); }
1118 bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(S: CS); }
1119 bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(S: DS); }
1120
1121 // break, continue, goto, and label statements are always trivial.
1122 bool VisitBreakStmt(const BreakStmt *) { return true; }
1123 bool VisitContinueStmt(const ContinueStmt *) { return true; }
1124 bool VisitGotoStmt(const GotoStmt *) { return true; }
1125 bool VisitLabelStmt(const LabelStmt *) { return true; }
1126
1127 bool VisitUnaryOperator(const UnaryOperator *UO) {
1128 // Unary operators are trivial if its operand is trivial except co_await.
1129 return UO->getOpcode() != UO_Coawait && Visit(S: UO->getSubExpr());
1130 }
1131
1132 bool VisitBinaryOperator(const BinaryOperator *BO) {
1133 // Binary operators are trivial if their operands are trivial.
1134 return Visit(S: BO->getLHS()) && Visit(S: BO->getRHS());
1135 }
1136
1137 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
1138 // Compound assignment operator such as |= is trivial if its
1139 // subexpresssions are trivial.
1140 return VisitChildren(S: CAO);
1141 }
1142
1143 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
1144 return VisitChildren(S: ASE);
1145 }
1146
1147 bool VisitConditionalOperator(const ConditionalOperator *CO) {
1148 // Ternary operators are trivial if their conditions & values are trivial.
1149 return VisitChildren(S: CO);
1150 }
1151
1152 bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(S: E); }
1153
1154 bool VisitStaticAssertDecl(const StaticAssertDecl *SAD) {
1155 // Any static_assert is considered trivial.
1156 return true;
1157 }
1158
1159 bool VisitCallExpr(const CallExpr *CE) {
1160 if (!checkArguments(CE))
1161 return false;
1162
1163 auto *Callee = CE->getDirectCallee();
1164 if (!Callee)
1165 return false;
1166
1167 if (isPtrConversion(F: Callee))
1168 return true;
1169
1170 const auto &Name = safeGetName(ASTNode: Callee);
1171
1172 if (Callee->isInStdNamespace() &&
1173 (Name == "addressof" || Name == "forward" || Name == "move"))
1174 return true;
1175
1176 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
1177 Name == "WTFReportBacktrace" ||
1178 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
1179 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
1180 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
1181 Name == "isWebThread" || Name == "isUIThread" ||
1182 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
1183 isTrivialBuiltinFunction(F: Callee))
1184 return true;
1185
1186 return IsFunctionTrivial(D: Callee);
1187 }
1188
1189 bool VisitGCCAsmStmt(const GCCAsmStmt *AS) {
1190 return AS->getAsmString() == "brk #0xc471";
1191 }
1192
1193 bool
1194 VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) {
1195 // Non-type template paramter is compile time constant and trivial.
1196 return true;
1197 }
1198
1199 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
1200 return VisitChildren(S: E);
1201 }
1202
1203 bool VisitPredefinedExpr(const PredefinedExpr *E) {
1204 // A predefined identifier such as "func" is considered trivial.
1205 return true;
1206 }
1207
1208 bool VisitOffsetOfExpr(const OffsetOfExpr *OE) {
1209 // offsetof(T, D) is considered trivial.
1210 return true;
1211 }
1212
1213 bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
1214 if (!checkArguments(CE: MCE))
1215 return false;
1216
1217 bool TrivialThis = Visit(S: MCE->getImplicitObjectArgument());
1218 if (!TrivialThis)
1219 return false;
1220
1221 auto *Callee = MCE->getMethodDecl();
1222 if (!Callee)
1223 return false;
1224
1225 if (isa<CXXDestructorDecl>(Val: Callee) &&
1226 !CanTriviallyDestruct(Ty: MCE->getObjectType()))
1227 return false;
1228
1229 auto Name = safeGetName(ASTNode: Callee);
1230 if (Name == "ref" || Name == "incrementCheckedPtrCount")
1231 return true;
1232
1233 std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(M: Callee);
1234 if (IsGetterOfRefCounted && *IsGetterOfRefCounted)
1235 return true;
1236
1237 // Recursively descend into the callee to confirm that it's trivial as well.
1238 return IsFunctionTrivial(D: Callee);
1239 }
1240
1241 bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
1242 if (!checkArguments(CE: OCE))
1243 return false;
1244 auto *Callee = OCE->getCalleeDecl();
1245 if (!Callee)
1246 return false;
1247 // Recursively descend into the callee to confirm that it's trivial as well.
1248 return IsFunctionTrivial(D: Callee);
1249 }
1250
1251 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *Op) {
1252 auto *SemanticExpr = Op->getSemanticForm();
1253 return SemanticExpr && Visit(S: SemanticExpr);
1254 }
1255
1256 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
1257 if (auto *Expr = E->getExpr()) {
1258 if (!Visit(S: Expr))
1259 return false;
1260 }
1261 return true;
1262 }
1263
1264 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
1265 return Visit(S: E->getExpr());
1266 }
1267
1268 bool checkArguments(const CallExpr *CE) {
1269 for (const Expr *Arg : CE->arguments()) {
1270 if (Arg && !Visit(S: Arg))
1271 return false;
1272 }
1273 return true;
1274 }
1275
1276 // Triviality check for a return value that may elide a smart-pointer
1277 // temporary's destructor.
1278 //
1279 // This is only valid for *return values*: a returned class prvalue is
1280 // constructed directly into the function's return slot (C++17 guaranteed copy
1281 // elision), so the temporary is destructed by the caller rather than here.
1282 //
1283 // It is deliberately NOT applied to call/constructor arguments. An argument
1284 // temporary's lifetime ends at the full-expression *in this function* (the
1285 // caller destroys arguments, e.g. per the Itanium C++ ABI), so its destructor
1286 // runs here and may invoke delete. Proving otherwise would require
1287 // interprocedural ownership analysis, so arguments are checked normally.
1288 bool visitReturnValueElidingTemp(const Expr *Arg) {
1289 QualType OriginalQT = Arg->getType();
1290 auto *Type = OriginalQT.getTypePtrOrNull();
1291 if (!Type)
1292 return Visit(S: Arg);
1293 auto *CXXRD = Type->getAsCXXRecordDecl();
1294 if (!CXXRD || !isSmartPtrClass(Name: safeGetName(ASTNode: CXXRD)))
1295 return Visit(S: Arg);
1296 Arg = Arg->IgnoreParenCasts();
1297 if (!Arg->isPRValue())
1298 return Visit(S: Arg);
1299 if (auto *Init = dyn_cast<InitListExpr>(Val: Arg)) {
1300 if (Init->getNumInits() == 1)
1301 Arg = Init->getInit(Init: 0);
1302 }
1303 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Arg)) {
1304 // Only elide when the temporary *is* the returned object, i.e. it has the
1305 // same smart-pointer type as the return value. Compare canonical,
1306 // unqualified types rather than relying on exact QualType identity, which
1307 // is sensitive to sugar (typedefs/aliases) and cv-qualifiers.
1308 if (OriginalQT.getCanonicalType().getUnqualifiedType() ==
1309 BTE->getType().getCanonicalType().getUnqualifiedType())
1310 return Visit(S: BTE->getSubExpr());
1311 }
1312 return Visit(S: Arg);
1313 }
1314
1315 bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
1316 if (CE->getNumArgs() == 1) {
1317 auto *InnerArg = CE->getArg(Arg: 0);
1318 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: InnerArg)) {
1319 auto *InnerExpr = MTE->getSubExpr();
1320 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: InnerExpr))
1321 InnerExpr = BTE->getSubExpr();
1322 auto InnerQT = InnerExpr->getType();
1323 if (auto *InnerDecl = InnerQT->getAsCXXRecordDecl()) {
1324 auto *OuterCls = CE->getConstructor()->getParent();
1325 if (isRefType(Name: safeGetName(ASTNode: OuterCls)) &&
1326 isRefType(Name: safeGetName(ASTNode: InnerDecl)))
1327 return Visit(S: InnerExpr);
1328 }
1329 }
1330 }
1331
1332 for (const Expr *Arg : CE->arguments()) {
1333 if (Arg && !Visit(S: Arg))
1334 return false;
1335 }
1336
1337 // Recursively descend into the callee to confirm that it's trivial.
1338 return IsFunctionTrivial(D: CE->getConstructor());
1339 }
1340
1341 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E) {
1342 return IsFunctionTrivial(D: E->getConstructor());
1343 }
1344
1345 bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(S: NE); }
1346
1347 bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
1348 return Visit(S: ICE->getSubExpr());
1349 }
1350
1351 bool VisitExplicitCastExpr(const ExplicitCastExpr *ECE) {
1352 return Visit(S: ECE->getSubExpr());
1353 }
1354
1355 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *VMT) {
1356 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: VMT->getSubExpr());
1357 ICE && ICE->getCastKind() == CK_NoOp &&
1358 ICE->getType().isConstQualified()) {
1359 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: ICE->getSubExpr());
1360 BTE && isNullSmartPtr(E: BTE->getSubExpr()))
1361 return Visit(S: BTE->getSubExpr());
1362 }
1363 return Visit(S: VMT->getSubExpr());
1364 }
1365
1366 // Returns true if E is known to evaluate to a smart pointer which holds
1367 // nullptr, e.g. RefPtr<T>(), RefPtr<T>(nullptr), Ref<T>(HashTableEmptyValue),
1368 // or a call to a function which simply returns one such as
1369 // HashTraits<Ref<T>>::emptyValue(). Destructing such a smart pointer can't
1370 // delete anything.
1371 bool isNullSmartPtr(const Expr *E, unsigned Depth = 0) {
1372 if (!E || Depth > 4)
1373 return false;
1374 while (true) {
1375 E = E->IgnoreParenCasts();
1376 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: E))
1377 E = EWC->getSubExpr();
1378 else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E))
1379 E = MTE->getSubExpr();
1380 else if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: E))
1381 E = BTE->getSubExpr();
1382 else
1383 break;
1384 }
1385 if (auto *CE = dyn_cast<CXXConstructExpr>(Val: E)) {
1386 auto *Ctor = CE->getConstructor();
1387 if (!Ctor || !isOwnerPtr(Name: safeGetName(ASTNode: Ctor->getParent())))
1388 return false;
1389 if (Ctor->isDefaultConstructor())
1390 return true;
1391 if (CE->getNumArgs() != 1)
1392 return false;
1393 auto *Arg = CE->getArg(Arg: 0)->IgnoreParenImpCasts();
1394 auto ArgType = Arg->getType();
1395 if (ArgType->isNullPtrType())
1396 return true;
1397 if (auto *TD = ArgType->getAsTagDecl();
1398 TD && safeGetName(ASTNode: TD) == "HashTableEmptyValueType")
1399 return true;
1400 if (Ctor->isCopyOrMoveConstructor())
1401 return isNullSmartPtr(E: Arg, Depth: Depth + 1);
1402 return false;
1403 }
1404 if (auto *CE = dyn_cast<CallExpr>(Val: E)) {
1405 auto *Callee = CE->getDirectCallee();
1406 if (!Callee)
1407 return false;
1408 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Callee); MD && MD->isVirtual())
1409 return false;
1410 auto *Body = dyn_cast_or_null<CompoundStmt>(Val: Callee->getBody());
1411 if (!Body || Body->size() != 1)
1412 return false;
1413 auto *RS = dyn_cast<ReturnStmt>(Val: Body->body_front());
1414 return RS && isNullSmartPtr(E: RS->getRetValue(), Depth: Depth + 1);
1415 }
1416 return false;
1417 }
1418
1419 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE) {
1420 if (auto *Temp = BTE->getTemporary()) {
1421 if (!IsFunctionTrivial(D: Temp->getDestructor()))
1422 return false;
1423 }
1424 return Visit(S: BTE->getSubExpr());
1425 }
1426
1427 bool VisitLambdaExpr(const LambdaExpr *LE) {
1428 // Creating the closure object runs each capture's initializer here.
1429 for (const Expr *Init : LE->capture_inits()) {
1430 if (Init && !Visit(S: Init))
1431 return false;
1432 }
1433
1434 // The body does not run at this point, but a closure that could destruct
1435 // an object is not safe to hand out from a nodelete function either, so
1436 // check it here rather than relying on finding the call.
1437 if (LE->isGenericLambda()) {
1438 // A generic lambda's own body is a dependent pattern whose calls are
1439 // unresolved. Only its instantiations describe code that runs; one that
1440 // is never instantiated cannot destruct anything.
1441 auto *CallOpTemplate =
1442 LE->getLambdaClass()->getDependentLambdaCallOperator();
1443 if (!CallOpTemplate)
1444 return true;
1445 for (const FunctionDecl *Spec : CallOpTemplate->specializations()) {
1446 if (const Stmt *Body = Spec->getBody()) {
1447 if (!Visit(S: Body))
1448 return false;
1449 }
1450 }
1451 return true;
1452 }
1453
1454 const auto *CallOp = LE->getCallOperator();
1455 if (!CallOp)
1456 return true;
1457 // The body is written inside the function being analyzed, so visit it
1458 // directly: that keeps the blame on the offending statement itself instead
1459 // of on the whole lambda. The parameters are destructed by whoever calls
1460 // the closure, and that call site is checked separately.
1461 const Stmt *Body = CallOp->getBody();
1462 return !Body || Visit(S: Body);
1463 }
1464
1465 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) {
1466 return Visit(S: AILE->getCommonExpr()) && Visit(S: AILE->getSubExpr());
1467 }
1468
1469 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *AIIE) {
1470 return true; // The current array index in VisitArrayInitLoopExpr is always
1471 // trivial.
1472 }
1473
1474 bool VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
1475 return Visit(S: OVE->getSourceExpr());
1476 }
1477
1478 bool VisitExprWithCleanups(const ExprWithCleanups *EWC) {
1479 return Visit(S: EWC->getSubExpr());
1480 }
1481
1482 bool VisitParenExpr(const ParenExpr *PE) { return Visit(S: PE->getSubExpr()); }
1483
1484 bool VisitInitListExpr(const InitListExpr *ILE) {
1485 for (const Expr *Child : ILE->inits()) {
1486 if (Child && !Visit(S: Child))
1487 return false;
1488 }
1489 return true;
1490 }
1491
1492 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *ILE) {
1493 auto *SubExpr = ILE->getSubExpr();
1494 if (!SubExpr)
1495 return false;
1496 // The backing array of a std::initializer_list is a temporary whose
1497 // lifetime ends in this function, so its elements are destructed here.
1498 if (!CanTriviallyDestruct(Ty: SubExpr->getType()))
1499 return false;
1500 return Visit(S: SubExpr);
1501 }
1502
1503 bool VisitMemberExpr(const MemberExpr *ME) {
1504 // Field access is allowed but the base pointer may itself be non-trivial.
1505 return Visit(S: ME->getBase());
1506 }
1507
1508 bool VisitCXXThisExpr(const CXXThisExpr *CTE) {
1509 // The expression 'this' is always trivial, be it explicit or implicit.
1510 return true;
1511 }
1512
1513 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1514 // nullptr is trivial.
1515 return true;
1516 }
1517
1518 bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
1519 // The use of a variable is trivial.
1520 return true;
1521 }
1522
1523 // Constant literal expressions are always trivial
1524 bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; }
1525 bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; }
1526 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; }
1527 bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; }
1528 bool VisitStringLiteral(const StringLiteral *E) { return true; }
1529 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; }
1530
1531 bool VisitConstantExpr(const ConstantExpr *CE) {
1532 // Constant expressions are trivial.
1533 return true;
1534 }
1535
1536 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *IVIE) {
1537 // An implicit value initialization is trvial.
1538 return true;
1539 }
1540
1541 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1542 // A value initialization of a scalar type such as int() is trivial.
1543 return true;
1544 }
1545
1546private:
1547 CacheTy &Cache;
1548 CacheTy FieldCtorCache;
1549 CacheTy FieldDtorCache;
1550 CacheTy RecursiveFn;
1551 const Stmt **OffendingStmt;
1552 SmallVectorImpl<NonTrivialityReason::Frame> *CallStack;
1553 unsigned ActiveDepth = 0;
1554};
1555
1556bool TrivialFunctionAnalysis::isTrivialImpl(
1557 const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache) {
1558 TrivialFunctionAnalysisVisitor V(Cache);
1559 return V.IsFunctionTrivial(D);
1560}
1561
1562bool TrivialFunctionAnalysis::isTrivialImpl(
1563 const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache) {
1564 TrivialFunctionAnalysisVisitor V(Cache);
1565 return V.IsStatementTrivial(S);
1566}
1567
1568NonTrivialityReason TrivialFunctionAnalysis::computeReason(const Stmt *S) {
1569 NonTrivialityReason Reason;
1570 CacheTy Cache;
1571 TrivialFunctionAnalysisVisitor V(Cache, &Reason);
1572 [[maybe_unused]] bool Trivial = V.IsStatementTrivial(S);
1573 assert(!Trivial && "computeReason called on a trivial statement");
1574 return Reason;
1575}
1576
1577bool TrivialFunctionAnalysis::hasTrivialDtorImpl(const VarDecl *VD,
1578 CacheTy &Cache) {
1579 TrivialFunctionAnalysisVisitor V(Cache);
1580 return V.HasTrivialDestructor(VD);
1581}
1582
1583const FieldDecl *
1584TrivialFunctionAnalysis::fieldWithNonTrivialCtorImpl(const CXXRecordDecl *RD,
1585 CacheTy &Cache) {
1586 TrivialFunctionAnalysisVisitor V(Cache);
1587 return V.FieldWithNonTrivialCtor(Cls: RD);
1588}
1589
1590const FieldDecl *
1591TrivialFunctionAnalysis::fieldWithNonTrivialDtorImpl(const CXXRecordDecl *RD,
1592 CacheTy &Cache) {
1593 TrivialFunctionAnalysisVisitor V(Cache);
1594 return V.FieldWithNonTrivialDtor(Cls: RD);
1595}
1596
1597} // namespace clang
1598