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