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