1 //===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===// 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 // This file implements the C++ related Decl classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/ASTUnresolvedSet.h" 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/DeclarationName.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/LambdaCapture.h" 26 #include "clang/AST/NestedNameSpecifier.h" 27 #include "clang/AST/ODRHash.h" 28 #include "clang/AST/Type.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/AST/UnresolvedSet.h" 31 #include "clang/Basic/Diagnostic.h" 32 #include "clang/Basic/IdentifierTable.h" 33 #include "clang/Basic/LLVM.h" 34 #include "clang/Basic/LangOptions.h" 35 #include "clang/Basic/OperatorKinds.h" 36 #include "clang/Basic/PartialDiagnostic.h" 37 #include "clang/Basic/SourceLocation.h" 38 #include "clang/Basic/Specifiers.h" 39 #include "clang/Basic/TargetInfo.h" 40 #include "llvm/ADT/SmallPtrSet.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/ADT/iterator_range.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/Format.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstddef> 50 #include <cstdint> 51 52 using namespace clang; 53 54 //===----------------------------------------------------------------------===// 55 // Decl Allocation/Deallocation Method Implementations 56 //===----------------------------------------------------------------------===// 57 58 void AccessSpecDecl::anchor() {} 59 60 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 61 return new (C, ID) AccessSpecDecl(EmptyShell()); 62 } 63 64 void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const { 65 ExternalASTSource *Source = C.getExternalSource(); 66 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set"); 67 assert(Source && "getFromExternalSource with no external source"); 68 69 for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I) 70 I.setDecl(cast<NamedDecl>(Source->GetExternalDecl( 71 reinterpret_cast<uintptr_t>(I.getDecl()) >> 2))); 72 Impl.Decls.setLazy(false); 73 } 74 75 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D) 76 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0), 77 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false), 78 Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true), 79 HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false), 80 HasPrivateFields(false), HasProtectedFields(false), 81 HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false), 82 HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false), 83 HasUninitializedReferenceMember(false), HasUninitializedFields(false), 84 HasInheritedConstructor(false), HasInheritedDefaultConstructor(false), 85 HasInheritedAssignment(false), 86 NeedOverloadResolutionForCopyConstructor(false), 87 NeedOverloadResolutionForMoveConstructor(false), 88 NeedOverloadResolutionForCopyAssignment(false), 89 NeedOverloadResolutionForMoveAssignment(false), 90 NeedOverloadResolutionForDestructor(false), 91 DefaultedCopyConstructorIsDeleted(false), 92 DefaultedMoveConstructorIsDeleted(false), 93 DefaultedCopyAssignmentIsDeleted(false), 94 DefaultedMoveAssignmentIsDeleted(false), 95 DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All), 96 HasTrivialSpecialMembersForCall(SMF_All), 97 DeclaredNonTrivialSpecialMembers(0), 98 DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true), 99 HasConstexprNonCopyMoveConstructor(false), 100 HasDefaultedDefaultConstructor(false), 101 DefaultedDefaultConstructorIsConstexpr(true), 102 HasConstexprDefaultConstructor(false), 103 DefaultedDestructorIsConstexpr(true), 104 HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true), 105 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0), 106 ImplicitCopyConstructorCanHaveConstParamForVBase(true), 107 ImplicitCopyConstructorCanHaveConstParamForNonVBase(true), 108 ImplicitCopyAssignmentHasConstParam(true), 109 HasDeclaredCopyConstructorWithConstParam(false), 110 HasDeclaredCopyAssignmentWithConstParam(false), 111 IsAnyDestructorNoReturn(false), IsLambda(false), 112 IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false), 113 HasODRHash(false), Definition(D) {} 114 115 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const { 116 return Bases.get(Definition->getASTContext().getExternalSource()); 117 } 118 119 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const { 120 return VBases.get(Definition->getASTContext().getExternalSource()); 121 } 122 123 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, 124 DeclContext *DC, SourceLocation StartLoc, 125 SourceLocation IdLoc, IdentifierInfo *Id, 126 CXXRecordDecl *PrevDecl) 127 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl), 128 DefinitionData(PrevDecl ? PrevDecl->DefinitionData 129 : nullptr) {} 130 131 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK, 132 DeclContext *DC, SourceLocation StartLoc, 133 SourceLocation IdLoc, IdentifierInfo *Id, 134 CXXRecordDecl *PrevDecl, 135 bool DelayTypeCreation) { 136 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, 137 PrevDecl); 138 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 139 140 // FIXME: DelayTypeCreation seems like such a hack 141 if (!DelayTypeCreation) 142 C.getTypeDeclType(R, PrevDecl); 143 return R; 144 } 145 146 CXXRecordDecl * 147 CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC, 148 TypeSourceInfo *Info, SourceLocation Loc, 149 unsigned DependencyKind, bool IsGeneric, 150 LambdaCaptureDefault CaptureDefault) { 151 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc, 152 Loc, nullptr, nullptr); 153 R->setBeingDefined(true); 154 R->DefinitionData = new (C) struct LambdaDefinitionData( 155 R, Info, DependencyKind, IsGeneric, CaptureDefault); 156 R->setMayHaveOutOfDateDef(false); 157 R->setImplicit(true); 158 159 C.getTypeDeclType(R, /*PrevDecl=*/nullptr); 160 return R; 161 } 162 163 CXXRecordDecl * 164 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 165 auto *R = new (C, ID) 166 CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr, 167 SourceLocation(), SourceLocation(), nullptr, nullptr); 168 R->setMayHaveOutOfDateDef(false); 169 return R; 170 } 171 172 /// Determine whether a class has a repeated base class. This is intended for 173 /// use when determining if a class is standard-layout, so makes no attempt to 174 /// handle virtual bases. 175 static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) { 176 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes; 177 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD}; 178 while (!WorkList.empty()) { 179 const CXXRecordDecl *RD = WorkList.pop_back_val(); 180 if (RD->getTypeForDecl()->isDependentType()) 181 continue; 182 for (const CXXBaseSpecifier &BaseSpec : RD->bases()) { 183 if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) { 184 if (!SeenBaseTypes.insert(B).second) 185 return true; 186 WorkList.push_back(B); 187 } 188 } 189 } 190 return false; 191 } 192 193 void 194 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, 195 unsigned NumBases) { 196 ASTContext &C = getASTContext(); 197 198 if (!data().Bases.isOffset() && data().NumBases > 0) 199 C.Deallocate(data().getBases()); 200 201 if (NumBases) { 202 if (!C.getLangOpts().CPlusPlus17) { 203 // C++ [dcl.init.aggr]p1: 204 // An aggregate is [...] a class with [...] no base classes [...]. 205 data().Aggregate = false; 206 } 207 208 // C++ [class]p4: 209 // A POD-struct is an aggregate class... 210 data().PlainOldData = false; 211 } 212 213 // The set of seen virtual base types. 214 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; 215 216 // The virtual bases of this class. 217 SmallVector<const CXXBaseSpecifier *, 8> VBases; 218 219 data().Bases = new(C) CXXBaseSpecifier [NumBases]; 220 data().NumBases = NumBases; 221 for (unsigned i = 0; i < NumBases; ++i) { 222 data().getBases()[i] = *Bases[i]; 223 // Keep track of inherited vbases for this base class. 224 const CXXBaseSpecifier *Base = Bases[i]; 225 QualType BaseType = Base->getType(); 226 // Skip dependent types; we can't do any checking on them now. 227 if (BaseType->isDependentType()) 228 continue; 229 auto *BaseClassDecl = 230 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl()); 231 232 // C++2a [class]p7: 233 // A standard-layout class is a class that: 234 // [...] 235 // -- has all non-static data members and bit-fields in the class and 236 // its base classes first declared in the same class 237 if (BaseClassDecl->data().HasBasesWithFields || 238 !BaseClassDecl->field_empty()) { 239 if (data().HasBasesWithFields) 240 // Two bases have members or bit-fields: not standard-layout. 241 data().IsStandardLayout = false; 242 data().HasBasesWithFields = true; 243 } 244 245 // C++11 [class]p7: 246 // A standard-layout class is a class that: 247 // -- [...] has [...] at most one base class with non-static data 248 // members 249 if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers || 250 BaseClassDecl->hasDirectFields()) { 251 if (data().HasBasesWithNonStaticDataMembers) 252 data().IsCXX11StandardLayout = false; 253 data().HasBasesWithNonStaticDataMembers = true; 254 } 255 256 if (!BaseClassDecl->isEmpty()) { 257 // C++14 [meta.unary.prop]p4: 258 // T is a class type [...] with [...] no base class B for which 259 // is_empty<B>::value is false. 260 data().Empty = false; 261 } 262 263 // C++1z [dcl.init.agg]p1: 264 // An aggregate is a class with [...] no private or protected base classes 265 if (Base->getAccessSpecifier() != AS_public) { 266 data().Aggregate = false; 267 268 // C++20 [temp.param]p7: 269 // A structural type is [...] a literal class type with [...] all base 270 // classes [...] public 271 data().StructuralIfLiteral = false; 272 } 273 274 // C++ [class.virtual]p1: 275 // A class that declares or inherits a virtual function is called a 276 // polymorphic class. 277 if (BaseClassDecl->isPolymorphic()) { 278 data().Polymorphic = true; 279 280 // An aggregate is a class with [...] no virtual functions. 281 data().Aggregate = false; 282 } 283 284 // C++0x [class]p7: 285 // A standard-layout class is a class that: [...] 286 // -- has no non-standard-layout base classes 287 if (!BaseClassDecl->isStandardLayout()) 288 data().IsStandardLayout = false; 289 if (!BaseClassDecl->isCXX11StandardLayout()) 290 data().IsCXX11StandardLayout = false; 291 292 // Record if this base is the first non-literal field or base. 293 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) 294 data().HasNonLiteralTypeFieldsOrBases = true; 295 296 // Now go through all virtual bases of this base and add them. 297 for (const auto &VBase : BaseClassDecl->vbases()) { 298 // Add this base if it's not already in the list. 299 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) { 300 VBases.push_back(&VBase); 301 302 // C++11 [class.copy]p8: 303 // The implicitly-declared copy constructor for a class X will have 304 // the form 'X::X(const X&)' if each [...] virtual base class B of X 305 // has a copy constructor whose first parameter is of type 306 // 'const B&' or 'const volatile B&' [...] 307 if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl()) 308 if (!VBaseDecl->hasCopyConstructorWithConstParam()) 309 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; 310 311 // C++1z [dcl.init.agg]p1: 312 // An aggregate is a class with [...] no virtual base classes 313 data().Aggregate = false; 314 } 315 } 316 317 if (Base->isVirtual()) { 318 // Add this base if it's not already in the list. 319 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second) 320 VBases.push_back(Base); 321 322 // C++14 [meta.unary.prop] is_empty: 323 // T is a class type, but not a union type, with ... no virtual base 324 // classes 325 data().Empty = false; 326 327 // C++1z [dcl.init.agg]p1: 328 // An aggregate is a class with [...] no virtual base classes 329 data().Aggregate = false; 330 331 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 332 // A [default constructor, copy/move constructor, or copy/move assignment 333 // operator for a class X] is trivial [...] if: 334 // -- class X has [...] no virtual base classes 335 data().HasTrivialSpecialMembers &= SMF_Destructor; 336 data().HasTrivialSpecialMembersForCall &= SMF_Destructor; 337 338 // C++0x [class]p7: 339 // A standard-layout class is a class that: [...] 340 // -- has [...] no virtual base classes 341 data().IsStandardLayout = false; 342 data().IsCXX11StandardLayout = false; 343 344 // C++20 [dcl.constexpr]p3: 345 // In the definition of a constexpr function [...] 346 // -- if the function is a constructor or destructor, 347 // its class shall not have any virtual base classes 348 data().DefaultedDefaultConstructorIsConstexpr = false; 349 data().DefaultedDestructorIsConstexpr = false; 350 351 // C++1z [class.copy]p8: 352 // The implicitly-declared copy constructor for a class X will have 353 // the form 'X::X(const X&)' if each potentially constructed subobject 354 // has a copy constructor whose first parameter is of type 355 // 'const B&' or 'const volatile B&' [...] 356 if (!BaseClassDecl->hasCopyConstructorWithConstParam()) 357 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; 358 } else { 359 // C++ [class.ctor]p5: 360 // A default constructor is trivial [...] if: 361 // -- all the direct base classes of its class have trivial default 362 // constructors. 363 if (!BaseClassDecl->hasTrivialDefaultConstructor()) 364 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 365 366 // C++0x [class.copy]p13: 367 // A copy/move constructor for class X is trivial if [...] 368 // [...] 369 // -- the constructor selected to copy/move each direct base class 370 // subobject is trivial, and 371 if (!BaseClassDecl->hasTrivialCopyConstructor()) 372 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; 373 374 if (!BaseClassDecl->hasTrivialCopyConstructorForCall()) 375 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; 376 377 // If the base class doesn't have a simple move constructor, we'll eagerly 378 // declare it and perform overload resolution to determine which function 379 // it actually calls. If it does have a simple move constructor, this 380 // check is correct. 381 if (!BaseClassDecl->hasTrivialMoveConstructor()) 382 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; 383 384 if (!BaseClassDecl->hasTrivialMoveConstructorForCall()) 385 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; 386 387 // C++0x [class.copy]p27: 388 // A copy/move assignment operator for class X is trivial if [...] 389 // [...] 390 // -- the assignment operator selected to copy/move each direct base 391 // class subobject is trivial, and 392 if (!BaseClassDecl->hasTrivialCopyAssignment()) 393 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; 394 // If the base class doesn't have a simple move assignment, we'll eagerly 395 // declare it and perform overload resolution to determine which function 396 // it actually calls. If it does have a simple move assignment, this 397 // check is correct. 398 if (!BaseClassDecl->hasTrivialMoveAssignment()) 399 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; 400 401 // C++11 [class.ctor]p6: 402 // If that user-written default constructor would satisfy the 403 // requirements of a constexpr constructor, the implicitly-defined 404 // default constructor is constexpr. 405 if (!BaseClassDecl->hasConstexprDefaultConstructor()) 406 data().DefaultedDefaultConstructorIsConstexpr = false; 407 408 // C++1z [class.copy]p8: 409 // The implicitly-declared copy constructor for a class X will have 410 // the form 'X::X(const X&)' if each potentially constructed subobject 411 // has a copy constructor whose first parameter is of type 412 // 'const B&' or 'const volatile B&' [...] 413 if (!BaseClassDecl->hasCopyConstructorWithConstParam()) 414 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; 415 } 416 417 // C++ [class.ctor]p3: 418 // A destructor is trivial if all the direct base classes of its class 419 // have trivial destructors. 420 if (!BaseClassDecl->hasTrivialDestructor()) 421 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 422 423 if (!BaseClassDecl->hasTrivialDestructorForCall()) 424 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 425 426 if (!BaseClassDecl->hasIrrelevantDestructor()) 427 data().HasIrrelevantDestructor = false; 428 429 if (BaseClassDecl->isAnyDestructorNoReturn()) 430 data().IsAnyDestructorNoReturn = true; 431 432 // C++11 [class.copy]p18: 433 // The implicitly-declared copy assignment operator for a class X will 434 // have the form 'X& X::operator=(const X&)' if each direct base class B 435 // of X has a copy assignment operator whose parameter is of type 'const 436 // B&', 'const volatile B&', or 'B' [...] 437 if (!BaseClassDecl->hasCopyAssignmentWithConstParam()) 438 data().ImplicitCopyAssignmentHasConstParam = false; 439 440 // A class has an Objective-C object member if... or any of its bases 441 // has an Objective-C object member. 442 if (BaseClassDecl->hasObjectMember()) 443 setHasObjectMember(true); 444 445 if (BaseClassDecl->hasVolatileMember()) 446 setHasVolatileMember(true); 447 448 if (BaseClassDecl->getArgPassingRestrictions() == 449 RecordArgPassingKind::CanNeverPassInRegs) 450 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 451 452 // Keep track of the presence of mutable fields. 453 if (BaseClassDecl->hasMutableFields()) 454 data().HasMutableFields = true; 455 456 if (BaseClassDecl->hasUninitializedReferenceMember()) 457 data().HasUninitializedReferenceMember = true; 458 459 if (!BaseClassDecl->allowConstDefaultInit()) 460 data().HasUninitializedFields = true; 461 462 addedClassSubobject(BaseClassDecl); 463 } 464 465 // C++2a [class]p7: 466 // A class S is a standard-layout class if it: 467 // -- has at most one base class subobject of any given type 468 // 469 // Note that we only need to check this for classes with more than one base 470 // class. If there's only one base class, and it's standard layout, then 471 // we know there are no repeated base classes. 472 if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this)) 473 data().IsStandardLayout = false; 474 475 if (VBases.empty()) { 476 data().IsParsingBaseSpecifiers = false; 477 return; 478 } 479 480 // Create base specifier for any direct or indirect virtual bases. 481 data().VBases = new (C) CXXBaseSpecifier[VBases.size()]; 482 data().NumVBases = VBases.size(); 483 for (int I = 0, E = VBases.size(); I != E; ++I) { 484 QualType Type = VBases[I]->getType(); 485 if (!Type->isDependentType()) 486 addedClassSubobject(Type->getAsCXXRecordDecl()); 487 data().getVBases()[I] = *VBases[I]; 488 } 489 490 data().IsParsingBaseSpecifiers = false; 491 } 492 493 unsigned CXXRecordDecl::getODRHash() const { 494 assert(hasDefinition() && "ODRHash only for records with definitions"); 495 496 // Previously calculated hash is stored in DefinitionData. 497 if (DefinitionData->HasODRHash) 498 return DefinitionData->ODRHash; 499 500 // Only calculate hash on first call of getODRHash per record. 501 ODRHash Hash; 502 Hash.AddCXXRecordDecl(getDefinition()); 503 DefinitionData->HasODRHash = true; 504 DefinitionData->ODRHash = Hash.CalculateHash(); 505 506 return DefinitionData->ODRHash; 507 } 508 509 void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) { 510 // C++11 [class.copy]p11: 511 // A defaulted copy/move constructor for a class X is defined as 512 // deleted if X has: 513 // -- a direct or virtual base class B that cannot be copied/moved [...] 514 // -- a non-static data member of class type M (or array thereof) 515 // that cannot be copied or moved [...] 516 if (!Subobj->hasSimpleCopyConstructor()) 517 data().NeedOverloadResolutionForCopyConstructor = true; 518 if (!Subobj->hasSimpleMoveConstructor()) 519 data().NeedOverloadResolutionForMoveConstructor = true; 520 521 // C++11 [class.copy]p23: 522 // A defaulted copy/move assignment operator for a class X is defined as 523 // deleted if X has: 524 // -- a direct or virtual base class B that cannot be copied/moved [...] 525 // -- a non-static data member of class type M (or array thereof) 526 // that cannot be copied or moved [...] 527 if (!Subobj->hasSimpleCopyAssignment()) 528 data().NeedOverloadResolutionForCopyAssignment = true; 529 if (!Subobj->hasSimpleMoveAssignment()) 530 data().NeedOverloadResolutionForMoveAssignment = true; 531 532 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5: 533 // A defaulted [ctor or dtor] for a class X is defined as 534 // deleted if X has: 535 // -- any direct or virtual base class [...] has a type with a destructor 536 // that is deleted or inaccessible from the defaulted [ctor or dtor]. 537 // -- any non-static data member has a type with a destructor 538 // that is deleted or inaccessible from the defaulted [ctor or dtor]. 539 if (!Subobj->hasSimpleDestructor()) { 540 data().NeedOverloadResolutionForCopyConstructor = true; 541 data().NeedOverloadResolutionForMoveConstructor = true; 542 data().NeedOverloadResolutionForDestructor = true; 543 } 544 545 // C++2a [dcl.constexpr]p4: 546 // The definition of a constexpr destructor [shall] satisfy the 547 // following requirement: 548 // -- for every subobject of class type or (possibly multi-dimensional) 549 // array thereof, that class type shall have a constexpr destructor 550 if (!Subobj->hasConstexprDestructor()) 551 data().DefaultedDestructorIsConstexpr = false; 552 553 // C++20 [temp.param]p7: 554 // A structural type is [...] a literal class type [for which] the types 555 // of all base classes and non-static data members are structural types or 556 // (possibly multi-dimensional) array thereof 557 if (!Subobj->data().StructuralIfLiteral) 558 data().StructuralIfLiteral = false; 559 } 560 561 bool CXXRecordDecl::hasConstexprDestructor() const { 562 auto *Dtor = getDestructor(); 563 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr(); 564 } 565 566 bool CXXRecordDecl::hasAnyDependentBases() const { 567 if (!isDependentContext()) 568 return false; 569 570 return !forallBases([](const CXXRecordDecl *) { return true; }); 571 } 572 573 bool CXXRecordDecl::isTriviallyCopyable() const { 574 // C++0x [class]p5: 575 // A trivially copyable class is a class that: 576 // -- has no non-trivial copy constructors, 577 if (hasNonTrivialCopyConstructor()) return false; 578 // -- has no non-trivial move constructors, 579 if (hasNonTrivialMoveConstructor()) return false; 580 // -- has no non-trivial copy assignment operators, 581 if (hasNonTrivialCopyAssignment()) return false; 582 // -- has no non-trivial move assignment operators, and 583 if (hasNonTrivialMoveAssignment()) return false; 584 // -- has a trivial destructor. 585 if (!hasTrivialDestructor()) return false; 586 587 return true; 588 } 589 590 bool CXXRecordDecl::isTriviallyCopyConstructible() const { 591 592 // A trivially copy constructible class is a class that: 593 // -- has no non-trivial copy constructors, 594 if (hasNonTrivialCopyConstructor()) 595 return false; 596 // -- has a trivial destructor. 597 if (!hasTrivialDestructor()) 598 return false; 599 600 return true; 601 } 602 603 void CXXRecordDecl::markedVirtualFunctionPure() { 604 // C++ [class.abstract]p2: 605 // A class is abstract if it has at least one pure virtual function. 606 data().Abstract = true; 607 } 608 609 bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType( 610 ASTContext &Ctx, const CXXRecordDecl *XFirst) { 611 if (!getNumBases()) 612 return false; 613 614 llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases; 615 llvm::SmallPtrSet<const CXXRecordDecl*, 8> M; 616 SmallVector<const CXXRecordDecl*, 8> WorkList; 617 618 // Visit a type that we have determined is an element of M(S). 619 auto Visit = [&](const CXXRecordDecl *RD) -> bool { 620 RD = RD->getCanonicalDecl(); 621 622 // C++2a [class]p8: 623 // A class S is a standard-layout class if it [...] has no element of the 624 // set M(S) of types as a base class. 625 // 626 // If we find a subobject of an empty type, it might also be a base class, 627 // so we'll need to walk the base classes to check. 628 if (!RD->data().HasBasesWithFields) { 629 // Walk the bases the first time, stopping if we find the type. Build a 630 // set of them so we don't need to walk them again. 631 if (Bases.empty()) { 632 bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool { 633 Base = Base->getCanonicalDecl(); 634 if (RD == Base) 635 return false; 636 Bases.insert(Base); 637 return true; 638 }); 639 if (RDIsBase) 640 return true; 641 } else { 642 if (Bases.count(RD)) 643 return true; 644 } 645 } 646 647 if (M.insert(RD).second) 648 WorkList.push_back(RD); 649 return false; 650 }; 651 652 if (Visit(XFirst)) 653 return true; 654 655 while (!WorkList.empty()) { 656 const CXXRecordDecl *X = WorkList.pop_back_val(); 657 658 // FIXME: We don't check the bases of X. That matches the standard, but 659 // that sure looks like a wording bug. 660 661 // -- If X is a non-union class type with a non-static data member 662 // [recurse to each field] that is either of zero size or is the 663 // first non-static data member of X 664 // -- If X is a union type, [recurse to union members] 665 bool IsFirstField = true; 666 for (auto *FD : X->fields()) { 667 // FIXME: Should we really care about the type of the first non-static 668 // data member of a non-union if there are preceding unnamed bit-fields? 669 if (FD->isUnnamedBitfield()) 670 continue; 671 672 if (!IsFirstField && !FD->isZeroSize(Ctx)) 673 continue; 674 675 // -- If X is n array type, [visit the element type] 676 QualType T = Ctx.getBaseElementType(FD->getType()); 677 if (auto *RD = T->getAsCXXRecordDecl()) 678 if (Visit(RD)) 679 return true; 680 681 if (!X->isUnion()) 682 IsFirstField = false; 683 } 684 } 685 686 return false; 687 } 688 689 bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const { 690 assert(isLambda() && "not a lambda"); 691 692 // C++2a [expr.prim.lambda.capture]p11: 693 // The closure type associated with a lambda-expression has no default 694 // constructor if the lambda-expression has a lambda-capture and a 695 // defaulted default constructor otherwise. It has a deleted copy 696 // assignment operator if the lambda-expression has a lambda-capture and 697 // defaulted copy and move assignment operators otherwise. 698 // 699 // C++17 [expr.prim.lambda]p21: 700 // The closure type associated with a lambda-expression has no default 701 // constructor and a deleted copy assignment operator. 702 if (!isCapturelessLambda()) 703 return false; 704 return getASTContext().getLangOpts().CPlusPlus20; 705 } 706 707 void CXXRecordDecl::addedMember(Decl *D) { 708 if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) && 709 (!isa<TagDecl>(D) || 710 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Class || 711 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Interface)) 712 data().HasOnlyCMembers = false; 713 714 // Ignore friends and invalid declarations. 715 if (D->getFriendObjectKind() || D->isInvalidDecl()) 716 return; 717 718 auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 719 if (FunTmpl) 720 D = FunTmpl->getTemplatedDecl(); 721 722 // FIXME: Pass NamedDecl* to addedMember? 723 Decl *DUnderlying = D; 724 if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) { 725 DUnderlying = ND->getUnderlyingDecl(); 726 if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying)) 727 DUnderlying = UnderlyingFunTmpl->getTemplatedDecl(); 728 } 729 730 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 731 if (Method->isVirtual()) { 732 // C++ [dcl.init.aggr]p1: 733 // An aggregate is an array or a class with [...] no virtual functions. 734 data().Aggregate = false; 735 736 // C++ [class]p4: 737 // A POD-struct is an aggregate class... 738 data().PlainOldData = false; 739 740 // C++14 [meta.unary.prop]p4: 741 // T is a class type [...] with [...] no virtual member functions... 742 data().Empty = false; 743 744 // C++ [class.virtual]p1: 745 // A class that declares or inherits a virtual function is called a 746 // polymorphic class. 747 data().Polymorphic = true; 748 749 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 750 // A [default constructor, copy/move constructor, or copy/move 751 // assignment operator for a class X] is trivial [...] if: 752 // -- class X has no virtual functions [...] 753 data().HasTrivialSpecialMembers &= SMF_Destructor; 754 data().HasTrivialSpecialMembersForCall &= SMF_Destructor; 755 756 // C++0x [class]p7: 757 // A standard-layout class is a class that: [...] 758 // -- has no virtual functions 759 data().IsStandardLayout = false; 760 data().IsCXX11StandardLayout = false; 761 } 762 } 763 764 // Notify the listener if an implicit member was added after the definition 765 // was completed. 766 if (!isBeingDefined() && D->isImplicit()) 767 if (ASTMutationListener *L = getASTMutationListener()) 768 L->AddedCXXImplicitMember(data().Definition, D); 769 770 // The kind of special member this declaration is, if any. 771 unsigned SMKind = 0; 772 773 // Handle constructors. 774 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 775 if (Constructor->isInheritingConstructor()) { 776 // Ignore constructor shadow declarations. They are lazily created and 777 // so shouldn't affect any properties of the class. 778 } else { 779 if (!Constructor->isImplicit()) { 780 // Note that we have a user-declared constructor. 781 data().UserDeclaredConstructor = true; 782 783 const TargetInfo &TI = getASTContext().getTargetInfo(); 784 if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) || 785 !TI.areDefaultedSMFStillPOD(getLangOpts())) { 786 // C++ [class]p4: 787 // A POD-struct is an aggregate class [...] 788 // Since the POD bit is meant to be C++03 POD-ness, clear it even if 789 // the type is technically an aggregate in C++0x since it wouldn't be 790 // in 03. 791 data().PlainOldData = false; 792 } 793 } 794 795 if (Constructor->isDefaultConstructor()) { 796 SMKind |= SMF_DefaultConstructor; 797 798 if (Constructor->isUserProvided()) 799 data().UserProvidedDefaultConstructor = true; 800 if (Constructor->isConstexpr()) 801 data().HasConstexprDefaultConstructor = true; 802 if (Constructor->isDefaulted()) 803 data().HasDefaultedDefaultConstructor = true; 804 } 805 806 if (!FunTmpl) { 807 unsigned Quals; 808 if (Constructor->isCopyConstructor(Quals)) { 809 SMKind |= SMF_CopyConstructor; 810 811 if (Quals & Qualifiers::Const) 812 data().HasDeclaredCopyConstructorWithConstParam = true; 813 } else if (Constructor->isMoveConstructor()) 814 SMKind |= SMF_MoveConstructor; 815 } 816 817 // C++11 [dcl.init.aggr]p1: DR1518 818 // An aggregate is an array or a class with no user-provided [or] 819 // explicit [...] constructors 820 // C++20 [dcl.init.aggr]p1: 821 // An aggregate is an array or a class with no user-declared [...] 822 // constructors 823 if (getASTContext().getLangOpts().CPlusPlus20 824 ? !Constructor->isImplicit() 825 : (Constructor->isUserProvided() || Constructor->isExplicit())) 826 data().Aggregate = false; 827 } 828 } 829 830 // Handle constructors, including those inherited from base classes. 831 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) { 832 // Record if we see any constexpr constructors which are neither copy 833 // nor move constructors. 834 // C++1z [basic.types]p10: 835 // [...] has at least one constexpr constructor or constructor template 836 // (possibly inherited from a base class) that is not a copy or move 837 // constructor [...] 838 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor()) 839 data().HasConstexprNonCopyMoveConstructor = true; 840 if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor()) 841 data().HasInheritedDefaultConstructor = true; 842 } 843 844 // Handle member functions. 845 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 846 if (isa<CXXDestructorDecl>(D)) 847 SMKind |= SMF_Destructor; 848 849 if (Method->isCopyAssignmentOperator()) { 850 SMKind |= SMF_CopyAssignment; 851 852 const auto *ParamTy = 853 Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>(); 854 if (!ParamTy || ParamTy->getPointeeType().isConstQualified()) 855 data().HasDeclaredCopyAssignmentWithConstParam = true; 856 } 857 858 if (Method->isMoveAssignmentOperator()) 859 SMKind |= SMF_MoveAssignment; 860 861 // Keep the list of conversion functions up-to-date. 862 if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) { 863 // FIXME: We use the 'unsafe' accessor for the access specifier here, 864 // because Sema may not have set it yet. That's really just a misdesign 865 // in Sema. However, LLDB *will* have set the access specifier correctly, 866 // and adds declarations after the class is technically completed, 867 // so completeDefinition()'s overriding of the access specifiers doesn't 868 // work. 869 AccessSpecifier AS = Conversion->getAccessUnsafe(); 870 871 if (Conversion->getPrimaryTemplate()) { 872 // We don't record specializations. 873 } else { 874 ASTContext &Ctx = getASTContext(); 875 ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx); 876 NamedDecl *Primary = 877 FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion); 878 if (Primary->getPreviousDecl()) 879 Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()), 880 Primary, AS); 881 else 882 Conversions.addDecl(Ctx, Primary, AS); 883 } 884 } 885 886 if (SMKind) { 887 // If this is the first declaration of a special member, we no longer have 888 // an implicit trivial special member. 889 data().HasTrivialSpecialMembers &= 890 data().DeclaredSpecialMembers | ~SMKind; 891 data().HasTrivialSpecialMembersForCall &= 892 data().DeclaredSpecialMembers | ~SMKind; 893 894 // Note when we have declared a declared special member, and suppress the 895 // implicit declaration of this special member. 896 data().DeclaredSpecialMembers |= SMKind; 897 if (!Method->isImplicit()) { 898 data().UserDeclaredSpecialMembers |= SMKind; 899 900 const TargetInfo &TI = getASTContext().getTargetInfo(); 901 if ((!Method->isDeleted() && !Method->isDefaulted() && 902 SMKind != SMF_MoveAssignment) || 903 !TI.areDefaultedSMFStillPOD(getLangOpts())) { 904 // C++03 [class]p4: 905 // A POD-struct is an aggregate class that has [...] no user-defined 906 // copy assignment operator and no user-defined destructor. 907 // 908 // Since the POD bit is meant to be C++03 POD-ness, and in C++03, 909 // aggregates could not have any constructors, clear it even for an 910 // explicitly defaulted or deleted constructor. 911 // type is technically an aggregate in C++0x since it wouldn't be in 912 // 03. 913 // 914 // Also, a user-declared move assignment operator makes a class 915 // non-POD. This is an extension in C++03. 916 data().PlainOldData = false; 917 } 918 } 919 // When instantiating a class, we delay updating the destructor and 920 // triviality properties of the class until selecting a destructor and 921 // computing the eligibility of its special member functions. This is 922 // because there might be function constraints that we need to evaluate 923 // and compare later in the instantiation. 924 if (!Method->isIneligibleOrNotSelected()) { 925 addedEligibleSpecialMemberFunction(Method, SMKind); 926 } 927 } 928 929 return; 930 } 931 932 // Handle non-static data members. 933 if (const auto *Field = dyn_cast<FieldDecl>(D)) { 934 ASTContext &Context = getASTContext(); 935 936 // C++2a [class]p7: 937 // A standard-layout class is a class that: 938 // [...] 939 // -- has all non-static data members and bit-fields in the class and 940 // its base classes first declared in the same class 941 if (data().HasBasesWithFields) 942 data().IsStandardLayout = false; 943 944 // C++ [class.bit]p2: 945 // A declaration for a bit-field that omits the identifier declares an 946 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 947 // initialized. 948 if (Field->isUnnamedBitfield()) { 949 // C++ [meta.unary.prop]p4: [LWG2358] 950 // T is a class type [...] with [...] no unnamed bit-fields of non-zero 951 // length 952 if (data().Empty && !Field->isZeroLengthBitField(Context) && 953 Context.getLangOpts().getClangABICompat() > 954 LangOptions::ClangABI::Ver6) 955 data().Empty = false; 956 return; 957 } 958 959 // C++11 [class]p7: 960 // A standard-layout class is a class that: 961 // -- either has no non-static data members in the most derived class 962 // [...] or has no base classes with non-static data members 963 if (data().HasBasesWithNonStaticDataMembers) 964 data().IsCXX11StandardLayout = false; 965 966 // C++ [dcl.init.aggr]p1: 967 // An aggregate is an array or a class (clause 9) with [...] no 968 // private or protected non-static data members (clause 11). 969 // 970 // A POD must be an aggregate. 971 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { 972 data().Aggregate = false; 973 data().PlainOldData = false; 974 975 // C++20 [temp.param]p7: 976 // A structural type is [...] a literal class type [for which] all 977 // non-static data members are public 978 data().StructuralIfLiteral = false; 979 } 980 981 // Track whether this is the first field. We use this when checking 982 // whether the class is standard-layout below. 983 bool IsFirstField = !data().HasPrivateFields && 984 !data().HasProtectedFields && !data().HasPublicFields; 985 986 // C++0x [class]p7: 987 // A standard-layout class is a class that: 988 // [...] 989 // -- has the same access control for all non-static data members, 990 switch (D->getAccess()) { 991 case AS_private: data().HasPrivateFields = true; break; 992 case AS_protected: data().HasProtectedFields = true; break; 993 case AS_public: data().HasPublicFields = true; break; 994 case AS_none: llvm_unreachable("Invalid access specifier"); 995 }; 996 if ((data().HasPrivateFields + data().HasProtectedFields + 997 data().HasPublicFields) > 1) { 998 data().IsStandardLayout = false; 999 data().IsCXX11StandardLayout = false; 1000 } 1001 1002 // Keep track of the presence of mutable fields. 1003 if (Field->isMutable()) { 1004 data().HasMutableFields = true; 1005 1006 // C++20 [temp.param]p7: 1007 // A structural type is [...] a literal class type [for which] all 1008 // non-static data members are public 1009 data().StructuralIfLiteral = false; 1010 } 1011 1012 // C++11 [class.union]p8, DR1460: 1013 // If X is a union, a non-static data member of X that is not an anonymous 1014 // union is a variant member of X. 1015 if (isUnion() && !Field->isAnonymousStructOrUnion()) 1016 data().HasVariantMembers = true; 1017 1018 // C++0x [class]p9: 1019 // A POD struct is a class that is both a trivial class and a 1020 // standard-layout class, and has no non-static data members of type 1021 // non-POD struct, non-POD union (or array of such types). 1022 // 1023 // Automatic Reference Counting: the presence of a member of Objective-C pointer type 1024 // that does not explicitly have no lifetime makes the class a non-POD. 1025 QualType T = Context.getBaseElementType(Field->getType()); 1026 if (T->isObjCRetainableType() || T.isObjCGCStrong()) { 1027 if (T.hasNonTrivialObjCLifetime()) { 1028 // Objective-C Automatic Reference Counting: 1029 // If a class has a non-static data member of Objective-C pointer 1030 // type (or array thereof), it is a non-POD type and its 1031 // default constructor (if any), copy constructor, move constructor, 1032 // copy assignment operator, move assignment operator, and destructor are 1033 // non-trivial. 1034 setHasObjectMember(true); 1035 struct DefinitionData &Data = data(); 1036 Data.PlainOldData = false; 1037 Data.HasTrivialSpecialMembers = 0; 1038 1039 // __strong or __weak fields do not make special functions non-trivial 1040 // for the purpose of calls. 1041 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime(); 1042 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak) 1043 data().HasTrivialSpecialMembersForCall = 0; 1044 1045 // Structs with __weak fields should never be passed directly. 1046 if (LT == Qualifiers::OCL_Weak) 1047 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 1048 1049 Data.HasIrrelevantDestructor = false; 1050 1051 if (isUnion()) { 1052 data().DefaultedCopyConstructorIsDeleted = true; 1053 data().DefaultedMoveConstructorIsDeleted = true; 1054 data().DefaultedCopyAssignmentIsDeleted = true; 1055 data().DefaultedMoveAssignmentIsDeleted = true; 1056 data().DefaultedDestructorIsDeleted = true; 1057 data().NeedOverloadResolutionForCopyConstructor = true; 1058 data().NeedOverloadResolutionForMoveConstructor = true; 1059 data().NeedOverloadResolutionForCopyAssignment = true; 1060 data().NeedOverloadResolutionForMoveAssignment = true; 1061 data().NeedOverloadResolutionForDestructor = true; 1062 } 1063 } else if (!Context.getLangOpts().ObjCAutoRefCount) { 1064 setHasObjectMember(true); 1065 } 1066 } else if (!T.isCXX98PODType(Context)) 1067 data().PlainOldData = false; 1068 1069 if (T->isReferenceType()) { 1070 if (!Field->hasInClassInitializer()) 1071 data().HasUninitializedReferenceMember = true; 1072 1073 // C++0x [class]p7: 1074 // A standard-layout class is a class that: 1075 // -- has no non-static data members of type [...] reference, 1076 data().IsStandardLayout = false; 1077 data().IsCXX11StandardLayout = false; 1078 1079 // C++1z [class.copy.ctor]p10: 1080 // A defaulted copy constructor for a class X is defined as deleted if X has: 1081 // -- a non-static data member of rvalue reference type 1082 if (T->isRValueReferenceType()) 1083 data().DefaultedCopyConstructorIsDeleted = true; 1084 } 1085 1086 if (!Field->hasInClassInitializer() && !Field->isMutable()) { 1087 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) { 1088 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit()) 1089 data().HasUninitializedFields = true; 1090 } else { 1091 data().HasUninitializedFields = true; 1092 } 1093 } 1094 1095 // Record if this field is the first non-literal or volatile field or base. 1096 if (!T->isLiteralType(Context) || T.isVolatileQualified()) 1097 data().HasNonLiteralTypeFieldsOrBases = true; 1098 1099 if (Field->hasInClassInitializer() || 1100 (Field->isAnonymousStructOrUnion() && 1101 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) { 1102 data().HasInClassInitializer = true; 1103 1104 // C++11 [class]p5: 1105 // A default constructor is trivial if [...] no non-static data member 1106 // of its class has a brace-or-equal-initializer. 1107 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1108 1109 // C++11 [dcl.init.aggr]p1: 1110 // An aggregate is a [...] class with [...] no 1111 // brace-or-equal-initializers for non-static data members. 1112 // 1113 // This rule was removed in C++14. 1114 if (!getASTContext().getLangOpts().CPlusPlus14) 1115 data().Aggregate = false; 1116 1117 // C++11 [class]p10: 1118 // A POD struct is [...] a trivial class. 1119 data().PlainOldData = false; 1120 } 1121 1122 // C++11 [class.copy]p23: 1123 // A defaulted copy/move assignment operator for a class X is defined 1124 // as deleted if X has: 1125 // -- a non-static data member of reference type 1126 if (T->isReferenceType()) { 1127 data().DefaultedCopyAssignmentIsDeleted = true; 1128 data().DefaultedMoveAssignmentIsDeleted = true; 1129 } 1130 1131 // Bitfields of length 0 are also zero-sized, but we already bailed out for 1132 // those because they are always unnamed. 1133 bool IsZeroSize = Field->isZeroSize(Context); 1134 1135 if (const auto *RecordTy = T->getAs<RecordType>()) { 1136 auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl()); 1137 if (FieldRec->getDefinition()) { 1138 addedClassSubobject(FieldRec); 1139 1140 // We may need to perform overload resolution to determine whether a 1141 // field can be moved if it's const or volatile qualified. 1142 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) { 1143 // We need to care about 'const' for the copy constructor because an 1144 // implicit copy constructor might be declared with a non-const 1145 // parameter. 1146 data().NeedOverloadResolutionForCopyConstructor = true; 1147 data().NeedOverloadResolutionForMoveConstructor = true; 1148 data().NeedOverloadResolutionForCopyAssignment = true; 1149 data().NeedOverloadResolutionForMoveAssignment = true; 1150 } 1151 1152 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 1153 // A defaulted [special member] for a class X is defined as 1154 // deleted if: 1155 // -- X is a union-like class that has a variant member with a 1156 // non-trivial [corresponding special member] 1157 if (isUnion()) { 1158 if (FieldRec->hasNonTrivialCopyConstructor()) 1159 data().DefaultedCopyConstructorIsDeleted = true; 1160 if (FieldRec->hasNonTrivialMoveConstructor()) 1161 data().DefaultedMoveConstructorIsDeleted = true; 1162 if (FieldRec->hasNonTrivialCopyAssignment()) 1163 data().DefaultedCopyAssignmentIsDeleted = true; 1164 if (FieldRec->hasNonTrivialMoveAssignment()) 1165 data().DefaultedMoveAssignmentIsDeleted = true; 1166 if (FieldRec->hasNonTrivialDestructor()) 1167 data().DefaultedDestructorIsDeleted = true; 1168 } 1169 1170 // For an anonymous union member, our overload resolution will perform 1171 // overload resolution for its members. 1172 if (Field->isAnonymousStructOrUnion()) { 1173 data().NeedOverloadResolutionForCopyConstructor |= 1174 FieldRec->data().NeedOverloadResolutionForCopyConstructor; 1175 data().NeedOverloadResolutionForMoveConstructor |= 1176 FieldRec->data().NeedOverloadResolutionForMoveConstructor; 1177 data().NeedOverloadResolutionForCopyAssignment |= 1178 FieldRec->data().NeedOverloadResolutionForCopyAssignment; 1179 data().NeedOverloadResolutionForMoveAssignment |= 1180 FieldRec->data().NeedOverloadResolutionForMoveAssignment; 1181 data().NeedOverloadResolutionForDestructor |= 1182 FieldRec->data().NeedOverloadResolutionForDestructor; 1183 } 1184 1185 // C++0x [class.ctor]p5: 1186 // A default constructor is trivial [...] if: 1187 // -- for all the non-static data members of its class that are of 1188 // class type (or array thereof), each such class has a trivial 1189 // default constructor. 1190 if (!FieldRec->hasTrivialDefaultConstructor()) 1191 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1192 1193 // C++0x [class.copy]p13: 1194 // A copy/move constructor for class X is trivial if [...] 1195 // [...] 1196 // -- for each non-static data member of X that is of class type (or 1197 // an array thereof), the constructor selected to copy/move that 1198 // member is trivial; 1199 if (!FieldRec->hasTrivialCopyConstructor()) 1200 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; 1201 1202 if (!FieldRec->hasTrivialCopyConstructorForCall()) 1203 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; 1204 1205 // If the field doesn't have a simple move constructor, we'll eagerly 1206 // declare the move constructor for this class and we'll decide whether 1207 // it's trivial then. 1208 if (!FieldRec->hasTrivialMoveConstructor()) 1209 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; 1210 1211 if (!FieldRec->hasTrivialMoveConstructorForCall()) 1212 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; 1213 1214 // C++0x [class.copy]p27: 1215 // A copy/move assignment operator for class X is trivial if [...] 1216 // [...] 1217 // -- for each non-static data member of X that is of class type (or 1218 // an array thereof), the assignment operator selected to 1219 // copy/move that member is trivial; 1220 if (!FieldRec->hasTrivialCopyAssignment()) 1221 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; 1222 // If the field doesn't have a simple move assignment, we'll eagerly 1223 // declare the move assignment for this class and we'll decide whether 1224 // it's trivial then. 1225 if (!FieldRec->hasTrivialMoveAssignment()) 1226 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; 1227 1228 if (!FieldRec->hasTrivialDestructor()) 1229 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 1230 if (!FieldRec->hasTrivialDestructorForCall()) 1231 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 1232 if (!FieldRec->hasIrrelevantDestructor()) 1233 data().HasIrrelevantDestructor = false; 1234 if (FieldRec->isAnyDestructorNoReturn()) 1235 data().IsAnyDestructorNoReturn = true; 1236 if (FieldRec->hasObjectMember()) 1237 setHasObjectMember(true); 1238 if (FieldRec->hasVolatileMember()) 1239 setHasVolatileMember(true); 1240 if (FieldRec->getArgPassingRestrictions() == 1241 RecordArgPassingKind::CanNeverPassInRegs) 1242 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 1243 1244 // C++0x [class]p7: 1245 // A standard-layout class is a class that: 1246 // -- has no non-static data members of type non-standard-layout 1247 // class (or array of such types) [...] 1248 if (!FieldRec->isStandardLayout()) 1249 data().IsStandardLayout = false; 1250 if (!FieldRec->isCXX11StandardLayout()) 1251 data().IsCXX11StandardLayout = false; 1252 1253 // C++2a [class]p7: 1254 // A standard-layout class is a class that: 1255 // [...] 1256 // -- has no element of the set M(S) of types as a base class. 1257 if (data().IsStandardLayout && 1258 (isUnion() || IsFirstField || IsZeroSize) && 1259 hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec)) 1260 data().IsStandardLayout = false; 1261 1262 // C++11 [class]p7: 1263 // A standard-layout class is a class that: 1264 // -- has no base classes of the same type as the first non-static 1265 // data member 1266 if (data().IsCXX11StandardLayout && IsFirstField) { 1267 // FIXME: We should check all base classes here, not just direct 1268 // base classes. 1269 for (const auto &BI : bases()) { 1270 if (Context.hasSameUnqualifiedType(BI.getType(), T)) { 1271 data().IsCXX11StandardLayout = false; 1272 break; 1273 } 1274 } 1275 } 1276 1277 // Keep track of the presence of mutable fields. 1278 if (FieldRec->hasMutableFields()) 1279 data().HasMutableFields = true; 1280 1281 if (Field->isMutable()) { 1282 // Our copy constructor/assignment might call something other than 1283 // the subobject's copy constructor/assignment if it's mutable and of 1284 // class type. 1285 data().NeedOverloadResolutionForCopyConstructor = true; 1286 data().NeedOverloadResolutionForCopyAssignment = true; 1287 } 1288 1289 // C++11 [class.copy]p13: 1290 // If the implicitly-defined constructor would satisfy the 1291 // requirements of a constexpr constructor, the implicitly-defined 1292 // constructor is constexpr. 1293 // C++11 [dcl.constexpr]p4: 1294 // -- every constructor involved in initializing non-static data 1295 // members [...] shall be a constexpr constructor 1296 if (!Field->hasInClassInitializer() && 1297 !FieldRec->hasConstexprDefaultConstructor() && !isUnion()) 1298 // The standard requires any in-class initializer to be a constant 1299 // expression. We consider this to be a defect. 1300 data().DefaultedDefaultConstructorIsConstexpr = false; 1301 1302 // C++11 [class.copy]p8: 1303 // The implicitly-declared copy constructor for a class X will have 1304 // the form 'X::X(const X&)' if each potentially constructed subobject 1305 // of a class type M (or array thereof) has a copy constructor whose 1306 // first parameter is of type 'const M&' or 'const volatile M&'. 1307 if (!FieldRec->hasCopyConstructorWithConstParam()) 1308 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; 1309 1310 // C++11 [class.copy]p18: 1311 // The implicitly-declared copy assignment oeprator for a class X will 1312 // have the form 'X& X::operator=(const X&)' if [...] for all the 1313 // non-static data members of X that are of a class type M (or array 1314 // thereof), each such class type has a copy assignment operator whose 1315 // parameter is of type 'const M&', 'const volatile M&' or 'M'. 1316 if (!FieldRec->hasCopyAssignmentWithConstParam()) 1317 data().ImplicitCopyAssignmentHasConstParam = false; 1318 1319 if (FieldRec->hasUninitializedReferenceMember() && 1320 !Field->hasInClassInitializer()) 1321 data().HasUninitializedReferenceMember = true; 1322 1323 // C++11 [class.union]p8, DR1460: 1324 // a non-static data member of an anonymous union that is a member of 1325 // X is also a variant member of X. 1326 if (FieldRec->hasVariantMembers() && 1327 Field->isAnonymousStructOrUnion()) 1328 data().HasVariantMembers = true; 1329 } 1330 } else { 1331 // Base element type of field is a non-class type. 1332 if (!T->isLiteralType(Context) || 1333 (!Field->hasInClassInitializer() && !isUnion() && 1334 !Context.getLangOpts().CPlusPlus20)) 1335 data().DefaultedDefaultConstructorIsConstexpr = false; 1336 1337 // C++11 [class.copy]p23: 1338 // A defaulted copy/move assignment operator for a class X is defined 1339 // as deleted if X has: 1340 // -- a non-static data member of const non-class type (or array 1341 // thereof) 1342 if (T.isConstQualified()) { 1343 data().DefaultedCopyAssignmentIsDeleted = true; 1344 data().DefaultedMoveAssignmentIsDeleted = true; 1345 } 1346 1347 // C++20 [temp.param]p7: 1348 // A structural type is [...] a literal class type [for which] the 1349 // types of all non-static data members are structural types or 1350 // (possibly multidimensional) array thereof 1351 // We deal with class types elsewhere. 1352 if (!T->isStructuralType()) 1353 data().StructuralIfLiteral = false; 1354 } 1355 1356 // C++14 [meta.unary.prop]p4: 1357 // T is a class type [...] with [...] no non-static data members other 1358 // than subobjects of zero size 1359 if (data().Empty && !IsZeroSize) 1360 data().Empty = false; 1361 } 1362 1363 // Handle using declarations of conversion functions. 1364 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) { 1365 if (Shadow->getDeclName().getNameKind() 1366 == DeclarationName::CXXConversionFunctionName) { 1367 ASTContext &Ctx = getASTContext(); 1368 data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess()); 1369 } 1370 } 1371 1372 if (const auto *Using = dyn_cast<UsingDecl>(D)) { 1373 if (Using->getDeclName().getNameKind() == 1374 DeclarationName::CXXConstructorName) { 1375 data().HasInheritedConstructor = true; 1376 // C++1z [dcl.init.aggr]p1: 1377 // An aggregate is [...] a class [...] with no inherited constructors 1378 data().Aggregate = false; 1379 } 1380 1381 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal) 1382 data().HasInheritedAssignment = true; 1383 } 1384 } 1385 1386 void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) { 1387 DD->setIneligibleOrNotSelected(false); 1388 addedEligibleSpecialMemberFunction(DD, SMF_Destructor); 1389 } 1390 1391 void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD, 1392 unsigned SMKind) { 1393 // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is 1394 // a function template, but this needs CWG attention before we break ABI. 1395 // See https://github.com/llvm/llvm-project/issues/59206 1396 1397 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1398 if (DD->isUserProvided()) 1399 data().HasIrrelevantDestructor = false; 1400 // If the destructor is explicitly defaulted and not trivial or not public 1401 // or if the destructor is deleted, we clear HasIrrelevantDestructor in 1402 // finishedDefaultedOrDeletedMember. 1403 1404 // C++11 [class.dtor]p5: 1405 // A destructor is trivial if [...] the destructor is not virtual. 1406 if (DD->isVirtual()) { 1407 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 1408 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 1409 } 1410 1411 if (DD->isNoReturn()) 1412 data().IsAnyDestructorNoReturn = true; 1413 } 1414 1415 if (!MD->isImplicit() && !MD->isUserProvided()) { 1416 // This method is user-declared but not user-provided. We can't work 1417 // out whether it's trivial yet (not until we get to the end of the 1418 // class). We'll handle this method in 1419 // finishedDefaultedOrDeletedMember. 1420 } else if (MD->isTrivial()) { 1421 data().HasTrivialSpecialMembers |= SMKind; 1422 data().HasTrivialSpecialMembersForCall |= SMKind; 1423 } else if (MD->isTrivialForCall()) { 1424 data().HasTrivialSpecialMembersForCall |= SMKind; 1425 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1426 } else { 1427 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1428 // If this is a user-provided function, do not set 1429 // DeclaredNonTrivialSpecialMembersForCall here since we don't know 1430 // yet whether the method would be considered non-trivial for the 1431 // purpose of calls (attribute "trivial_abi" can be dropped from the 1432 // class later, which can change the special method's triviality). 1433 if (!MD->isUserProvided()) 1434 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 1435 } 1436 } 1437 1438 void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) { 1439 assert(!D->isImplicit() && !D->isUserProvided()); 1440 1441 // The kind of special member this declaration is, if any. 1442 unsigned SMKind = 0; 1443 1444 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1445 if (Constructor->isDefaultConstructor()) { 1446 SMKind |= SMF_DefaultConstructor; 1447 if (Constructor->isConstexpr()) 1448 data().HasConstexprDefaultConstructor = true; 1449 } 1450 if (Constructor->isCopyConstructor()) 1451 SMKind |= SMF_CopyConstructor; 1452 else if (Constructor->isMoveConstructor()) 1453 SMKind |= SMF_MoveConstructor; 1454 else if (Constructor->isConstexpr()) 1455 // We may now know that the constructor is constexpr. 1456 data().HasConstexprNonCopyMoveConstructor = true; 1457 } else if (isa<CXXDestructorDecl>(D)) { 1458 SMKind |= SMF_Destructor; 1459 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted()) 1460 data().HasIrrelevantDestructor = false; 1461 } else if (D->isCopyAssignmentOperator()) 1462 SMKind |= SMF_CopyAssignment; 1463 else if (D->isMoveAssignmentOperator()) 1464 SMKind |= SMF_MoveAssignment; 1465 1466 // Update which trivial / non-trivial special members we have. 1467 // addedMember will have skipped this step for this member. 1468 if (!D->isIneligibleOrNotSelected()) { 1469 if (D->isTrivial()) 1470 data().HasTrivialSpecialMembers |= SMKind; 1471 else 1472 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1473 } 1474 } 1475 1476 void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx, 1477 Capture *CaptureList) { 1478 Captures.push_back(CaptureList); 1479 if (Captures.size() == 2) { 1480 // The TinyPtrVector member now needs destruction. 1481 Ctx.addDestruction(&Captures); 1482 } 1483 } 1484 1485 void CXXRecordDecl::setCaptures(ASTContext &Context, 1486 ArrayRef<LambdaCapture> Captures) { 1487 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData(); 1488 1489 // Copy captures. 1490 Data.NumCaptures = Captures.size(); 1491 Data.NumExplicitCaptures = 0; 1492 auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) * 1493 Captures.size()); 1494 Data.AddCaptureList(Context, ToCapture); 1495 for (unsigned I = 0, N = Captures.size(); I != N; ++I) { 1496 if (Captures[I].isExplicit()) 1497 ++Data.NumExplicitCaptures; 1498 1499 new (ToCapture) LambdaCapture(Captures[I]); 1500 ToCapture++; 1501 } 1502 1503 if (!lambdaIsDefaultConstructibleAndAssignable()) 1504 Data.DefaultedCopyAssignmentIsDeleted = true; 1505 } 1506 1507 void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) { 1508 unsigned SMKind = 0; 1509 1510 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1511 if (Constructor->isCopyConstructor()) 1512 SMKind = SMF_CopyConstructor; 1513 else if (Constructor->isMoveConstructor()) 1514 SMKind = SMF_MoveConstructor; 1515 } else if (isa<CXXDestructorDecl>(D)) 1516 SMKind = SMF_Destructor; 1517 1518 if (D->isTrivialForCall()) 1519 data().HasTrivialSpecialMembersForCall |= SMKind; 1520 else 1521 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 1522 } 1523 1524 bool CXXRecordDecl::isCLike() const { 1525 if (getTagKind() == TagTypeKind::Class || 1526 getTagKind() == TagTypeKind::Interface || 1527 !TemplateOrInstantiation.isNull()) 1528 return false; 1529 if (!hasDefinition()) 1530 return true; 1531 1532 return isPOD() && data().HasOnlyCMembers; 1533 } 1534 1535 bool CXXRecordDecl::isGenericLambda() const { 1536 if (!isLambda()) return false; 1537 return getLambdaData().IsGenericLambda; 1538 } 1539 1540 #ifndef NDEBUG 1541 static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) { 1542 for (auto *D : R) 1543 if (!declaresSameEntity(D, R.front())) 1544 return false; 1545 return true; 1546 } 1547 #endif 1548 1549 static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) { 1550 if (!RD.isLambda()) return nullptr; 1551 DeclarationName Name = 1552 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); 1553 DeclContext::lookup_result Calls = RD.lookup(Name); 1554 1555 assert(!Calls.empty() && "Missing lambda call operator!"); 1556 assert(allLookupResultsAreTheSame(Calls) && 1557 "More than one lambda call operator!"); 1558 return Calls.front(); 1559 } 1560 1561 FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const { 1562 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1563 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp); 1564 } 1565 1566 CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const { 1567 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1568 1569 if (CallOp == nullptr) 1570 return nullptr; 1571 1572 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) 1573 return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); 1574 1575 return cast<CXXMethodDecl>(CallOp); 1576 } 1577 1578 CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { 1579 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1580 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv(); 1581 return getLambdaStaticInvoker(CC); 1582 } 1583 1584 static DeclContext::lookup_result 1585 getLambdaStaticInvokers(const CXXRecordDecl &RD) { 1586 assert(RD.isLambda() && "Must be a lambda"); 1587 DeclarationName Name = 1588 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName()); 1589 return RD.lookup(Name); 1590 } 1591 1592 static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) { 1593 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND)) 1594 return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); 1595 return cast<CXXMethodDecl>(ND); 1596 } 1597 1598 CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const { 1599 if (!isLambda()) 1600 return nullptr; 1601 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this); 1602 1603 for (NamedDecl *ND : Invoker) { 1604 const auto *FTy = 1605 cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>(); 1606 if (FTy->getCallConv() == CC) 1607 return getInvokerAsMethod(ND); 1608 } 1609 1610 return nullptr; 1611 } 1612 1613 void CXXRecordDecl::getCaptureFields( 1614 llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures, 1615 FieldDecl *&ThisCapture) const { 1616 Captures.clear(); 1617 ThisCapture = nullptr; 1618 1619 LambdaDefinitionData &Lambda = getLambdaData(); 1620 for (const LambdaCapture *List : Lambda.Captures) { 1621 RecordDecl::field_iterator Field = field_begin(); 1622 for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures; 1623 C != CEnd; ++C, ++Field) { 1624 if (C->capturesThis()) 1625 ThisCapture = *Field; 1626 else if (C->capturesVariable()) 1627 Captures[C->getCapturedVar()] = *Field; 1628 } 1629 assert(Field == field_end()); 1630 } 1631 } 1632 1633 TemplateParameterList * 1634 CXXRecordDecl::getGenericLambdaTemplateParameterList() const { 1635 if (!isGenericLambda()) return nullptr; 1636 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1637 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) 1638 return Tmpl->getTemplateParameters(); 1639 return nullptr; 1640 } 1641 1642 ArrayRef<NamedDecl *> 1643 CXXRecordDecl::getLambdaExplicitTemplateParameters() const { 1644 TemplateParameterList *List = getGenericLambdaTemplateParameterList(); 1645 if (!List) 1646 return {}; 1647 1648 assert(std::is_partitioned(List->begin(), List->end(), 1649 [](const NamedDecl *D) { return !D->isImplicit(); }) 1650 && "Explicit template params should be ordered before implicit ones"); 1651 1652 const auto ExplicitEnd = llvm::partition_point( 1653 *List, [](const NamedDecl *D) { return !D->isImplicit(); }); 1654 return llvm::ArrayRef(List->begin(), ExplicitEnd); 1655 } 1656 1657 Decl *CXXRecordDecl::getLambdaContextDecl() const { 1658 assert(isLambda() && "Not a lambda closure type!"); 1659 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1660 return getLambdaData().ContextDecl.get(Source); 1661 } 1662 1663 void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) { 1664 assert(isLambda() && "Not a lambda closure type!"); 1665 getLambdaData().ManglingNumber = Numbering.ManglingNumber; 1666 if (Numbering.DeviceManglingNumber) 1667 getASTContext().DeviceLambdaManglingNumbers[this] = 1668 Numbering.DeviceManglingNumber; 1669 getLambdaData().IndexInContext = Numbering.IndexInContext; 1670 getLambdaData().ContextDecl = Numbering.ContextDecl; 1671 getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage; 1672 } 1673 1674 unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const { 1675 assert(isLambda() && "Not a lambda closure type!"); 1676 return getASTContext().DeviceLambdaManglingNumbers.lookup(this); 1677 } 1678 1679 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) { 1680 QualType T = 1681 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction()) 1682 ->getConversionType(); 1683 return Context.getCanonicalType(T); 1684 } 1685 1686 /// Collect the visible conversions of a base class. 1687 /// 1688 /// \param Record a base class of the class we're considering 1689 /// \param InVirtual whether this base class is a virtual base (or a base 1690 /// of a virtual base) 1691 /// \param Access the access along the inheritance path to this base 1692 /// \param ParentHiddenTypes the conversions provided by the inheritors 1693 /// of this base 1694 /// \param Output the set to which to add conversions from non-virtual bases 1695 /// \param VOutput the set to which to add conversions from virtual bases 1696 /// \param HiddenVBaseCs the set of conversions which were hidden in a 1697 /// virtual base along some inheritance path 1698 static void CollectVisibleConversions( 1699 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual, 1700 AccessSpecifier Access, 1701 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes, 1702 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput, 1703 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) { 1704 // The set of types which have conversions in this class or its 1705 // subclasses. As an optimization, we don't copy the derived set 1706 // unless it might change. 1707 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes; 1708 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer; 1709 1710 // Collect the direct conversions and figure out which conversions 1711 // will be hidden in the subclasses. 1712 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1713 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1714 if (ConvI != ConvE) { 1715 HiddenTypesBuffer = ParentHiddenTypes; 1716 HiddenTypes = &HiddenTypesBuffer; 1717 1718 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) { 1719 CanQualType ConvType(GetConversionType(Context, I.getDecl())); 1720 bool Hidden = ParentHiddenTypes.count(ConvType); 1721 if (!Hidden) 1722 HiddenTypesBuffer.insert(ConvType); 1723 1724 // If this conversion is hidden and we're in a virtual base, 1725 // remember that it's hidden along some inheritance path. 1726 if (Hidden && InVirtual) 1727 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())); 1728 1729 // If this conversion isn't hidden, add it to the appropriate output. 1730 else if (!Hidden) { 1731 AccessSpecifier IAccess 1732 = CXXRecordDecl::MergeAccess(Access, I.getAccess()); 1733 1734 if (InVirtual) 1735 VOutput.addDecl(I.getDecl(), IAccess); 1736 else 1737 Output.addDecl(Context, I.getDecl(), IAccess); 1738 } 1739 } 1740 } 1741 1742 // Collect information recursively from any base classes. 1743 for (const auto &I : Record->bases()) { 1744 const auto *RT = I.getType()->getAs<RecordType>(); 1745 if (!RT) continue; 1746 1747 AccessSpecifier BaseAccess 1748 = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); 1749 bool BaseInVirtual = InVirtual || I.isVirtual(); 1750 1751 auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 1752 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess, 1753 *HiddenTypes, Output, VOutput, HiddenVBaseCs); 1754 } 1755 } 1756 1757 /// Collect the visible conversions of a class. 1758 /// 1759 /// This would be extremely straightforward if it weren't for virtual 1760 /// bases. It might be worth special-casing that, really. 1761 static void CollectVisibleConversions(ASTContext &Context, 1762 const CXXRecordDecl *Record, 1763 ASTUnresolvedSet &Output) { 1764 // The collection of all conversions in virtual bases that we've 1765 // found. These will be added to the output as long as they don't 1766 // appear in the hidden-conversions set. 1767 UnresolvedSet<8> VBaseCs; 1768 1769 // The set of conversions in virtual bases that we've determined to 1770 // be hidden. 1771 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; 1772 1773 // The set of types hidden by classes derived from this one. 1774 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes; 1775 1776 // Go ahead and collect the direct conversions and add them to the 1777 // hidden-types set. 1778 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1779 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1780 Output.append(Context, ConvI, ConvE); 1781 for (; ConvI != ConvE; ++ConvI) 1782 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl())); 1783 1784 // Recursively collect conversions from base classes. 1785 for (const auto &I : Record->bases()) { 1786 const auto *RT = I.getType()->getAs<RecordType>(); 1787 if (!RT) continue; 1788 1789 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()), 1790 I.isVirtual(), I.getAccessSpecifier(), 1791 HiddenTypes, Output, VBaseCs, HiddenVBaseCs); 1792 } 1793 1794 // Add any unhidden conversions provided by virtual bases. 1795 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); 1796 I != E; ++I) { 1797 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()))) 1798 Output.addDecl(Context, I.getDecl(), I.getAccess()); 1799 } 1800 } 1801 1802 /// getVisibleConversionFunctions - get all conversion functions visible 1803 /// in current class; including conversion function templates. 1804 llvm::iterator_range<CXXRecordDecl::conversion_iterator> 1805 CXXRecordDecl::getVisibleConversionFunctions() const { 1806 ASTContext &Ctx = getASTContext(); 1807 1808 ASTUnresolvedSet *Set; 1809 if (bases_begin() == bases_end()) { 1810 // If root class, all conversions are visible. 1811 Set = &data().Conversions.get(Ctx); 1812 } else { 1813 Set = &data().VisibleConversions.get(Ctx); 1814 // If visible conversion list is not evaluated, evaluate it. 1815 if (!data().ComputedVisibleConversions) { 1816 CollectVisibleConversions(Ctx, this, *Set); 1817 data().ComputedVisibleConversions = true; 1818 } 1819 } 1820 return llvm::make_range(Set->begin(), Set->end()); 1821 } 1822 1823 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) { 1824 // This operation is O(N) but extremely rare. Sema only uses it to 1825 // remove UsingShadowDecls in a class that were followed by a direct 1826 // declaration, e.g.: 1827 // class A : B { 1828 // using B::operator int; 1829 // operator int(); 1830 // }; 1831 // This is uncommon by itself and even more uncommon in conjunction 1832 // with sufficiently large numbers of directly-declared conversions 1833 // that asymptotic behavior matters. 1834 1835 ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext()); 1836 for (unsigned I = 0, E = Convs.size(); I != E; ++I) { 1837 if (Convs[I].getDecl() == ConvDecl) { 1838 Convs.erase(I); 1839 assert(!llvm::is_contained(Convs, ConvDecl) && 1840 "conversion was found multiple times in unresolved set"); 1841 return; 1842 } 1843 } 1844 1845 llvm_unreachable("conversion not found in set!"); 1846 } 1847 1848 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const { 1849 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1850 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom()); 1851 1852 return nullptr; 1853 } 1854 1855 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const { 1856 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>(); 1857 } 1858 1859 void 1860 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, 1861 TemplateSpecializationKind TSK) { 1862 assert(TemplateOrInstantiation.isNull() && 1863 "Previous template or instantiation?"); 1864 assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); 1865 TemplateOrInstantiation 1866 = new (getASTContext()) MemberSpecializationInfo(RD, TSK); 1867 } 1868 1869 ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const { 1870 return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>(); 1871 } 1872 1873 void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) { 1874 TemplateOrInstantiation = Template; 1875 } 1876 1877 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ 1878 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) 1879 return Spec->getSpecializationKind(); 1880 1881 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1882 return MSInfo->getTemplateSpecializationKind(); 1883 1884 return TSK_Undeclared; 1885 } 1886 1887 void 1888 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { 1889 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1890 Spec->setSpecializationKind(TSK); 1891 return; 1892 } 1893 1894 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1895 MSInfo->setTemplateSpecializationKind(TSK); 1896 return; 1897 } 1898 1899 llvm_unreachable("Not a class template or member class specialization"); 1900 } 1901 1902 const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const { 1903 auto GetDefinitionOrSelf = 1904 [](const CXXRecordDecl *D) -> const CXXRecordDecl * { 1905 if (auto *Def = D->getDefinition()) 1906 return Def; 1907 return D; 1908 }; 1909 1910 // If it's a class template specialization, find the template or partial 1911 // specialization from which it was instantiated. 1912 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1913 auto From = TD->getInstantiatedFrom(); 1914 if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) { 1915 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) { 1916 if (NewCTD->isMemberSpecialization()) 1917 break; 1918 CTD = NewCTD; 1919 } 1920 return GetDefinitionOrSelf(CTD->getTemplatedDecl()); 1921 } 1922 if (auto *CTPSD = 1923 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 1924 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) { 1925 if (NewCTPSD->isMemberSpecialization()) 1926 break; 1927 CTPSD = NewCTPSD; 1928 } 1929 return GetDefinitionOrSelf(CTPSD); 1930 } 1931 } 1932 1933 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1934 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 1935 const CXXRecordDecl *RD = this; 1936 while (auto *NewRD = RD->getInstantiatedFromMemberClass()) 1937 RD = NewRD; 1938 return GetDefinitionOrSelf(RD); 1939 } 1940 } 1941 1942 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) && 1943 "couldn't find pattern for class template instantiation"); 1944 return nullptr; 1945 } 1946 1947 CXXDestructorDecl *CXXRecordDecl::getDestructor() const { 1948 ASTContext &Context = getASTContext(); 1949 QualType ClassType = Context.getTypeDeclType(this); 1950 1951 DeclarationName Name 1952 = Context.DeclarationNames.getCXXDestructorName( 1953 Context.getCanonicalType(ClassType)); 1954 1955 DeclContext::lookup_result R = lookup(Name); 1956 1957 // If a destructor was marked as not selected, we skip it. We don't always 1958 // have a selected destructor: dependent types, unnamed structs. 1959 for (auto *Decl : R) { 1960 auto* DD = dyn_cast<CXXDestructorDecl>(Decl); 1961 if (DD && !DD->isIneligibleOrNotSelected()) 1962 return DD; 1963 } 1964 return nullptr; 1965 } 1966 1967 static bool isDeclContextInNamespace(const DeclContext *DC) { 1968 while (!DC->isTranslationUnit()) { 1969 if (DC->isNamespace()) 1970 return true; 1971 DC = DC->getParent(); 1972 } 1973 return false; 1974 } 1975 1976 bool CXXRecordDecl::isInterfaceLike() const { 1977 assert(hasDefinition() && "checking for interface-like without a definition"); 1978 // All __interfaces are inheritently interface-like. 1979 if (isInterface()) 1980 return true; 1981 1982 // Interface-like types cannot have a user declared constructor, destructor, 1983 // friends, VBases, conversion functions, or fields. Additionally, lambdas 1984 // cannot be interface types. 1985 if (isLambda() || hasUserDeclaredConstructor() || 1986 hasUserDeclaredDestructor() || !field_empty() || hasFriends() || 1987 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0) 1988 return false; 1989 1990 // No interface-like type can have a method with a definition. 1991 for (const auto *const Method : methods()) 1992 if (Method->isDefined() && !Method->isImplicit()) 1993 return false; 1994 1995 // Check "Special" types. 1996 const auto *Uuid = getAttr<UuidAttr>(); 1997 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an 1998 // extern C++ block directly in the TU. These are only valid if in one 1999 // of these two situations. 2000 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() && 2001 !isDeclContextInNamespace(getDeclContext()) && 2002 ((getName() == "IUnknown" && 2003 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") || 2004 (getName() == "IDispatch" && 2005 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) { 2006 if (getNumBases() > 0) 2007 return false; 2008 return true; 2009 } 2010 2011 // FIXME: Any access specifiers is supposed to make this no longer interface 2012 // like. 2013 2014 // If this isn't a 'special' type, it must have a single interface-like base. 2015 if (getNumBases() != 1) 2016 return false; 2017 2018 const auto BaseSpec = *bases_begin(); 2019 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public) 2020 return false; 2021 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 2022 if (Base->isInterface() || !Base->isInterfaceLike()) 2023 return false; 2024 return true; 2025 } 2026 2027 void CXXRecordDecl::completeDefinition() { 2028 completeDefinition(nullptr); 2029 } 2030 2031 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { 2032 RecordDecl::completeDefinition(); 2033 2034 // If the class may be abstract (but hasn't been marked as such), check for 2035 // any pure final overriders. 2036 if (mayBeAbstract()) { 2037 CXXFinalOverriderMap MyFinalOverriders; 2038 if (!FinalOverriders) { 2039 getFinalOverriders(MyFinalOverriders); 2040 FinalOverriders = &MyFinalOverriders; 2041 } 2042 2043 bool Done = false; 2044 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), 2045 MEnd = FinalOverriders->end(); 2046 M != MEnd && !Done; ++M) { 2047 for (OverridingMethods::iterator SO = M->second.begin(), 2048 SOEnd = M->second.end(); 2049 SO != SOEnd && !Done; ++SO) { 2050 assert(SO->second.size() > 0 && 2051 "All virtual functions have overriding virtual functions"); 2052 2053 // C++ [class.abstract]p4: 2054 // A class is abstract if it contains or inherits at least one 2055 // pure virtual function for which the final overrider is pure 2056 // virtual. 2057 if (SO->second.front().Method->isPure()) { 2058 data().Abstract = true; 2059 Done = true; 2060 break; 2061 } 2062 } 2063 } 2064 } 2065 2066 // Set access bits correctly on the directly-declared conversions. 2067 for (conversion_iterator I = conversion_begin(), E = conversion_end(); 2068 I != E; ++I) 2069 I.setAccess((*I)->getAccess()); 2070 } 2071 2072 bool CXXRecordDecl::mayBeAbstract() const { 2073 if (data().Abstract || isInvalidDecl() || !data().Polymorphic || 2074 isDependentContext()) 2075 return false; 2076 2077 for (const auto &B : bases()) { 2078 const auto *BaseDecl = 2079 cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl()); 2080 if (BaseDecl->isAbstract()) 2081 return true; 2082 } 2083 2084 return false; 2085 } 2086 2087 bool CXXRecordDecl::isEffectivelyFinal() const { 2088 auto *Def = getDefinition(); 2089 if (!Def) 2090 return false; 2091 if (Def->hasAttr<FinalAttr>()) 2092 return true; 2093 if (const auto *Dtor = Def->getDestructor()) 2094 if (Dtor->hasAttr<FinalAttr>()) 2095 return true; 2096 return false; 2097 } 2098 2099 void CXXDeductionGuideDecl::anchor() {} 2100 2101 bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const { 2102 if ((getKind() != Other.getKind() || 2103 getKind() == ExplicitSpecKind::Unresolved)) { 2104 if (getKind() == ExplicitSpecKind::Unresolved && 2105 Other.getKind() == ExplicitSpecKind::Unresolved) { 2106 ODRHash SelfHash, OtherHash; 2107 SelfHash.AddStmt(getExpr()); 2108 OtherHash.AddStmt(Other.getExpr()); 2109 return SelfHash.CalculateHash() == OtherHash.CalculateHash(); 2110 } else 2111 return false; 2112 } 2113 return true; 2114 } 2115 2116 ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) { 2117 switch (Function->getDeclKind()) { 2118 case Decl::Kind::CXXConstructor: 2119 return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier(); 2120 case Decl::Kind::CXXConversion: 2121 return cast<CXXConversionDecl>(Function)->getExplicitSpecifier(); 2122 case Decl::Kind::CXXDeductionGuide: 2123 return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier(); 2124 default: 2125 return {}; 2126 } 2127 } 2128 2129 CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create( 2130 ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 2131 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, 2132 TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor, 2133 DeductionCandidate Kind) { 2134 return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T, 2135 TInfo, EndLocation, Ctor, Kind); 2136 } 2137 2138 CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, 2139 unsigned ID) { 2140 return new (C, ID) CXXDeductionGuideDecl( 2141 C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(), 2142 QualType(), nullptr, SourceLocation(), nullptr, 2143 DeductionCandidate::Normal); 2144 } 2145 2146 RequiresExprBodyDecl *RequiresExprBodyDecl::Create( 2147 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) { 2148 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc); 2149 } 2150 2151 RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, 2152 unsigned ID) { 2153 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation()); 2154 } 2155 2156 void CXXMethodDecl::anchor() {} 2157 2158 bool CXXMethodDecl::isStatic() const { 2159 const CXXMethodDecl *MD = getCanonicalDecl(); 2160 2161 if (MD->getStorageClass() == SC_Static) 2162 return true; 2163 2164 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator(); 2165 return isStaticOverloadedOperator(OOK); 2166 } 2167 2168 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD, 2169 const CXXMethodDecl *BaseMD) { 2170 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) { 2171 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl()) 2172 return true; 2173 if (recursivelyOverrides(MD, BaseMD)) 2174 return true; 2175 } 2176 return false; 2177 } 2178 2179 CXXMethodDecl * 2180 CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, 2181 bool MayBeBase) { 2182 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl()) 2183 return this; 2184 2185 // Lookup doesn't work for destructors, so handle them separately. 2186 if (isa<CXXDestructorDecl>(this)) { 2187 CXXMethodDecl *MD = RD->getDestructor(); 2188 if (MD) { 2189 if (recursivelyOverrides(MD, this)) 2190 return MD; 2191 if (MayBeBase && recursivelyOverrides(this, MD)) 2192 return MD; 2193 } 2194 return nullptr; 2195 } 2196 2197 for (auto *ND : RD->lookup(getDeclName())) { 2198 auto *MD = dyn_cast<CXXMethodDecl>(ND); 2199 if (!MD) 2200 continue; 2201 if (recursivelyOverrides(MD, this)) 2202 return MD; 2203 if (MayBeBase && recursivelyOverrides(this, MD)) 2204 return MD; 2205 } 2206 2207 return nullptr; 2208 } 2209 2210 CXXMethodDecl * 2211 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD, 2212 bool MayBeBase) { 2213 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase)) 2214 return MD; 2215 2216 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders; 2217 auto AddFinalOverrider = [&](CXXMethodDecl *D) { 2218 // If this function is overridden by a candidate final overrider, it is not 2219 // a final overrider. 2220 for (CXXMethodDecl *OtherD : FinalOverriders) { 2221 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D)) 2222 return; 2223 } 2224 2225 // Other candidate final overriders might be overridden by this function. 2226 llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) { 2227 return recursivelyOverrides(D, OtherD); 2228 }); 2229 2230 FinalOverriders.push_back(D); 2231 }; 2232 2233 for (const auto &I : RD->bases()) { 2234 const RecordType *RT = I.getType()->getAs<RecordType>(); 2235 if (!RT) 2236 continue; 2237 const auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 2238 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base)) 2239 AddFinalOverrider(D); 2240 } 2241 2242 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr; 2243 } 2244 2245 CXXMethodDecl * 2246 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2247 const DeclarationNameInfo &NameInfo, QualType T, 2248 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 2249 bool isInline, ConstexprSpecKind ConstexprKind, 2250 SourceLocation EndLocation, 2251 Expr *TrailingRequiresClause) { 2252 return new (C, RD) CXXMethodDecl( 2253 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 2254 isInline, ConstexprKind, EndLocation, TrailingRequiresClause); 2255 } 2256 2257 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2258 return new (C, ID) CXXMethodDecl( 2259 CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(), 2260 QualType(), nullptr, SC_None, false, false, 2261 ConstexprSpecKind::Unspecified, SourceLocation(), nullptr); 2262 } 2263 2264 CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base, 2265 bool IsAppleKext) { 2266 assert(isVirtual() && "this method is expected to be virtual"); 2267 2268 // When building with -fapple-kext, all calls must go through the vtable since 2269 // the kernel linker can do runtime patching of vtables. 2270 if (IsAppleKext) 2271 return nullptr; 2272 2273 // If the member function is marked 'final', we know that it can't be 2274 // overridden and can therefore devirtualize it unless it's pure virtual. 2275 if (hasAttr<FinalAttr>()) 2276 return isPure() ? nullptr : this; 2277 2278 // If Base is unknown, we cannot devirtualize. 2279 if (!Base) 2280 return nullptr; 2281 2282 // If the base expression (after skipping derived-to-base conversions) is a 2283 // class prvalue, then we can devirtualize. 2284 Base = Base->getBestDynamicClassTypeExpr(); 2285 if (Base->isPRValue() && Base->getType()->isRecordType()) 2286 return this; 2287 2288 // If we don't even know what we would call, we can't devirtualize. 2289 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2290 if (!BestDynamicDecl) 2291 return nullptr; 2292 2293 // There may be a method corresponding to MD in a derived class. 2294 CXXMethodDecl *DevirtualizedMethod = 2295 getCorrespondingMethodInClass(BestDynamicDecl); 2296 2297 // If there final overrider in the dynamic type is ambiguous, we can't 2298 // devirtualize this call. 2299 if (!DevirtualizedMethod) 2300 return nullptr; 2301 2302 // If that method is pure virtual, we can't devirtualize. If this code is 2303 // reached, the result would be UB, not a direct call to the derived class 2304 // function, and we can't assume the derived class function is defined. 2305 if (DevirtualizedMethod->isPure()) 2306 return nullptr; 2307 2308 // If that method is marked final, we can devirtualize it. 2309 if (DevirtualizedMethod->hasAttr<FinalAttr>()) 2310 return DevirtualizedMethod; 2311 2312 // Similarly, if the class itself or its destructor is marked 'final', 2313 // the class can't be derived from and we can therefore devirtualize the 2314 // member function call. 2315 if (BestDynamicDecl->isEffectivelyFinal()) 2316 return DevirtualizedMethod; 2317 2318 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) { 2319 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2320 if (VD->getType()->isRecordType()) 2321 // This is a record decl. We know the type and can devirtualize it. 2322 return DevirtualizedMethod; 2323 2324 return nullptr; 2325 } 2326 2327 // We can devirtualize calls on an object accessed by a class member access 2328 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2329 // a derived class object constructed in the same location. 2330 if (const auto *ME = dyn_cast<MemberExpr>(Base)) { 2331 const ValueDecl *VD = ME->getMemberDecl(); 2332 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr; 2333 } 2334 2335 // Likewise for calls on an object accessed by a (non-reference) pointer to 2336 // member access. 2337 if (auto *BO = dyn_cast<BinaryOperator>(Base)) { 2338 if (BO->isPtrMemOp()) { 2339 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>(); 2340 if (MPT->getPointeeType()->isRecordType()) 2341 return DevirtualizedMethod; 2342 } 2343 } 2344 2345 // We can't devirtualize the call. 2346 return nullptr; 2347 } 2348 2349 bool CXXMethodDecl::isUsualDeallocationFunction( 2350 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const { 2351 assert(PreventedBy.empty() && "PreventedBy is expected to be empty"); 2352 if (getOverloadedOperator() != OO_Delete && 2353 getOverloadedOperator() != OO_Array_Delete) 2354 return false; 2355 2356 // C++ [basic.stc.dynamic.deallocation]p2: 2357 // A template instance is never a usual deallocation function, 2358 // regardless of its signature. 2359 if (getPrimaryTemplate()) 2360 return false; 2361 2362 // C++ [basic.stc.dynamic.deallocation]p2: 2363 // If a class T has a member deallocation function named operator delete 2364 // with exactly one parameter, then that function is a usual (non-placement) 2365 // deallocation function. [...] 2366 if (getNumParams() == 1) 2367 return true; 2368 unsigned UsualParams = 1; 2369 2370 // C++ P0722: 2371 // A destroying operator delete is a usual deallocation function if 2372 // removing the std::destroying_delete_t parameter and changing the 2373 // first parameter type from T* to void* results in the signature of 2374 // a usual deallocation function. 2375 if (isDestroyingOperatorDelete()) 2376 ++UsualParams; 2377 2378 // C++ <=14 [basic.stc.dynamic.deallocation]p2: 2379 // [...] If class T does not declare such an operator delete but does 2380 // declare a member deallocation function named operator delete with 2381 // exactly two parameters, the second of which has type std::size_t (18.1), 2382 // then this function is a usual deallocation function. 2383 // 2384 // C++17 says a usual deallocation function is one with the signature 2385 // (void* [, size_t] [, std::align_val_t] [, ...]) 2386 // and all such functions are usual deallocation functions. It's not clear 2387 // that allowing varargs functions was intentional. 2388 ASTContext &Context = getASTContext(); 2389 if (UsualParams < getNumParams() && 2390 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(), 2391 Context.getSizeType())) 2392 ++UsualParams; 2393 2394 if (UsualParams < getNumParams() && 2395 getParamDecl(UsualParams)->getType()->isAlignValT()) 2396 ++UsualParams; 2397 2398 if (UsualParams != getNumParams()) 2399 return false; 2400 2401 // In C++17 onwards, all potential usual deallocation functions are actual 2402 // usual deallocation functions. Honor this behavior when post-C++14 2403 // deallocation functions are offered as extensions too. 2404 // FIXME(EricWF): Destroying Delete should be a language option. How do we 2405 // handle when destroying delete is used prior to C++17? 2406 if (Context.getLangOpts().CPlusPlus17 || 2407 Context.getLangOpts().AlignedAllocation || 2408 isDestroyingOperatorDelete()) 2409 return true; 2410 2411 // This function is a usual deallocation function if there are no 2412 // single-parameter deallocation functions of the same kind. 2413 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); 2414 bool Result = true; 2415 for (const auto *D : R) { 2416 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2417 if (FD->getNumParams() == 1) { 2418 PreventedBy.push_back(FD); 2419 Result = false; 2420 } 2421 } 2422 } 2423 return Result; 2424 } 2425 2426 bool CXXMethodDecl::isExplicitObjectMemberFunction() const { 2427 // C++2b [dcl.fct]p6: 2428 // An explicit object member function is a non-static member 2429 // function with an explicit object parameter 2430 return !isStatic() && hasCXXExplicitFunctionObjectParameter(); 2431 } 2432 2433 bool CXXMethodDecl::isImplicitObjectMemberFunction() const { 2434 return !isStatic() && !hasCXXExplicitFunctionObjectParameter(); 2435 } 2436 2437 bool CXXMethodDecl::isCopyAssignmentOperator() const { 2438 // C++0x [class.copy]p17: 2439 // A user-declared copy assignment operator X::operator= is a non-static 2440 // non-template member function of class X with exactly one parameter of 2441 // type X, X&, const X&, volatile X& or const volatile X&. 2442 if (/*operator=*/getOverloadedOperator() != OO_Equal || 2443 /*non-static*/ isStatic() || 2444 2445 /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() || 2446 getNumExplicitParams() != 1) 2447 return false; 2448 2449 QualType ParamType = getNonObjectParameter(0)->getType(); 2450 if (const auto *Ref = ParamType->getAs<LValueReferenceType>()) 2451 ParamType = Ref->getPointeeType(); 2452 2453 ASTContext &Context = getASTContext(); 2454 QualType ClassType 2455 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2456 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2457 } 2458 2459 bool CXXMethodDecl::isMoveAssignmentOperator() const { 2460 // C++0x [class.copy]p19: 2461 // A user-declared move assignment operator X::operator= is a non-static 2462 // non-template member function of class X with exactly one parameter of type 2463 // X&&, const X&&, volatile X&&, or const volatile X&&. 2464 if (getOverloadedOperator() != OO_Equal || isStatic() || 2465 getPrimaryTemplate() || getDescribedFunctionTemplate() || 2466 getNumExplicitParams() != 1) 2467 return false; 2468 2469 QualType ParamType = getNonObjectParameter(0)->getType(); 2470 if (!ParamType->isRValueReferenceType()) 2471 return false; 2472 ParamType = ParamType->getPointeeType(); 2473 2474 ASTContext &Context = getASTContext(); 2475 QualType ClassType 2476 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2477 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2478 } 2479 2480 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { 2481 assert(MD->isCanonicalDecl() && "Method is not canonical!"); 2482 assert(!MD->getParent()->isDependentContext() && 2483 "Can't add an overridden method to a class template!"); 2484 assert(MD->isVirtual() && "Method is not virtual!"); 2485 2486 getASTContext().addOverriddenMethod(this, MD); 2487 } 2488 2489 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { 2490 if (isa<CXXConstructorDecl>(this)) return nullptr; 2491 return getASTContext().overridden_methods_begin(this); 2492 } 2493 2494 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { 2495 if (isa<CXXConstructorDecl>(this)) return nullptr; 2496 return getASTContext().overridden_methods_end(this); 2497 } 2498 2499 unsigned CXXMethodDecl::size_overridden_methods() const { 2500 if (isa<CXXConstructorDecl>(this)) return 0; 2501 return getASTContext().overridden_methods_size(this); 2502 } 2503 2504 CXXMethodDecl::overridden_method_range 2505 CXXMethodDecl::overridden_methods() const { 2506 if (isa<CXXConstructorDecl>(this)) 2507 return overridden_method_range(nullptr, nullptr); 2508 return getASTContext().overridden_methods(this); 2509 } 2510 2511 static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT, 2512 const CXXRecordDecl *Decl) { 2513 QualType ClassTy = C.getTypeDeclType(Decl); 2514 return C.getQualifiedType(ClassTy, FPT->getMethodQuals()); 2515 } 2516 2517 QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT, 2518 const CXXRecordDecl *Decl) { 2519 ASTContext &C = Decl->getASTContext(); 2520 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl); 2521 return C.getLangOpts().HLSL ? C.getLValueReferenceType(ObjectTy) 2522 : C.getPointerType(ObjectTy); 2523 } 2524 2525 QualType CXXMethodDecl::getThisType() const { 2526 // C++ 9.3.2p1: The type of this in a member function of a class X is X*. 2527 // If the member function is declared const, the type of this is const X*, 2528 // if the member function is declared volatile, the type of this is 2529 // volatile X*, and if the member function is declared const volatile, 2530 // the type of this is const volatile X*. 2531 assert(isInstance() && "No 'this' for static methods!"); 2532 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(), 2533 getParent()); 2534 } 2535 2536 QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const { 2537 if (isExplicitObjectMemberFunction()) 2538 return parameters()[0]->getType(); 2539 2540 ASTContext &C = getParentASTContext(); 2541 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>(); 2542 QualType Type = ::getThisObjectType(C, FPT, getParent()); 2543 RefQualifierKind RK = FPT->getRefQualifier(); 2544 if (RK == RefQualifierKind::RQ_RValue) 2545 return C.getRValueReferenceType(Type); 2546 return C.getLValueReferenceType(Type); 2547 } 2548 2549 bool CXXMethodDecl::hasInlineBody() const { 2550 // If this function is a template instantiation, look at the template from 2551 // which it was instantiated. 2552 const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); 2553 if (!CheckFn) 2554 CheckFn = this; 2555 2556 const FunctionDecl *fn; 2557 return CheckFn->isDefined(fn) && !fn->isOutOfLine() && 2558 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody()); 2559 } 2560 2561 bool CXXMethodDecl::isLambdaStaticInvoker() const { 2562 const CXXRecordDecl *P = getParent(); 2563 return P->isLambda() && getDeclName().isIdentifier() && 2564 getName() == getLambdaStaticInvokerName(); 2565 } 2566 2567 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2568 TypeSourceInfo *TInfo, bool IsVirtual, 2569 SourceLocation L, Expr *Init, 2570 SourceLocation R, 2571 SourceLocation EllipsisLoc) 2572 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc), 2573 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), 2574 IsWritten(false), SourceOrder(0) {} 2575 2576 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, 2577 SourceLocation MemberLoc, 2578 SourceLocation L, Expr *Init, 2579 SourceLocation R) 2580 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2581 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2582 IsWritten(false), SourceOrder(0) {} 2583 2584 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2585 IndirectFieldDecl *Member, 2586 SourceLocation MemberLoc, 2587 SourceLocation L, Expr *Init, 2588 SourceLocation R) 2589 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2590 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2591 IsWritten(false), SourceOrder(0) {} 2592 2593 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2594 TypeSourceInfo *TInfo, 2595 SourceLocation L, Expr *Init, 2596 SourceLocation R) 2597 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), 2598 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} 2599 2600 int64_t CXXCtorInitializer::getID(const ASTContext &Context) const { 2601 return Context.getAllocator() 2602 .identifyKnownAlignedObject<CXXCtorInitializer>(this); 2603 } 2604 2605 TypeLoc CXXCtorInitializer::getBaseClassLoc() const { 2606 if (isBaseInitializer()) 2607 return Initializee.get<TypeSourceInfo*>()->getTypeLoc(); 2608 else 2609 return {}; 2610 } 2611 2612 const Type *CXXCtorInitializer::getBaseClass() const { 2613 if (isBaseInitializer()) 2614 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr(); 2615 else 2616 return nullptr; 2617 } 2618 2619 SourceLocation CXXCtorInitializer::getSourceLocation() const { 2620 if (isInClassMemberInitializer()) 2621 return getAnyMember()->getLocation(); 2622 2623 if (isAnyMemberInitializer()) 2624 return getMemberLocation(); 2625 2626 if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>()) 2627 return TSInfo->getTypeLoc().getBeginLoc(); 2628 2629 return {}; 2630 } 2631 2632 SourceRange CXXCtorInitializer::getSourceRange() const { 2633 if (isInClassMemberInitializer()) { 2634 FieldDecl *D = getAnyMember(); 2635 if (Expr *I = D->getInClassInitializer()) 2636 return I->getSourceRange(); 2637 return {}; 2638 } 2639 2640 return SourceRange(getSourceLocation(), getRParenLoc()); 2641 } 2642 2643 CXXConstructorDecl::CXXConstructorDecl( 2644 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2645 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2646 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2647 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2648 InheritedConstructor Inherited, Expr *TrailingRequiresClause) 2649 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo, 2650 SC_None, UsesFPIntrin, isInline, ConstexprKind, 2651 SourceLocation(), TrailingRequiresClause) { 2652 setNumCtorInitializers(0); 2653 setInheritingConstructor(static_cast<bool>(Inherited)); 2654 setImplicit(isImplicitlyDeclared); 2655 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0; 2656 if (Inherited) 2657 *getTrailingObjects<InheritedConstructor>() = Inherited; 2658 setExplicitSpecifier(ES); 2659 } 2660 2661 void CXXConstructorDecl::anchor() {} 2662 2663 CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C, 2664 unsigned ID, 2665 uint64_t AllocKind) { 2666 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit); 2667 bool isInheritingConstructor = 2668 static_cast<bool>(AllocKind & TAKInheritsConstructor); 2669 unsigned Extra = 2670 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2671 isInheritingConstructor, hasTrailingExplicit); 2672 auto *Result = new (C, ID, Extra) CXXConstructorDecl( 2673 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2674 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified, 2675 InheritedConstructor(), nullptr); 2676 Result->setInheritingConstructor(isInheritingConstructor); 2677 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier = 2678 hasTrailingExplicit; 2679 Result->setExplicitSpecifier(ExplicitSpecifier()); 2680 return Result; 2681 } 2682 2683 CXXConstructorDecl *CXXConstructorDecl::Create( 2684 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2685 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2686 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2687 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2688 InheritedConstructor Inherited, Expr *TrailingRequiresClause) { 2689 assert(NameInfo.getName().getNameKind() 2690 == DeclarationName::CXXConstructorName && 2691 "Name must refer to a constructor"); 2692 unsigned Extra = 2693 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2694 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0); 2695 return new (C, RD, Extra) CXXConstructorDecl( 2696 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline, 2697 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause); 2698 } 2699 2700 CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const { 2701 return CtorInitializers.get(getASTContext().getExternalSource()); 2702 } 2703 2704 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const { 2705 assert(isDelegatingConstructor() && "Not a delegating constructor!"); 2706 Expr *E = (*init_begin())->getInit()->IgnoreImplicit(); 2707 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E)) 2708 return Construct->getConstructor(); 2709 2710 return nullptr; 2711 } 2712 2713 bool CXXConstructorDecl::isDefaultConstructor() const { 2714 // C++ [class.default.ctor]p1: 2715 // A default constructor for a class X is a constructor of class X for 2716 // which each parameter that is not a function parameter pack has a default 2717 // argument (including the case of a constructor with no parameters) 2718 return getMinRequiredArguments() == 0; 2719 } 2720 2721 bool 2722 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { 2723 return isCopyOrMoveConstructor(TypeQuals) && 2724 getParamDecl(0)->getType()->isLValueReferenceType(); 2725 } 2726 2727 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const { 2728 return isCopyOrMoveConstructor(TypeQuals) && 2729 getParamDecl(0)->getType()->isRValueReferenceType(); 2730 } 2731 2732 /// Determine whether this is a copy or move constructor. 2733 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { 2734 // C++ [class.copy]p2: 2735 // A non-template constructor for class X is a copy constructor 2736 // if its first parameter is of type X&, const X&, volatile X& or 2737 // const volatile X&, and either there are no other parameters 2738 // or else all other parameters have default arguments (8.3.6). 2739 // C++0x [class.copy]p3: 2740 // A non-template constructor for class X is a move constructor if its 2741 // first parameter is of type X&&, const X&&, volatile X&&, or 2742 // const volatile X&&, and either there are no other parameters or else 2743 // all other parameters have default arguments. 2744 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr || 2745 getDescribedFunctionTemplate() != nullptr) 2746 return false; 2747 2748 const ParmVarDecl *Param = getParamDecl(0); 2749 2750 // Do we have a reference type? 2751 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>(); 2752 if (!ParamRefType) 2753 return false; 2754 2755 // Is it a reference to our class type? 2756 ASTContext &Context = getASTContext(); 2757 2758 CanQualType PointeeType 2759 = Context.getCanonicalType(ParamRefType->getPointeeType()); 2760 CanQualType ClassTy 2761 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2762 if (PointeeType.getUnqualifiedType() != ClassTy) 2763 return false; 2764 2765 // FIXME: other qualifiers? 2766 2767 // We have a copy or move constructor. 2768 TypeQuals = PointeeType.getCVRQualifiers(); 2769 return true; 2770 } 2771 2772 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { 2773 // C++ [class.conv.ctor]p1: 2774 // A constructor declared without the function-specifier explicit 2775 // that can be called with a single parameter specifies a 2776 // conversion from the type of its first parameter to the type of 2777 // its class. Such a constructor is called a converting 2778 // constructor. 2779 if (isExplicit() && !AllowExplicit) 2780 return false; 2781 2782 // FIXME: This has nothing to do with the definition of converting 2783 // constructor, but is convenient for how we use this function in overload 2784 // resolution. 2785 return getNumParams() == 0 2786 ? getType()->castAs<FunctionProtoType>()->isVariadic() 2787 : getMinRequiredArguments() <= 1; 2788 } 2789 2790 bool CXXConstructorDecl::isSpecializationCopyingObject() const { 2791 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr) 2792 return false; 2793 2794 const ParmVarDecl *Param = getParamDecl(0); 2795 2796 ASTContext &Context = getASTContext(); 2797 CanQualType ParamType = Context.getCanonicalType(Param->getType()); 2798 2799 // Is it the same as our class type? 2800 CanQualType ClassTy 2801 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2802 if (ParamType.getUnqualifiedType() != ClassTy) 2803 return false; 2804 2805 return true; 2806 } 2807 2808 void CXXDestructorDecl::anchor() {} 2809 2810 CXXDestructorDecl * 2811 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2812 return new (C, ID) CXXDestructorDecl( 2813 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2814 false, false, false, ConstexprSpecKind::Unspecified, nullptr); 2815 } 2816 2817 CXXDestructorDecl *CXXDestructorDecl::Create( 2818 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2819 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2820 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, 2821 ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) { 2822 assert(NameInfo.getName().getNameKind() 2823 == DeclarationName::CXXDestructorName && 2824 "Name must refer to a destructor"); 2825 return new (C, RD) CXXDestructorDecl( 2826 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, 2827 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause); 2828 } 2829 2830 void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) { 2831 auto *First = cast<CXXDestructorDecl>(getFirstDecl()); 2832 if (OD && !First->OperatorDelete) { 2833 First->OperatorDelete = OD; 2834 First->OperatorDeleteThisArg = ThisArg; 2835 if (auto *L = getASTMutationListener()) 2836 L->ResolvedOperatorDelete(First, OD, ThisArg); 2837 } 2838 } 2839 2840 void CXXConversionDecl::anchor() {} 2841 2842 CXXConversionDecl * 2843 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2844 return new (C, ID) CXXConversionDecl( 2845 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2846 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, 2847 SourceLocation(), nullptr); 2848 } 2849 2850 CXXConversionDecl *CXXConversionDecl::Create( 2851 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2852 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2853 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, 2854 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, 2855 Expr *TrailingRequiresClause) { 2856 assert(NameInfo.getName().getNameKind() 2857 == DeclarationName::CXXConversionFunctionName && 2858 "Name must refer to a conversion function"); 2859 return new (C, RD) CXXConversionDecl( 2860 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES, 2861 ConstexprKind, EndLocation, TrailingRequiresClause); 2862 } 2863 2864 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const { 2865 return isImplicit() && getParent()->isLambda() && 2866 getConversionType()->isBlockPointerType(); 2867 } 2868 2869 LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, 2870 SourceLocation LangLoc, 2871 LinkageSpecLanguageIDs lang, bool HasBraces) 2872 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec), 2873 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) { 2874 setLanguage(lang); 2875 LinkageSpecDeclBits.HasBraces = HasBraces; 2876 } 2877 2878 void LinkageSpecDecl::anchor() {} 2879 2880 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC, 2881 SourceLocation ExternLoc, 2882 SourceLocation LangLoc, 2883 LinkageSpecLanguageIDs Lang, 2884 bool HasBraces) { 2885 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces); 2886 } 2887 2888 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, 2889 unsigned ID) { 2890 return new (C, ID) 2891 LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(), 2892 LinkageSpecLanguageIDs::C, false); 2893 } 2894 2895 void UsingDirectiveDecl::anchor() {} 2896 2897 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, 2898 SourceLocation L, 2899 SourceLocation NamespaceLoc, 2900 NestedNameSpecifierLoc QualifierLoc, 2901 SourceLocation IdentLoc, 2902 NamedDecl *Used, 2903 DeclContext *CommonAncestor) { 2904 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used)) 2905 Used = NS->getOriginalNamespace(); 2906 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc, 2907 IdentLoc, Used, CommonAncestor); 2908 } 2909 2910 UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C, 2911 unsigned ID) { 2912 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(), 2913 SourceLocation(), 2914 NestedNameSpecifierLoc(), 2915 SourceLocation(), nullptr, nullptr); 2916 } 2917 2918 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() { 2919 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace)) 2920 return NA->getNamespace(); 2921 return cast_or_null<NamespaceDecl>(NominatedNamespace); 2922 } 2923 2924 NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, 2925 SourceLocation StartLoc, SourceLocation IdLoc, 2926 IdentifierInfo *Id, NamespaceDecl *PrevDecl, 2927 bool Nested) 2928 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace), 2929 redeclarable_base(C), LocStart(StartLoc) { 2930 unsigned Flags = 0; 2931 if (Inline) 2932 Flags |= F_Inline; 2933 if (Nested) 2934 Flags |= F_Nested; 2935 AnonOrFirstNamespaceAndFlags = {nullptr, Flags}; 2936 setPreviousDecl(PrevDecl); 2937 2938 if (PrevDecl) 2939 AnonOrFirstNamespaceAndFlags.setPointer(PrevDecl->getOriginalNamespace()); 2940 } 2941 2942 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2943 bool Inline, SourceLocation StartLoc, 2944 SourceLocation IdLoc, IdentifierInfo *Id, 2945 NamespaceDecl *PrevDecl, bool Nested) { 2946 return new (C, DC) 2947 NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested); 2948 } 2949 2950 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2951 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(), 2952 SourceLocation(), nullptr, nullptr, false); 2953 } 2954 2955 NamespaceDecl *NamespaceDecl::getOriginalNamespace() { 2956 if (isFirstDecl()) 2957 return this; 2958 2959 return AnonOrFirstNamespaceAndFlags.getPointer(); 2960 } 2961 2962 const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const { 2963 if (isFirstDecl()) 2964 return this; 2965 2966 return AnonOrFirstNamespaceAndFlags.getPointer(); 2967 } 2968 2969 bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); } 2970 2971 NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() { 2972 return getNextRedeclaration(); 2973 } 2974 2975 NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() { 2976 return getPreviousDecl(); 2977 } 2978 2979 NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() { 2980 return getMostRecentDecl(); 2981 } 2982 2983 void NamespaceAliasDecl::anchor() {} 2984 2985 NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() { 2986 return getNextRedeclaration(); 2987 } 2988 2989 NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() { 2990 return getPreviousDecl(); 2991 } 2992 2993 NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() { 2994 return getMostRecentDecl(); 2995 } 2996 2997 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, 2998 SourceLocation UsingLoc, 2999 SourceLocation AliasLoc, 3000 IdentifierInfo *Alias, 3001 NestedNameSpecifierLoc QualifierLoc, 3002 SourceLocation IdentLoc, 3003 NamedDecl *Namespace) { 3004 // FIXME: Preserve the aliased namespace as written. 3005 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace)) 3006 Namespace = NS->getOriginalNamespace(); 3007 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias, 3008 QualifierLoc, IdentLoc, Namespace); 3009 } 3010 3011 NamespaceAliasDecl * 3012 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3013 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(), 3014 SourceLocation(), nullptr, 3015 NestedNameSpecifierLoc(), 3016 SourceLocation(), nullptr); 3017 } 3018 3019 void LifetimeExtendedTemporaryDecl::anchor() {} 3020 3021 /// Retrieve the storage duration for the materialized temporary. 3022 StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const { 3023 const ValueDecl *ExtendingDecl = getExtendingDecl(); 3024 if (!ExtendingDecl) 3025 return SD_FullExpression; 3026 // FIXME: This is not necessarily correct for a temporary materialized 3027 // within a default initializer. 3028 if (isa<FieldDecl>(ExtendingDecl)) 3029 return SD_Automatic; 3030 // FIXME: This only works because storage class specifiers are not allowed 3031 // on decomposition declarations. 3032 if (isa<BindingDecl>(ExtendingDecl)) 3033 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic 3034 : SD_Static; 3035 return cast<VarDecl>(ExtendingDecl)->getStorageDuration(); 3036 } 3037 3038 APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const { 3039 assert(getStorageDuration() == SD_Static && 3040 "don't need to cache the computed value for this temporary"); 3041 if (MayCreate && !Value) { 3042 Value = (new (getASTContext()) APValue); 3043 getASTContext().addDestruction(Value); 3044 } 3045 assert(Value && "may not be null"); 3046 return Value; 3047 } 3048 3049 void UsingShadowDecl::anchor() {} 3050 3051 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, 3052 SourceLocation Loc, DeclarationName Name, 3053 BaseUsingDecl *Introducer, NamedDecl *Target) 3054 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C), 3055 UsingOrNextShadow(Introducer) { 3056 if (Target) { 3057 assert(!isa<UsingShadowDecl>(Target)); 3058 setTargetDecl(Target); 3059 } 3060 setImplicit(); 3061 } 3062 3063 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty) 3064 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()), 3065 redeclarable_base(C) {} 3066 3067 UsingShadowDecl * 3068 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3069 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell()); 3070 } 3071 3072 BaseUsingDecl *UsingShadowDecl::getIntroducer() const { 3073 const UsingShadowDecl *Shadow = this; 3074 while (const auto *NextShadow = 3075 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow)) 3076 Shadow = NextShadow; 3077 return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow); 3078 } 3079 3080 void ConstructorUsingShadowDecl::anchor() {} 3081 3082 ConstructorUsingShadowDecl * 3083 ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC, 3084 SourceLocation Loc, UsingDecl *Using, 3085 NamedDecl *Target, bool IsVirtual) { 3086 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target, 3087 IsVirtual); 3088 } 3089 3090 ConstructorUsingShadowDecl * 3091 ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3092 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell()); 3093 } 3094 3095 CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const { 3096 return getIntroducer()->getQualifier()->getAsRecordDecl(); 3097 } 3098 3099 void BaseUsingDecl::anchor() {} 3100 3101 void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) { 3102 assert(!llvm::is_contained(shadows(), S) && "declaration already in set"); 3103 assert(S->getIntroducer() == this); 3104 3105 if (FirstUsingShadow.getPointer()) 3106 S->UsingOrNextShadow = FirstUsingShadow.getPointer(); 3107 FirstUsingShadow.setPointer(S); 3108 } 3109 3110 void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) { 3111 assert(llvm::is_contained(shadows(), S) && "declaration not in set"); 3112 assert(S->getIntroducer() == this); 3113 3114 // Remove S from the shadow decl chain. This is O(n) but hopefully rare. 3115 3116 if (FirstUsingShadow.getPointer() == S) { 3117 FirstUsingShadow.setPointer( 3118 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow)); 3119 S->UsingOrNextShadow = this; 3120 return; 3121 } 3122 3123 UsingShadowDecl *Prev = FirstUsingShadow.getPointer(); 3124 while (Prev->UsingOrNextShadow != S) 3125 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow); 3126 Prev->UsingOrNextShadow = S->UsingOrNextShadow; 3127 S->UsingOrNextShadow = this; 3128 } 3129 3130 void UsingDecl::anchor() {} 3131 3132 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL, 3133 NestedNameSpecifierLoc QualifierLoc, 3134 const DeclarationNameInfo &NameInfo, 3135 bool HasTypename) { 3136 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename); 3137 } 3138 3139 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3140 return new (C, ID) UsingDecl(nullptr, SourceLocation(), 3141 NestedNameSpecifierLoc(), DeclarationNameInfo(), 3142 false); 3143 } 3144 3145 SourceRange UsingDecl::getSourceRange() const { 3146 SourceLocation Begin = isAccessDeclaration() 3147 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3148 return SourceRange(Begin, getNameInfo().getEndLoc()); 3149 } 3150 3151 void UsingEnumDecl::anchor() {} 3152 3153 UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC, 3154 SourceLocation UL, 3155 SourceLocation EL, 3156 SourceLocation NL, 3157 TypeSourceInfo *EnumType) { 3158 assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl())); 3159 return new (C, DC) 3160 UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType); 3161 } 3162 3163 UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3164 return new (C, ID) 3165 UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(), 3166 SourceLocation(), SourceLocation(), nullptr); 3167 } 3168 3169 SourceRange UsingEnumDecl::getSourceRange() const { 3170 return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc()); 3171 } 3172 3173 void UsingPackDecl::anchor() {} 3174 3175 UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC, 3176 NamedDecl *InstantiatedFrom, 3177 ArrayRef<NamedDecl *> UsingDecls) { 3178 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size()); 3179 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls); 3180 } 3181 3182 UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3183 unsigned NumExpansions) { 3184 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions); 3185 auto *Result = 3186 new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, std::nullopt); 3187 Result->NumExpansions = NumExpansions; 3188 auto *Trail = Result->getTrailingObjects<NamedDecl *>(); 3189 for (unsigned I = 0; I != NumExpansions; ++I) 3190 new (Trail + I) NamedDecl*(nullptr); 3191 return Result; 3192 } 3193 3194 void UnresolvedUsingValueDecl::anchor() {} 3195 3196 UnresolvedUsingValueDecl * 3197 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC, 3198 SourceLocation UsingLoc, 3199 NestedNameSpecifierLoc QualifierLoc, 3200 const DeclarationNameInfo &NameInfo, 3201 SourceLocation EllipsisLoc) { 3202 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc, 3203 QualifierLoc, NameInfo, 3204 EllipsisLoc); 3205 } 3206 3207 UnresolvedUsingValueDecl * 3208 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3209 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(), 3210 SourceLocation(), 3211 NestedNameSpecifierLoc(), 3212 DeclarationNameInfo(), 3213 SourceLocation()); 3214 } 3215 3216 SourceRange UnresolvedUsingValueDecl::getSourceRange() const { 3217 SourceLocation Begin = isAccessDeclaration() 3218 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3219 return SourceRange(Begin, getNameInfo().getEndLoc()); 3220 } 3221 3222 void UnresolvedUsingTypenameDecl::anchor() {} 3223 3224 UnresolvedUsingTypenameDecl * 3225 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC, 3226 SourceLocation UsingLoc, 3227 SourceLocation TypenameLoc, 3228 NestedNameSpecifierLoc QualifierLoc, 3229 SourceLocation TargetNameLoc, 3230 DeclarationName TargetName, 3231 SourceLocation EllipsisLoc) { 3232 return new (C, DC) UnresolvedUsingTypenameDecl( 3233 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc, 3234 TargetName.getAsIdentifierInfo(), EllipsisLoc); 3235 } 3236 3237 UnresolvedUsingTypenameDecl * 3238 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3239 return new (C, ID) UnresolvedUsingTypenameDecl( 3240 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), 3241 SourceLocation(), nullptr, SourceLocation()); 3242 } 3243 3244 UnresolvedUsingIfExistsDecl * 3245 UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC, 3246 SourceLocation Loc, DeclarationName Name) { 3247 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name); 3248 } 3249 3250 UnresolvedUsingIfExistsDecl * 3251 UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) { 3252 return new (Ctx, ID) 3253 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName()); 3254 } 3255 3256 UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC, 3257 SourceLocation Loc, 3258 DeclarationName Name) 3259 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {} 3260 3261 void UnresolvedUsingIfExistsDecl::anchor() {} 3262 3263 void StaticAssertDecl::anchor() {} 3264 3265 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC, 3266 SourceLocation StaticAssertLoc, 3267 Expr *AssertExpr, Expr *Message, 3268 SourceLocation RParenLoc, 3269 bool Failed) { 3270 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message, 3271 RParenLoc, Failed); 3272 } 3273 3274 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, 3275 unsigned ID) { 3276 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr, 3277 nullptr, SourceLocation(), false); 3278 } 3279 3280 VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() { 3281 assert((isa<VarDecl, BindingDecl>(this)) && 3282 "expected a VarDecl or a BindingDecl"); 3283 if (auto *Var = llvm::dyn_cast<VarDecl>(this)) 3284 return Var; 3285 if (auto *BD = llvm::dyn_cast<BindingDecl>(this)) 3286 return llvm::dyn_cast<VarDecl>(BD->getDecomposedDecl()); 3287 return nullptr; 3288 } 3289 3290 void BindingDecl::anchor() {} 3291 3292 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC, 3293 SourceLocation IdLoc, IdentifierInfo *Id) { 3294 return new (C, DC) BindingDecl(DC, IdLoc, Id); 3295 } 3296 3297 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3298 return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr); 3299 } 3300 3301 VarDecl *BindingDecl::getHoldingVar() const { 3302 Expr *B = getBinding(); 3303 if (!B) 3304 return nullptr; 3305 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit()); 3306 if (!DRE) 3307 return nullptr; 3308 3309 auto *VD = cast<VarDecl>(DRE->getDecl()); 3310 assert(VD->isImplicit() && "holding var for binding decl not implicit"); 3311 return VD; 3312 } 3313 3314 void DecompositionDecl::anchor() {} 3315 3316 DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC, 3317 SourceLocation StartLoc, 3318 SourceLocation LSquareLoc, 3319 QualType T, TypeSourceInfo *TInfo, 3320 StorageClass SC, 3321 ArrayRef<BindingDecl *> Bindings) { 3322 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size()); 3323 return new (C, DC, Extra) 3324 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings); 3325 } 3326 3327 DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C, 3328 unsigned ID, 3329 unsigned NumBindings) { 3330 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings); 3331 auto *Result = new (C, ID, Extra) 3332 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(), 3333 QualType(), nullptr, StorageClass(), std::nullopt); 3334 // Set up and clean out the bindings array. 3335 Result->NumBindings = NumBindings; 3336 auto *Trail = Result->getTrailingObjects<BindingDecl *>(); 3337 for (unsigned I = 0; I != NumBindings; ++I) 3338 new (Trail + I) BindingDecl*(nullptr); 3339 return Result; 3340 } 3341 3342 void DecompositionDecl::printName(llvm::raw_ostream &OS, 3343 const PrintingPolicy &Policy) const { 3344 OS << '['; 3345 bool Comma = false; 3346 for (const auto *B : bindings()) { 3347 if (Comma) 3348 OS << ", "; 3349 B->printName(OS, Policy); 3350 Comma = true; 3351 } 3352 OS << ']'; 3353 } 3354 3355 void MSPropertyDecl::anchor() {} 3356 3357 MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC, 3358 SourceLocation L, DeclarationName N, 3359 QualType T, TypeSourceInfo *TInfo, 3360 SourceLocation StartL, 3361 IdentifierInfo *Getter, 3362 IdentifierInfo *Setter) { 3363 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter); 3364 } 3365 3366 MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, 3367 unsigned ID) { 3368 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(), 3369 DeclarationName(), QualType(), nullptr, 3370 SourceLocation(), nullptr, nullptr); 3371 } 3372 3373 void MSGuidDecl::anchor() {} 3374 3375 MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P) 3376 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T), 3377 PartVal(P) {} 3378 3379 MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) { 3380 DeclContext *DC = C.getTranslationUnitDecl(); 3381 return new (C, DC) MSGuidDecl(DC, T, P); 3382 } 3383 3384 MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3385 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts()); 3386 } 3387 3388 void MSGuidDecl::printName(llvm::raw_ostream &OS, 3389 const PrintingPolicy &) const { 3390 OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-", 3391 PartVal.Part1, PartVal.Part2, PartVal.Part3); 3392 unsigned I = 0; 3393 for (uint8_t Byte : PartVal.Part4And5) { 3394 OS << llvm::format("%02" PRIx8, Byte); 3395 if (++I == 2) 3396 OS << '-'; 3397 } 3398 OS << '}'; 3399 } 3400 3401 /// Determine if T is a valid 'struct _GUID' of the shape that we expect. 3402 static bool isValidStructGUID(ASTContext &Ctx, QualType T) { 3403 // FIXME: We only need to check this once, not once each time we compute a 3404 // GUID APValue. 3405 using MatcherRef = llvm::function_ref<bool(QualType)>; 3406 3407 auto IsInt = [&Ctx](unsigned N) { 3408 return [&Ctx, N](QualType T) { 3409 return T->isUnsignedIntegerOrEnumerationType() && 3410 Ctx.getIntWidth(T) == N; 3411 }; 3412 }; 3413 3414 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) { 3415 return [&Ctx, Elem, N](QualType T) { 3416 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T); 3417 return CAT && CAT->getSize() == N && Elem(CAT->getElementType()); 3418 }; 3419 }; 3420 3421 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) { 3422 return [Fields](QualType T) { 3423 const RecordDecl *RD = T->getAsRecordDecl(); 3424 if (!RD || RD->isUnion()) 3425 return false; 3426 RD = RD->getDefinition(); 3427 if (!RD) 3428 return false; 3429 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 3430 if (CXXRD->getNumBases()) 3431 return false; 3432 auto MatcherIt = Fields.begin(); 3433 for (const FieldDecl *FD : RD->fields()) { 3434 if (FD->isUnnamedBitfield()) continue; 3435 if (FD->isBitField() || MatcherIt == Fields.end() || 3436 !(*MatcherIt)(FD->getType())) 3437 return false; 3438 ++MatcherIt; 3439 } 3440 return MatcherIt == Fields.end(); 3441 }; 3442 }; 3443 3444 // We expect an {i32, i16, i16, [8 x i8]}. 3445 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T); 3446 } 3447 3448 APValue &MSGuidDecl::getAsAPValue() const { 3449 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) { 3450 using llvm::APInt; 3451 using llvm::APSInt; 3452 APVal = APValue(APValue::UninitStruct(), 0, 4); 3453 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true)); 3454 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true)); 3455 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true)); 3456 APValue &Arr = APVal.getStructField(3) = 3457 APValue(APValue::UninitArray(), 8, 8); 3458 for (unsigned I = 0; I != 8; ++I) { 3459 Arr.getArrayInitializedElt(I) = 3460 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true)); 3461 } 3462 // Register this APValue to be destroyed if necessary. (Note that the 3463 // MSGuidDecl destructor is never run.) 3464 getASTContext().addDestruction(&APVal); 3465 } 3466 3467 return APVal; 3468 } 3469 3470 void UnnamedGlobalConstantDecl::anchor() {} 3471 3472 UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C, 3473 DeclContext *DC, 3474 QualType Ty, 3475 const APValue &Val) 3476 : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(), 3477 DeclarationName(), Ty), 3478 Value(Val) { 3479 // Cleanup the embedded APValue if required (note that our destructor is never 3480 // run) 3481 if (Value.needsCleanup()) 3482 C.addDestruction(&Value); 3483 } 3484 3485 UnnamedGlobalConstantDecl * 3486 UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T, 3487 const APValue &Value) { 3488 DeclContext *DC = C.getTranslationUnitDecl(); 3489 return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value); 3490 } 3491 3492 UnnamedGlobalConstantDecl * 3493 UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3494 return new (C, ID) 3495 UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue()); 3496 } 3497 3498 void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS, 3499 const PrintingPolicy &) const { 3500 OS << "unnamed-global-constant"; 3501 } 3502 3503 static const char *getAccessName(AccessSpecifier AS) { 3504 switch (AS) { 3505 case AS_none: 3506 llvm_unreachable("Invalid access specifier!"); 3507 case AS_public: 3508 return "public"; 3509 case AS_private: 3510 return "private"; 3511 case AS_protected: 3512 return "protected"; 3513 } 3514 llvm_unreachable("Invalid access specifier!"); 3515 } 3516 3517 const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB, 3518 AccessSpecifier AS) { 3519 return DB << getAccessName(AS); 3520 } 3521