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
587 auto RetType = FD->getReturnType();
588 auto *Type = RetType.getTypePtrOrNull();
589 if (auto *MacroQualified = dyn_cast_or_null<MacroQualifiedType>(Type))
590 Type = MacroQualified->desugar().getTypePtrOrNull();
591 auto *Attr = dyn_cast_or_null<AttributedType>(Type);
592 if (!Attr)
594 auto *AnnotateType = dyn_cast_or_null<AnnotateTypeAttr>(Attr->getAttr());
595 if (!AnnotateType)
597 auto Annotation = AnnotateType->getAnnotation();
598 if (Annotation == "webkit.pointerconversion")
600 if (Annotation == "webkit.nodelete")
603}
604
606 assert(F);
607 if (isCtorOfRefCounted(F))
608 return true;
609
610 // FIXME: check # of params == 1
611 const auto FunctionName = safeGetName(F);
612 if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
613 FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
614 FunctionName == "checkedDowncast" || FunctionName == "bit_cast" ||
615 FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" ||
616 FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" ||
617 FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" ||
618 FunctionName == "dynamic_objc_cast" ||
619 FunctionName == "checked_objc_cast")
620 return true;
621
623 return true;
624
625 return false;
626}
627
631
633 if (llvm::any_of(F->redecls(), isNoDeleteFunctionDecl))
634 return true;
635
636 const auto *MD = dyn_cast<CXXMethodDecl>(F);
637 if (!MD || !MD->isVirtual())
638 return false;
639
640 auto Overriders = llvm::to_vector(MD->overridden_methods());
641 while (!Overriders.empty()) {
642 const auto *Fn = Overriders.pop_back_val();
643 llvm::append_range(Overriders, Fn->overridden_methods());
645 return true;
646 }
647
648 return false;
649}
650
652 if (!F || !F->getDeclName().isIdentifier())
653 return false;
654 auto Name = F->getName();
655 return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" ||
656 Name.starts_with("os_log") || Name.starts_with("_os_log");
657}
658
659bool isSingleton(const NamedDecl *F) {
660 assert(F);
661 // FIXME: check # of params == 1
662 if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(F)) {
663 if (!MethodDecl->isStatic())
664 return false;
665 }
666 const auto &NameStr = safeGetName(F);
667 StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef.
668 return Name == "singleton" || Name.ends_with("Singleton");
669}
670
671// We only care about statements so let's use the simple
672// (non-recursive) visitor.
674 : public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> {
675
676 // Returns false if at least one child is non-trivial.
677 bool VisitChildren(const Stmt *S) {
678 for (const Stmt *Child : S->children()) {
679 if (Child && !Visit(Child)) {
680 if (OffendingStmt && !*OffendingStmt)
681 *OffendingStmt = Child;
682 return false;
683 }
684 }
685
686 return true;
687 }
688
689 template <typename StmtOrDecl, typename CheckFunction>
690 bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) {
691 auto CacheIt = Cache.find(S);
692 if (CacheIt != Cache.end() && !OffendingStmt)
693 return CacheIt->second;
694
695 // Treat a recursive statement to be trivial until proven otherwise.
696 auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true));
697 if (!IsNew)
698 return RecursiveIt->second;
699
700 bool Result = Function();
701
702 if (!Result) {
703 for (auto &It : RecursiveFn)
704 It.second = false;
705 }
706 RecursiveIt = RecursiveFn.find(S);
707 assert(RecursiveIt != RecursiveFn.end());
708 Result = RecursiveIt->second;
709 RecursiveFn.erase(RecursiveIt);
710 Cache[S] = Result;
711
712 return Result;
713 }
714
715 bool CanTriviallyDestruct(QualType Ty) {
716 if (Ty.isNull())
717 return false;
718
719 // T*, T& or T&& does not run its destructor.
720 if (Ty->isPointerOrReferenceType())
721 return true;
722
723 // FIXME: Handle a case when there is a local autorelease pool.
724 if (Ty->isObjCObjectPointerType()) {
725 auto Type = Ty.isDestructedType();
727 return true;
728 // strong lifetime in ARC could dealloc an object.
729 }
730
731 // Fundamental types (integral, nullptr_t, etc...) don't have destructors.
733 return true;
734
735 if (const auto *R = Ty->getAsCXXRecordDecl()) {
736 // C++ trivially destructible classes are fine.
737 if (R->hasDefinition() && R->hasTrivialDestructor())
738 return true;
739
740 if (HasFieldWithNonTrivialDtor(R))
741 return false;
742
743 // For Webkit, side-effects are fine as long as we don't delete objects,
744 // so check recursively.
745 if (const auto *Dtor = R->getDestructor())
746 return IsFunctionTrivial(Dtor);
747 }
748
749 // Structs in C are trivial.
750 if (Ty->isRecordType())
751 return true;
752
753 // For arrays it depends on the element type.
754 // FIXME: We should really use ASTContext::getAsArrayType instead.
755 if (const auto *AT = Ty->getAsArrayTypeUnsafe())
756 return CanTriviallyDestruct(AT->getElementType());
757
758 return false; // Otherwise it's likely not trivial.
759 }
760
761 bool HasFieldWithNonTrivialDtor(const CXXRecordDecl *Cls) {
762 auto CacheIt = FieldDtorCache.find(Cls);
763 if (CacheIt != FieldDtorCache.end())
764 return CacheIt->second;
765
766 bool Result = ([&] {
767 auto HasNonTrivialField = [&](const CXXRecordDecl *R) {
768 for (const FieldDecl *F : R->fields()) {
769 if (!CanTriviallyDestruct(F->getType()))
770 return true;
771 }
772 return false;
773 };
774
775 if (HasNonTrivialField(Cls))
776 return true;
777
778 if (!Cls->hasDefinition())
779 return false;
780
781 CXXBasePaths Paths;
782 Paths.setOrigin(const_cast<CXXRecordDecl *>(Cls));
783 return Cls->lookupInBases(
784 [&](const CXXBaseSpecifier *B, CXXBasePath &) {
785 auto *T = B->getType().getTypePtrOrNull();
786 if (!T)
787 return false;
788 auto *R = T->getAsCXXRecordDecl();
789 return R && HasNonTrivialField(R);
790 },
791 Paths, /*LookupInDependent =*/true);
792 })();
793
794 FieldDtorCache[Cls] = Result;
795
796 return Result;
797 }
798
799public:
800 using CacheTy = TrivialFunctionAnalysis::CacheTy;
801
803 const Stmt **OffendingStmt = nullptr)
804 : Cache(Cache), OffendingStmt(OffendingStmt) {}
805
806 bool IsFunctionTrivial(const Decl *D) {
807 const Stmt **SavedOffendingStmt = std::exchange(OffendingStmt, nullptr);
808 auto Result = WithCachedResult(D, [&]() {
809 auto *FnDecl = dyn_cast<FunctionDecl>(D);
810 auto *MethodDecl = dyn_cast<CXXMethodDecl>(D);
811 auto *CtorDecl = dyn_cast<CXXConstructorDecl>(D);
812 auto *DtorDecl = dyn_cast<CXXDestructorDecl>(D);
813
814 if (FnDecl) {
815 if (isNoDeleteFunction(FnDecl))
816 return true;
817 if (MethodDecl && MethodDecl->isVirtual())
818 return false;
819 for (auto *Param : FnDecl->parameters()) {
820 if (!HasTrivialDestructor(Param))
821 return false;
822 }
823 }
824 if (CtorDecl) {
825 for (auto *CtorInit : CtorDecl->inits()) {
826 if (!Visit(CtorInit->getInit()))
827 return false;
828 }
829 }
830 // An implicit or =default special member runs no user code when it is
831 // trivial in the C++ standard sense, so it cannot delete. Such a
832 // member's synthesized body is typically absent from the AST until
833 // codegen materialises it, which the generic null-body check below
834 // would otherwise conservatively classify as non-trivial.
835 if (MethodDecl && !MethodDecl->isUserProvided()) {
836 if (CtorDecl) {
837 const CXXRecordDecl *RD = CtorDecl->getParent();
838 if ((CtorDecl->isDefaultConstructor() &&
840 (CtorDecl->isCopyConstructor() &&
842 (CtorDecl->isMoveConstructor() &&
844 return true;
845 }
846 if (DtorDecl && DtorDecl->getParent()->hasTrivialDestructor())
847 return true;
848 }
849 const Stmt *Body = D->getBody();
850 if (!Body)
851 return false;
852 return Visit(Body);
853 });
854 OffendingStmt = SavedOffendingStmt;
855 return Result;
856 }
857
859 return WithCachedResult(
860 VD, [&] { return CanTriviallyDestruct(VD->getType()); });
861 }
862
863 bool IsStatementTrivial(const Stmt *S) {
864 auto CacheIt = Cache.find(S);
865 if (CacheIt != Cache.end())
866 return CacheIt->second;
867 bool Result = Visit(S);
868 Cache[S] = Result;
869 return Result;
870 }
871
872 bool VisitStmt(const Stmt *S) {
873 // All statements are non-trivial unless overriden later.
874 // Don't even recurse into children by default.
875 return false;
876 }
877
879 // Ignore attributes.
880 return Visit(AS->getSubStmt());
881 }
882
884 // A compound statement is allowed as long each individual sub-statement
885 // is trivial.
886 return WithCachedResult(CS, [&]() { return VisitChildren(CS); });
887 }
888
890 return WithCachedResult(CBS, [&]() { return VisitChildren(CBS); });
891 }
892
893 bool VisitReturnStmt(const ReturnStmt *RS) {
894 // A return statement is allowed as long as the return value is trivial. A
895 // returned smart-pointer prvalue is special: under guaranteed copy elision
896 // the temporary *is* the function's return slot, so it is destructed by the
897 // caller, not here. Hence we may ignore that temporary's destructor.
898 if (auto *RV = RS->getRetValue())
900 return true;
901 }
902
903 bool VisitDeclStmt(const DeclStmt *DS) {
904 for (auto &Decl : DS->decls()) {
905 // FIXME: Handle DecompositionDecls.
906 if (auto *VD = dyn_cast<VarDecl>(Decl)) {
907 if (!HasTrivialDestructor(VD))
908 return false;
909 }
910 }
911 return VisitChildren(DS);
912 }
913 bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
914 bool VisitIfStmt(const IfStmt *IS) {
915 return WithCachedResult(IS, [&]() { return VisitChildren(IS); });
916 }
917 bool VisitForStmt(const ForStmt *FS) {
918 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
919 }
921 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
922 }
923 bool VisitWhileStmt(const WhileStmt *WS) {
924 return WithCachedResult(WS, [&]() { return VisitChildren(WS); });
925 }
926 bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
927 bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
928 bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(DS); }
929
930 // break, continue, goto, and label statements are always trivial.
931 bool VisitBreakStmt(const BreakStmt *) { return true; }
932 bool VisitContinueStmt(const ContinueStmt *) { return true; }
933 bool VisitGotoStmt(const GotoStmt *) { return true; }
934 bool VisitLabelStmt(const LabelStmt *) { return true; }
935
937 // Unary operators are trivial if its operand is trivial except co_await.
938 return UO->getOpcode() != UO_Coawait && Visit(UO->getSubExpr());
939 }
940
942 // Binary operators are trivial if their operands are trivial.
943 return Visit(BO->getLHS()) && Visit(BO->getRHS());
944 }
945
947 // Compound assignment operator such as |= is trivial if its
948 // subexpresssions are trivial.
949 return VisitChildren(CAO);
950 }
951
953 return VisitChildren(ASE);
954 }
955
957 // Ternary operators are trivial if their conditions & values are trivial.
958 return VisitChildren(CO);
959 }
960
961 bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(E); }
962
964 // Any static_assert is considered trivial.
965 return true;
966 }
967
968 bool VisitCallExpr(const CallExpr *CE) {
969 if (!checkArguments(CE))
970 return false;
971
972 auto *Callee = CE->getDirectCallee();
973 if (!Callee)
974 return false;
975
976 if (isPtrConversion(Callee))
977 return true;
978
979 const auto &Name = safeGetName(Callee);
980
981 if (Callee->isInStdNamespace() &&
982 (Name == "addressof" || Name == "forward" || Name == "move"))
983 return true;
984
985 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
986 Name == "WTFReportBacktrace" ||
987 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
988 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
989 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
990 Name == "isWebThread" || Name == "isUIThread" ||
991 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
993 return true;
994
995 return IsFunctionTrivial(Callee);
996 }
997
998 bool VisitGCCAsmStmt(const GCCAsmStmt *AS) {
999 return AS->getAsmString() == "brk #0xc471";
1000 }
1001
1002 bool
1004 // Non-type template paramter is compile time constant and trivial.
1005 return true;
1006 }
1007
1009 return VisitChildren(E);
1010 }
1011
1013 // A predefined identifier such as "func" is considered trivial.
1014 return true;
1015 }
1016
1018 // offsetof(T, D) is considered trivial.
1019 return true;
1020 }
1021
1023 if (!checkArguments(MCE))
1024 return false;
1025
1026 bool TrivialThis = Visit(MCE->getImplicitObjectArgument());
1027 if (!TrivialThis)
1028 return false;
1029
1030 auto *Callee = MCE->getMethodDecl();
1031 if (!Callee)
1032 return false;
1033
1034 if (isa<CXXDestructorDecl>(Callee) &&
1035 !CanTriviallyDestruct(MCE->getObjectType()))
1036 return false;
1037
1038 auto Name = safeGetName(Callee);
1039 if (Name == "ref" || Name == "incrementCheckedPtrCount")
1040 return true;
1041
1042 std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(Callee);
1043 if (IsGetterOfRefCounted && *IsGetterOfRefCounted)
1044 return true;
1045
1046 // Recursively descend into the callee to confirm that it's trivial as well.
1047 return IsFunctionTrivial(Callee);
1048 }
1049
1051 if (!checkArguments(OCE))
1052 return false;
1053 auto *Callee = OCE->getCalleeDecl();
1054 if (!Callee)
1055 return false;
1056 // Recursively descend into the callee to confirm that it's trivial as well.
1057 return IsFunctionTrivial(Callee);
1058 }
1059
1061 auto *SemanticExpr = Op->getSemanticForm();
1062 return SemanticExpr && Visit(SemanticExpr);
1063 }
1064
1066 if (auto *Expr = E->getExpr()) {
1067 if (!Visit(Expr))
1068 return false;
1069 }
1070 return true;
1071 }
1072
1074 return Visit(E->getExpr());
1075 }
1076
1077 bool checkArguments(const CallExpr *CE) {
1078 for (const Expr *Arg : CE->arguments()) {
1079 if (Arg && !Visit(Arg))
1080 return false;
1081 }
1082 return true;
1083 }
1084
1085 // Triviality check for a return value that may elide a smart-pointer
1086 // temporary's destructor.
1087 //
1088 // This is only valid for *return values*: a returned class prvalue is
1089 // constructed directly into the function's return slot (C++17 guaranteed copy
1090 // elision), so the temporary is destructed by the caller rather than here.
1091 //
1092 // It is deliberately NOT applied to call/constructor arguments. An argument
1093 // temporary's lifetime ends at the full-expression *in this function* (the
1094 // caller destroys arguments, e.g. per the Itanium C++ ABI), so its destructor
1095 // runs here and may invoke delete. Proving otherwise would require
1096 // interprocedural ownership analysis, so arguments are checked normally.
1098 QualType OriginalQT = Arg->getType();
1099 auto *Type = OriginalQT.getTypePtrOrNull();
1100 if (!Type)
1101 return Visit(Arg);
1102 auto *CXXRD = Type->getAsCXXRecordDecl();
1103 if (!CXXRD || !isSmartPtrClass(safeGetName(CXXRD)))
1104 return Visit(Arg);
1105 Arg = Arg->IgnoreParenCasts();
1106 if (!Arg->isPRValue())
1107 return Visit(Arg);
1108 if (auto *Init = dyn_cast<InitListExpr>(Arg)) {
1109 if (Init->getNumInits() == 1)
1110 Arg = Init->getInit(0);
1111 }
1112 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Arg)) {
1113 // Only elide when the temporary *is* the returned object, i.e. it has the
1114 // same smart-pointer type as the return value. Compare canonical,
1115 // unqualified types rather than relying on exact QualType identity, which
1116 // is sensitive to sugar (typedefs/aliases) and cv-qualifiers.
1117 if (OriginalQT.getCanonicalType().getUnqualifiedType() ==
1118 BTE->getType().getCanonicalType().getUnqualifiedType())
1119 return Visit(BTE->getSubExpr());
1120 }
1121 return Visit(Arg);
1122 }
1123
1125 if (CE->getNumArgs() == 1) {
1126 auto *InnerArg = CE->getArg(0);
1127 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(InnerArg)) {
1128 auto *InnerExpr = MTE->getSubExpr();
1129 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(InnerExpr))
1130 InnerExpr = BTE->getSubExpr();
1131 auto InnerQT = InnerExpr->getType();
1132 if (auto *InnerDecl = InnerQT->getAsCXXRecordDecl()) {
1133 auto *OuterCls = CE->getConstructor()->getParent();
1134 if (isRefType(safeGetName(OuterCls)) &&
1135 isRefType(safeGetName(InnerDecl)))
1136 return Visit(InnerExpr);
1137 }
1138 }
1139 }
1140
1141 for (const Expr *Arg : CE->arguments()) {
1142 if (Arg && !Visit(Arg))
1143 return false;
1144 }
1145
1146 // Recursively descend into the callee to confirm that it's trivial.
1147 return IsFunctionTrivial(CE->getConstructor());
1148 }
1149
1153
1154 bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(NE); }
1155
1157 return Visit(ICE->getSubExpr());
1158 }
1159
1161 return Visit(ECE->getSubExpr());
1162 }
1163
1165 return Visit(VMT->getSubExpr());
1166 }
1167
1169 if (auto *Temp = BTE->getTemporary()) {
1170 if (!IsFunctionTrivial(Temp->getDestructor()))
1171 return false;
1172 }
1173 return Visit(BTE->getSubExpr());
1174 }
1175
1177 return Visit(AILE->getCommonExpr()) && Visit(AILE->getSubExpr());
1178 }
1179
1181 return true; // The current array index in VisitArrayInitLoopExpr is always
1182 // trivial.
1183 }
1184
1186 return Visit(OVE->getSourceExpr());
1187 }
1188
1190 return Visit(EWC->getSubExpr());
1191 }
1192
1193 bool VisitParenExpr(const ParenExpr *PE) { return Visit(PE->getSubExpr()); }
1194
1196 for (const Expr *Child : ILE->inits()) {
1197 if (Child && !Visit(Child))
1198 return false;
1199 }
1200 return true;
1201 }
1202
1203 bool VisitMemberExpr(const MemberExpr *ME) {
1204 // Field access is allowed but the base pointer may itself be non-trivial.
1205 return Visit(ME->getBase());
1206 }
1207
1209 // The expression 'this' is always trivial, be it explicit or implicit.
1210 return true;
1211 }
1212
1214 // nullptr is trivial.
1215 return true;
1216 }
1217
1219 // The use of a variable is trivial.
1220 return true;
1221 }
1222
1223 // Constant literal expressions are always trivial
1224 bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; }
1225 bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; }
1226 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; }
1227 bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; }
1228 bool VisitStringLiteral(const StringLiteral *E) { return true; }
1229 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; }
1230
1232 // Constant expressions are trivial.
1233 return true;
1234 }
1235
1237 // An implicit value initialization is trvial.
1238 return true;
1239 }
1240
1241private:
1242 CacheTy &Cache;
1243 CacheTy FieldDtorCache;
1244 CacheTy RecursiveFn;
1245 const Stmt **OffendingStmt;
1246};
1247
1248bool TrivialFunctionAnalysis::isTrivialImpl(
1249 const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache,
1250 const Stmt **OffendingStmt) {
1251 TrivialFunctionAnalysisVisitor V(Cache, OffendingStmt);
1252 return V.IsFunctionTrivial(D);
1253}
1254
1255bool TrivialFunctionAnalysis::isTrivialImpl(
1256 const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache,
1257 const Stmt **OffendingStmt) {
1258 TrivialFunctionAnalysisVisitor V(Cache, OffendingStmt);
1259 return V.IsStatementTrivial(S);
1260}
1261
1262bool TrivialFunctionAnalysis::hasTrivialDtorImpl(const VarDecl *VD,
1263 CacheTy &Cache) {
1265 return V.HasTrivialDestructor(VD);
1266}
1267
1268} // 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:5077
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:6071
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6033
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6978
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:4082
Expr * getLHS() const
Definition Expr.h:4132
Expr * getRHS() const
Definition Expr.h:4134
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:1497
CXXTemporary * getTemporary()
Definition ExprCXX.h:1515
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
arg_range arguments()
Definition ExprCXX.h:1676
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
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:1755
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:774
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:755
QualType getObjectType() const
Retrieve the type of the object argument.
Definition ExprCXX.cpp:767
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:2359
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
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:290
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
Represents the this expression in C++.
Definition ExprCXX.h:1158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
arg_range arguments()
Definition Expr.h:3239
Decl * getCalleeDecl()
Definition Expr.h:3164
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Expr * getSubExpr()
Definition Expr.h:3770
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4344
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
ConditionalOperator - The ?
Definition Expr.h:4435
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:1102
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:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
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
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:3972
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3714
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:3128
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:3295
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
const Expr * getSubExpr() const
Definition Expr.h:1082
Represents a function declaration or definition.
Definition Decl.h:2059
QualType getReturnType() const
Definition Decl.h:2976
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:4169
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:3897
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Describes an C or C++ initializer list.
Definition Expr.h:5352
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
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:4973
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4990
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
Expr * getBase() const
Definition Expr.h:3485
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:2571
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
const Expr * getSubExpr() const
Definition Expr.h:2243
Represents a parameter to a function.
Definition Decl.h:1820
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2049
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:8428
QualType getCanonicalType() const
Definition TypeBase.h:8480
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
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:8432
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
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4166
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4717
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 VisitStringLiteral(const StringLiteral *E)
bool VisitStaticAssertDecl(const StaticAssertDecl *SAD)
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE)
bool VisitCXXThisExpr(const CXXThisExpr *CTE)
bool VisitUnaryOperator(const UnaryOperator *UO)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitContinueStmt(const ContinueStmt *)
bool VisitSwitchStmt(const SwitchStmt *SS)
bool VisitGCCAsmStmt(const GCCAsmStmt *AS)
bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO)
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 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)
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)
TrivialFunctionAnalysisVisitor(CacheTy &Cache, const Stmt **OffendingStmt=nullptr)
bool VisitReturnStmt(const ReturnStmt *RS)
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:8628
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:881
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9159
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9317
bool isPointerOrReferenceType() const
Definition TypeBase.h:8669
bool isObjCObjectPointerType() const
Definition TypeBase.h:8844
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isRecordType() const
Definition TypeBase.h:8792
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3802
QualType getUnderlyingType() const
Definition Decl.h:3752
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
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:125
bool isRetainPtrOrOSPtrType(const clang::QualType T)
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)
static WebKitAnnotation typeAnnotationForReturnType(const FunctionDecl *FD)
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
The alignment was not explicit in code.
Definition ASTContext.h:176
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6017
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6007
std::optional< bool > isUncounted(const QualType T)
std::optional< bool > isUncheckedPtr(const QualType T)
bool isWeakPtr(const CXXRecordDecl *R)