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