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/ExprCXX.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
18#include <optional>
19
20using namespace clang;
21
22namespace {
23
24bool hasPublicMethodInBaseClass(const CXXRecordDecl *R, StringRef NameToMatch) {
25 assert(R);
26 assert(R->hasDefinition());
27
28 for (const CXXMethodDecl *MD : R->methods()) {
29 const auto MethodName = safeGetName(ASTNode: MD);
30 if (MethodName == NameToMatch && MD->getAccess() == AS_public)
31 return true;
32 }
33 return false;
34}
35
36} // namespace
37
38namespace clang {
39
40std::optional<const clang::CXXRecordDecl *>
41hasPublicMethodInBase(const CXXBaseSpecifier *Base, StringRef NameToMatch) {
42 assert(Base);
43
44 const Type *T = Base->getType().getTypePtrOrNull();
45 if (!T)
46 return std::nullopt;
47
48 const CXXRecordDecl *R = T->getAsCXXRecordDecl();
49 if (!R) {
50 auto CT = Base->getType().getCanonicalType();
51 if (auto *TST = dyn_cast<TemplateSpecializationType>(Val&: CT)) {
52 auto TmplName = TST->getTemplateName();
53 if (!TmplName.isNull()) {
54 if (auto *TD = TmplName.getAsTemplateDecl())
55 R = dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl());
56 }
57 }
58 if (!R)
59 return std::nullopt;
60 }
61 if (!R->hasDefinition())
62 return std::nullopt;
63
64 return hasPublicMethodInBaseClass(R, NameToMatch) ? R : nullptr;
65}
66
67std::optional<bool> isSmartPtrCompatible(const CXXRecordDecl *R,
68 StringRef IncMethodName,
69 StringRef DecMethodName) {
70 assert(R);
71
72 R = R->getDefinition();
73 if (!R)
74 return std::nullopt;
75
76 bool hasRef = hasPublicMethodInBaseClass(R, NameToMatch: IncMethodName);
77 bool hasDeref = hasPublicMethodInBaseClass(R, NameToMatch: DecMethodName);
78 if (hasRef && hasDeref)
79 return true;
80
81 CXXBasePaths Paths;
82 Paths.setOrigin(const_cast<CXXRecordDecl *>(R));
83
84 bool AnyInconclusiveBase = false;
85 const auto hasPublicRefInBase = [&](const CXXBaseSpecifier *Base,
86 CXXBasePath &) {
87 auto hasRefInBase = clang::hasPublicMethodInBase(Base, NameToMatch: IncMethodName);
88 if (!hasRefInBase) {
89 AnyInconclusiveBase = true;
90 return false;
91 }
92 return (*hasRefInBase) != nullptr;
93 };
94
95 hasRef = hasRef || R->lookupInBases(BaseMatches: hasPublicRefInBase, Paths,
96 /*LookupInDependent =*/true);
97 if (AnyInconclusiveBase)
98 return std::nullopt;
99
100 Paths.clear();
101 const auto hasPublicDerefInBase = [&](const CXXBaseSpecifier *Base,
102 CXXBasePath &) {
103 auto hasDerefInBase = clang::hasPublicMethodInBase(Base, NameToMatch: DecMethodName);
104 if (!hasDerefInBase) {
105 AnyInconclusiveBase = true;
106 return false;
107 }
108 return (*hasDerefInBase) != nullptr;
109 };
110 hasDeref = hasDeref || R->lookupInBases(BaseMatches: hasPublicDerefInBase, Paths,
111 /*LookupInDependent =*/true);
112 if (AnyInconclusiveBase)
113 return std::nullopt;
114
115 return hasRef && hasDeref;
116}
117
118std::optional<bool> isRefCountable(const clang::CXXRecordDecl *R) {
119 return isSmartPtrCompatible(R, IncMethodName: "ref", DecMethodName: "deref");
120}
121
122std::optional<bool> isCheckedPtrCapable(const clang::CXXRecordDecl *R) {
123 return isSmartPtrCompatible(R, IncMethodName: "incrementCheckedPtrCount",
124 DecMethodName: "decrementCheckedPtrCount");
125}
126
127bool isRefType(const std::string &Name) {
128 return Name == "Ref" || Name == "RefAllowingPartiallyDestroyed" ||
129 Name == "RefPtr" || Name == "RefPtrAllowingPartiallyDestroyed";
130}
131
132bool isRetainPtrOrOSPtr(const std::string &Name) {
133 return Name == "RetainPtr" || Name == "RetainPtrArc" ||
134 Name == "OSObjectPtr" || Name == "OSObjectPtrArc";
135}
136
137bool isCheckedPtr(const std::string &Name) {
138 return Name == "CheckedPtr" || Name == "CheckedRef";
139}
140
141bool isOwnerPtr(const std::string &Name) {
142 return isRefType(Name) || isCheckedPtr(Name) || Name == "unique_ptr" ||
143 Name == "UniqueRef" || Name == "LazyUniqueRef";
144}
145
146bool isSmartPtrClass(const std::string &Name) {
147 return isRefType(Name) || isCheckedPtr(Name) || isRetainPtrOrOSPtr(Name) ||
148 Name == "WeakPtr" || Name == "WeakPtrFactory" ||
149 Name == "WeakPtrFactoryWithBitField" || Name == "WeakPtrImplBase" ||
150 Name == "WeakPtrImplBaseSingleThread" || Name == "ThreadSafeWeakPtr" ||
151 Name == "ThreadSafeWeakOrStrongPtr" ||
152 Name == "ThreadSafeWeakPtrControlBlock" ||
153 Name == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr";
154}
155
156bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
157 assert(F);
158 const std::string &FunctionName = safeGetName(ASTNode: F);
159
160 return isRefType(Name: FunctionName) || FunctionName == "adoptRef" ||
161 FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
162 FunctionName == "makeUniqueRefWithoutFastMallocCheck"
163
164 || FunctionName == "String" || FunctionName == "AtomString" ||
165 FunctionName == "UniqueString"
166 // FIXME: Implement as attribute.
167 || FunctionName == "Identifier";
168}
169
170bool isCtorOfCheckedPtr(const clang::FunctionDecl *F) {
171 assert(F);
172 return isCheckedPtr(Name: safeGetName(ASTNode: F));
173}
174
175bool isCtorOfRetainPtrOrOSPtr(const clang::FunctionDecl *F) {
176 const std::string &FunctionName = safeGetName(ASTNode: F);
177 return FunctionName == "RetainPtr" || FunctionName == "adoptNS" ||
178 FunctionName == "adoptCF" || FunctionName == "retainPtr" ||
179 FunctionName == "RetainPtrArc" || FunctionName == "adoptNSArc" ||
180 FunctionName == "adoptOSObject" || FunctionName == "adoptOSObjectArc";
181}
182
183bool isCtorOfSafePtr(const clang::FunctionDecl *F) {
184 return isCtorOfRefCounted(F) || isCtorOfCheckedPtr(F) ||
185 isCtorOfRetainPtrOrOSPtr(F);
186}
187
188bool isStdOrWTFMove(const clang::FunctionDecl *F) {
189 auto FnName = safeGetName(ASTNode: F);
190 auto *Namespace = F->getParent();
191 if (!Namespace)
192 return false;
193 auto *TUDeck = Namespace->getParent();
194 if (!isa_and_nonnull<TranslationUnitDecl>(Val: TUDeck))
195 return false;
196 auto NsName = safeGetName(ASTNode: Namespace);
197 return (NsName == "WTF" || NsName == "std") && FnName == "move";
198}
199
200template <typename Predicate>
201static bool isPtrOfType(const clang::QualType T, Predicate Pred) {
202 QualType type = T;
203 while (!type.isNull()) {
204 if (auto *SpecialT = type->getAs<TemplateSpecializationType>()) {
205 auto *Decl = SpecialT->getTemplateName().getAsTemplateDecl();
206 return Decl && Pred(Decl->getNameAsString());
207 } else if (auto *DTS = type->getAs<DeducedTemplateSpecializationType>()) {
208 auto *Decl = DTS->getTemplateName().getAsTemplateDecl();
209 return Decl && Pred(Decl->getNameAsString());
210 } else
211 break;
212 }
213 return false;
214}
215
216bool isRefOrCheckedPtrType(const clang::QualType T) {
217 return isPtrOfType(
218 T, Pred: [](auto Name) { return isRefType(Name) || isCheckedPtr(Name); });
219}
220
221bool isRetainPtrOrOSPtrType(const clang::QualType T) {
222 return isPtrOfType(T, Pred: [](auto Name) { return isRetainPtrOrOSPtr(Name); });
223}
224
225bool isOwnerPtrType(const clang::QualType T) {
226 return isPtrOfType(T, Pred: [](auto Name) { return isOwnerPtr(Name); });
227}
228
229std::optional<bool> isUncounted(const QualType T) {
230 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Val: T)) {
231 if (auto *Decl = Subst->getAssociatedDecl()) {
232 if (isRefType(Name: safeGetName(ASTNode: Decl)))
233 return false;
234 }
235 }
236 return isUncounted(Class: T->getAsCXXRecordDecl());
237}
238
239std::optional<bool> isUnchecked(const QualType T) {
240 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Val: T)) {
241 if (auto *Decl = Subst->getAssociatedDecl()) {
242 if (isCheckedPtr(Name: safeGetName(ASTNode: Decl)))
243 return false;
244 }
245 }
246 return isUnchecked(Class: T->getAsCXXRecordDecl());
247}
248
249void RetainTypeChecker::visitTranslationUnitDecl(
250 const TranslationUnitDecl *TUD) {
251 IsARCEnabled = TUD->getLangOpts().ObjCAutoRefCount;
252 DefaultSynthProperties = TUD->getLangOpts().ObjCDefaultSynthProperties;
253}
254
255void RetainTypeChecker::visitTypedef(const TypedefDecl *TD) {
256 auto QT = TD->getUnderlyingType();
257 if (!QT->isPointerType())
258 return;
259
260 auto PointeeQT = QT->getPointeeType();
261 const RecordType *RT = PointeeQT->getAsCanonical<RecordType>();
262 if (!RT) {
263 if (TD->hasAttr<ObjCBridgeAttr>() || TD->hasAttr<ObjCBridgeMutableAttr>()) {
264 RecordlessTypes.insert(V: TD->getASTContext()
265 .getTypedefType(Keyword: ElaboratedTypeKeyword::None,
266 /*Qualifier=*/std::nullopt, Decl: TD)
267 .getTypePtr());
268 }
269 return;
270 }
271
272 for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
273 if (Redecl->getAttr<ObjCBridgeAttr>() ||
274 Redecl->getAttr<ObjCBridgeMutableAttr>()) {
275 CFPointees.insert(V: RT);
276 return;
277 }
278 }
279}
280
281bool RetainTypeChecker::isUnretained(const QualType QT, bool ignoreARC) {
282 if (ento::cocoa::isCocoaObjectRef(T: QT) && (!IsARCEnabled || ignoreARC))
283 return true;
284 if (auto *RT = dyn_cast_or_null<RecordType>(
285 Val: QT.getCanonicalType()->getPointeeType().getTypePtrOrNull()))
286 return CFPointees.contains(V: RT);
287 return RecordlessTypes.contains(V: QT.getTypePtr());
288}
289
290std::optional<bool> isUncounted(const CXXRecordDecl* Class)
291{
292 // Keep isRefCounted first as it's cheaper.
293 if (!Class || isRefCounted(Class))
294 return false;
295
296 std::optional<bool> IsRefCountable = isRefCountable(R: Class);
297 if (!IsRefCountable)
298 return std::nullopt;
299
300 return (*IsRefCountable);
301}
302
303std::optional<bool> isUnchecked(const CXXRecordDecl *Class) {
304 if (!Class || isCheckedPtr(Class))
305 return false; // Cheaper than below
306 return isCheckedPtrCapable(R: Class);
307}
308
309std::optional<bool> isUncountedPtr(const QualType T) {
310 if (T->isPointerType() || T->isReferenceType()) {
311 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
312 return isUncounted(Class: CXXRD);
313 }
314 return false;
315}
316
317std::optional<bool> isUncheckedPtr(const QualType T) {
318 if (T->isPointerType() || T->isReferenceType()) {
319 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
320 return isUnchecked(Class: CXXRD);
321 }
322 return false;
323}
324
325std::optional<bool> isGetterOfSafePtr(const CXXMethodDecl *M) {
326 assert(M);
327
328 if (isa<CXXMethodDecl>(Val: M)) {
329 const CXXRecordDecl *calleeMethodsClass = M->getParent();
330 auto className = safeGetName(ASTNode: calleeMethodsClass);
331 auto method = safeGetName(ASTNode: M);
332
333 if (isCheckedPtr(Name: className) && (method == "get" || method == "ptr"))
334 return true;
335
336 if ((isRefType(Name: className) && (method == "get" || method == "ptr")) ||
337 ((className == "String" || className == "AtomString" ||
338 className == "AtomStringImpl" || className == "UniqueString" ||
339 className == "UniqueStringImpl" || className == "Identifier") &&
340 method == "impl"))
341 return true;
342
343 if (isRetainPtrOrOSPtr(Name: className) && method == "get")
344 return true;
345
346 // Ref<T> -> T conversion
347 // FIXME: Currently allowing any Ref<T> -> whatever cast.
348 if (isRefType(Name: className)) {
349 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
350 auto QT = maybeRefToRawOperator->getConversionType();
351 auto *T = QT.getTypePtrOrNull();
352 return T && (T->isPointerType() || T->isReferenceType());
353 }
354 }
355
356 if (isCheckedPtr(Name: className)) {
357 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
358 auto QT = maybeRefToRawOperator->getConversionType();
359 auto *T = QT.getTypePtrOrNull();
360 return T && (T->isPointerType() || T->isReferenceType());
361 }
362 }
363
364 if (isRetainPtrOrOSPtr(Name: className)) {
365 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(Val: M)) {
366 auto QT = maybeRefToRawOperator->getConversionType();
367 auto *T = QT.getTypePtrOrNull();
368 return T && (T->isPointerType() || T->isReferenceType() ||
369 T->isObjCObjectPointerType());
370 }
371 }
372 }
373 return false;
374}
375
376bool isRefCounted(const CXXRecordDecl *R) {
377 assert(R);
378 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
379 // FIXME: String/AtomString/UniqueString
380 const auto &ClassName = safeGetName(ASTNode: TmplR);
381 return isRefType(Name: ClassName);
382 }
383 return false;
384}
385
386bool isCheckedPtr(const CXXRecordDecl *R) {
387 assert(R);
388 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
389 const auto &ClassName = safeGetName(ASTNode: TmplR);
390 return isCheckedPtr(Name: ClassName);
391 }
392 return false;
393}
394
395bool isRetainPtrOrOSPtr(const CXXRecordDecl *R) {
396 assert(R);
397 if (auto *TmplR = R->getTemplateInstantiationPattern())
398 return isRetainPtrOrOSPtr(Name: safeGetName(ASTNode: TmplR));
399 return false;
400}
401
402bool isSmartPtr(const CXXRecordDecl *R) {
403 assert(R);
404 if (auto *TmplR = R->getTemplateInstantiationPattern())
405 return isSmartPtrClass(Name: safeGetName(ASTNode: TmplR));
406 return false;
407}
408
409enum class WebKitAnnotation : uint8_t {
410 None,
411 PointerConversion,
412 NoDelete,
413};
414
415static WebKitAnnotation typeAnnotationForReturnType(const FunctionDecl *FD) {
416 auto RetType = FD->getReturnType();
417 auto *Type = RetType.getTypePtrOrNull();
418 if (auto *MacroQualified = dyn_cast_or_null<MacroQualifiedType>(Val: Type))
419 Type = MacroQualified->desugar().getTypePtrOrNull();
420 auto *Attr = dyn_cast_or_null<AttributedType>(Val: Type);
421 if (!Attr)
422 return WebKitAnnotation::None;
423 auto *AnnotateType = dyn_cast_or_null<AnnotateTypeAttr>(Val: Attr->getAttr());
424 if (!AnnotateType)
425 return WebKitAnnotation::None;
426 auto Annotation = AnnotateType->getAnnotation();
427 if (Annotation == "webkit.pointerconversion")
428 return WebKitAnnotation::PointerConversion;
429 if (Annotation == "webkit.nodelete")
430 return WebKitAnnotation::NoDelete;
431 return WebKitAnnotation::None;
432}
433
434bool isPtrConversion(const FunctionDecl *F) {
435 assert(F);
436 if (isCtorOfRefCounted(F))
437 return true;
438
439 // FIXME: check # of params == 1
440 const auto FunctionName = safeGetName(ASTNode: F);
441 if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
442 FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
443 FunctionName == "checkedDowncast" || FunctionName == "bit_cast" ||
444 FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" ||
445 FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" ||
446 FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" ||
447 FunctionName == "dynamic_objc_cast" ||
448 FunctionName == "checked_objc_cast")
449 return true;
450
451 if (typeAnnotationForReturnType(FD: F) == WebKitAnnotation::PointerConversion)
452 return true;
453
454 return false;
455}
456
457bool isNoDeleteFunction(const FunctionDecl *F) {
458 return typeAnnotationForReturnType(FD: F) == WebKitAnnotation::NoDelete;
459}
460
461bool isTrivialBuiltinFunction(const FunctionDecl *F) {
462 if (!F || !F->getDeclName().isIdentifier())
463 return false;
464 auto Name = F->getName();
465 return Name.starts_with(Prefix: "__builtin") || Name == "__libcpp_verbose_abort" ||
466 Name.starts_with(Prefix: "os_log") || Name.starts_with(Prefix: "_os_log");
467}
468
469bool isSingleton(const NamedDecl *F) {
470 assert(F);
471 // FIXME: check # of params == 1
472 if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: F)) {
473 if (!MethodDecl->isStatic())
474 return false;
475 }
476 const auto &NameStr = safeGetName(ASTNode: F);
477 StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef.
478 return Name == "singleton" || Name.ends_with(Suffix: "Singleton");
479}
480
481// We only care about statements so let's use the simple
482// (non-recursive) visitor.
483class TrivialFunctionAnalysisVisitor
484 : public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> {
485
486 // Returns false if at least one child is non-trivial.
487 bool VisitChildren(const Stmt *S) {
488 for (const Stmt *Child : S->children()) {
489 if (Child && !Visit(S: Child)) {
490 if (OffendingStmt && !*OffendingStmt)
491 *OffendingStmt = Child;
492 return false;
493 }
494 }
495
496 return true;
497 }
498
499 template <typename StmtOrDecl, typename CheckFunction>
500 bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) {
501 auto CacheIt = Cache.find(S);
502 if (CacheIt != Cache.end() && !OffendingStmt)
503 return CacheIt->second;
504
505 // Treat a recursive statement to be trivial until proven otherwise.
506 auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true));
507 if (!IsNew)
508 return RecursiveIt->second;
509
510 bool Result = Function();
511
512 if (!Result) {
513 for (auto &It : RecursiveFn)
514 It.second = false;
515 }
516 RecursiveIt = RecursiveFn.find(S);
517 assert(RecursiveIt != RecursiveFn.end());
518 Result = RecursiveIt->second;
519 RecursiveFn.erase(RecursiveIt);
520 Cache[S] = Result;
521
522 return Result;
523 }
524
525 bool CanTriviallyDestruct(QualType Ty) {
526 if (Ty.isNull())
527 return false;
528
529 // T*, T& or T&& does not run its destructor.
530 if (Ty->isPointerOrReferenceType())
531 return true;
532
533 // Fundamental types (integral, nullptr_t, etc...) don't have destructors.
534 if (Ty->isFundamentalType() || Ty->isIntegralOrEnumerationType())
535 return true;
536
537 if (const auto *R = Ty->getAsCXXRecordDecl()) {
538 // C++ trivially destructible classes are fine.
539 if (R->hasDefinition() && R->hasTrivialDestructor())
540 return true;
541
542 // For Webkit, side-effects are fine as long as we don't delete objects,
543 // so check recursively.
544 if (const auto *Dtor = R->getDestructor())
545 return IsFunctionTrivial(D: Dtor);
546 }
547
548 // Structs in C are trivial.
549 if (Ty->isRecordType())
550 return true;
551
552 // For arrays it depends on the element type.
553 // FIXME: We should really use ASTContext::getAsArrayType instead.
554 if (const auto *AT = Ty->getAsArrayTypeUnsafe())
555 return CanTriviallyDestruct(Ty: AT->getElementType());
556
557 return false; // Otherwise it's likely not trivial.
558 }
559
560public:
561 using CacheTy = TrivialFunctionAnalysis::CacheTy;
562
563 TrivialFunctionAnalysisVisitor(CacheTy &Cache,
564 const Stmt **OffendingStmt = nullptr)
565 : Cache(Cache), OffendingStmt(OffendingStmt) {}
566
567 bool IsFunctionTrivial(const Decl *D) {
568 const Stmt **SavedOffendingStmt = std::exchange(obj&: OffendingStmt, new_val: nullptr);
569 auto Result = WithCachedResult(S: D, Function: [&]() {
570 if (auto *FnDecl = dyn_cast<FunctionDecl>(Val: D)) {
571 if (isNoDeleteFunction(F: FnDecl))
572 return true;
573 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D); MD && MD->isVirtual())
574 return false;
575 for (auto *Param : FnDecl->parameters()) {
576 if (!HasTrivialDestructor(VD: Param))
577 return false;
578 }
579 }
580 if (auto *CtorDecl = dyn_cast<CXXConstructorDecl>(Val: D)) {
581 for (auto *CtorInit : CtorDecl->inits()) {
582 if (!Visit(S: CtorInit->getInit()))
583 return false;
584 }
585 }
586 const Stmt *Body = D->getBody();
587 if (!Body)
588 return false;
589 return Visit(S: Body);
590 });
591 OffendingStmt = SavedOffendingStmt;
592 return Result;
593 }
594
595 bool HasTrivialDestructor(const VarDecl *VD) {
596 return WithCachedResult(
597 S: VD, Function: [&] { return CanTriviallyDestruct(Ty: VD->getType()); });
598 }
599
600 bool IsStatementTrivial(const Stmt *S) {
601 auto CacheIt = Cache.find(Val: S);
602 if (CacheIt != Cache.end())
603 return CacheIt->second;
604 bool Result = Visit(S);
605 Cache[S] = Result;
606 return Result;
607 }
608
609 bool VisitStmt(const Stmt *S) {
610 // All statements are non-trivial unless overriden later.
611 // Don't even recurse into children by default.
612 return false;
613 }
614
615 bool VisitAttributedStmt(const AttributedStmt *AS) {
616 // Ignore attributes.
617 return Visit(S: AS->getSubStmt());
618 }
619
620 bool VisitCompoundStmt(const CompoundStmt *CS) {
621 // A compound statement is allowed as long each individual sub-statement
622 // is trivial.
623 return WithCachedResult(S: CS, Function: [&]() { return VisitChildren(S: CS); });
624 }
625
626 bool VisitCoroutineBodyStmt(const CoroutineBodyStmt *CBS) {
627 return WithCachedResult(S: CBS, Function: [&]() { return VisitChildren(S: CBS); });
628 }
629
630 bool VisitReturnStmt(const ReturnStmt *RS) {
631 // A return statement is allowed as long as the return value is trivial.
632 if (auto *RV = RS->getRetValue())
633 return Visit(S: RV);
634 return true;
635 }
636
637 bool VisitDeclStmt(const DeclStmt *DS) {
638 for (auto &Decl : DS->decls()) {
639 // FIXME: Handle DecompositionDecls.
640 if (auto *VD = dyn_cast<VarDecl>(Val: Decl)) {
641 if (!HasTrivialDestructor(VD))
642 return false;
643 }
644 }
645 return VisitChildren(S: DS);
646 }
647 bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(S: DS); }
648 bool VisitIfStmt(const IfStmt *IS) {
649 return WithCachedResult(S: IS, Function: [&]() { return VisitChildren(S: IS); });
650 }
651 bool VisitForStmt(const ForStmt *FS) {
652 return WithCachedResult(S: FS, Function: [&]() { return VisitChildren(S: FS); });
653 }
654 bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) {
655 return WithCachedResult(S: FS, Function: [&]() { return VisitChildren(S: FS); });
656 }
657 bool VisitWhileStmt(const WhileStmt *WS) {
658 return WithCachedResult(S: WS, Function: [&]() { return VisitChildren(S: WS); });
659 }
660 bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(S: SS); }
661 bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(S: CS); }
662 bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(S: DS); }
663
664 // break, continue, goto, and label statements are always trivial.
665 bool VisitBreakStmt(const BreakStmt *) { return true; }
666 bool VisitContinueStmt(const ContinueStmt *) { return true; }
667 bool VisitGotoStmt(const GotoStmt *) { return true; }
668 bool VisitLabelStmt(const LabelStmt *) { return true; }
669
670 bool VisitUnaryOperator(const UnaryOperator *UO) {
671 // Unary operators are trivial if its operand is trivial except co_await.
672 return UO->getOpcode() != UO_Coawait && Visit(S: UO->getSubExpr());
673 }
674
675 bool VisitBinaryOperator(const BinaryOperator *BO) {
676 // Binary operators are trivial if their operands are trivial.
677 return Visit(S: BO->getLHS()) && Visit(S: BO->getRHS());
678 }
679
680 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
681 // Compound assignment operator such as |= is trivial if its
682 // subexpresssions are trivial.
683 return VisitChildren(S: CAO);
684 }
685
686 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
687 return VisitChildren(S: ASE);
688 }
689
690 bool VisitConditionalOperator(const ConditionalOperator *CO) {
691 // Ternary operators are trivial if their conditions & values are trivial.
692 return VisitChildren(S: CO);
693 }
694
695 bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(S: E); }
696
697 bool VisitStaticAssertDecl(const StaticAssertDecl *SAD) {
698 // Any static_assert is considered trivial.
699 return true;
700 }
701
702 bool VisitCallExpr(const CallExpr *CE) {
703 if (!checkArguments(CE))
704 return false;
705
706 auto *Callee = CE->getDirectCallee();
707 if (!Callee)
708 return false;
709
710 if (isPtrConversion(F: Callee))
711 return true;
712
713 const auto &Name = safeGetName(ASTNode: Callee);
714
715 if (Callee->isInStdNamespace() &&
716 (Name == "addressof" || Name == "forward" || Name == "move"))
717 return true;
718
719 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
720 Name == "WTFReportBacktrace" ||
721 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
722 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
723 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
724 Name == "isWebThread" || Name == "isUIThread" ||
725 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
726 isTrivialBuiltinFunction(F: Callee))
727 return true;
728
729 return IsFunctionTrivial(D: Callee);
730 }
731
732 bool VisitGCCAsmStmt(const GCCAsmStmt *AS) {
733 return AS->getAsmString() == "brk #0xc471";
734 }
735
736 bool
737 VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) {
738 // Non-type template paramter is compile time constant and trivial.
739 return true;
740 }
741
742 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
743 return VisitChildren(S: E);
744 }
745
746 bool VisitPredefinedExpr(const PredefinedExpr *E) {
747 // A predefined identifier such as "func" is considered trivial.
748 return true;
749 }
750
751 bool VisitOffsetOfExpr(const OffsetOfExpr *OE) {
752 // offsetof(T, D) is considered trivial.
753 return true;
754 }
755
756 bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
757 if (!checkArguments(CE: MCE))
758 return false;
759
760 bool TrivialThis = Visit(S: MCE->getImplicitObjectArgument());
761 if (!TrivialThis)
762 return false;
763
764 auto *Callee = MCE->getMethodDecl();
765 if (!Callee)
766 return false;
767
768 auto Name = safeGetName(ASTNode: Callee);
769 if (Name == "ref" || Name == "incrementCheckedPtrCount")
770 return true;
771
772 std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(M: Callee);
773 if (IsGetterOfRefCounted && *IsGetterOfRefCounted)
774 return true;
775
776 // Recursively descend into the callee to confirm that it's trivial as well.
777 return IsFunctionTrivial(D: Callee);
778 }
779
780 bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
781 if (!checkArguments(CE: OCE))
782 return false;
783 auto *Callee = OCE->getCalleeDecl();
784 if (!Callee)
785 return false;
786 // Recursively descend into the callee to confirm that it's trivial as well.
787 return IsFunctionTrivial(D: Callee);
788 }
789
790 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
791 if (auto *Expr = E->getExpr()) {
792 if (!Visit(S: Expr))
793 return false;
794 }
795 return true;
796 }
797
798 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
799 return Visit(S: E->getExpr());
800 }
801
802 bool checkArguments(const CallExpr *CE) {
803 for (const Expr *Arg : CE->arguments()) {
804 if (Arg && !Visit(S: Arg))
805 return false;
806 }
807 return true;
808 }
809
810 bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
811 for (const Expr *Arg : CE->arguments()) {
812 if (Arg && !Visit(S: Arg))
813 return false;
814 }
815
816 // Recursively descend into the callee to confirm that it's trivial.
817 return IsFunctionTrivial(D: CE->getConstructor());
818 }
819
820 bool VisitCXXDeleteExpr(const CXXDeleteExpr *DE) {
821 return CanTriviallyDestruct(Ty: DE->getDestroyedType());
822 }
823
824 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E) {
825 return IsFunctionTrivial(D: E->getConstructor());
826 }
827
828 bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(S: NE); }
829
830 bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
831 return Visit(S: ICE->getSubExpr());
832 }
833
834 bool VisitExplicitCastExpr(const ExplicitCastExpr *ECE) {
835 return Visit(S: ECE->getSubExpr());
836 }
837
838 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *VMT) {
839 return Visit(S: VMT->getSubExpr());
840 }
841
842 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE) {
843 if (auto *Temp = BTE->getTemporary()) {
844 if (!IsFunctionTrivial(D: Temp->getDestructor()))
845 return false;
846 }
847 return Visit(S: BTE->getSubExpr());
848 }
849
850 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) {
851 return Visit(S: AILE->getCommonExpr()) && Visit(S: AILE->getSubExpr());
852 }
853
854 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *AIIE) {
855 return true; // The current array index in VisitArrayInitLoopExpr is always
856 // trivial.
857 }
858
859 bool VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
860 return Visit(S: OVE->getSourceExpr());
861 }
862
863 bool VisitExprWithCleanups(const ExprWithCleanups *EWC) {
864 return Visit(S: EWC->getSubExpr());
865 }
866
867 bool VisitParenExpr(const ParenExpr *PE) { return Visit(S: PE->getSubExpr()); }
868
869 bool VisitInitListExpr(const InitListExpr *ILE) {
870 for (const Expr *Child : ILE->inits()) {
871 if (Child && !Visit(S: Child))
872 return false;
873 }
874 return true;
875 }
876
877 bool VisitMemberExpr(const MemberExpr *ME) {
878 // Field access is allowed but the base pointer may itself be non-trivial.
879 return Visit(S: ME->getBase());
880 }
881
882 bool VisitCXXThisExpr(const CXXThisExpr *CTE) {
883 // The expression 'this' is always trivial, be it explicit or implicit.
884 return true;
885 }
886
887 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
888 // nullptr is trivial.
889 return true;
890 }
891
892 bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
893 // The use of a variable is trivial.
894 return true;
895 }
896
897 // Constant literal expressions are always trivial
898 bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; }
899 bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; }
900 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; }
901 bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; }
902 bool VisitStringLiteral(const StringLiteral *E) { return true; }
903 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; }
904
905 bool VisitConstantExpr(const ConstantExpr *CE) {
906 // Constant expressions are trivial.
907 return true;
908 }
909
910 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *IVIE) {
911 // An implicit value initialization is trvial.
912 return true;
913 }
914
915private:
916 CacheTy &Cache;
917 CacheTy RecursiveFn;
918 const Stmt **OffendingStmt;
919};
920
921bool TrivialFunctionAnalysis::isTrivialImpl(
922 const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache,
923 const Stmt **OffendingStmt) {
924 TrivialFunctionAnalysisVisitor V(Cache, OffendingStmt);
925 return V.IsFunctionTrivial(D);
926}
927
928bool TrivialFunctionAnalysis::isTrivialImpl(
929 const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache,
930 const Stmt **OffendingStmt) {
931 TrivialFunctionAnalysisVisitor V(Cache, OffendingStmt);
932 return V.IsStatementTrivial(S);
933}
934
935bool TrivialFunctionAnalysis::hasTrivialDtorImpl(const VarDecl *VD,
936 CacheTy &Cache) {
937 TrivialFunctionAnalysisVisitor V(Cache);
938 return V.HasTrivialDestructor(VD);
939}
940
941} // namespace clang
942