clang 24.0.0git
PtrTypesSemantics.cpp
Go to the documentation of this file.
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"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ExprCXX.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(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>(D);
39 if (!Shadow || Shadow->getAccess() != AS_public)
40 continue;
41 const auto *MD = dyn_cast<CXXMethodDecl>(Shadow->getTargetDecl());
42 if (MD && safeGetName(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>(CT)) {
64 auto TmplName = TST->getTemplateName();
65 if (!TmplName.isNull()) {
66 if (auto *TD = TmplName.getAsTemplateDecl())
67 R = dyn_cast_or_null<CXXRecordDecl>(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, 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, MethodName);
97 if (!HasMethodInBase) {
98 AnyInconclusiveBase = true;
99 return false;
100 }
101 return (*HasMethodInBase) != nullptr;
102 };
103
104 bool Found = R->lookupInBases(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, IncMethodName);
118 if (!HasInc)
119 return std::nullopt;
120
121 auto HasDec = hasPublicMethodInHierarchy(R, 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, "ref", "deref");
130}
131
132std::optional<bool> isCheckedPtrCapable(const clang::CXXRecordDecl *R) {
133 return isSmartPtrCompatible(R, "incrementCheckedPtrCount",
134 "decrementCheckedPtrCount");
135}
136
137std::optional<bool> isBorrowable(const clang::CXXRecordDecl *R) {
138 assert(R);
139 return hasPublicMethodInHierarchy(R, "crashIfBorrowed");
140}
141
143 if (!R)
144 return false;
145 return isBorrow(safeGetName(R));
146}
147
149 return isBorrow(T->getAsCXXRecordDecl());
150}
151
153 while (!T.isNull()) {
154 QualType Pointee = T->getPointeeType();
155 if (Pointee.isNull())
156 break;
157 T = Pointee;
158 }
159 return T;
160}
161
163 const auto *Specialization =
164 dyn_cast_or_null<ClassTemplateSpecializationDecl>(
165 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
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
188 if (!R || !R->getIdentifier() || R->getName() != "view_interface")
189 return false;
190 const auto *NS = dyn_cast<NamespaceDecl>(R->getDeclContext());
191 return NS && NS->getIdentifier() && NS->getName() == "ranges" &&
192 NS->getParent()->isStdNamespace();
193}
194
196 if (!R)
197 return false;
198 R = R->getDefinition();
199 if (!R)
200 return false;
202 return true;
203 for (const CXXBaseSpecifier &Base : R->bases()) {
204 if (derivesFromViewInterface(Base.getType()->getAsCXXRecordDecl()))
205 return true;
206 }
207 return false;
208}
209
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(R->getName()))
220 return true;
222 return true;
223 if (const auto *Parent = dyn_cast<CXXRecordDecl>(R->getDeclContext()))
224 return isStdView(Parent);
225 return false;
226}
227
229 if (T->isReferenceType())
230 return true;
232 return true;
233 auto *Record = T->getAsCXXRecordDecl();
234 if (isStdView(Record))
235 return true;
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
281 if (auto *Ctor = dyn_cast_or_null<CXXConstructorDecl>(F))
282 return safeGetName(Ctor->getParent());
283 return safeGetName(F);
284}
285
287 assert(F);
288 auto FunctionName = getConstructorName(F);
289 return isRefType(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
300 assert(F);
302}
303
305 auto FunctionName = getConstructorName(F);
306 return isRetainPtrOrOSPtr(FunctionName) || FunctionName == "adoptNS" ||
307 FunctionName == "adoptNSNullable" || FunctionName == "adoptCF" ||
308 FunctionName == "adoptCFNullable" || FunctionName == "retainPtr" ||
309 FunctionName == "adoptNSArc" || FunctionName == "adoptOSObject" ||
310 FunctionName == "adoptOSObjectArc";
311}
312
317
319 auto FnName = safeGetName(F);
320 auto *Namespace = F->getParent();
321 if (!Namespace)
322 return false;
323 auto *TUDeck = Namespace->getParent();
324 if (!isa_and_nonnull<TranslationUnitDecl>(TUDeck))
325 return false;
326 auto NsName = safeGetName(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
350 return isPtrOfType(
351 T, [](auto Name) { return isRefType(Name) || isCheckedPtr(Name); });
352}
353
355 return isPtrOfType(T, [](auto Name) { return isRetainPtrOrOSPtr(Name); });
356}
357
359 return isPtrOfType(T, [](auto Name) { return isOwnerPtr(Name); });
360}
361
362std::optional<bool> isUncounted(const QualType T) {
363 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) {
364 if (auto *Decl = Subst->getAssociatedDecl()) {
366 return false;
367 }
368 }
369 return isUncounted(T->getAsCXXRecordDecl());
370}
371
372std::optional<bool> isUnchecked(const QualType T) {
373 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) {
374 if (auto *Decl = Subst->getAssociatedDecl()) {
376 return false;
377 }
378 }
379 return isUnchecked(T->getAsCXXRecordDecl());
380}
381
383 const TranslationUnitDecl *TUD) {
384 IsARCEnabled = TUD->getLangOpts().ObjCAutoRefCount;
385 DefaultSynthProperties = TUD->getLangOpts().ObjCDefaultSynthProperties;
386}
387
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(TD->getASTContext()
399 /*Qualifier=*/std::nullopt, 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({RT, TD});
409 return;
410 }
411 }
412}
413
414bool RetainTypeChecker::isUnretained(const QualType QT, bool ignoreARC) {
415 if (ento::cocoa::isCocoaObjectRef(QT) && (!IsARCEnabled || ignoreARC))
416 return true;
417 if (auto *RT = dyn_cast_or_null<RecordType>(
419 return CFPointees.contains(RT);
420 return RecordlessTypes.contains(QT.getTypePtr());
421}
422
424 if (auto *TT = dyn_cast_or_null<TypedefType>(QT.getTypePtrOrNull())) {
425 if (auto *TD = dyn_cast<TypedefDecl>(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>(PointeeType);
434 if (!RD)
435 return nullptr;
436 return CFPointees.lookup(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(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
456}
457
458std::optional<bool> isUncountedPtr(const QualType T) {
459 if (T->isPointerType() || T->isReferenceType()) {
460 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
461 return isUncounted(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(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(calleeMethodsClass);
479 std::string method = safeGetName(M);
480
481 auto OpType = M->getOverloadedOperator();
482 if (isCheckedPtr(className) &&
483 (method == "get" || method == "ptr" || OpType == OO_Star))
484 return true;
485
486 if ((isRefType(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(className) && method == "get")
495 return true;
496
497 // Ref<T> -> T conversion
498 // FIXME: Currently allowing any Ref<T> -> whatever cast.
499 if (isRefType(className)) {
500 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(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(className)) {
508 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(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(className)) {
516 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(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
527 assert(M);
529 return false;
530 auto method = safeGetName(M);
531 if (method == "get" || method == "ptr")
532 return true;
533 if (auto *conversion = dyn_cast<CXXConversionDecl>(M)) {
534 const Type *T = conversion->getConversionType().getTypePtrOrNull();
535 return T && (T->isPointerType() || T->isReferenceType());
536 }
537 return false;
538}
539
541 assert(R);
542 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
543 // FIXME: String/AtomString/UniqueString
544 const auto &ClassName = safeGetName(TmplR);
545 return isRefType(ClassName);
546 }
547 return false;
548}
549
551 assert(R);
552 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
553 const auto &ClassName = safeGetName(TmplR);
554 return isCheckedPtr(ClassName);
555 }
556 return false;
557}
558
560 assert(R);
561 if (auto *TmplR = R->getTemplateInstantiationPattern())
562 return isRetainPtrOrOSPtr(safeGetName(TmplR));
563 return false;
564}
565
566bool isWeakPtr(const CXXRecordDecl *R) {
567 assert(R);
568 if (auto *TmplR = R->getTemplateInstantiationPattern())
569 return isWeakPtrClass(safeGetName(TmplR));
570 return false;
571}
572
573bool isSmartPtr(const CXXRecordDecl *R) {
574 assert(R);
575 if (auto *TmplR = R->getTemplateInstantiationPattern())
576 return isSmartPtrClass(safeGetName(TmplR));
577 return false;
578}
579
585
586static WebKitAnnotation annotationType(StringRef Annotation) {
587 if (Annotation == "webkit.pointerconversion")
589 if (Annotation == "webkit.nodelete")
592}
593
595 WebKitAnnotation TargetAnnotation) {
596 for (auto *Attr : FD->specific_attrs<AnnotateAttr>()) {
597 if (annotationType(Attr->getAnnotation()) == TargetAnnotation)
598 return true;
599 }
600 auto RetType = FD->getReturnType();
601 auto *Type = RetType.getTypePtrOrNull();
602 if (auto *MacroQualified = dyn_cast_or_null<MacroQualifiedType>(Type))
603 Type = MacroQualified->desugar().getTypePtrOrNull();
604 auto *Attr = dyn_cast_or_null<AttributedType>(Type);
605 if (!Attr)
606 return false;
607 auto *AnnotateType = dyn_cast_or_null<AnnotateTypeAttr>(Attr->getAttr());
608 if (!AnnotateType)
609 return false;
610 return annotationType(AnnotateType->getAnnotation()) == TargetAnnotation;
611}
612
614 assert(F);
615 if (isCtorOfRefCounted(F))
616 return true;
617
618 // FIXME: check # of params == 1
619 const auto FunctionName = safeGetName(F);
620 if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
621 FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
622 FunctionName == "checkedDowncast" || FunctionName == "bit_cast" ||
623 FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" ||
624 FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" ||
625 FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" ||
626 FunctionName == "dynamic_objc_cast" ||
627 FunctionName == "checked_objc_cast")
628 return true;
629
631 return true;
632
633 return false;
634}
635
639
641 if (llvm::any_of(F->redecls(), isNoDeleteFunctionDecl))
642 return true;
643
644 const auto *MD = dyn_cast<CXXMethodDecl>(F);
645 if (!MD || !MD->isVirtual())
646 return false;
647
648 auto Overriders = llvm::to_vector(MD->overridden_methods());
649 while (!Overriders.empty()) {
650 const auto *Fn = Overriders.pop_back_val();
651 llvm::append_range(Overriders, Fn->overridden_methods());
653 return true;
654 }
655
656 return false;
657}
658
660 if (!F || !F->getDeclName().isIdentifier())
661 return false;
662 auto Name = F->getName();
663 return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" ||
664 Name.starts_with("os_log") || Name.starts_with("_os_log");
665}
666
667bool isSingleton(const NamedDecl *F) {
668 assert(F);
669 // FIXME: check # of params == 1
670 if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(F)) {
671 if (!MethodDecl->isStatic())
672 return false;
673 }
674 const auto &NameStr = safeGetName(F);
675 StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef.
676 return Name == "singleton" || Name.ends_with("Singleton");
677}
678
679// We only care about statements so let's use the simple
680// (non-recursive) visitor.
682 : public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> {
684
685 // Returns false if at least one child is non-trivial.
686 bool VisitChildren(const Stmt *S) {
687 for (const Stmt *Child : S->children()) {
688 if (Child && !Visit(Child))
689 return false;
690 }
691
692 return true;
693 }
694
695 bool canUseCachedResult(bool CachedResult) const {
696 return CachedResult || !CallStack;
697 }
698
699 template <typename StmtOrDecl, typename CheckFunction>
700 bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) {
701 auto CacheIt = Cache.find(S);
702 if (CacheIt != Cache.end() && canUseCachedResult(CacheIt->second))
703 return CacheIt->second;
704
705 // Treat a recursive statement to be trivial until proven otherwise.
706 auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true));
707 if (!IsNew)
708 return RecursiveIt->second;
709
710 bool Result = Function();
711
712 if (!Result) {
713 for (auto &It : RecursiveFn)
714 It.second = false;
715 }
716 RecursiveIt = RecursiveFn.find(S);
717 assert(RecursiveIt != RecursiveFn.end());
718 Result = RecursiveIt->second;
719 RecursiveFn.erase(RecursiveIt);
720 Cache[S] = Result;
721
722 return Result;
723 }
724
725 static bool isTrivialType(QualType Ty) {
726 // T*, T&, or T&& does not delete.
727 if (Ty->isPointerOrReferenceType())
728 return true;
729
730 // Fundamental types (integral, nullptr, etc...) does not delete.
732 return true;
733
734 return false;
735 }
736
737 bool CanTriviallyDestruct(QualType Ty) {
738 if (Ty.isNull())
739 return false;
740
741 // FIXME: Handle a case when there is a local autorelease pool.
742 if (Ty->isObjCObjectPointerType()) {
743 auto Type = Ty.isDestructedType();
745 return true;
746 // strong lifetime in ARC could dealloc an object.
747 }
748
749 if (isTrivialType(Ty))
750 return true;
751
752 if (const auto *R = Ty->getAsCXXRecordDecl()) {
753 // C++ trivially destructible classes are fine.
754 if (R->hasDefinition() && R->hasTrivialDestructor())
755 return true;
756
757 if (auto *Dtor = R->getDestructor()) {
758 if (isNoDeleteFunction(Dtor))
759 return true;
760 }
761
763 return false;
764
765 // For Webkit, side-effects are fine as long as we don't delete objects,
766 // so check recursively.
767 if (const auto *Dtor = R->getDestructor())
768 return IsFunctionTrivial(Dtor);
769 }
770
771 // Structs in C are trivial.
772 if (Ty->isRecordType())
773 return true;
774
775 // For arrays it depends on the element type.
776 // FIXME: We should really use ASTContext::getAsArrayType instead.
777 if (const auto *AT = Ty->getAsArrayTypeUnsafe())
778 return CanTriviallyDestruct(AT->getElementType());
779
780 return false; // Otherwise it's likely not trivial.
781 }
782
783 bool CanTriviallyConstruct(QualType Ty) {
784 if (Ty.isNull())
785 return false;
786
787 if (isTrivialType(Ty))
788 return true;
789
790 if (const auto *R = Ty->getAsCXXRecordDecl()) {
791 // C++ trivially destructible classes are fine.
792 if (R->hasDefinition() && R->hasTrivialDefaultConstructor())
793 return true;
794 for (auto *Ctor : R->ctors()) {
795 if (Ctor->isDefaultConstructor() && IsFunctionTrivial(Ctor))
796 return true;
797 }
798 }
799
800 return false;
801 }
802
803 template <typename CacheTy, typename IsTrivialTypeFn>
804 bool hasNonTrivialField(const CXXRecordDecl *Cls,
805 const FieldDecl **OffendingField, CacheTy &Cache,
806 IsTrivialTypeFn IsTrivialType) {
807 auto CacheIt = Cache.find(Cls);
808 if (CacheIt != Cache.end() && !OffendingField)
809 return CacheIt->second;
810
811 bool Result = ([&] {
812 auto HasNonTrivialField = [&](const CXXRecordDecl *R) {
813 for (const FieldDecl *F : R->fields()) {
814 if (!IsTrivialType(F->getType())) {
815 if (OffendingField)
816 *OffendingField = F;
817 return true;
818 }
819 }
820 return false;
821 };
822
823 if (HasNonTrivialField(Cls))
824 return true;
825
826 if (!Cls->hasDefinition())
827 return false;
828
829 CXXBasePaths Paths;
830 Paths.setOrigin(const_cast<CXXRecordDecl *>(Cls));
831 return Cls->lookupInBases(
832 [&](const CXXBaseSpecifier *B, CXXBasePath &) {
833 auto *T = B->getType().getTypePtrOrNull();
834 if (!T)
835 return false;
836 auto *R = T->getAsCXXRecordDecl();
837 return R && HasNonTrivialField(R);
838 },
839 Paths, /*LookupInDependent =*/true);
840 })();
841
842 Cache[Cls] = Result;
843
844 return Result;
845 }
846
847public:
848 using CacheTy = TrivialFunctionAnalysis::CacheTy;
849
851 NonTrivialityReason *Reason = nullptr)
852 : Cache(Cache), OffendingStmt(Reason ? &Reason->OffendingStmt : nullptr),
853 CallStack(Reason ? &Reason->CallStack : nullptr) {}
854
855 // Hides ConstStmtVisitor::Visit so that every recursive step in this class
856 // funnels through here. Recursion unwinds innermost-first, so the first
857 // statement recorded is the deepest one that failed -- the code actually
858 // responsible, rather than the enclosing statement that contains it.
859 // Implicit nodes have no location to point at, so they are passed over in
860 // favour of the nearest enclosing node that was actually written.
861 bool Visit(const Stmt *S) {
862 bool Result = Base::Visit(S);
863 if (!Result && OffendingStmt && !*OffendingStmt &&
864 S->getBeginLoc().isValid())
865 *OffendingStmt = S;
866 return Result;
867 }
868
869 bool IsFunctionTrivial(const Decl *D) {
870 if (!CallStack)
871 return IsFunctionTrivialImpl(D);
872
873 const auto *FnDecl = dyn_cast<FunctionDecl>(D);
874 if (!FnDecl)
875 return IsFunctionTrivialImpl(D);
876
877 // CallStack[0, ActiveDepth) mirrors the functions currently being
878 // analyzed. Anything past that was left by a callee whose failure was
879 // tolerated, e.g. one of several candidate default constructors, and is
880 // not part of the chain that explains this call.
881 CallStack->truncate(ActiveDepth);
882 size_t Index = ActiveDepth++;
883 CallStack->push_back({FnDecl, nullptr});
884
885 // Blame is recorded separately for each function, so that every frame
886 // can point at the code within it that leads further down the chain.
887 const Stmt *CalleeOffendingStmt = nullptr;
888 const Stmt **SavedOffendingStmt =
889 std::exchange(OffendingStmt, &CalleeOffendingStmt);
891 OffendingStmt = SavedOffendingStmt;
892
893 --ActiveDepth;
894 // On failure, keep this frame along with the frames its body left behind:
895 // together they are the chain from here down to the root cause.
896 if (Result)
897 CallStack->truncate(Index);
898 else
899 (*CallStack)[Index].OffendingStmt = CalleeOffendingStmt;
900 return Result;
901 }
902
904 return WithCachedResult(D, [&]() {
905 auto *FnDecl = dyn_cast<FunctionDecl>(D);
906 auto *MethodDecl = dyn_cast<CXXMethodDecl>(D);
907 auto *CtorDecl = dyn_cast<CXXConstructorDecl>(D);
908 auto *DtorDecl = dyn_cast<CXXDestructorDecl>(D);
909
910 if (FnDecl) {
911 if (isNoDeleteFunction(FnDecl))
912 return true;
913 if (MethodDecl && MethodDecl->isVirtual())
914 return false;
915 for (auto *Param : FnDecl->parameters()) {
916 if (!HasTrivialDestructor(Param))
917 return false;
918 }
919 }
920 if (CtorDecl) {
921 for (auto *CtorInit : CtorDecl->inits()) {
922 if (!Visit(CtorInit->getInit()))
923 return false;
924 }
925 }
926 // An implicit or =default special member runs no user code when it is
927 // trivial in the C++ standard sense, so it cannot delete. Such a
928 // member's synthesized body is typically absent from the AST until
929 // codegen materialises it, which the generic null-body check below
930 // would otherwise conservatively classify as non-trivial.
931 if (MethodDecl && !MethodDecl->isUserProvided()) {
932 if (CtorDecl) {
933 const CXXRecordDecl *RD = CtorDecl->getParent();
934 if ((CtorDecl->isDefaultConstructor() &&
936 (CtorDecl->isCopyConstructor() &&
938 (CtorDecl->isMoveConstructor() &&
940 return true;
941 }
942 if (DtorDecl && DtorDecl->getParent()->hasTrivialDestructor())
943 return true;
944 }
945 const Stmt *Body = D->getBody();
946 if (!Body)
947 return false;
948 return Visit(Body);
949 });
950 }
951
953 return WithCachedResult(
954 VD, [&] { return CanTriviallyDestruct(VD->getType()); });
955 }
956
958 const FieldDecl *OffendingField = nullptr;
959 hasNonTrivialField(
960 Cls, &OffendingField, FieldCtorCache,
961 [&](const QualType Ty) { return CanTriviallyConstruct(Ty); });
962 return OffendingField;
963 }
964
966 const FieldDecl *OffendingField = nullptr;
967 hasNonTrivialField(
968 Cls, &OffendingField, FieldDtorCache,
969 [&](const QualType Ty) { return CanTriviallyDestruct(Ty); });
970 return OffendingField;
971 }
972
973 bool IsStatementTrivial(const Stmt *S) {
974 auto CacheIt = Cache.find(S);
975 if (CacheIt != Cache.end() && canUseCachedResult(CacheIt->second))
976 return CacheIt->second;
977 bool Result = Visit(S);
978 Cache[S] = Result;
979 return Result;
980 }
981
982 bool VisitStmt(const Stmt *S) {
983 // All statements are non-trivial unless overriden later.
984 // Don't even recurse into children by default.
985 return false;
986 }
987
989 // Ignore attributes.
990 return Visit(AS->getSubStmt());
991 }
992
994 // A compound statement is allowed as long each individual sub-statement
995 // is trivial.
996 return WithCachedResult(CS, [&]() { return VisitChildren(CS); });
997 }
998
1000 return WithCachedResult(CBS, [&]() { return VisitChildren(CBS); });
1001 }
1002
1003 bool VisitReturnStmt(const ReturnStmt *RS) {
1004 // A return statement is allowed as long as the return value is trivial. A
1005 // returned smart-pointer prvalue is special: under guaranteed copy elision
1006 // the temporary *is* the function's return slot, so it is destructed by the
1007 // caller, not here. Hence we may ignore that temporary's destructor.
1008 if (auto *RV = RS->getRetValue())
1009 return visitReturnValueElidingTemp(RV);
1010 return true;
1011 }
1012
1013 bool VisitDeclStmt(const DeclStmt *DS) {
1014 for (auto &Decl : DS->decls()) {
1015 // FIXME: Handle DecompositionDecls.
1016 if (auto *VD = dyn_cast<VarDecl>(Decl)) {
1017 if (!HasTrivialDestructor(VD))
1018 return false;
1019 }
1020 }
1021 return VisitChildren(DS);
1022 }
1023 bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
1024 bool VisitIfStmt(const IfStmt *IS) {
1025 return WithCachedResult(IS, [&]() { return VisitChildren(IS); });
1026 }
1027 bool VisitForStmt(const ForStmt *FS) {
1028 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
1029 }
1031 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
1032 }
1033 bool VisitWhileStmt(const WhileStmt *WS) {
1034 return WithCachedResult(WS, [&]() { return VisitChildren(WS); });
1035 }
1036 bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
1037 bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
1038 bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(DS); }
1039
1040 // break, continue, goto, and label statements are always trivial.
1041 bool VisitBreakStmt(const BreakStmt *) { return true; }
1042 bool VisitContinueStmt(const ContinueStmt *) { return true; }
1043 bool VisitGotoStmt(const GotoStmt *) { return true; }
1044 bool VisitLabelStmt(const LabelStmt *) { return true; }
1045
1047 // Unary operators are trivial if its operand is trivial except co_await.
1048 return UO->getOpcode() != UO_Coawait && Visit(UO->getSubExpr());
1049 }
1050
1052 // Binary operators are trivial if their operands are trivial.
1053 return Visit(BO->getLHS()) && Visit(BO->getRHS());
1054 }
1055
1057 // Compound assignment operator such as |= is trivial if its
1058 // subexpresssions are trivial.
1059 return VisitChildren(CAO);
1060 }
1061
1063 return VisitChildren(ASE);
1064 }
1065
1067 // Ternary operators are trivial if their conditions & values are trivial.
1068 return VisitChildren(CO);
1069 }
1070
1071 bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(E); }
1072
1074 // Any static_assert is considered trivial.
1075 return true;
1076 }
1077
1078 bool VisitCallExpr(const CallExpr *CE) {
1079 if (!checkArguments(CE))
1080 return false;
1081
1082 auto *Callee = CE->getDirectCallee();
1083 if (!Callee)
1084 return false;
1085
1086 if (isPtrConversion(Callee))
1087 return true;
1088
1089 const auto &Name = safeGetName(Callee);
1090
1091 if (Callee->isInStdNamespace() &&
1092 (Name == "addressof" || Name == "forward" || Name == "move"))
1093 return true;
1094
1095 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
1096 Name == "WTFReportBacktrace" ||
1097 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
1098 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
1099 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
1100 Name == "isWebThread" || Name == "isUIThread" ||
1101 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
1103 return true;
1104
1105 return IsFunctionTrivial(Callee);
1106 }
1107
1108 bool VisitGCCAsmStmt(const GCCAsmStmt *AS) {
1109 return AS->getAsmString() == "brk #0xc471";
1110 }
1111
1112 bool
1114 // Non-type template paramter is compile time constant and trivial.
1115 return true;
1116 }
1117
1119 return VisitChildren(E);
1120 }
1121
1123 // A predefined identifier such as "func" is considered trivial.
1124 return true;
1125 }
1126
1128 // offsetof(T, D) is considered trivial.
1129 return true;
1130 }
1131
1133 if (!checkArguments(MCE))
1134 return false;
1135
1136 bool TrivialThis = Visit(MCE->getImplicitObjectArgument());
1137 if (!TrivialThis)
1138 return false;
1139
1140 auto *Callee = MCE->getMethodDecl();
1141 if (!Callee)
1142 return false;
1143
1144 if (isa<CXXDestructorDecl>(Callee) &&
1145 !CanTriviallyDestruct(MCE->getObjectType()))
1146 return false;
1147
1148 auto Name = safeGetName(Callee);
1149 if (Name == "ref" || Name == "incrementCheckedPtrCount")
1150 return true;
1151
1152 std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(Callee);
1153 if (IsGetterOfRefCounted && *IsGetterOfRefCounted)
1154 return true;
1155
1156 // Recursively descend into the callee to confirm that it's trivial as well.
1157 return IsFunctionTrivial(Callee);
1158 }
1159
1161 if (!checkArguments(OCE))
1162 return false;
1163 auto *Callee = OCE->getCalleeDecl();
1164 if (!Callee)
1165 return false;
1166 // Recursively descend into the callee to confirm that it's trivial as well.
1167 return IsFunctionTrivial(Callee);
1168 }
1169
1171 auto *SemanticExpr = Op->getSemanticForm();
1172 return SemanticExpr && Visit(SemanticExpr);
1173 }
1174
1176 if (auto *Expr = E->getExpr()) {
1177 if (!Visit(Expr))
1178 return false;
1179 }
1180 return true;
1181 }
1182
1184 return Visit(E->getExpr());
1185 }
1186
1187 bool checkArguments(const CallExpr *CE) {
1188 for (const Expr *Arg : CE->arguments()) {
1189 if (Arg && !Visit(Arg))
1190 return false;
1191 }
1192 return true;
1193 }
1194
1195 // Triviality check for a return value that may elide a smart-pointer
1196 // temporary's destructor.
1197 //
1198 // This is only valid for *return values*: a returned class prvalue is
1199 // constructed directly into the function's return slot (C++17 guaranteed copy
1200 // elision), so the temporary is destructed by the caller rather than here.
1201 //
1202 // It is deliberately NOT applied to call/constructor arguments. An argument
1203 // temporary's lifetime ends at the full-expression *in this function* (the
1204 // caller destroys arguments, e.g. per the Itanium C++ ABI), so its destructor
1205 // runs here and may invoke delete. Proving otherwise would require
1206 // interprocedural ownership analysis, so arguments are checked normally.
1208 QualType OriginalQT = Arg->getType();
1209 auto *Type = OriginalQT.getTypePtrOrNull();
1210 if (!Type)
1211 return Visit(Arg);
1212 auto *CXXRD = Type->getAsCXXRecordDecl();
1213 if (!CXXRD || !isSmartPtrClass(safeGetName(CXXRD)))
1214 return Visit(Arg);
1215 Arg = Arg->IgnoreParenCasts();
1216 if (!Arg->isPRValue())
1217 return Visit(Arg);
1218 if (auto *Init = dyn_cast<InitListExpr>(Arg)) {
1219 if (Init->getNumInits() == 1)
1220 Arg = Init->getInit(0);
1221 }
1222 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Arg)) {
1223 // Only elide when the temporary *is* the returned object, i.e. it has the
1224 // same smart-pointer type as the return value. Compare canonical,
1225 // unqualified types rather than relying on exact QualType identity, which
1226 // is sensitive to sugar (typedefs/aliases) and cv-qualifiers.
1227 if (OriginalQT.getCanonicalType().getUnqualifiedType() ==
1228 BTE->getType().getCanonicalType().getUnqualifiedType())
1229 return Visit(BTE->getSubExpr());
1230 }
1231 return Visit(Arg);
1232 }
1233
1235 if (CE->getNumArgs() == 1) {
1236 auto *InnerArg = CE->getArg(0);
1237 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(InnerArg)) {
1238 auto *InnerExpr = MTE->getSubExpr();
1239 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(InnerExpr))
1240 InnerExpr = BTE->getSubExpr();
1241 auto InnerQT = InnerExpr->getType();
1242 if (auto *InnerDecl = InnerQT->getAsCXXRecordDecl()) {
1243 auto *OuterCls = CE->getConstructor()->getParent();
1244 if (isRefType(safeGetName(OuterCls)) &&
1245 isRefType(safeGetName(InnerDecl)))
1246 return Visit(InnerExpr);
1247 }
1248 }
1249 }
1250
1251 for (const Expr *Arg : CE->arguments()) {
1252 if (Arg && !Visit(Arg))
1253 return false;
1254 }
1255
1256 // Recursively descend into the callee to confirm that it's trivial.
1257 return IsFunctionTrivial(CE->getConstructor());
1258 }
1259
1263
1264 bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(NE); }
1265
1267 return Visit(ICE->getSubExpr());
1268 }
1269
1271 return Visit(ECE->getSubExpr());
1272 }
1273
1275 if (auto *ICE = dyn_cast<ImplicitCastExpr>(VMT->getSubExpr());
1276 ICE && ICE->getCastKind() == CK_NoOp &&
1277 ICE->getType().isConstQualified()) {
1278 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(ICE->getSubExpr());
1279 BTE && isNullSmartPtr(BTE->getSubExpr()))
1280 return Visit(BTE->getSubExpr());
1281 }
1282 return Visit(VMT->getSubExpr());
1283 }
1284
1285 // Returns true if E is known to evaluate to a smart pointer which holds
1286 // nullptr, e.g. RefPtr<T>(), RefPtr<T>(nullptr), Ref<T>(HashTableEmptyValue),
1287 // or a call to a function which simply returns one such as
1288 // HashTraits<Ref<T>>::emptyValue(). Destructing such a smart pointer can't
1289 // delete anything.
1290 bool isNullSmartPtr(const Expr *E, unsigned Depth = 0) {
1291 if (!E || Depth > 4)
1292 return false;
1293 while (true) {
1294 E = E->IgnoreParenCasts();
1295 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
1296 E = EWC->getSubExpr();
1297 else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1298 E = MTE->getSubExpr();
1299 else if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
1300 E = BTE->getSubExpr();
1301 else
1302 break;
1303 }
1304 if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
1305 auto *Ctor = CE->getConstructor();
1306 if (!Ctor || !isOwnerPtr(safeGetName(Ctor->getParent())))
1307 return false;
1308 if (Ctor->isDefaultConstructor())
1309 return true;
1310 if (CE->getNumArgs() != 1)
1311 return false;
1312 auto *Arg = CE->getArg(0)->IgnoreParenImpCasts();
1313 auto ArgType = Arg->getType();
1314 if (ArgType->isNullPtrType())
1315 return true;
1316 if (auto *TD = ArgType->getAsTagDecl();
1317 TD && safeGetName(TD) == "HashTableEmptyValueType")
1318 return true;
1319 if (Ctor->isCopyOrMoveConstructor())
1320 return isNullSmartPtr(Arg, Depth + 1);
1321 return false;
1322 }
1323 if (auto *CE = dyn_cast<CallExpr>(E)) {
1324 auto *Callee = CE->getDirectCallee();
1325 if (!Callee)
1326 return false;
1327 if (auto *MD = dyn_cast<CXXMethodDecl>(Callee); MD && MD->isVirtual())
1328 return false;
1329 auto *Body = dyn_cast_or_null<CompoundStmt>(Callee->getBody());
1330 if (!Body || Body->size() != 1)
1331 return false;
1332 auto *RS = dyn_cast<ReturnStmt>(Body->body_front());
1333 return RS && isNullSmartPtr(RS->getRetValue(), Depth + 1);
1334 }
1335 return false;
1336 }
1337
1339 if (auto *Temp = BTE->getTemporary()) {
1340 if (!IsFunctionTrivial(Temp->getDestructor()))
1341 return false;
1342 }
1343 return Visit(BTE->getSubExpr());
1344 }
1345
1347 return Visit(AILE->getCommonExpr()) && Visit(AILE->getSubExpr());
1348 }
1349
1351 return true; // The current array index in VisitArrayInitLoopExpr is always
1352 // trivial.
1353 }
1354
1356 return Visit(OVE->getSourceExpr());
1357 }
1358
1360 return Visit(EWC->getSubExpr());
1361 }
1362
1363 bool VisitParenExpr(const ParenExpr *PE) { return Visit(PE->getSubExpr()); }
1364
1366 for (const Expr *Child : ILE->inits()) {
1367 if (Child && !Visit(Child))
1368 return false;
1369 }
1370 return true;
1371 }
1372
1374 auto *SubExpr = ILE->getSubExpr();
1375 if (!SubExpr)
1376 return false;
1377 // The backing array of a std::initializer_list is a temporary whose
1378 // lifetime ends in this function, so its elements are destructed here.
1379 if (!CanTriviallyDestruct(SubExpr->getType()))
1380 return false;
1381 return Visit(SubExpr);
1382 }
1383
1384 bool VisitMemberExpr(const MemberExpr *ME) {
1385 // Field access is allowed but the base pointer may itself be non-trivial.
1386 return Visit(ME->getBase());
1387 }
1388
1390 // The expression 'this' is always trivial, be it explicit or implicit.
1391 return true;
1392 }
1393
1395 // nullptr is trivial.
1396 return true;
1397 }
1398
1400 // The use of a variable is trivial.
1401 return true;
1402 }
1403
1404 // Constant literal expressions are always trivial
1405 bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; }
1406 bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; }
1407 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; }
1408 bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; }
1409 bool VisitStringLiteral(const StringLiteral *E) { return true; }
1410 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; }
1411
1413 // Constant expressions are trivial.
1414 return true;
1415 }
1416
1418 // An implicit value initialization is trvial.
1419 return true;
1420 }
1421
1423 // A value initialization of a scalar type such as int() is trivial.
1424 return true;
1425 }
1426
1427private:
1428 CacheTy &Cache;
1429 CacheTy FieldCtorCache;
1430 CacheTy FieldDtorCache;
1431 CacheTy RecursiveFn;
1432 const Stmt **OffendingStmt;
1434 unsigned ActiveDepth = 0;
1435};
1436
1437bool TrivialFunctionAnalysis::isTrivialImpl(
1438 const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache) {
1440 return V.IsFunctionTrivial(D);
1441}
1442
1443bool TrivialFunctionAnalysis::isTrivialImpl(
1444 const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache) {
1446 return V.IsStatementTrivial(S);
1447}
1448
1450 NonTrivialityReason Reason;
1451 CacheTy Cache;
1453 [[maybe_unused]] bool Trivial = V.IsStatementTrivial(S);
1454 assert(!Trivial && "computeReason called on a trivial statement");
1455 return Reason;
1456}
1457
1458bool TrivialFunctionAnalysis::hasTrivialDtorImpl(const VarDecl *VD,
1459 CacheTy &Cache) {
1461 return V.HasTrivialDestructor(VD);
1462}
1463
1464const FieldDecl *
1465TrivialFunctionAnalysis::fieldWithNonTrivialCtorImpl(const CXXRecordDecl *RD,
1466 CacheTy &Cache) {
1468 return V.FieldWithNonTrivialCtor(RD);
1469}
1470
1471const FieldDecl *
1472TrivialFunctionAnalysis::fieldWithNonTrivialDtorImpl(const CXXRecordDecl *RD,
1473 CacheTy &Cache) {
1475 return V.FieldWithNonTrivialDtor(RD);
1476}
1477
1478} // namespace clang
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Record Record
Definition MachO.h:31
TypePropertyCache< Private > Cache
Definition Type.cpp:5094
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6075
Represents a loop initializing the elements of an array.
Definition Expr.h:6022
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6037
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6042
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2769
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6982
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
Stmt * getSubStmt()
Definition Stmt.h:2251
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4086
Expr * getLHS() const
Definition Expr.h:4136
Expr * getRHS() const
Definition Expr.h:4138
BreakStmt - This represents a break.
Definition Stmt.h:3147
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
void setOrigin(const CXXRecordDecl *Rec)
Represents a base class of a C++ class.
Definition DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXTemporary * getTemporary()
Definition ExprCXX.h:1516
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:728
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
arg_range arguments()
Definition ExprCXX.h:1677
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1756
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1793
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
QualType getObjectType() const
Retrieve the type of the object argument.
Definition ExprCXX.cpp:766
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1317
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1294
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool hasDefinition() const
Definition DeclCXX.h:562
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:291
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:309
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2201
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:805
Represents the this expression in C++.
Definition ExprCXX.h:1159
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3174
arg_range arguments()
Definition Expr.h:3243
Decl * getCalleeDecl()
Definition Expr.h:3168
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Expr * getSubExpr()
Definition Expr.h:3774
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4348
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
ConditionalOperator - The ?
Definition Expr.h:4439
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1106
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
Represents the body of a coroutine.
Definition StmtCXX.h:321
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2120
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1104
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
bool hasAttr() const
Definition DeclBase.h:585
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition DeclBase.cpp:556
bool isIdentifier() const
Predicate functions for querying what type of name this is.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3976
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3715
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
bool isPRValue() const
Definition Expr.h:286
QualType getType() const
Definition Expr.h:145
Represents a member of a struct/union/class.
Definition Decl.h:3299
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
const Expr * getSubExpr() const
Definition Expr.h:1086
Represents a function declaration or definition.
Definition Decl.h:2059
QualType getReturnType() const
Definition Decl.h:2980
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4179
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3458
std::string getAsmString() const
Definition Stmt.cpp:574
GotoStmt - This represents a direct goto.
Definition Stmt.h:2981
IfStmt - This represents an if/then/else.
Definition Stmt.h:2271
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3901
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6111
Describes an C or C++ initializer list.
Definition Expr.h:5356
ArrayRef< Expr * > inits() const
Definition Expr.h:5409
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2158
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3412
Expr * getBase() const
Definition Expr.h:3489
This represents a decl that may have a name.
Definition Decl.h:275
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2575
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1202
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1252
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2230
const Expr * getSubExpr() const
Definition Expr.h:2247
Represents a parameter to a function.
Definition Decl.h:1820
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2053
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
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8450
const TypedefDecl * getCanonicalDecl(QualType)
bool isUnretained(const QualType, bool ignoreARC=false)
void visitTranslationUnitDecl(const TranslationUnitDecl *)
void visitTypedef(const TypedefDecl *)
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
Expr * getRetValue()
Definition Stmt.h:3199
bool isValid() const
Return true if this is a valid SourceLocation object.
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4166
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition StmtVisitor.h:45
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1823
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4718
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
@ Type
The template argument is a type.
The top declaration context.
Definition Decl.h:106
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitStaticAssertDecl(const StaticAssertDecl *SAD)
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE)
bool VisitCXXThisExpr(const CXXThisExpr *CTE)
TrivialFunctionAnalysisVisitor(CacheTy &Cache, NonTrivialityReason *Reason=nullptr)
bool VisitUnaryOperator(const UnaryOperator *UO)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitContinueStmt(const ContinueStmt *)
bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO)
const FieldDecl * FieldWithNonTrivialDtor(const CXXRecordDecl *Cls)
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
bool VisitDeclRefExpr(const DeclRefExpr *DRE)
bool VisitIntegerLiteral(const IntegerLiteral *E)
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *VMT)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *Op)
bool VisitFloatingLiteral(const FloatingLiteral *E)
TrivialFunctionAnalysis::CacheTy CacheTy
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *ILE)
bool VisitConditionalOperator(const ConditionalOperator *CO)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitCompoundStmt(const CompoundStmt *CS)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *IVIE)
bool VisitConstantExpr(const ConstantExpr *CE)
bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE)
bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *OVE)
bool VisitExprWithCleanups(const ExprWithCleanups *EWC)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE)
bool VisitBinaryOperator(const BinaryOperator *BO)
bool VisitCoroutineBodyStmt(const CoroutineBodyStmt *CBS)
bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE)
bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool VisitInitListExpr(const InitListExpr *ILE)
bool VisitAttributedStmt(const AttributedStmt *AS)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
const FieldDecl * FieldWithNonTrivialCtor(const CXXRecordDecl *Cls)
bool VisitExplicitCastExpr(const ExplicitCastExpr *ECE)
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *AIIE)
bool VisitDefaultStmt(const DefaultStmt *DS)
bool VisitOffsetOfExpr(const OffsetOfExpr *OE)
bool VisitCXXConstructExpr(const CXXConstructExpr *CE)
bool isNullSmartPtr(const Expr *E, unsigned Depth=0)
static NonTrivialityReason computeReason(const Stmt *S)
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition TypeBase.h:8646
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
bool isPointerOrReferenceType() const
Definition TypeBase.h:8687
bool isObjCObjectPointerType() const
Definition TypeBase.h:8862
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isRecordType() const
Definition TypeBase.h:8810
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3806
QualType getUnderlyingType() const
Definition Decl.h:3756
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2673
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2292
Expr * getSubExpr() const
Definition Expr.h:2333
Opcode getOpcode() const
Definition Expr.h:2328
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool isCocoaObjectRef(QualType T)
bool isPointerLikeType(QualType QT)
Top level wrappers for InstallAPI frontend operations.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isTrivialBuiltinFunction(const FunctionDecl *F)
bool isa(CodeGen::Address addr)
Definition Address.h:330
static bool isNoDeleteFunctionDecl(const FunctionDecl *F)
bool isPtrConversion(const FunctionDecl *F)
static bool isWeakPtrClass(const std::string &Name)
QualType pointeeType(QualType T)
std::optional< bool > isCheckedPtrCapable(const clang::CXXRecordDecl *R)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
std::optional< bool > isUnchecked(const QualType T)
QualType borrowedType(QualType T)
bool isCtorOfRefCounted(const clang::FunctionDecl *F)
bool isRefOrCheckedPtrType(const clang::QualType T)
bool isView(const clang::QualType T)
static bool hasLifetimeBoundCtor(const clang::CXXRecordDecl *R)
@ AS_public
Definition Specifiers.h:128
bool isRetainPtrOrOSPtrType(const clang::QualType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isGetterOfUniquePtr(const CXXMethodDecl *M)
static bool isStdRangesViewInterface(const clang::CXXRecordDecl *R)
bool isCtorOfRetainPtrOrOSPtr(const clang::FunctionDecl *F)
bool isBorrow(const clang::CXXRecordDecl *R)
std::optional< bool > isBorrowable(const clang::CXXRecordDecl *R)
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool isOwnerPtr(const std::string &Name)
bool isStdView(const clang::CXXRecordDecl *R)
const FunctionProtoType * T
std::optional< bool > isRefCountable(const clang::CXXRecordDecl *R)
std::optional< const clang::CXXRecordDecl * > hasPublicMethodInBase(const CXXBaseSpecifier *Base, StringRef NameToMatch)
bool isSmartPtrClass(const std::string &Name)
std::string getConstructorName(const clang::FunctionDecl *F)
bool isRefCounted(const CXXRecordDecl *R)
static bool derivesFromViewInterface(const clang::CXXRecordDecl *R)
static bool isPtrOfType(const clang::QualType T, Predicate Pred)
std::optional< bool > isSmartPtrCompatible(const CXXRecordDecl *R, StringRef IncMethodName, StringRef DecMethodName)
bool isNoDeleteFunction(const FunctionDecl *F)
bool isOwnerPtrType(const clang::QualType T)
bool isSmartPtr(const CXXRecordDecl *R)
std::optional< bool > isGetterOfSafePtr(const CXXMethodDecl *M)
bool isRetainPtrOrOSPtr(const std::string &Name)
bool isRefType(const std::string &Name)
bool isUniquePtr(const std::string &Name)
std::optional< bool > isUncountedPtr(const QualType T)
static std::optional< bool > hasPublicMethodInHierarchy(const CXXRecordDecl *R, StringRef MethodName)
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:109
bool isCtorOfCheckedPtr(const clang::FunctionDecl *F)
bool isSingleton(const NamedDecl *F)
bool isCheckedPtr(const std::string &Name)
bool isStdOrWTFMove(const clang::FunctionDecl *F)
bool isBorrowType(const clang::QualType T)
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
static bool hasAnnotationForFunction(const FunctionDecl *FD, WebKitAnnotation TargetAnnotation)
std::optional< bool > isUncounted(const QualType T)
static WebKitAnnotation annotationType(StringRef Annotation)
std::optional< bool > isUncheckedPtr(const QualType T)
bool isWeakPtr(const CXXRecordDecl *R)
Explains why TrivialFunctionAnalysis rejected a statement, so that a diagnostic can blame the code th...