clang 22.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"
15#include "clang/AST/ExprCXX.h"
18#include <optional>
19
20using namespace clang;
21
22namespace {
23
24bool hasPublicMethodInBaseClass(const CXXRecordDecl *R, StringRef NameToMatch) {
25 assert(R);
26 assert(R->hasDefinition());
27
28 for (const CXXMethodDecl *MD : R->methods()) {
29 const auto MethodName = safeGetName(MD);
30 if (MethodName == NameToMatch && MD->getAccess() == AS_public)
31 return true;
32 }
33 return false;
34}
35
36} // namespace
37
38namespace clang {
39
40std::optional<const clang::CXXRecordDecl *>
41hasPublicMethodInBase(const CXXBaseSpecifier *Base, StringRef NameToMatch) {
42 assert(Base);
43
44 const Type *T = Base->getType().getTypePtrOrNull();
45 if (!T)
46 return std::nullopt;
47
48 const CXXRecordDecl *R = T->getAsCXXRecordDecl();
49 if (!R) {
50 auto CT = Base->getType().getCanonicalType();
51 if (auto *TST = dyn_cast<TemplateSpecializationType>(CT)) {
52 auto TmplName = TST->getTemplateName();
53 if (!TmplName.isNull()) {
54 if (auto *TD = TmplName.getAsTemplateDecl())
55 R = dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
56 }
57 }
58 if (!R)
59 return std::nullopt;
60 }
61 if (!R->hasDefinition())
62 return std::nullopt;
63
64 return hasPublicMethodInBaseClass(R, NameToMatch) ? R : nullptr;
65}
66
67std::optional<bool> isSmartPtrCompatible(const CXXRecordDecl *R,
68 StringRef IncMethodName,
69 StringRef DecMethodName) {
70 assert(R);
71
72 R = R->getDefinition();
73 if (!R)
74 return std::nullopt;
75
76 bool hasRef = hasPublicMethodInBaseClass(R, IncMethodName);
77 bool hasDeref = hasPublicMethodInBaseClass(R, DecMethodName);
78 if (hasRef && hasDeref)
79 return true;
80
81 CXXBasePaths Paths;
82 Paths.setOrigin(const_cast<CXXRecordDecl *>(R));
83
84 bool AnyInconclusiveBase = false;
85 const auto hasPublicRefInBase = [&](const CXXBaseSpecifier *Base,
86 CXXBasePath &) {
87 auto hasRefInBase = clang::hasPublicMethodInBase(Base, IncMethodName);
88 if (!hasRefInBase) {
89 AnyInconclusiveBase = true;
90 return false;
91 }
92 return (*hasRefInBase) != nullptr;
93 };
94
95 hasRef = hasRef || R->lookupInBases(hasPublicRefInBase, Paths,
96 /*LookupInDependent =*/true);
97 if (AnyInconclusiveBase)
98 return std::nullopt;
99
100 Paths.clear();
101 const auto hasPublicDerefInBase = [&](const CXXBaseSpecifier *Base,
102 CXXBasePath &) {
103 auto hasDerefInBase = clang::hasPublicMethodInBase(Base, DecMethodName);
104 if (!hasDerefInBase) {
105 AnyInconclusiveBase = true;
106 return false;
107 }
108 return (*hasDerefInBase) != nullptr;
109 };
110 hasDeref = hasDeref || R->lookupInBases(hasPublicDerefInBase, Paths,
111 /*LookupInDependent =*/true);
112 if (AnyInconclusiveBase)
113 return std::nullopt;
114
115 return hasRef && hasDeref;
116}
117
118std::optional<bool> isRefCountable(const clang::CXXRecordDecl *R) {
119 return isSmartPtrCompatible(R, "ref", "deref");
120}
121
122std::optional<bool> isCheckedPtrCapable(const clang::CXXRecordDecl *R) {
123 return isSmartPtrCompatible(R, "incrementCheckedPtrCount",
124 "decrementCheckedPtrCount");
125}
126
127bool isRefType(const std::string &Name) {
128 return Name == "Ref" || Name == "RefAllowingPartiallyDestroyed" ||
129 Name == "RefPtr" || Name == "RefPtrAllowingPartiallyDestroyed";
130}
131
132bool isRetainPtrOrOSPtr(const std::string &Name) {
133 return Name == "RetainPtr" || Name == "RetainPtrArc" ||
134 Name == "OSObjectPtr" || Name == "OSObjectPtrArc";
135}
136
137bool isCheckedPtr(const std::string &Name) {
138 return Name == "CheckedPtr" || Name == "CheckedRef";
139}
140
141bool isOwnerPtr(const std::string &Name) {
142 return isRefType(Name) || isCheckedPtr(Name) || Name == "unique_ptr" ||
143 Name == "UniqueRef" || Name == "LazyUniqueRef";
144}
145
146bool isSmartPtrClass(const std::string &Name) {
147 return isRefType(Name) || isCheckedPtr(Name) || isRetainPtrOrOSPtr(Name) ||
148 Name == "WeakPtr" || Name == "WeakPtrFactory" ||
149 Name == "WeakPtrFactoryWithBitField" || Name == "WeakPtrImplBase" ||
150 Name == "WeakPtrImplBaseSingleThread" || Name == "ThreadSafeWeakPtr" ||
151 Name == "ThreadSafeWeakOrStrongPtr" ||
152 Name == "ThreadSafeWeakPtrControlBlock" ||
153 Name == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr";
154}
155
157 assert(F);
158 const std::string &FunctionName = safeGetName(F);
159
160 return isRefType(FunctionName) || FunctionName == "adoptRef" ||
161 FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
162 FunctionName == "makeUniqueRefWithoutFastMallocCheck"
163
164 || FunctionName == "String" || FunctionName == "AtomString" ||
165 FunctionName == "UniqueString"
166 // FIXME: Implement as attribute.
167 || FunctionName == "Identifier";
168}
169
171 assert(F);
172 return isCheckedPtr(safeGetName(F));
173}
174
176 const std::string &FunctionName = safeGetName(F);
177 return FunctionName == "RetainPtr" || FunctionName == "adoptNS" ||
178 FunctionName == "adoptCF" || FunctionName == "retainPtr" ||
179 FunctionName == "RetainPtrArc" || FunctionName == "adoptNSArc" ||
180 FunctionName == "adoptOSObject" || FunctionName == "adoptOSObjectArc";
181}
182
187
188template <typename Predicate>
189static bool isPtrOfType(const clang::QualType T, Predicate Pred) {
190 QualType type = T;
191 while (!type.isNull()) {
192 if (auto *SpecialT = type->getAs<TemplateSpecializationType>()) {
193 auto *Decl = SpecialT->getTemplateName().getAsTemplateDecl();
194 return Decl && Pred(Decl->getNameAsString());
195 } else if (auto *DTS = type->getAs<DeducedTemplateSpecializationType>()) {
196 auto *Decl = DTS->getTemplateName().getAsTemplateDecl();
197 return Decl && Pred(Decl->getNameAsString());
198 } else
199 break;
200 }
201 return false;
202}
203
205 return isPtrOfType(
206 T, [](auto Name) { return isRefType(Name) || isCheckedPtr(Name); });
207}
208
210 return isPtrOfType(T, [](auto Name) { return isRetainPtrOrOSPtr(Name); });
211}
212
214 return isPtrOfType(T, [](auto Name) { return isOwnerPtr(Name); });
215}
216
217std::optional<bool> isUncounted(const QualType T) {
218 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) {
219 if (auto *Decl = Subst->getAssociatedDecl()) {
221 return false;
222 }
223 }
224 return isUncounted(T->getAsCXXRecordDecl());
225}
226
227std::optional<bool> isUnchecked(const QualType T) {
228 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) {
229 if (auto *Decl = Subst->getAssociatedDecl()) {
231 return false;
232 }
233 }
234 return isUnchecked(T->getAsCXXRecordDecl());
235}
236
238 const TranslationUnitDecl *TUD) {
239 IsARCEnabled = TUD->getLangOpts().ObjCAutoRefCount;
240 DefaultSynthProperties = TUD->getLangOpts().ObjCDefaultSynthProperties;
241}
242
244 auto QT = TD->getUnderlyingType();
245 if (!QT->isPointerType())
246 return;
247
248 auto PointeeQT = QT->getPointeeType();
249 const RecordType *RT = PointeeQT->getAsCanonical<RecordType>();
250 if (!RT) {
251 if (TD->hasAttr<ObjCBridgeAttr>() || TD->hasAttr<ObjCBridgeMutableAttr>()) {
252 RecordlessTypes.insert(TD->getASTContext()
254 /*Qualifier=*/std::nullopt, TD)
255 .getTypePtr());
256 }
257 return;
258 }
259
260 for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
261 if (Redecl->getAttr<ObjCBridgeAttr>() ||
262 Redecl->getAttr<ObjCBridgeMutableAttr>()) {
263 CFPointees.insert(RT);
264 return;
265 }
266 }
267}
268
269bool RetainTypeChecker::isUnretained(const QualType QT, bool ignoreARC) {
270 if (ento::cocoa::isCocoaObjectRef(QT) && (!IsARCEnabled || ignoreARC))
271 return true;
272 if (auto *RT = dyn_cast_or_null<RecordType>(
274 return CFPointees.contains(RT);
275 return RecordlessTypes.contains(QT.getTypePtr());
276}
277
278std::optional<bool> isUnretained(const QualType T, bool IsARCEnabled) {
279 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) {
280 if (auto *Decl = Subst->getAssociatedDecl()) {
282 return false;
283 }
284 }
285 if ((ento::cocoa::isCocoaObjectRef(T) && !IsARCEnabled) ||
287 return true;
288
289 // RetainPtr strips typedef for CF*Ref. Manually check for struct __CF* types.
290 auto CanonicalType = T.getCanonicalType();
291 auto *Type = CanonicalType.getTypePtrOrNull();
292 if (!Type)
293 return false;
294 auto Pointee = Type->getPointeeType();
295 auto *PointeeType = Pointee.getTypePtrOrNull();
296 if (!PointeeType)
297 return false;
298 auto *Record = PointeeType->getAsStructureType();
299 if (!Record)
300 return false;
301 auto *Decl = Record->getDecl();
302 if (!Decl)
303 return false;
304 auto TypeName = Decl->getName();
305 return TypeName.starts_with("__CF") || TypeName.starts_with("__CG") ||
306 TypeName.starts_with("__CM");
307}
308
309std::optional<bool> isUncounted(const CXXRecordDecl* Class)
310{
311 // Keep isRefCounted first as it's cheaper.
312 if (!Class || isRefCounted(Class))
313 return false;
314
315 std::optional<bool> IsRefCountable = isRefCountable(Class);
316 if (!IsRefCountable)
317 return std::nullopt;
318
319 return (*IsRefCountable);
320}
321
322std::optional<bool> isUnchecked(const CXXRecordDecl *Class) {
323 if (!Class || isCheckedPtr(Class))
324 return false; // Cheaper than below
326}
327
328std::optional<bool> isUncountedPtr(const QualType T) {
329 if (T->isPointerType() || T->isReferenceType()) {
330 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
331 return isUncounted(CXXRD);
332 }
333 return false;
334}
335
336std::optional<bool> isUncheckedPtr(const QualType T) {
337 if (T->isPointerType() || T->isReferenceType()) {
338 if (auto *CXXRD = T->getPointeeCXXRecordDecl())
339 return isUnchecked(CXXRD);
340 }
341 return false;
342}
343
344std::optional<bool> isUnsafePtr(const QualType T, bool IsArcEnabled) {
345 if (T->isPointerType() || T->isReferenceType()) {
346 if (auto *CXXRD = T->getPointeeCXXRecordDecl()) {
347 auto isUncountedPtr = isUncounted(CXXRD);
348 auto isUncheckedPtr = isUnchecked(CXXRD);
349 auto isUnretainedPtr = isUnretained(T, IsArcEnabled);
350 std::optional<bool> result;
351 if (isUncountedPtr)
352 result = *isUncountedPtr;
353 if (isUncheckedPtr)
354 result = result ? *result || *isUncheckedPtr : *isUncheckedPtr;
355 if (isUnretainedPtr)
356 result = result ? *result || *isUnretainedPtr : *isUnretainedPtr;
357 return result;
358 }
359 }
360 return false;
361}
362
363std::optional<bool> isGetterOfSafePtr(const CXXMethodDecl *M) {
364 assert(M);
365
366 if (isa<CXXMethodDecl>(M)) {
367 const CXXRecordDecl *calleeMethodsClass = M->getParent();
368 auto className = safeGetName(calleeMethodsClass);
369 auto method = safeGetName(M);
370
371 if (isCheckedPtr(className) && (method == "get" || method == "ptr"))
372 return true;
373
374 if ((isRefType(className) && (method == "get" || method == "ptr")) ||
375 ((className == "String" || className == "AtomString" ||
376 className == "AtomStringImpl" || className == "UniqueString" ||
377 className == "UniqueStringImpl" || className == "Identifier") &&
378 method == "impl"))
379 return true;
380
381 if (isRetainPtrOrOSPtr(className) && method == "get")
382 return true;
383
384 // Ref<T> -> T conversion
385 // FIXME: Currently allowing any Ref<T> -> whatever cast.
386 if (isRefType(className)) {
387 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) {
388 auto QT = maybeRefToRawOperator->getConversionType();
389 auto *T = QT.getTypePtrOrNull();
390 return T && (T->isPointerType() || T->isReferenceType());
391 }
392 }
393
394 if (isCheckedPtr(className)) {
395 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) {
396 auto QT = maybeRefToRawOperator->getConversionType();
397 auto *T = QT.getTypePtrOrNull();
398 return T && (T->isPointerType() || T->isReferenceType());
399 }
400 }
401
402 if (isRetainPtrOrOSPtr(className)) {
403 if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) {
404 auto QT = maybeRefToRawOperator->getConversionType();
405 auto *T = QT.getTypePtrOrNull();
406 return T && (T->isPointerType() || T->isReferenceType() ||
407 T->isObjCObjectPointerType());
408 }
409 }
410 }
411 return false;
412}
413
415 assert(R);
416 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
417 // FIXME: String/AtomString/UniqueString
418 const auto &ClassName = safeGetName(TmplR);
419 return isRefType(ClassName);
420 }
421 return false;
422}
423
425 assert(R);
426 if (auto *TmplR = R->getTemplateInstantiationPattern()) {
427 const auto &ClassName = safeGetName(TmplR);
428 return isCheckedPtr(ClassName);
429 }
430 return false;
431}
432
434 assert(R);
435 if (auto *TmplR = R->getTemplateInstantiationPattern())
436 return isRetainPtrOrOSPtr(safeGetName(TmplR));
437 return false;
438}
439
440bool isSmartPtr(const CXXRecordDecl *R) {
441 assert(R);
442 if (auto *TmplR = R->getTemplateInstantiationPattern())
443 return isSmartPtrClass(safeGetName(TmplR));
444 return false;
445}
446
448 assert(F);
449 if (isCtorOfRefCounted(F))
450 return true;
451
452 // FIXME: check # of params == 1
453 const auto FunctionName = safeGetName(F);
454 if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
455 FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
456 FunctionName == "checkedDowncast" || FunctionName == "bit_cast" ||
457 FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" ||
458 FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" ||
459 FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" ||
460 FunctionName == "dynamic_objc_cast" ||
461 FunctionName == "checked_objc_cast")
462 return true;
463
464 auto ReturnType = F->getReturnType();
465 if (auto *Type = ReturnType.getTypePtrOrNull()) {
466 if (auto *AttrType = dyn_cast<AttributedType>(Type)) {
467 if (auto *Attr = AttrType->getAttr()) {
468 if (auto *AnnotateType = dyn_cast<AnnotateTypeAttr>(Attr)) {
469 if (AnnotateType->getAnnotation() == "webkit.pointerconversion")
470 return true;
471 }
472 }
473 }
474 }
475
476 return false;
477}
478
480 if (!F || !F->getDeclName().isIdentifier())
481 return false;
482 auto Name = F->getName();
483 return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" ||
484 Name.starts_with("os_log") || Name.starts_with("_os_log");
485}
486
487bool isSingleton(const NamedDecl *F) {
488 assert(F);
489 // FIXME: check # of params == 1
490 if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(F)) {
491 if (!MethodDecl->isStatic())
492 return false;
493 }
494 const auto &NameStr = safeGetName(F);
495 StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef.
496 return Name == "singleton" || Name.ends_with("Singleton");
497}
498
499// We only care about statements so let's use the simple
500// (non-recursive) visitor.
502 : public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> {
503
504 // Returns false if at least one child is non-trivial.
505 bool VisitChildren(const Stmt *S) {
506 for (const Stmt *Child : S->children()) {
507 if (Child && !Visit(Child))
508 return false;
509 }
510
511 return true;
512 }
513
514 template <typename StmtOrDecl, typename CheckFunction>
515 bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) {
516 auto CacheIt = Cache.find(S);
517 if (CacheIt != Cache.end())
518 return CacheIt->second;
519
520 // Treat a recursive statement to be trivial until proven otherwise.
521 auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true));
522 if (!IsNew)
523 return RecursiveIt->second;
524
525 bool Result = Function();
526
527 if (!Result) {
528 for (auto &It : RecursiveFn)
529 It.second = false;
530 }
531 RecursiveIt = RecursiveFn.find(S);
532 assert(RecursiveIt != RecursiveFn.end());
533 Result = RecursiveIt->second;
534 RecursiveFn.erase(RecursiveIt);
535 Cache[S] = Result;
536
537 return Result;
538 }
539
540public:
541 using CacheTy = TrivialFunctionAnalysis::CacheTy;
542
543 TrivialFunctionAnalysisVisitor(CacheTy &Cache) : Cache(Cache) {}
544
545 bool IsFunctionTrivial(const Decl *D) {
546 if (auto *FnDecl = dyn_cast<FunctionDecl>(D)) {
547 if (FnDecl->isVirtualAsWritten())
548 return false;
549 }
550 return WithCachedResult(D, [&]() {
551 if (auto *CtorDecl = dyn_cast<CXXConstructorDecl>(D)) {
552 for (auto *CtorInit : CtorDecl->inits()) {
553 if (!Visit(CtorInit->getInit()))
554 return false;
555 }
556 }
557 const Stmt *Body = D->getBody();
558 if (!Body)
559 return false;
560 return Visit(Body);
561 });
562 }
563
564 bool VisitStmt(const Stmt *S) {
565 // All statements are non-trivial unless overriden later.
566 // Don't even recurse into children by default.
567 return false;
568 }
569
571 // Ignore attributes.
572 return Visit(AS->getSubStmt());
573 }
574
576 // A compound statement is allowed as long each individual sub-statement
577 // is trivial.
578 return WithCachedResult(CS, [&]() { return VisitChildren(CS); });
579 }
580
581 bool VisitReturnStmt(const ReturnStmt *RS) {
582 // A return statement is allowed as long as the return value is trivial.
583 if (auto *RV = RS->getRetValue())
584 return Visit(RV);
585 return true;
586 }
587
588 bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); }
589 bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
590 bool VisitIfStmt(const IfStmt *IS) {
591 return WithCachedResult(IS, [&]() { return VisitChildren(IS); });
592 }
593 bool VisitForStmt(const ForStmt *FS) {
594 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
595 }
597 return WithCachedResult(FS, [&]() { return VisitChildren(FS); });
598 }
599 bool VisitWhileStmt(const WhileStmt *WS) {
600 return WithCachedResult(WS, [&]() { return VisitChildren(WS); });
601 }
602 bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
603 bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
604 bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(DS); }
605
606 // break, continue, goto, and label statements are always trivial.
607 bool VisitBreakStmt(const BreakStmt *) { return true; }
608 bool VisitContinueStmt(const ContinueStmt *) { return true; }
609 bool VisitGotoStmt(const GotoStmt *) { return true; }
610 bool VisitLabelStmt(const LabelStmt *) { return true; }
611
613 // Unary operators are trivial if its operand is trivial except co_await.
614 return UO->getOpcode() != UO_Coawait && Visit(UO->getSubExpr());
615 }
616
618 // Binary operators are trivial if their operands are trivial.
619 return Visit(BO->getLHS()) && Visit(BO->getRHS());
620 }
621
623 // Compound assignment operator such as |= is trivial if its
624 // subexpresssions are trivial.
625 return VisitChildren(CAO);
626 }
627
629 return VisitChildren(ASE);
630 }
631
633 // Ternary operators are trivial if their conditions & values are trivial.
634 return VisitChildren(CO);
635 }
636
637 bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(E); }
638
640 // Any static_assert is considered trivial.
641 return true;
642 }
643
644 bool VisitCallExpr(const CallExpr *CE) {
645 if (!checkArguments(CE))
646 return false;
647
648 auto *Callee = CE->getDirectCallee();
649 if (!Callee)
650 return false;
651
652 if (isPtrConversion(Callee))
653 return true;
654
655 const auto &Name = safeGetName(Callee);
656
657 if (Callee->isInStdNamespace() &&
658 (Name == "addressof" || Name == "forward" || Name == "move"))
659 return true;
660
661 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
662 Name == "WTFReportBacktrace" ||
663 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
664 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
665 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
666 Name == "isWebThread" || Name == "isUIThread" ||
667 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
669 return true;
670
671 return IsFunctionTrivial(Callee);
672 }
673
674 bool VisitGCCAsmStmt(const GCCAsmStmt *AS) {
675 return AS->getAsmString() == "brk #0xc471";
676 }
677
678 bool
680 // Non-type template paramter is compile time constant and trivial.
681 return true;
682 }
683
685 return VisitChildren(E);
686 }
687
689 // A predefined identifier such as "func" is considered trivial.
690 return true;
691 }
692
694 // offsetof(T, D) is considered trivial.
695 return true;
696 }
697
699 if (!checkArguments(MCE))
700 return false;
701
702 bool TrivialThis = Visit(MCE->getImplicitObjectArgument());
703 if (!TrivialThis)
704 return false;
705
706 auto *Callee = MCE->getMethodDecl();
707 if (!Callee)
708 return false;
709
710 auto Name = safeGetName(Callee);
711 if (Name == "ref" || Name == "incrementCheckedPtrCount")
712 return true;
713
714 std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(Callee);
715 if (IsGetterOfRefCounted && *IsGetterOfRefCounted)
716 return true;
717
718 // Recursively descend into the callee to confirm that it's trivial as well.
719 return IsFunctionTrivial(Callee);
720 }
721
723 if (!checkArguments(OCE))
724 return false;
725 auto *Callee = OCE->getCalleeDecl();
726 if (!Callee)
727 return false;
728 // Recursively descend into the callee to confirm that it's trivial as well.
729 return IsFunctionTrivial(Callee);
730 }
731
733 if (auto *Expr = E->getExpr()) {
734 if (!Visit(Expr))
735 return false;
736 }
737 return true;
738 }
739
740 bool checkArguments(const CallExpr *CE) {
741 for (const Expr *Arg : CE->arguments()) {
742 if (Arg && !Visit(Arg))
743 return false;
744 }
745 return true;
746 }
747
749 for (const Expr *Arg : CE->arguments()) {
750 if (Arg && !Visit(Arg))
751 return false;
752 }
753
754 // Recursively descend into the callee to confirm that it's trivial.
755 return IsFunctionTrivial(CE->getConstructor());
756 }
757
761
762 bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(NE); }
763
765 return Visit(ICE->getSubExpr());
766 }
767
769 return Visit(ECE->getSubExpr());
770 }
771
773 return Visit(VMT->getSubExpr());
774 }
775
777 if (auto *Temp = BTE->getTemporary()) {
778 if (!TrivialFunctionAnalysis::isTrivialImpl(Temp->getDestructor(), Cache))
779 return false;
780 }
781 return Visit(BTE->getSubExpr());
782 }
783
785 return Visit(AILE->getCommonExpr()) && Visit(AILE->getSubExpr());
786 }
787
789 return true; // The current array index in VisitArrayInitLoopExpr is always
790 // trivial.
791 }
792
794 return Visit(OVE->getSourceExpr());
795 }
796
798 return Visit(EWC->getSubExpr());
799 }
800
801 bool VisitParenExpr(const ParenExpr *PE) { return Visit(PE->getSubExpr()); }
802
804 for (const Expr *Child : ILE->inits()) {
805 if (Child && !Visit(Child))
806 return false;
807 }
808 return true;
809 }
810
811 bool VisitMemberExpr(const MemberExpr *ME) {
812 // Field access is allowed but the base pointer may itself be non-trivial.
813 return Visit(ME->getBase());
814 }
815
816 bool VisitCXXThisExpr(const CXXThisExpr *CTE) {
817 // The expression 'this' is always trivial, be it explicit or implicit.
818 return true;
819 }
820
822 // nullptr is trivial.
823 return true;
824 }
825
826 bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
827 // The use of a variable is trivial.
828 return true;
829 }
830
831 // Constant literal expressions are always trivial
832 bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; }
833 bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; }
834 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; }
835 bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; }
836 bool VisitStringLiteral(const StringLiteral *E) { return true; }
837 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; }
838
840 // Constant expressions are trivial.
841 return true;
842 }
843
845 // An implicit value initialization is trvial.
846 return true;
847 }
848
849private:
850 CacheTy &Cache;
851 CacheTy RecursiveFn;
852};
853
854bool TrivialFunctionAnalysis::isTrivialImpl(
855 const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache) {
857 return V.IsFunctionTrivial(D);
858}
859
860bool TrivialFunctionAnalysis::isTrivialImpl(
861 const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache) {
863 bool Result = V.Visit(S);
864 assert(Cache.contains(S) && "Top-level statement not properly cached!");
865 return Result;
866}
867
868} // namespace clang
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Record Record
Definition MachO.h:31
TypePropertyCache< Private > Cache
Definition Type.cpp:4785
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:5955
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
Attr - This represents one attribute.
Definition Attr.h:44
Represents an attribute applied to a statement.
Definition Stmt.h:2203
Stmt * getSubStmt()
Definition Stmt.h:2239
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
Expr * getRHS() const
Definition Expr.h:4024
BreakStmt - This represents a break.
Definition Stmt.h:3135
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)
void clear()
Clear the base-paths results.
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1494
CXXTemporary * getTemporary()
Definition ExprCXX.h:1512
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:723
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
arg_range arguments()
Definition ExprCXX.h:1673
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1271
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1753
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1790
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:741
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:722
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2357
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
method_range methods() const
Definition DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2075
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:561
Represents the this expression in C++.
Definition ExprCXX.h:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
arg_range arguments()
Definition Expr.h:3129
Decl * getCalleeDecl()
Definition Expr.h:3054
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
Expr * getSubExpr()
Definition Expr.h:3660
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4234
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
ConditionalOperator - The ?
Definition Expr.h:4325
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:1082
ContinueStmt - This represents a continue.
Definition Stmt.h:3119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
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:1087
bool hasAttr() const
Definition DeclBase.h:577
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition DeclBase.cpp:552
bool isIdentifier() const
Predicate functions for querying what type of name this is.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2832
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3663
This represents one expression.
Definition Expr.h:112
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
QualType getReturnType() const
Definition Decl.h:2845
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3395
std::string getAsmString() const
Definition Stmt.cpp:536
GotoStmt - This represents a direct goto.
Definition Stmt.h:2969
IfStmt - This represents an if/then/else.
Definition Stmt.h:2259
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
Describes an C or C++ initializer list.
Definition Expr.h:5233
ArrayRef< Expr * > inits()
Definition Expr.h:5283
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2146
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4922
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4939
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
Expr * getBase() const
Definition Expr.h:3375
This represents a decl that may have a name.
Definition Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2527
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
const Expr * getSubExpr() const
Definition Expr.h:2199
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2005
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
QualType getCanonicalType() const
Definition TypeBase.h:8330
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8282
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:3160
Expr * getRetValue()
Definition Stmt.h:3187
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4136
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:299
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4666
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
The top declaration context.
Definition Decl.h:105
bool VisitMemberExpr(const MemberExpr *ME)
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 VisitDeclRefExpr(const DeclRefExpr *DRE)
bool VisitIntegerLiteral(const IntegerLiteral *E)
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *VMT)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
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 VisitCXXNewExpr(const CXXNewExpr *NE)
bool VisitBinaryOperator(const BinaryOperator *BO)
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)
bool VisitReturnStmt(const ReturnStmt *RS)
The base class of the type hierarchy.
Definition TypeBase.h:1833
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
QualType getUnderlyingType() const
Definition Decl.h:3617
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool isCocoaObjectRef(QualType T)
The JSON file list parser is used to communicate input to InstallAPI.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isTrivialBuiltinFunction(const FunctionDecl *F)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isPtrConversion(const FunctionDecl *F)
std::optional< bool > isCheckedPtrCapable(const clang::CXXRecordDecl *R)
std::optional< bool > isUnchecked(const QualType T)
bool isCtorOfRefCounted(const clang::FunctionDecl *F)
bool isRefOrCheckedPtrType(const clang::QualType T)
@ AS_public
Definition Specifiers.h:124
bool isRetainPtrOrOSPtrType(const clang::QualType T)
bool isCtorOfRetainPtrOrOSPtr(const clang::FunctionDecl *F)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
bool isOwnerPtr(const std::string &Name)
std::optional< bool > isUnsafePtr(const QualType T, bool IsArcEnabled)
const FunctionProtoType * T
std::optional< bool > isUnretained(const QualType T, bool IsARCEnabled)
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)
bool isRefCounted(const CXXRecordDecl *R)
static bool isPtrOfType(const clang::QualType T, Predicate Pred)
std::optional< bool > isSmartPtrCompatible(const CXXRecordDecl *R, StringRef IncMethodName, StringRef DecMethodName)
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)
std::optional< bool > isUncountedPtr(const QualType T)
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:91
bool isCtorOfCheckedPtr(const clang::FunctionDecl *F)
bool isSingleton(const NamedDecl *F)
bool isCheckedPtr(const std::string &Name)
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
std::optional< bool > isUncounted(const QualType T)
std::optional< bool > isUncheckedPtr(const QualType T)