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