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 bool Dependent, 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 = 155 new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric, 156 CaptureDefault); 157 R->setMayHaveOutOfDateDef(false); 158 R->setImplicit(true); 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 destructors. 829 if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 830 SMKind |= SMF_Destructor; 831 832 if (DD->isUserProvided()) 833 data().HasIrrelevantDestructor = false; 834 // If the destructor is explicitly defaulted and not trivial or not public 835 // or if the destructor is deleted, we clear HasIrrelevantDestructor in 836 // finishedDefaultedOrDeletedMember. 837 838 // C++11 [class.dtor]p5: 839 // A destructor is trivial if [...] the destructor is not virtual. 840 if (DD->isVirtual()) { 841 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 842 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 843 } 844 845 if (DD->isNoReturn()) 846 data().IsAnyDestructorNoReturn = true; 847 } 848 849 // Handle member functions. 850 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 851 if (Method->isCopyAssignmentOperator()) { 852 SMKind |= SMF_CopyAssignment; 853 854 const auto *ParamTy = 855 Method->getParamDecl(0)->getType()->getAs<ReferenceType>(); 856 if (!ParamTy || ParamTy->getPointeeType().isConstQualified()) 857 data().HasDeclaredCopyAssignmentWithConstParam = true; 858 } 859 860 if (Method->isMoveAssignmentOperator()) 861 SMKind |= SMF_MoveAssignment; 862 863 // Keep the list of conversion functions up-to-date. 864 if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) { 865 // FIXME: We use the 'unsafe' accessor for the access specifier here, 866 // because Sema may not have set it yet. That's really just a misdesign 867 // in Sema. However, LLDB *will* have set the access specifier correctly, 868 // and adds declarations after the class is technically completed, 869 // so completeDefinition()'s overriding of the access specifiers doesn't 870 // work. 871 AccessSpecifier AS = Conversion->getAccessUnsafe(); 872 873 if (Conversion->getPrimaryTemplate()) { 874 // We don't record specializations. 875 } else { 876 ASTContext &Ctx = getASTContext(); 877 ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx); 878 NamedDecl *Primary = 879 FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion); 880 if (Primary->getPreviousDecl()) 881 Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()), 882 Primary, AS); 883 else 884 Conversions.addDecl(Ctx, Primary, AS); 885 } 886 } 887 888 if (SMKind) { 889 // If this is the first declaration of a special member, we no longer have 890 // an implicit trivial special member. 891 data().HasTrivialSpecialMembers &= 892 data().DeclaredSpecialMembers | ~SMKind; 893 data().HasTrivialSpecialMembersForCall &= 894 data().DeclaredSpecialMembers | ~SMKind; 895 896 if (!Method->isImplicit() && !Method->isUserProvided()) { 897 // This method is user-declared but not user-provided. We can't work out 898 // whether it's trivial yet (not until we get to the end of the class). 899 // We'll handle this method in finishedDefaultedOrDeletedMember. 900 } else if (Method->isTrivial()) { 901 data().HasTrivialSpecialMembers |= SMKind; 902 data().HasTrivialSpecialMembersForCall |= SMKind; 903 } else if (Method->isTrivialForCall()) { 904 data().HasTrivialSpecialMembersForCall |= SMKind; 905 data().DeclaredNonTrivialSpecialMembers |= SMKind; 906 } else { 907 data().DeclaredNonTrivialSpecialMembers |= SMKind; 908 // If this is a user-provided function, do not set 909 // DeclaredNonTrivialSpecialMembersForCall here since we don't know 910 // yet whether the method would be considered non-trivial for the 911 // purpose of calls (attribute "trivial_abi" can be dropped from the 912 // class later, which can change the special method's triviality). 913 if (!Method->isUserProvided()) 914 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 915 } 916 917 // Note when we have declared a declared special member, and suppress the 918 // implicit declaration of this special member. 919 data().DeclaredSpecialMembers |= SMKind; 920 921 if (!Method->isImplicit()) { 922 data().UserDeclaredSpecialMembers |= SMKind; 923 924 // C++03 [class]p4: 925 // A POD-struct is an aggregate class that has [...] no user-defined 926 // copy assignment operator and no user-defined destructor. 927 // 928 // Since the POD bit is meant to be C++03 POD-ness, and in C++03, 929 // aggregates could not have any constructors, clear it even for an 930 // explicitly defaulted or deleted constructor. 931 // type is technically an aggregate in C++0x since it wouldn't be in 03. 932 // 933 // Also, a user-declared move assignment operator makes a class non-POD. 934 // This is an extension in C++03. 935 data().PlainOldData = false; 936 } 937 } 938 939 return; 940 } 941 942 // Handle non-static data members. 943 if (const auto *Field = dyn_cast<FieldDecl>(D)) { 944 ASTContext &Context = getASTContext(); 945 946 // C++2a [class]p7: 947 // A standard-layout class is a class that: 948 // [...] 949 // -- has all non-static data members and bit-fields in the class and 950 // its base classes first declared in the same class 951 if (data().HasBasesWithFields) 952 data().IsStandardLayout = false; 953 954 // C++ [class.bit]p2: 955 // A declaration for a bit-field that omits the identifier declares an 956 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 957 // initialized. 958 if (Field->isUnnamedBitfield()) { 959 // C++ [meta.unary.prop]p4: [LWG2358] 960 // T is a class type [...] with [...] no unnamed bit-fields of non-zero 961 // length 962 if (data().Empty && !Field->isZeroLengthBitField(Context) && 963 Context.getLangOpts().getClangABICompat() > 964 LangOptions::ClangABI::Ver6) 965 data().Empty = false; 966 return; 967 } 968 969 // C++11 [class]p7: 970 // A standard-layout class is a class that: 971 // -- either has no non-static data members in the most derived class 972 // [...] or has no base classes with non-static data members 973 if (data().HasBasesWithNonStaticDataMembers) 974 data().IsCXX11StandardLayout = false; 975 976 // C++ [dcl.init.aggr]p1: 977 // An aggregate is an array or a class (clause 9) with [...] no 978 // private or protected non-static data members (clause 11). 979 // 980 // A POD must be an aggregate. 981 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { 982 data().Aggregate = false; 983 data().PlainOldData = false; 984 985 // C++20 [temp.param]p7: 986 // A structural type is [...] a literal class type [for which] all 987 // non-static data members are public 988 data().StructuralIfLiteral = false; 989 } 990 991 // Track whether this is the first field. We use this when checking 992 // whether the class is standard-layout below. 993 bool IsFirstField = !data().HasPrivateFields && 994 !data().HasProtectedFields && !data().HasPublicFields; 995 996 // C++0x [class]p7: 997 // A standard-layout class is a class that: 998 // [...] 999 // -- has the same access control for all non-static data members, 1000 switch (D->getAccess()) { 1001 case AS_private: data().HasPrivateFields = true; break; 1002 case AS_protected: data().HasProtectedFields = true; break; 1003 case AS_public: data().HasPublicFields = true; break; 1004 case AS_none: llvm_unreachable("Invalid access specifier"); 1005 }; 1006 if ((data().HasPrivateFields + data().HasProtectedFields + 1007 data().HasPublicFields) > 1) { 1008 data().IsStandardLayout = false; 1009 data().IsCXX11StandardLayout = false; 1010 } 1011 1012 // Keep track of the presence of mutable fields. 1013 if (Field->isMutable()) { 1014 data().HasMutableFields = true; 1015 1016 // C++20 [temp.param]p7: 1017 // A structural type is [...] a literal class type [for which] all 1018 // non-static data members are public 1019 data().StructuralIfLiteral = false; 1020 } 1021 1022 // C++11 [class.union]p8, DR1460: 1023 // If X is a union, a non-static data member of X that is not an anonymous 1024 // union is a variant member of X. 1025 if (isUnion() && !Field->isAnonymousStructOrUnion()) 1026 data().HasVariantMembers = true; 1027 1028 // C++0x [class]p9: 1029 // A POD struct is a class that is both a trivial class and a 1030 // standard-layout class, and has no non-static data members of type 1031 // non-POD struct, non-POD union (or array of such types). 1032 // 1033 // Automatic Reference Counting: the presence of a member of Objective-C pointer type 1034 // that does not explicitly have no lifetime makes the class a non-POD. 1035 QualType T = Context.getBaseElementType(Field->getType()); 1036 if (T->isObjCRetainableType() || T.isObjCGCStrong()) { 1037 if (T.hasNonTrivialObjCLifetime()) { 1038 // Objective-C Automatic Reference Counting: 1039 // If a class has a non-static data member of Objective-C pointer 1040 // type (or array thereof), it is a non-POD type and its 1041 // default constructor (if any), copy constructor, move constructor, 1042 // copy assignment operator, move assignment operator, and destructor are 1043 // non-trivial. 1044 setHasObjectMember(true); 1045 struct DefinitionData &Data = data(); 1046 Data.PlainOldData = false; 1047 Data.HasTrivialSpecialMembers = 0; 1048 1049 // __strong or __weak fields do not make special functions non-trivial 1050 // for the purpose of calls. 1051 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime(); 1052 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak) 1053 data().HasTrivialSpecialMembersForCall = 0; 1054 1055 // Structs with __weak fields should never be passed directly. 1056 if (LT == Qualifiers::OCL_Weak) 1057 setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 1058 1059 Data.HasIrrelevantDestructor = false; 1060 1061 if (isUnion()) { 1062 data().DefaultedCopyConstructorIsDeleted = true; 1063 data().DefaultedMoveConstructorIsDeleted = true; 1064 data().DefaultedCopyAssignmentIsDeleted = true; 1065 data().DefaultedMoveAssignmentIsDeleted = true; 1066 data().DefaultedDestructorIsDeleted = true; 1067 data().NeedOverloadResolutionForCopyConstructor = true; 1068 data().NeedOverloadResolutionForMoveConstructor = true; 1069 data().NeedOverloadResolutionForCopyAssignment = true; 1070 data().NeedOverloadResolutionForMoveAssignment = true; 1071 data().NeedOverloadResolutionForDestructor = true; 1072 } 1073 } else if (!Context.getLangOpts().ObjCAutoRefCount) { 1074 setHasObjectMember(true); 1075 } 1076 } else if (!T.isCXX98PODType(Context)) 1077 data().PlainOldData = false; 1078 1079 if (T->isReferenceType()) { 1080 if (!Field->hasInClassInitializer()) 1081 data().HasUninitializedReferenceMember = true; 1082 1083 // C++0x [class]p7: 1084 // A standard-layout class is a class that: 1085 // -- has no non-static data members of type [...] reference, 1086 data().IsStandardLayout = false; 1087 data().IsCXX11StandardLayout = false; 1088 1089 // C++1z [class.copy.ctor]p10: 1090 // A defaulted copy constructor for a class X is defined as deleted if X has: 1091 // -- a non-static data member of rvalue reference type 1092 if (T->isRValueReferenceType()) 1093 data().DefaultedCopyConstructorIsDeleted = true; 1094 } 1095 1096 if (!Field->hasInClassInitializer() && !Field->isMutable()) { 1097 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) { 1098 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit()) 1099 data().HasUninitializedFields = true; 1100 } else { 1101 data().HasUninitializedFields = true; 1102 } 1103 } 1104 1105 // Record if this field is the first non-literal or volatile field or base. 1106 if (!T->isLiteralType(Context) || T.isVolatileQualified()) 1107 data().HasNonLiteralTypeFieldsOrBases = true; 1108 1109 if (Field->hasInClassInitializer() || 1110 (Field->isAnonymousStructOrUnion() && 1111 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) { 1112 data().HasInClassInitializer = true; 1113 1114 // C++11 [class]p5: 1115 // A default constructor is trivial if [...] no non-static data member 1116 // of its class has a brace-or-equal-initializer. 1117 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1118 1119 // C++11 [dcl.init.aggr]p1: 1120 // An aggregate is a [...] class with [...] no 1121 // brace-or-equal-initializers for non-static data members. 1122 // 1123 // This rule was removed in C++14. 1124 if (!getASTContext().getLangOpts().CPlusPlus14) 1125 data().Aggregate = false; 1126 1127 // C++11 [class]p10: 1128 // A POD struct is [...] a trivial class. 1129 data().PlainOldData = false; 1130 } 1131 1132 // C++11 [class.copy]p23: 1133 // A defaulted copy/move assignment operator for a class X is defined 1134 // as deleted if X has: 1135 // -- a non-static data member of reference type 1136 if (T->isReferenceType()) { 1137 data().DefaultedCopyAssignmentIsDeleted = true; 1138 data().DefaultedMoveAssignmentIsDeleted = true; 1139 } 1140 1141 // Bitfields of length 0 are also zero-sized, but we already bailed out for 1142 // those because they are always unnamed. 1143 bool IsZeroSize = Field->isZeroSize(Context); 1144 1145 if (const auto *RecordTy = T->getAs<RecordType>()) { 1146 auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl()); 1147 if (FieldRec->getDefinition()) { 1148 addedClassSubobject(FieldRec); 1149 1150 // We may need to perform overload resolution to determine whether a 1151 // field can be moved if it's const or volatile qualified. 1152 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) { 1153 // We need to care about 'const' for the copy constructor because an 1154 // implicit copy constructor might be declared with a non-const 1155 // parameter. 1156 data().NeedOverloadResolutionForCopyConstructor = true; 1157 data().NeedOverloadResolutionForMoveConstructor = true; 1158 data().NeedOverloadResolutionForCopyAssignment = true; 1159 data().NeedOverloadResolutionForMoveAssignment = true; 1160 } 1161 1162 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 1163 // A defaulted [special member] for a class X is defined as 1164 // deleted if: 1165 // -- X is a union-like class that has a variant member with a 1166 // non-trivial [corresponding special member] 1167 if (isUnion()) { 1168 if (FieldRec->hasNonTrivialCopyConstructor()) 1169 data().DefaultedCopyConstructorIsDeleted = true; 1170 if (FieldRec->hasNonTrivialMoveConstructor()) 1171 data().DefaultedMoveConstructorIsDeleted = true; 1172 if (FieldRec->hasNonTrivialCopyAssignment()) 1173 data().DefaultedCopyAssignmentIsDeleted = true; 1174 if (FieldRec->hasNonTrivialMoveAssignment()) 1175 data().DefaultedMoveAssignmentIsDeleted = true; 1176 if (FieldRec->hasNonTrivialDestructor()) 1177 data().DefaultedDestructorIsDeleted = true; 1178 } 1179 1180 // For an anonymous union member, our overload resolution will perform 1181 // overload resolution for its members. 1182 if (Field->isAnonymousStructOrUnion()) { 1183 data().NeedOverloadResolutionForCopyConstructor |= 1184 FieldRec->data().NeedOverloadResolutionForCopyConstructor; 1185 data().NeedOverloadResolutionForMoveConstructor |= 1186 FieldRec->data().NeedOverloadResolutionForMoveConstructor; 1187 data().NeedOverloadResolutionForCopyAssignment |= 1188 FieldRec->data().NeedOverloadResolutionForCopyAssignment; 1189 data().NeedOverloadResolutionForMoveAssignment |= 1190 FieldRec->data().NeedOverloadResolutionForMoveAssignment; 1191 data().NeedOverloadResolutionForDestructor |= 1192 FieldRec->data().NeedOverloadResolutionForDestructor; 1193 } 1194 1195 // C++0x [class.ctor]p5: 1196 // A default constructor is trivial [...] if: 1197 // -- for all the non-static data members of its class that are of 1198 // class type (or array thereof), each such class has a trivial 1199 // default constructor. 1200 if (!FieldRec->hasTrivialDefaultConstructor()) 1201 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1202 1203 // C++0x [class.copy]p13: 1204 // A copy/move constructor for class X is trivial if [...] 1205 // [...] 1206 // -- for each non-static data member of X that is of class type (or 1207 // an array thereof), the constructor selected to copy/move that 1208 // member is trivial; 1209 if (!FieldRec->hasTrivialCopyConstructor()) 1210 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; 1211 1212 if (!FieldRec->hasTrivialCopyConstructorForCall()) 1213 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; 1214 1215 // If the field doesn't have a simple move constructor, we'll eagerly 1216 // declare the move constructor for this class and we'll decide whether 1217 // it's trivial then. 1218 if (!FieldRec->hasTrivialMoveConstructor()) 1219 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; 1220 1221 if (!FieldRec->hasTrivialMoveConstructorForCall()) 1222 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; 1223 1224 // C++0x [class.copy]p27: 1225 // A copy/move assignment operator for class X is trivial if [...] 1226 // [...] 1227 // -- for each non-static data member of X that is of class type (or 1228 // an array thereof), the assignment operator selected to 1229 // copy/move that member is trivial; 1230 if (!FieldRec->hasTrivialCopyAssignment()) 1231 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; 1232 // If the field doesn't have a simple move assignment, we'll eagerly 1233 // declare the move assignment for this class and we'll decide whether 1234 // it's trivial then. 1235 if (!FieldRec->hasTrivialMoveAssignment()) 1236 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; 1237 1238 if (!FieldRec->hasTrivialDestructor()) 1239 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 1240 if (!FieldRec->hasTrivialDestructorForCall()) 1241 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 1242 if (!FieldRec->hasIrrelevantDestructor()) 1243 data().HasIrrelevantDestructor = false; 1244 if (FieldRec->isAnyDestructorNoReturn()) 1245 data().IsAnyDestructorNoReturn = true; 1246 if (FieldRec->hasObjectMember()) 1247 setHasObjectMember(true); 1248 if (FieldRec->hasVolatileMember()) 1249 setHasVolatileMember(true); 1250 if (FieldRec->getArgPassingRestrictions() == 1251 RecordDecl::APK_CanNeverPassInRegs) 1252 setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 1253 1254 // C++0x [class]p7: 1255 // A standard-layout class is a class that: 1256 // -- has no non-static data members of type non-standard-layout 1257 // class (or array of such types) [...] 1258 if (!FieldRec->isStandardLayout()) 1259 data().IsStandardLayout = false; 1260 if (!FieldRec->isCXX11StandardLayout()) 1261 data().IsCXX11StandardLayout = false; 1262 1263 // C++2a [class]p7: 1264 // A standard-layout class is a class that: 1265 // [...] 1266 // -- has no element of the set M(S) of types as a base class. 1267 if (data().IsStandardLayout && 1268 (isUnion() || IsFirstField || IsZeroSize) && 1269 hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec)) 1270 data().IsStandardLayout = false; 1271 1272 // C++11 [class]p7: 1273 // A standard-layout class is a class that: 1274 // -- has no base classes of the same type as the first non-static 1275 // data member 1276 if (data().IsCXX11StandardLayout && IsFirstField) { 1277 // FIXME: We should check all base classes here, not just direct 1278 // base classes. 1279 for (const auto &BI : bases()) { 1280 if (Context.hasSameUnqualifiedType(BI.getType(), T)) { 1281 data().IsCXX11StandardLayout = false; 1282 break; 1283 } 1284 } 1285 } 1286 1287 // Keep track of the presence of mutable fields. 1288 if (FieldRec->hasMutableFields()) 1289 data().HasMutableFields = true; 1290 1291 if (Field->isMutable()) { 1292 // Our copy constructor/assignment might call something other than 1293 // the subobject's copy constructor/assignment if it's mutable and of 1294 // class type. 1295 data().NeedOverloadResolutionForCopyConstructor = true; 1296 data().NeedOverloadResolutionForCopyAssignment = true; 1297 } 1298 1299 // C++11 [class.copy]p13: 1300 // If the implicitly-defined constructor would satisfy the 1301 // requirements of a constexpr constructor, the implicitly-defined 1302 // constructor is constexpr. 1303 // C++11 [dcl.constexpr]p4: 1304 // -- every constructor involved in initializing non-static data 1305 // members [...] shall be a constexpr constructor 1306 if (!Field->hasInClassInitializer() && 1307 !FieldRec->hasConstexprDefaultConstructor() && !isUnion()) 1308 // The standard requires any in-class initializer to be a constant 1309 // expression. We consider this to be a defect. 1310 data().DefaultedDefaultConstructorIsConstexpr = false; 1311 1312 // C++11 [class.copy]p8: 1313 // The implicitly-declared copy constructor for a class X will have 1314 // the form 'X::X(const X&)' if each potentially constructed subobject 1315 // of a class type M (or array thereof) has a copy constructor whose 1316 // first parameter is of type 'const M&' or 'const volatile M&'. 1317 if (!FieldRec->hasCopyConstructorWithConstParam()) 1318 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; 1319 1320 // C++11 [class.copy]p18: 1321 // The implicitly-declared copy assignment oeprator for a class X will 1322 // have the form 'X& X::operator=(const X&)' if [...] for all the 1323 // non-static data members of X that are of a class type M (or array 1324 // thereof), each such class type has a copy assignment operator whose 1325 // parameter is of type 'const M&', 'const volatile M&' or 'M'. 1326 if (!FieldRec->hasCopyAssignmentWithConstParam()) 1327 data().ImplicitCopyAssignmentHasConstParam = false; 1328 1329 if (FieldRec->hasUninitializedReferenceMember() && 1330 !Field->hasInClassInitializer()) 1331 data().HasUninitializedReferenceMember = true; 1332 1333 // C++11 [class.union]p8, DR1460: 1334 // a non-static data member of an anonymous union that is a member of 1335 // X is also a variant member of X. 1336 if (FieldRec->hasVariantMembers() && 1337 Field->isAnonymousStructOrUnion()) 1338 data().HasVariantMembers = true; 1339 } 1340 } else { 1341 // Base element type of field is a non-class type. 1342 if (!T->isLiteralType(Context) || 1343 (!Field->hasInClassInitializer() && !isUnion() && 1344 !Context.getLangOpts().CPlusPlus20)) 1345 data().DefaultedDefaultConstructorIsConstexpr = false; 1346 1347 // C++11 [class.copy]p23: 1348 // A defaulted copy/move assignment operator for a class X is defined 1349 // as deleted if X has: 1350 // -- a non-static data member of const non-class type (or array 1351 // thereof) 1352 if (T.isConstQualified()) { 1353 data().DefaultedCopyAssignmentIsDeleted = true; 1354 data().DefaultedMoveAssignmentIsDeleted = true; 1355 } 1356 1357 // C++20 [temp.param]p7: 1358 // A structural type is [...] a literal class type [for which] the 1359 // types of all non-static data members are structural types or 1360 // (possibly multidimensional) array thereof 1361 // We deal with class types elsewhere. 1362 if (!T->isStructuralType()) 1363 data().StructuralIfLiteral = false; 1364 } 1365 1366 // C++14 [meta.unary.prop]p4: 1367 // T is a class type [...] with [...] no non-static data members other 1368 // than subobjects of zero size 1369 if (data().Empty && !IsZeroSize) 1370 data().Empty = false; 1371 } 1372 1373 // Handle using declarations of conversion functions. 1374 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) { 1375 if (Shadow->getDeclName().getNameKind() 1376 == DeclarationName::CXXConversionFunctionName) { 1377 ASTContext &Ctx = getASTContext(); 1378 data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess()); 1379 } 1380 } 1381 1382 if (const auto *Using = dyn_cast<UsingDecl>(D)) { 1383 if (Using->getDeclName().getNameKind() == 1384 DeclarationName::CXXConstructorName) { 1385 data().HasInheritedConstructor = true; 1386 // C++1z [dcl.init.aggr]p1: 1387 // An aggregate is [...] a class [...] with no inherited constructors 1388 data().Aggregate = false; 1389 } 1390 1391 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal) 1392 data().HasInheritedAssignment = true; 1393 } 1394 } 1395 1396 void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) { 1397 assert(!D->isImplicit() && !D->isUserProvided()); 1398 1399 // The kind of special member this declaration is, if any. 1400 unsigned SMKind = 0; 1401 1402 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1403 if (Constructor->isDefaultConstructor()) { 1404 SMKind |= SMF_DefaultConstructor; 1405 if (Constructor->isConstexpr()) 1406 data().HasConstexprDefaultConstructor = true; 1407 } 1408 if (Constructor->isCopyConstructor()) 1409 SMKind |= SMF_CopyConstructor; 1410 else if (Constructor->isMoveConstructor()) 1411 SMKind |= SMF_MoveConstructor; 1412 else if (Constructor->isConstexpr()) 1413 // We may now know that the constructor is constexpr. 1414 data().HasConstexprNonCopyMoveConstructor = true; 1415 } else if (isa<CXXDestructorDecl>(D)) { 1416 SMKind |= SMF_Destructor; 1417 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted()) 1418 data().HasIrrelevantDestructor = false; 1419 } else if (D->isCopyAssignmentOperator()) 1420 SMKind |= SMF_CopyAssignment; 1421 else if (D->isMoveAssignmentOperator()) 1422 SMKind |= SMF_MoveAssignment; 1423 1424 // Update which trivial / non-trivial special members we have. 1425 // addedMember will have skipped this step for this member. 1426 if (D->isTrivial()) 1427 data().HasTrivialSpecialMembers |= SMKind; 1428 else 1429 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1430 } 1431 1432 void CXXRecordDecl::setCaptures(ASTContext &Context, 1433 ArrayRef<LambdaCapture> Captures) { 1434 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData(); 1435 1436 // Copy captures. 1437 Data.NumCaptures = Captures.size(); 1438 Data.NumExplicitCaptures = 0; 1439 Data.Captures = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) * 1440 Captures.size()); 1441 LambdaCapture *ToCapture = Data.Captures; 1442 for (unsigned I = 0, N = Captures.size(); I != N; ++I) { 1443 if (Captures[I].isExplicit()) 1444 ++Data.NumExplicitCaptures; 1445 1446 *ToCapture++ = Captures[I]; 1447 } 1448 1449 if (!lambdaIsDefaultConstructibleAndAssignable()) 1450 Data.DefaultedCopyAssignmentIsDeleted = true; 1451 } 1452 1453 void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) { 1454 unsigned SMKind = 0; 1455 1456 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1457 if (Constructor->isCopyConstructor()) 1458 SMKind = SMF_CopyConstructor; 1459 else if (Constructor->isMoveConstructor()) 1460 SMKind = SMF_MoveConstructor; 1461 } else if (isa<CXXDestructorDecl>(D)) 1462 SMKind = SMF_Destructor; 1463 1464 if (D->isTrivialForCall()) 1465 data().HasTrivialSpecialMembersForCall |= SMKind; 1466 else 1467 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 1468 } 1469 1470 bool CXXRecordDecl::isCLike() const { 1471 if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface || 1472 !TemplateOrInstantiation.isNull()) 1473 return false; 1474 if (!hasDefinition()) 1475 return true; 1476 1477 return isPOD() && data().HasOnlyCMembers; 1478 } 1479 1480 bool CXXRecordDecl::isGenericLambda() const { 1481 if (!isLambda()) return false; 1482 return getLambdaData().IsGenericLambda; 1483 } 1484 1485 #ifndef NDEBUG 1486 static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) { 1487 for (auto *D : R) 1488 if (!declaresSameEntity(D, R.front())) 1489 return false; 1490 return true; 1491 } 1492 #endif 1493 1494 static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) { 1495 if (!RD.isLambda()) return nullptr; 1496 DeclarationName Name = 1497 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); 1498 DeclContext::lookup_result Calls = RD.lookup(Name); 1499 1500 assert(!Calls.empty() && "Missing lambda call operator!"); 1501 assert(allLookupResultsAreTheSame(Calls) && 1502 "More than one lambda call operator!"); 1503 return Calls.front(); 1504 } 1505 1506 FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const { 1507 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1508 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp); 1509 } 1510 1511 CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const { 1512 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1513 1514 if (CallOp == nullptr) 1515 return nullptr; 1516 1517 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) 1518 return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); 1519 1520 return cast<CXXMethodDecl>(CallOp); 1521 } 1522 1523 CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { 1524 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1525 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv(); 1526 return getLambdaStaticInvoker(CC); 1527 } 1528 1529 static DeclContext::lookup_result 1530 getLambdaStaticInvokers(const CXXRecordDecl &RD) { 1531 assert(RD.isLambda() && "Must be a lambda"); 1532 DeclarationName Name = 1533 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName()); 1534 return RD.lookup(Name); 1535 } 1536 1537 static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) { 1538 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND)) 1539 return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); 1540 return cast<CXXMethodDecl>(ND); 1541 } 1542 1543 CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const { 1544 if (!isLambda()) 1545 return nullptr; 1546 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this); 1547 1548 for (NamedDecl *ND : Invoker) { 1549 const auto *FTy = 1550 cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>(); 1551 if (FTy->getCallConv() == CC) 1552 return getInvokerAsMethod(ND); 1553 } 1554 1555 return nullptr; 1556 } 1557 1558 void CXXRecordDecl::getCaptureFields( 1559 llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures, 1560 FieldDecl *&ThisCapture) const { 1561 Captures.clear(); 1562 ThisCapture = nullptr; 1563 1564 LambdaDefinitionData &Lambda = getLambdaData(); 1565 RecordDecl::field_iterator Field = field_begin(); 1566 for (const LambdaCapture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures; 1567 C != CEnd; ++C, ++Field) { 1568 if (C->capturesThis()) 1569 ThisCapture = *Field; 1570 else if (C->capturesVariable()) 1571 Captures[C->getCapturedVar()] = *Field; 1572 } 1573 assert(Field == field_end()); 1574 } 1575 1576 TemplateParameterList * 1577 CXXRecordDecl::getGenericLambdaTemplateParameterList() const { 1578 if (!isGenericLambda()) return nullptr; 1579 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1580 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) 1581 return Tmpl->getTemplateParameters(); 1582 return nullptr; 1583 } 1584 1585 ArrayRef<NamedDecl *> 1586 CXXRecordDecl::getLambdaExplicitTemplateParameters() const { 1587 TemplateParameterList *List = getGenericLambdaTemplateParameterList(); 1588 if (!List) 1589 return {}; 1590 1591 assert(std::is_partitioned(List->begin(), List->end(), 1592 [](const NamedDecl *D) { return !D->isImplicit(); }) 1593 && "Explicit template params should be ordered before implicit ones"); 1594 1595 const auto ExplicitEnd = llvm::partition_point( 1596 *List, [](const NamedDecl *D) { return !D->isImplicit(); }); 1597 return llvm::makeArrayRef(List->begin(), ExplicitEnd); 1598 } 1599 1600 Decl *CXXRecordDecl::getLambdaContextDecl() const { 1601 assert(isLambda() && "Not a lambda closure type!"); 1602 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1603 return getLambdaData().ContextDecl.get(Source); 1604 } 1605 1606 void CXXRecordDecl::setDeviceLambdaManglingNumber(unsigned Num) const { 1607 assert(isLambda() && "Not a lambda closure type!"); 1608 if (Num) 1609 getASTContext().DeviceLambdaManglingNumbers[this] = Num; 1610 } 1611 1612 unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const { 1613 assert(isLambda() && "Not a lambda closure type!"); 1614 auto I = getASTContext().DeviceLambdaManglingNumbers.find(this); 1615 if (I != getASTContext().DeviceLambdaManglingNumbers.end()) 1616 return I->second; 1617 return 0; 1618 } 1619 1620 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) { 1621 QualType T = 1622 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction()) 1623 ->getConversionType(); 1624 return Context.getCanonicalType(T); 1625 } 1626 1627 /// Collect the visible conversions of a base class. 1628 /// 1629 /// \param Record a base class of the class we're considering 1630 /// \param InVirtual whether this base class is a virtual base (or a base 1631 /// of a virtual base) 1632 /// \param Access the access along the inheritance path to this base 1633 /// \param ParentHiddenTypes the conversions provided by the inheritors 1634 /// of this base 1635 /// \param Output the set to which to add conversions from non-virtual bases 1636 /// \param VOutput the set to which to add conversions from virtual bases 1637 /// \param HiddenVBaseCs the set of conversions which were hidden in a 1638 /// virtual base along some inheritance path 1639 static void CollectVisibleConversions( 1640 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual, 1641 AccessSpecifier Access, 1642 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes, 1643 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput, 1644 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) { 1645 // The set of types which have conversions in this class or its 1646 // subclasses. As an optimization, we don't copy the derived set 1647 // unless it might change. 1648 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes; 1649 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer; 1650 1651 // Collect the direct conversions and figure out which conversions 1652 // will be hidden in the subclasses. 1653 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1654 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1655 if (ConvI != ConvE) { 1656 HiddenTypesBuffer = ParentHiddenTypes; 1657 HiddenTypes = &HiddenTypesBuffer; 1658 1659 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) { 1660 CanQualType ConvType(GetConversionType(Context, I.getDecl())); 1661 bool Hidden = ParentHiddenTypes.count(ConvType); 1662 if (!Hidden) 1663 HiddenTypesBuffer.insert(ConvType); 1664 1665 // If this conversion is hidden and we're in a virtual base, 1666 // remember that it's hidden along some inheritance path. 1667 if (Hidden && InVirtual) 1668 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())); 1669 1670 // If this conversion isn't hidden, add it to the appropriate output. 1671 else if (!Hidden) { 1672 AccessSpecifier IAccess 1673 = CXXRecordDecl::MergeAccess(Access, I.getAccess()); 1674 1675 if (InVirtual) 1676 VOutput.addDecl(I.getDecl(), IAccess); 1677 else 1678 Output.addDecl(Context, I.getDecl(), IAccess); 1679 } 1680 } 1681 } 1682 1683 // Collect information recursively from any base classes. 1684 for (const auto &I : Record->bases()) { 1685 const auto *RT = I.getType()->getAs<RecordType>(); 1686 if (!RT) continue; 1687 1688 AccessSpecifier BaseAccess 1689 = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); 1690 bool BaseInVirtual = InVirtual || I.isVirtual(); 1691 1692 auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 1693 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess, 1694 *HiddenTypes, Output, VOutput, HiddenVBaseCs); 1695 } 1696 } 1697 1698 /// Collect the visible conversions of a class. 1699 /// 1700 /// This would be extremely straightforward if it weren't for virtual 1701 /// bases. It might be worth special-casing that, really. 1702 static void CollectVisibleConversions(ASTContext &Context, 1703 const CXXRecordDecl *Record, 1704 ASTUnresolvedSet &Output) { 1705 // The collection of all conversions in virtual bases that we've 1706 // found. These will be added to the output as long as they don't 1707 // appear in the hidden-conversions set. 1708 UnresolvedSet<8> VBaseCs; 1709 1710 // The set of conversions in virtual bases that we've determined to 1711 // be hidden. 1712 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; 1713 1714 // The set of types hidden by classes derived from this one. 1715 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes; 1716 1717 // Go ahead and collect the direct conversions and add them to the 1718 // hidden-types set. 1719 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1720 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1721 Output.append(Context, ConvI, ConvE); 1722 for (; ConvI != ConvE; ++ConvI) 1723 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl())); 1724 1725 // Recursively collect conversions from base classes. 1726 for (const auto &I : Record->bases()) { 1727 const auto *RT = I.getType()->getAs<RecordType>(); 1728 if (!RT) continue; 1729 1730 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()), 1731 I.isVirtual(), I.getAccessSpecifier(), 1732 HiddenTypes, Output, VBaseCs, HiddenVBaseCs); 1733 } 1734 1735 // Add any unhidden conversions provided by virtual bases. 1736 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); 1737 I != E; ++I) { 1738 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()))) 1739 Output.addDecl(Context, I.getDecl(), I.getAccess()); 1740 } 1741 } 1742 1743 /// getVisibleConversionFunctions - get all conversion functions visible 1744 /// in current class; including conversion function templates. 1745 llvm::iterator_range<CXXRecordDecl::conversion_iterator> 1746 CXXRecordDecl::getVisibleConversionFunctions() const { 1747 ASTContext &Ctx = getASTContext(); 1748 1749 ASTUnresolvedSet *Set; 1750 if (bases_begin() == bases_end()) { 1751 // If root class, all conversions are visible. 1752 Set = &data().Conversions.get(Ctx); 1753 } else { 1754 Set = &data().VisibleConversions.get(Ctx); 1755 // If visible conversion list is not evaluated, evaluate it. 1756 if (!data().ComputedVisibleConversions) { 1757 CollectVisibleConversions(Ctx, this, *Set); 1758 data().ComputedVisibleConversions = true; 1759 } 1760 } 1761 return llvm::make_range(Set->begin(), Set->end()); 1762 } 1763 1764 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) { 1765 // This operation is O(N) but extremely rare. Sema only uses it to 1766 // remove UsingShadowDecls in a class that were followed by a direct 1767 // declaration, e.g.: 1768 // class A : B { 1769 // using B::operator int; 1770 // operator int(); 1771 // }; 1772 // This is uncommon by itself and even more uncommon in conjunction 1773 // with sufficiently large numbers of directly-declared conversions 1774 // that asymptotic behavior matters. 1775 1776 ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext()); 1777 for (unsigned I = 0, E = Convs.size(); I != E; ++I) { 1778 if (Convs[I].getDecl() == ConvDecl) { 1779 Convs.erase(I); 1780 assert(!llvm::is_contained(Convs, ConvDecl) && 1781 "conversion was found multiple times in unresolved set"); 1782 return; 1783 } 1784 } 1785 1786 llvm_unreachable("conversion not found in set!"); 1787 } 1788 1789 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const { 1790 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1791 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom()); 1792 1793 return nullptr; 1794 } 1795 1796 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const { 1797 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>(); 1798 } 1799 1800 void 1801 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, 1802 TemplateSpecializationKind TSK) { 1803 assert(TemplateOrInstantiation.isNull() && 1804 "Previous template or instantiation?"); 1805 assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); 1806 TemplateOrInstantiation 1807 = new (getASTContext()) MemberSpecializationInfo(RD, TSK); 1808 } 1809 1810 ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const { 1811 return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>(); 1812 } 1813 1814 void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) { 1815 TemplateOrInstantiation = Template; 1816 } 1817 1818 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ 1819 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) 1820 return Spec->getSpecializationKind(); 1821 1822 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1823 return MSInfo->getTemplateSpecializationKind(); 1824 1825 return TSK_Undeclared; 1826 } 1827 1828 void 1829 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { 1830 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1831 Spec->setSpecializationKind(TSK); 1832 return; 1833 } 1834 1835 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1836 MSInfo->setTemplateSpecializationKind(TSK); 1837 return; 1838 } 1839 1840 llvm_unreachable("Not a class template or member class specialization"); 1841 } 1842 1843 const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const { 1844 auto GetDefinitionOrSelf = 1845 [](const CXXRecordDecl *D) -> const CXXRecordDecl * { 1846 if (auto *Def = D->getDefinition()) 1847 return Def; 1848 return D; 1849 }; 1850 1851 // If it's a class template specialization, find the template or partial 1852 // specialization from which it was instantiated. 1853 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1854 auto From = TD->getInstantiatedFrom(); 1855 if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) { 1856 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) { 1857 if (NewCTD->isMemberSpecialization()) 1858 break; 1859 CTD = NewCTD; 1860 } 1861 return GetDefinitionOrSelf(CTD->getTemplatedDecl()); 1862 } 1863 if (auto *CTPSD = 1864 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 1865 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) { 1866 if (NewCTPSD->isMemberSpecialization()) 1867 break; 1868 CTPSD = NewCTPSD; 1869 } 1870 return GetDefinitionOrSelf(CTPSD); 1871 } 1872 } 1873 1874 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1875 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 1876 const CXXRecordDecl *RD = this; 1877 while (auto *NewRD = RD->getInstantiatedFromMemberClass()) 1878 RD = NewRD; 1879 return GetDefinitionOrSelf(RD); 1880 } 1881 } 1882 1883 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) && 1884 "couldn't find pattern for class template instantiation"); 1885 return nullptr; 1886 } 1887 1888 CXXDestructorDecl *CXXRecordDecl::getDestructor() const { 1889 ASTContext &Context = getASTContext(); 1890 QualType ClassType = Context.getTypeDeclType(this); 1891 1892 DeclarationName Name 1893 = Context.DeclarationNames.getCXXDestructorName( 1894 Context.getCanonicalType(ClassType)); 1895 1896 DeclContext::lookup_result R = lookup(Name); 1897 1898 return R.empty() ? nullptr : dyn_cast<CXXDestructorDecl>(R.front()); 1899 } 1900 1901 static bool isDeclContextInNamespace(const DeclContext *DC) { 1902 while (!DC->isTranslationUnit()) { 1903 if (DC->isNamespace()) 1904 return true; 1905 DC = DC->getParent(); 1906 } 1907 return false; 1908 } 1909 1910 bool CXXRecordDecl::isInterfaceLike() const { 1911 assert(hasDefinition() && "checking for interface-like without a definition"); 1912 // All __interfaces are inheritently interface-like. 1913 if (isInterface()) 1914 return true; 1915 1916 // Interface-like types cannot have a user declared constructor, destructor, 1917 // friends, VBases, conversion functions, or fields. Additionally, lambdas 1918 // cannot be interface types. 1919 if (isLambda() || hasUserDeclaredConstructor() || 1920 hasUserDeclaredDestructor() || !field_empty() || hasFriends() || 1921 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0) 1922 return false; 1923 1924 // No interface-like type can have a method with a definition. 1925 for (const auto *const Method : methods()) 1926 if (Method->isDefined() && !Method->isImplicit()) 1927 return false; 1928 1929 // Check "Special" types. 1930 const auto *Uuid = getAttr<UuidAttr>(); 1931 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an 1932 // extern C++ block directly in the TU. These are only valid if in one 1933 // of these two situations. 1934 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() && 1935 !isDeclContextInNamespace(getDeclContext()) && 1936 ((getName() == "IUnknown" && 1937 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") || 1938 (getName() == "IDispatch" && 1939 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) { 1940 if (getNumBases() > 0) 1941 return false; 1942 return true; 1943 } 1944 1945 // FIXME: Any access specifiers is supposed to make this no longer interface 1946 // like. 1947 1948 // If this isn't a 'special' type, it must have a single interface-like base. 1949 if (getNumBases() != 1) 1950 return false; 1951 1952 const auto BaseSpec = *bases_begin(); 1953 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public) 1954 return false; 1955 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 1956 if (Base->isInterface() || !Base->isInterfaceLike()) 1957 return false; 1958 return true; 1959 } 1960 1961 void CXXRecordDecl::completeDefinition() { 1962 completeDefinition(nullptr); 1963 } 1964 1965 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { 1966 RecordDecl::completeDefinition(); 1967 1968 // If the class may be abstract (but hasn't been marked as such), check for 1969 // any pure final overriders. 1970 if (mayBeAbstract()) { 1971 CXXFinalOverriderMap MyFinalOverriders; 1972 if (!FinalOverriders) { 1973 getFinalOverriders(MyFinalOverriders); 1974 FinalOverriders = &MyFinalOverriders; 1975 } 1976 1977 bool Done = false; 1978 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), 1979 MEnd = FinalOverriders->end(); 1980 M != MEnd && !Done; ++M) { 1981 for (OverridingMethods::iterator SO = M->second.begin(), 1982 SOEnd = M->second.end(); 1983 SO != SOEnd && !Done; ++SO) { 1984 assert(SO->second.size() > 0 && 1985 "All virtual functions have overriding virtual functions"); 1986 1987 // C++ [class.abstract]p4: 1988 // A class is abstract if it contains or inherits at least one 1989 // pure virtual function for which the final overrider is pure 1990 // virtual. 1991 if (SO->second.front().Method->isPure()) { 1992 data().Abstract = true; 1993 Done = true; 1994 break; 1995 } 1996 } 1997 } 1998 } 1999 2000 // Set access bits correctly on the directly-declared conversions. 2001 for (conversion_iterator I = conversion_begin(), E = conversion_end(); 2002 I != E; ++I) 2003 I.setAccess((*I)->getAccess()); 2004 } 2005 2006 bool CXXRecordDecl::mayBeAbstract() const { 2007 if (data().Abstract || isInvalidDecl() || !data().Polymorphic || 2008 isDependentContext()) 2009 return false; 2010 2011 for (const auto &B : bases()) { 2012 const auto *BaseDecl = 2013 cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl()); 2014 if (BaseDecl->isAbstract()) 2015 return true; 2016 } 2017 2018 return false; 2019 } 2020 2021 bool CXXRecordDecl::isEffectivelyFinal() const { 2022 auto *Def = getDefinition(); 2023 if (!Def) 2024 return false; 2025 if (Def->hasAttr<FinalAttr>()) 2026 return true; 2027 if (const auto *Dtor = Def->getDestructor()) 2028 if (Dtor->hasAttr<FinalAttr>()) 2029 return true; 2030 return false; 2031 } 2032 2033 void CXXDeductionGuideDecl::anchor() {} 2034 2035 bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const { 2036 if ((getKind() != Other.getKind() || 2037 getKind() == ExplicitSpecKind::Unresolved)) { 2038 if (getKind() == ExplicitSpecKind::Unresolved && 2039 Other.getKind() == ExplicitSpecKind::Unresolved) { 2040 ODRHash SelfHash, OtherHash; 2041 SelfHash.AddStmt(getExpr()); 2042 OtherHash.AddStmt(Other.getExpr()); 2043 return SelfHash.CalculateHash() == OtherHash.CalculateHash(); 2044 } else 2045 return false; 2046 } 2047 return true; 2048 } 2049 2050 ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) { 2051 switch (Function->getDeclKind()) { 2052 case Decl::Kind::CXXConstructor: 2053 return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier(); 2054 case Decl::Kind::CXXConversion: 2055 return cast<CXXConversionDecl>(Function)->getExplicitSpecifier(); 2056 case Decl::Kind::CXXDeductionGuide: 2057 return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier(); 2058 default: 2059 return {}; 2060 } 2061 } 2062 2063 CXXDeductionGuideDecl * 2064 CXXDeductionGuideDecl::Create(ASTContext &C, DeclContext *DC, 2065 SourceLocation StartLoc, ExplicitSpecifier ES, 2066 const DeclarationNameInfo &NameInfo, QualType T, 2067 TypeSourceInfo *TInfo, SourceLocation EndLocation, 2068 CXXConstructorDecl *Ctor) { 2069 return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T, 2070 TInfo, EndLocation, Ctor); 2071 } 2072 2073 CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, 2074 unsigned ID) { 2075 return new (C, ID) CXXDeductionGuideDecl( 2076 C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(), 2077 QualType(), nullptr, SourceLocation(), nullptr); 2078 } 2079 2080 RequiresExprBodyDecl *RequiresExprBodyDecl::Create( 2081 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) { 2082 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc); 2083 } 2084 2085 RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, 2086 unsigned ID) { 2087 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation()); 2088 } 2089 2090 void CXXMethodDecl::anchor() {} 2091 2092 bool CXXMethodDecl::isStatic() const { 2093 const CXXMethodDecl *MD = getCanonicalDecl(); 2094 2095 if (MD->getStorageClass() == SC_Static) 2096 return true; 2097 2098 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator(); 2099 return isStaticOverloadedOperator(OOK); 2100 } 2101 2102 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD, 2103 const CXXMethodDecl *BaseMD) { 2104 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) { 2105 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl()) 2106 return true; 2107 if (recursivelyOverrides(MD, BaseMD)) 2108 return true; 2109 } 2110 return false; 2111 } 2112 2113 CXXMethodDecl * 2114 CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, 2115 bool MayBeBase) { 2116 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl()) 2117 return this; 2118 2119 // Lookup doesn't work for destructors, so handle them separately. 2120 if (isa<CXXDestructorDecl>(this)) { 2121 CXXMethodDecl *MD = RD->getDestructor(); 2122 if (MD) { 2123 if (recursivelyOverrides(MD, this)) 2124 return MD; 2125 if (MayBeBase && recursivelyOverrides(this, MD)) 2126 return MD; 2127 } 2128 return nullptr; 2129 } 2130 2131 for (auto *ND : RD->lookup(getDeclName())) { 2132 auto *MD = dyn_cast<CXXMethodDecl>(ND); 2133 if (!MD) 2134 continue; 2135 if (recursivelyOverrides(MD, this)) 2136 return MD; 2137 if (MayBeBase && recursivelyOverrides(this, MD)) 2138 return MD; 2139 } 2140 2141 return nullptr; 2142 } 2143 2144 CXXMethodDecl * 2145 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD, 2146 bool MayBeBase) { 2147 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase)) 2148 return MD; 2149 2150 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders; 2151 auto AddFinalOverrider = [&](CXXMethodDecl *D) { 2152 // If this function is overridden by a candidate final overrider, it is not 2153 // a final overrider. 2154 for (CXXMethodDecl *OtherD : FinalOverriders) { 2155 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D)) 2156 return; 2157 } 2158 2159 // Other candidate final overriders might be overridden by this function. 2160 llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) { 2161 return recursivelyOverrides(D, OtherD); 2162 }); 2163 2164 FinalOverriders.push_back(D); 2165 }; 2166 2167 for (const auto &I : RD->bases()) { 2168 const RecordType *RT = I.getType()->getAs<RecordType>(); 2169 if (!RT) 2170 continue; 2171 const auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 2172 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base)) 2173 AddFinalOverrider(D); 2174 } 2175 2176 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr; 2177 } 2178 2179 CXXMethodDecl * 2180 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2181 const DeclarationNameInfo &NameInfo, QualType T, 2182 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 2183 bool isInline, ConstexprSpecKind ConstexprKind, 2184 SourceLocation EndLocation, 2185 Expr *TrailingRequiresClause) { 2186 return new (C, RD) CXXMethodDecl( 2187 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 2188 isInline, ConstexprKind, EndLocation, TrailingRequiresClause); 2189 } 2190 2191 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2192 return new (C, ID) CXXMethodDecl( 2193 CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(), 2194 QualType(), nullptr, SC_None, false, false, 2195 ConstexprSpecKind::Unspecified, SourceLocation(), nullptr); 2196 } 2197 2198 CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base, 2199 bool IsAppleKext) { 2200 assert(isVirtual() && "this method is expected to be virtual"); 2201 2202 // When building with -fapple-kext, all calls must go through the vtable since 2203 // the kernel linker can do runtime patching of vtables. 2204 if (IsAppleKext) 2205 return nullptr; 2206 2207 // If the member function is marked 'final', we know that it can't be 2208 // overridden and can therefore devirtualize it unless it's pure virtual. 2209 if (hasAttr<FinalAttr>()) 2210 return isPure() ? nullptr : this; 2211 2212 // If Base is unknown, we cannot devirtualize. 2213 if (!Base) 2214 return nullptr; 2215 2216 // If the base expression (after skipping derived-to-base conversions) is a 2217 // class prvalue, then we can devirtualize. 2218 Base = Base->getBestDynamicClassTypeExpr(); 2219 if (Base->isPRValue() && Base->getType()->isRecordType()) 2220 return this; 2221 2222 // If we don't even know what we would call, we can't devirtualize. 2223 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2224 if (!BestDynamicDecl) 2225 return nullptr; 2226 2227 // There may be a method corresponding to MD in a derived class. 2228 CXXMethodDecl *DevirtualizedMethod = 2229 getCorrespondingMethodInClass(BestDynamicDecl); 2230 2231 // If there final overrider in the dynamic type is ambiguous, we can't 2232 // devirtualize this call. 2233 if (!DevirtualizedMethod) 2234 return nullptr; 2235 2236 // If that method is pure virtual, we can't devirtualize. If this code is 2237 // reached, the result would be UB, not a direct call to the derived class 2238 // function, and we can't assume the derived class function is defined. 2239 if (DevirtualizedMethod->isPure()) 2240 return nullptr; 2241 2242 // If that method is marked final, we can devirtualize it. 2243 if (DevirtualizedMethod->hasAttr<FinalAttr>()) 2244 return DevirtualizedMethod; 2245 2246 // Similarly, if the class itself or its destructor is marked 'final', 2247 // the class can't be derived from and we can therefore devirtualize the 2248 // member function call. 2249 if (BestDynamicDecl->isEffectivelyFinal()) 2250 return DevirtualizedMethod; 2251 2252 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) { 2253 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2254 if (VD->getType()->isRecordType()) 2255 // This is a record decl. We know the type and can devirtualize it. 2256 return DevirtualizedMethod; 2257 2258 return nullptr; 2259 } 2260 2261 // We can devirtualize calls on an object accessed by a class member access 2262 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2263 // a derived class object constructed in the same location. 2264 if (const auto *ME = dyn_cast<MemberExpr>(Base)) { 2265 const ValueDecl *VD = ME->getMemberDecl(); 2266 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr; 2267 } 2268 2269 // Likewise for calls on an object accessed by a (non-reference) pointer to 2270 // member access. 2271 if (auto *BO = dyn_cast<BinaryOperator>(Base)) { 2272 if (BO->isPtrMemOp()) { 2273 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>(); 2274 if (MPT->getPointeeType()->isRecordType()) 2275 return DevirtualizedMethod; 2276 } 2277 } 2278 2279 // We can't devirtualize the call. 2280 return nullptr; 2281 } 2282 2283 bool CXXMethodDecl::isUsualDeallocationFunction( 2284 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const { 2285 assert(PreventedBy.empty() && "PreventedBy is expected to be empty"); 2286 if (getOverloadedOperator() != OO_Delete && 2287 getOverloadedOperator() != OO_Array_Delete) 2288 return false; 2289 2290 // C++ [basic.stc.dynamic.deallocation]p2: 2291 // A template instance is never a usual deallocation function, 2292 // regardless of its signature. 2293 if (getPrimaryTemplate()) 2294 return false; 2295 2296 // C++ [basic.stc.dynamic.deallocation]p2: 2297 // If a class T has a member deallocation function named operator delete 2298 // with exactly one parameter, then that function is a usual (non-placement) 2299 // deallocation function. [...] 2300 if (getNumParams() == 1) 2301 return true; 2302 unsigned UsualParams = 1; 2303 2304 // C++ P0722: 2305 // A destroying operator delete is a usual deallocation function if 2306 // removing the std::destroying_delete_t parameter and changing the 2307 // first parameter type from T* to void* results in the signature of 2308 // a usual deallocation function. 2309 if (isDestroyingOperatorDelete()) 2310 ++UsualParams; 2311 2312 // C++ <=14 [basic.stc.dynamic.deallocation]p2: 2313 // [...] If class T does not declare such an operator delete but does 2314 // declare a member deallocation function named operator delete with 2315 // exactly two parameters, the second of which has type std::size_t (18.1), 2316 // then this function is a usual deallocation function. 2317 // 2318 // C++17 says a usual deallocation function is one with the signature 2319 // (void* [, size_t] [, std::align_val_t] [, ...]) 2320 // and all such functions are usual deallocation functions. It's not clear 2321 // that allowing varargs functions was intentional. 2322 ASTContext &Context = getASTContext(); 2323 if (UsualParams < getNumParams() && 2324 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(), 2325 Context.getSizeType())) 2326 ++UsualParams; 2327 2328 if (UsualParams < getNumParams() && 2329 getParamDecl(UsualParams)->getType()->isAlignValT()) 2330 ++UsualParams; 2331 2332 if (UsualParams != getNumParams()) 2333 return false; 2334 2335 // In C++17 onwards, all potential usual deallocation functions are actual 2336 // usual deallocation functions. Honor this behavior when post-C++14 2337 // deallocation functions are offered as extensions too. 2338 // FIXME(EricWF): Destroying Delete should be a language option. How do we 2339 // handle when destroying delete is used prior to C++17? 2340 if (Context.getLangOpts().CPlusPlus17 || 2341 Context.getLangOpts().AlignedAllocation || 2342 isDestroyingOperatorDelete()) 2343 return true; 2344 2345 // This function is a usual deallocation function if there are no 2346 // single-parameter deallocation functions of the same kind. 2347 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); 2348 bool Result = true; 2349 for (const auto *D : R) { 2350 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2351 if (FD->getNumParams() == 1) { 2352 PreventedBy.push_back(FD); 2353 Result = false; 2354 } 2355 } 2356 } 2357 return Result; 2358 } 2359 2360 bool CXXMethodDecl::isCopyAssignmentOperator() const { 2361 // C++0x [class.copy]p17: 2362 // A user-declared copy assignment operator X::operator= is a non-static 2363 // non-template member function of class X with exactly one parameter of 2364 // type X, X&, const X&, volatile X& or const volatile X&. 2365 if (/*operator=*/getOverloadedOperator() != OO_Equal || 2366 /*non-static*/ isStatic() || 2367 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() || 2368 getNumParams() != 1) 2369 return false; 2370 2371 QualType ParamType = getParamDecl(0)->getType(); 2372 if (const auto *Ref = ParamType->getAs<LValueReferenceType>()) 2373 ParamType = Ref->getPointeeType(); 2374 2375 ASTContext &Context = getASTContext(); 2376 QualType ClassType 2377 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2378 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2379 } 2380 2381 bool CXXMethodDecl::isMoveAssignmentOperator() const { 2382 // C++0x [class.copy]p19: 2383 // A user-declared move assignment operator X::operator= is a non-static 2384 // non-template member function of class X with exactly one parameter of type 2385 // X&&, const X&&, volatile X&&, or const volatile X&&. 2386 if (getOverloadedOperator() != OO_Equal || isStatic() || 2387 getPrimaryTemplate() || getDescribedFunctionTemplate() || 2388 getNumParams() != 1) 2389 return false; 2390 2391 QualType ParamType = getParamDecl(0)->getType(); 2392 if (!isa<RValueReferenceType>(ParamType)) 2393 return false; 2394 ParamType = ParamType->getPointeeType(); 2395 2396 ASTContext &Context = getASTContext(); 2397 QualType ClassType 2398 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2399 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2400 } 2401 2402 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { 2403 assert(MD->isCanonicalDecl() && "Method is not canonical!"); 2404 assert(!MD->getParent()->isDependentContext() && 2405 "Can't add an overridden method to a class template!"); 2406 assert(MD->isVirtual() && "Method is not virtual!"); 2407 2408 getASTContext().addOverriddenMethod(this, MD); 2409 } 2410 2411 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { 2412 if (isa<CXXConstructorDecl>(this)) return nullptr; 2413 return getASTContext().overridden_methods_begin(this); 2414 } 2415 2416 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { 2417 if (isa<CXXConstructorDecl>(this)) return nullptr; 2418 return getASTContext().overridden_methods_end(this); 2419 } 2420 2421 unsigned CXXMethodDecl::size_overridden_methods() const { 2422 if (isa<CXXConstructorDecl>(this)) return 0; 2423 return getASTContext().overridden_methods_size(this); 2424 } 2425 2426 CXXMethodDecl::overridden_method_range 2427 CXXMethodDecl::overridden_methods() const { 2428 if (isa<CXXConstructorDecl>(this)) 2429 return overridden_method_range(nullptr, nullptr); 2430 return getASTContext().overridden_methods(this); 2431 } 2432 2433 static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT, 2434 const CXXRecordDecl *Decl) { 2435 QualType ClassTy = C.getTypeDeclType(Decl); 2436 return C.getQualifiedType(ClassTy, FPT->getMethodQuals()); 2437 } 2438 2439 QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT, 2440 const CXXRecordDecl *Decl) { 2441 ASTContext &C = Decl->getASTContext(); 2442 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl); 2443 return C.getPointerType(ObjectTy); 2444 } 2445 2446 QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT, 2447 const CXXRecordDecl *Decl) { 2448 ASTContext &C = Decl->getASTContext(); 2449 return ::getThisObjectType(C, FPT, Decl); 2450 } 2451 2452 QualType CXXMethodDecl::getThisType() const { 2453 // C++ 9.3.2p1: The type of this in a member function of a class X is X*. 2454 // If the member function is declared const, the type of this is const X*, 2455 // if the member function is declared volatile, the type of this is 2456 // volatile X*, and if the member function is declared const volatile, 2457 // the type of this is const volatile X*. 2458 assert(isInstance() && "No 'this' for static methods!"); 2459 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(), 2460 getParent()); 2461 } 2462 2463 QualType CXXMethodDecl::getThisObjectType() const { 2464 // Ditto getThisType. 2465 assert(isInstance() && "No 'this' for static methods!"); 2466 return CXXMethodDecl::getThisObjectType( 2467 getType()->castAs<FunctionProtoType>(), getParent()); 2468 } 2469 2470 bool CXXMethodDecl::hasInlineBody() const { 2471 // If this function is a template instantiation, look at the template from 2472 // which it was instantiated. 2473 const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); 2474 if (!CheckFn) 2475 CheckFn = this; 2476 2477 const FunctionDecl *fn; 2478 return CheckFn->isDefined(fn) && !fn->isOutOfLine() && 2479 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody()); 2480 } 2481 2482 bool CXXMethodDecl::isLambdaStaticInvoker() const { 2483 const CXXRecordDecl *P = getParent(); 2484 return P->isLambda() && getDeclName().isIdentifier() && 2485 getName() == getLambdaStaticInvokerName(); 2486 } 2487 2488 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2489 TypeSourceInfo *TInfo, bool IsVirtual, 2490 SourceLocation L, Expr *Init, 2491 SourceLocation R, 2492 SourceLocation EllipsisLoc) 2493 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc), 2494 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), 2495 IsWritten(false), SourceOrder(0) {} 2496 2497 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, 2498 SourceLocation MemberLoc, 2499 SourceLocation L, Expr *Init, 2500 SourceLocation R) 2501 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2502 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2503 IsWritten(false), SourceOrder(0) {} 2504 2505 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2506 IndirectFieldDecl *Member, 2507 SourceLocation MemberLoc, 2508 SourceLocation L, Expr *Init, 2509 SourceLocation R) 2510 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2511 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2512 IsWritten(false), SourceOrder(0) {} 2513 2514 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2515 TypeSourceInfo *TInfo, 2516 SourceLocation L, Expr *Init, 2517 SourceLocation R) 2518 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), 2519 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} 2520 2521 int64_t CXXCtorInitializer::getID(const ASTContext &Context) const { 2522 return Context.getAllocator() 2523 .identifyKnownAlignedObject<CXXCtorInitializer>(this); 2524 } 2525 2526 TypeLoc CXXCtorInitializer::getBaseClassLoc() const { 2527 if (isBaseInitializer()) 2528 return Initializee.get<TypeSourceInfo*>()->getTypeLoc(); 2529 else 2530 return {}; 2531 } 2532 2533 const Type *CXXCtorInitializer::getBaseClass() const { 2534 if (isBaseInitializer()) 2535 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr(); 2536 else 2537 return nullptr; 2538 } 2539 2540 SourceLocation CXXCtorInitializer::getSourceLocation() const { 2541 if (isInClassMemberInitializer()) 2542 return getAnyMember()->getLocation(); 2543 2544 if (isAnyMemberInitializer()) 2545 return getMemberLocation(); 2546 2547 if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>()) 2548 return TSInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2549 2550 return {}; 2551 } 2552 2553 SourceRange CXXCtorInitializer::getSourceRange() const { 2554 if (isInClassMemberInitializer()) { 2555 FieldDecl *D = getAnyMember(); 2556 if (Expr *I = D->getInClassInitializer()) 2557 return I->getSourceRange(); 2558 return {}; 2559 } 2560 2561 return SourceRange(getSourceLocation(), getRParenLoc()); 2562 } 2563 2564 CXXConstructorDecl::CXXConstructorDecl( 2565 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2566 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2567 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2568 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2569 InheritedConstructor Inherited, Expr *TrailingRequiresClause) 2570 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo, 2571 SC_None, UsesFPIntrin, isInline, ConstexprKind, 2572 SourceLocation(), TrailingRequiresClause) { 2573 setNumCtorInitializers(0); 2574 setInheritingConstructor(static_cast<bool>(Inherited)); 2575 setImplicit(isImplicitlyDeclared); 2576 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0; 2577 if (Inherited) 2578 *getTrailingObjects<InheritedConstructor>() = Inherited; 2579 setExplicitSpecifier(ES); 2580 } 2581 2582 void CXXConstructorDecl::anchor() {} 2583 2584 CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C, 2585 unsigned ID, 2586 uint64_t AllocKind) { 2587 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit); 2588 bool isInheritingConstructor = 2589 static_cast<bool>(AllocKind & TAKInheritsConstructor); 2590 unsigned Extra = 2591 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2592 isInheritingConstructor, hasTrailingExplicit); 2593 auto *Result = new (C, ID, Extra) CXXConstructorDecl( 2594 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2595 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified, 2596 InheritedConstructor(), nullptr); 2597 Result->setInheritingConstructor(isInheritingConstructor); 2598 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier = 2599 hasTrailingExplicit; 2600 Result->setExplicitSpecifier(ExplicitSpecifier()); 2601 return Result; 2602 } 2603 2604 CXXConstructorDecl *CXXConstructorDecl::Create( 2605 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2606 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2607 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2608 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2609 InheritedConstructor Inherited, Expr *TrailingRequiresClause) { 2610 assert(NameInfo.getName().getNameKind() 2611 == DeclarationName::CXXConstructorName && 2612 "Name must refer to a constructor"); 2613 unsigned Extra = 2614 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2615 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0); 2616 return new (C, RD, Extra) CXXConstructorDecl( 2617 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline, 2618 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause); 2619 } 2620 2621 CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const { 2622 return CtorInitializers.get(getASTContext().getExternalSource()); 2623 } 2624 2625 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const { 2626 assert(isDelegatingConstructor() && "Not a delegating constructor!"); 2627 Expr *E = (*init_begin())->getInit()->IgnoreImplicit(); 2628 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E)) 2629 return Construct->getConstructor(); 2630 2631 return nullptr; 2632 } 2633 2634 bool CXXConstructorDecl::isDefaultConstructor() const { 2635 // C++ [class.default.ctor]p1: 2636 // A default constructor for a class X is a constructor of class X for 2637 // which each parameter that is not a function parameter pack has a default 2638 // argument (including the case of a constructor with no parameters) 2639 return getMinRequiredArguments() == 0; 2640 } 2641 2642 bool 2643 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { 2644 return isCopyOrMoveConstructor(TypeQuals) && 2645 getParamDecl(0)->getType()->isLValueReferenceType(); 2646 } 2647 2648 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const { 2649 return isCopyOrMoveConstructor(TypeQuals) && 2650 getParamDecl(0)->getType()->isRValueReferenceType(); 2651 } 2652 2653 /// Determine whether this is a copy or move constructor. 2654 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { 2655 // C++ [class.copy]p2: 2656 // A non-template constructor for class X is a copy constructor 2657 // if its first parameter is of type X&, const X&, volatile X& or 2658 // const volatile X&, and either there are no other parameters 2659 // or else all other parameters have default arguments (8.3.6). 2660 // C++0x [class.copy]p3: 2661 // A non-template constructor for class X is a move constructor if its 2662 // first parameter is of type X&&, const X&&, volatile X&&, or 2663 // const volatile X&&, and either there are no other parameters or else 2664 // all other parameters have default arguments. 2665 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr || 2666 getDescribedFunctionTemplate() != nullptr) 2667 return false; 2668 2669 const ParmVarDecl *Param = getParamDecl(0); 2670 2671 // Do we have a reference type? 2672 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>(); 2673 if (!ParamRefType) 2674 return false; 2675 2676 // Is it a reference to our class type? 2677 ASTContext &Context = getASTContext(); 2678 2679 CanQualType PointeeType 2680 = Context.getCanonicalType(ParamRefType->getPointeeType()); 2681 CanQualType ClassTy 2682 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2683 if (PointeeType.getUnqualifiedType() != ClassTy) 2684 return false; 2685 2686 // FIXME: other qualifiers? 2687 2688 // We have a copy or move constructor. 2689 TypeQuals = PointeeType.getCVRQualifiers(); 2690 return true; 2691 } 2692 2693 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { 2694 // C++ [class.conv.ctor]p1: 2695 // A constructor declared without the function-specifier explicit 2696 // that can be called with a single parameter specifies a 2697 // conversion from the type of its first parameter to the type of 2698 // its class. Such a constructor is called a converting 2699 // constructor. 2700 if (isExplicit() && !AllowExplicit) 2701 return false; 2702 2703 // FIXME: This has nothing to do with the definition of converting 2704 // constructor, but is convenient for how we use this function in overload 2705 // resolution. 2706 return getNumParams() == 0 2707 ? getType()->castAs<FunctionProtoType>()->isVariadic() 2708 : getMinRequiredArguments() <= 1; 2709 } 2710 2711 bool CXXConstructorDecl::isSpecializationCopyingObject() const { 2712 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr) 2713 return false; 2714 2715 const ParmVarDecl *Param = getParamDecl(0); 2716 2717 ASTContext &Context = getASTContext(); 2718 CanQualType ParamType = Context.getCanonicalType(Param->getType()); 2719 2720 // Is it the same as our class type? 2721 CanQualType ClassTy 2722 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2723 if (ParamType.getUnqualifiedType() != ClassTy) 2724 return false; 2725 2726 return true; 2727 } 2728 2729 void CXXDestructorDecl::anchor() {} 2730 2731 CXXDestructorDecl * 2732 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2733 return new (C, ID) CXXDestructorDecl( 2734 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2735 false, false, false, ConstexprSpecKind::Unspecified, nullptr); 2736 } 2737 2738 CXXDestructorDecl *CXXDestructorDecl::Create( 2739 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2740 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2741 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, 2742 ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) { 2743 assert(NameInfo.getName().getNameKind() 2744 == DeclarationName::CXXDestructorName && 2745 "Name must refer to a destructor"); 2746 return new (C, RD) CXXDestructorDecl( 2747 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, 2748 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause); 2749 } 2750 2751 void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) { 2752 auto *First = cast<CXXDestructorDecl>(getFirstDecl()); 2753 if (OD && !First->OperatorDelete) { 2754 First->OperatorDelete = OD; 2755 First->OperatorDeleteThisArg = ThisArg; 2756 if (auto *L = getASTMutationListener()) 2757 L->ResolvedOperatorDelete(First, OD, ThisArg); 2758 } 2759 } 2760 2761 void CXXConversionDecl::anchor() {} 2762 2763 CXXConversionDecl * 2764 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2765 return new (C, ID) CXXConversionDecl( 2766 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2767 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, 2768 SourceLocation(), nullptr); 2769 } 2770 2771 CXXConversionDecl *CXXConversionDecl::Create( 2772 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2773 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2774 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, 2775 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, 2776 Expr *TrailingRequiresClause) { 2777 assert(NameInfo.getName().getNameKind() 2778 == DeclarationName::CXXConversionFunctionName && 2779 "Name must refer to a conversion function"); 2780 return new (C, RD) CXXConversionDecl( 2781 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES, 2782 ConstexprKind, EndLocation, TrailingRequiresClause); 2783 } 2784 2785 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const { 2786 return isImplicit() && getParent()->isLambda() && 2787 getConversionType()->isBlockPointerType(); 2788 } 2789 2790 LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, 2791 SourceLocation LangLoc, LanguageIDs lang, 2792 bool HasBraces) 2793 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec), 2794 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) { 2795 setLanguage(lang); 2796 LinkageSpecDeclBits.HasBraces = HasBraces; 2797 } 2798 2799 void LinkageSpecDecl::anchor() {} 2800 2801 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, 2802 DeclContext *DC, 2803 SourceLocation ExternLoc, 2804 SourceLocation LangLoc, 2805 LanguageIDs Lang, 2806 bool HasBraces) { 2807 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces); 2808 } 2809 2810 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, 2811 unsigned ID) { 2812 return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(), 2813 SourceLocation(), lang_c, false); 2814 } 2815 2816 void UsingDirectiveDecl::anchor() {} 2817 2818 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, 2819 SourceLocation L, 2820 SourceLocation NamespaceLoc, 2821 NestedNameSpecifierLoc QualifierLoc, 2822 SourceLocation IdentLoc, 2823 NamedDecl *Used, 2824 DeclContext *CommonAncestor) { 2825 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used)) 2826 Used = NS->getOriginalNamespace(); 2827 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc, 2828 IdentLoc, Used, CommonAncestor); 2829 } 2830 2831 UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C, 2832 unsigned ID) { 2833 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(), 2834 SourceLocation(), 2835 NestedNameSpecifierLoc(), 2836 SourceLocation(), nullptr, nullptr); 2837 } 2838 2839 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() { 2840 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace)) 2841 return NA->getNamespace(); 2842 return cast_or_null<NamespaceDecl>(NominatedNamespace); 2843 } 2844 2845 NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, 2846 SourceLocation StartLoc, SourceLocation IdLoc, 2847 IdentifierInfo *Id, NamespaceDecl *PrevDecl) 2848 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace), 2849 redeclarable_base(C), LocStart(StartLoc), 2850 AnonOrFirstNamespaceAndInline(nullptr, Inline) { 2851 setPreviousDecl(PrevDecl); 2852 2853 if (PrevDecl) 2854 AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace()); 2855 } 2856 2857 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2858 bool Inline, SourceLocation StartLoc, 2859 SourceLocation IdLoc, IdentifierInfo *Id, 2860 NamespaceDecl *PrevDecl) { 2861 return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, 2862 PrevDecl); 2863 } 2864 2865 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2866 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(), 2867 SourceLocation(), nullptr, nullptr); 2868 } 2869 2870 NamespaceDecl *NamespaceDecl::getOriginalNamespace() { 2871 if (isFirstDecl()) 2872 return this; 2873 2874 return AnonOrFirstNamespaceAndInline.getPointer(); 2875 } 2876 2877 const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const { 2878 if (isFirstDecl()) 2879 return this; 2880 2881 return AnonOrFirstNamespaceAndInline.getPointer(); 2882 } 2883 2884 bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); } 2885 2886 NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() { 2887 return getNextRedeclaration(); 2888 } 2889 2890 NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() { 2891 return getPreviousDecl(); 2892 } 2893 2894 NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() { 2895 return getMostRecentDecl(); 2896 } 2897 2898 void NamespaceAliasDecl::anchor() {} 2899 2900 NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() { 2901 return getNextRedeclaration(); 2902 } 2903 2904 NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() { 2905 return getPreviousDecl(); 2906 } 2907 2908 NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() { 2909 return getMostRecentDecl(); 2910 } 2911 2912 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, 2913 SourceLocation UsingLoc, 2914 SourceLocation AliasLoc, 2915 IdentifierInfo *Alias, 2916 NestedNameSpecifierLoc QualifierLoc, 2917 SourceLocation IdentLoc, 2918 NamedDecl *Namespace) { 2919 // FIXME: Preserve the aliased namespace as written. 2920 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace)) 2921 Namespace = NS->getOriginalNamespace(); 2922 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias, 2923 QualifierLoc, IdentLoc, Namespace); 2924 } 2925 2926 NamespaceAliasDecl * 2927 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2928 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(), 2929 SourceLocation(), nullptr, 2930 NestedNameSpecifierLoc(), 2931 SourceLocation(), nullptr); 2932 } 2933 2934 void LifetimeExtendedTemporaryDecl::anchor() {} 2935 2936 /// Retrieve the storage duration for the materialized temporary. 2937 StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const { 2938 const ValueDecl *ExtendingDecl = getExtendingDecl(); 2939 if (!ExtendingDecl) 2940 return SD_FullExpression; 2941 // FIXME: This is not necessarily correct for a temporary materialized 2942 // within a default initializer. 2943 if (isa<FieldDecl>(ExtendingDecl)) 2944 return SD_Automatic; 2945 // FIXME: This only works because storage class specifiers are not allowed 2946 // on decomposition declarations. 2947 if (isa<BindingDecl>(ExtendingDecl)) 2948 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic 2949 : SD_Static; 2950 return cast<VarDecl>(ExtendingDecl)->getStorageDuration(); 2951 } 2952 2953 APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const { 2954 assert(getStorageDuration() == SD_Static && 2955 "don't need to cache the computed value for this temporary"); 2956 if (MayCreate && !Value) { 2957 Value = (new (getASTContext()) APValue); 2958 getASTContext().addDestruction(Value); 2959 } 2960 assert(Value && "may not be null"); 2961 return Value; 2962 } 2963 2964 void UsingShadowDecl::anchor() {} 2965 2966 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, 2967 SourceLocation Loc, DeclarationName Name, 2968 BaseUsingDecl *Introducer, NamedDecl *Target) 2969 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C), 2970 UsingOrNextShadow(Introducer) { 2971 if (Target) 2972 setTargetDecl(Target); 2973 setImplicit(); 2974 } 2975 2976 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty) 2977 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()), 2978 redeclarable_base(C) {} 2979 2980 UsingShadowDecl * 2981 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2982 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell()); 2983 } 2984 2985 BaseUsingDecl *UsingShadowDecl::getIntroducer() const { 2986 const UsingShadowDecl *Shadow = this; 2987 while (const auto *NextShadow = 2988 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow)) 2989 Shadow = NextShadow; 2990 return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow); 2991 } 2992 2993 void ConstructorUsingShadowDecl::anchor() {} 2994 2995 ConstructorUsingShadowDecl * 2996 ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC, 2997 SourceLocation Loc, UsingDecl *Using, 2998 NamedDecl *Target, bool IsVirtual) { 2999 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target, 3000 IsVirtual); 3001 } 3002 3003 ConstructorUsingShadowDecl * 3004 ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3005 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell()); 3006 } 3007 3008 CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const { 3009 return getIntroducer()->getQualifier()->getAsRecordDecl(); 3010 } 3011 3012 void BaseUsingDecl::anchor() {} 3013 3014 void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) { 3015 assert(!llvm::is_contained(shadows(), S) && "declaration already in set"); 3016 assert(S->getIntroducer() == this); 3017 3018 if (FirstUsingShadow.getPointer()) 3019 S->UsingOrNextShadow = FirstUsingShadow.getPointer(); 3020 FirstUsingShadow.setPointer(S); 3021 } 3022 3023 void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) { 3024 assert(llvm::is_contained(shadows(), S) && "declaration not in set"); 3025 assert(S->getIntroducer() == this); 3026 3027 // Remove S from the shadow decl chain. This is O(n) but hopefully rare. 3028 3029 if (FirstUsingShadow.getPointer() == S) { 3030 FirstUsingShadow.setPointer( 3031 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow)); 3032 S->UsingOrNextShadow = this; 3033 return; 3034 } 3035 3036 UsingShadowDecl *Prev = FirstUsingShadow.getPointer(); 3037 while (Prev->UsingOrNextShadow != S) 3038 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow); 3039 Prev->UsingOrNextShadow = S->UsingOrNextShadow; 3040 S->UsingOrNextShadow = this; 3041 } 3042 3043 void UsingDecl::anchor() {} 3044 3045 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL, 3046 NestedNameSpecifierLoc QualifierLoc, 3047 const DeclarationNameInfo &NameInfo, 3048 bool HasTypename) { 3049 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename); 3050 } 3051 3052 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3053 return new (C, ID) UsingDecl(nullptr, SourceLocation(), 3054 NestedNameSpecifierLoc(), DeclarationNameInfo(), 3055 false); 3056 } 3057 3058 SourceRange UsingDecl::getSourceRange() const { 3059 SourceLocation Begin = isAccessDeclaration() 3060 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3061 return SourceRange(Begin, getNameInfo().getEndLoc()); 3062 } 3063 3064 void UsingEnumDecl::anchor() {} 3065 3066 UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC, 3067 SourceLocation UL, SourceLocation EL, 3068 SourceLocation NL, EnumDecl *Enum) { 3069 return new (C, DC) UsingEnumDecl(DC, Enum->getDeclName(), UL, EL, NL, Enum); 3070 } 3071 3072 UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3073 return new (C, ID) UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(), 3074 SourceLocation(), SourceLocation(), nullptr); 3075 } 3076 3077 SourceRange UsingEnumDecl::getSourceRange() const { 3078 return SourceRange(EnumLocation, getLocation()); 3079 } 3080 3081 void UsingPackDecl::anchor() {} 3082 3083 UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC, 3084 NamedDecl *InstantiatedFrom, 3085 ArrayRef<NamedDecl *> UsingDecls) { 3086 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size()); 3087 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls); 3088 } 3089 3090 UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3091 unsigned NumExpansions) { 3092 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions); 3093 auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, None); 3094 Result->NumExpansions = NumExpansions; 3095 auto *Trail = Result->getTrailingObjects<NamedDecl *>(); 3096 for (unsigned I = 0; I != NumExpansions; ++I) 3097 new (Trail + I) NamedDecl*(nullptr); 3098 return Result; 3099 } 3100 3101 void UnresolvedUsingValueDecl::anchor() {} 3102 3103 UnresolvedUsingValueDecl * 3104 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC, 3105 SourceLocation UsingLoc, 3106 NestedNameSpecifierLoc QualifierLoc, 3107 const DeclarationNameInfo &NameInfo, 3108 SourceLocation EllipsisLoc) { 3109 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc, 3110 QualifierLoc, NameInfo, 3111 EllipsisLoc); 3112 } 3113 3114 UnresolvedUsingValueDecl * 3115 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3116 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(), 3117 SourceLocation(), 3118 NestedNameSpecifierLoc(), 3119 DeclarationNameInfo(), 3120 SourceLocation()); 3121 } 3122 3123 SourceRange UnresolvedUsingValueDecl::getSourceRange() const { 3124 SourceLocation Begin = isAccessDeclaration() 3125 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3126 return SourceRange(Begin, getNameInfo().getEndLoc()); 3127 } 3128 3129 void UnresolvedUsingTypenameDecl::anchor() {} 3130 3131 UnresolvedUsingTypenameDecl * 3132 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC, 3133 SourceLocation UsingLoc, 3134 SourceLocation TypenameLoc, 3135 NestedNameSpecifierLoc QualifierLoc, 3136 SourceLocation TargetNameLoc, 3137 DeclarationName TargetName, 3138 SourceLocation EllipsisLoc) { 3139 return new (C, DC) UnresolvedUsingTypenameDecl( 3140 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc, 3141 TargetName.getAsIdentifierInfo(), EllipsisLoc); 3142 } 3143 3144 UnresolvedUsingTypenameDecl * 3145 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3146 return new (C, ID) UnresolvedUsingTypenameDecl( 3147 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), 3148 SourceLocation(), nullptr, SourceLocation()); 3149 } 3150 3151 UnresolvedUsingIfExistsDecl * 3152 UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC, 3153 SourceLocation Loc, DeclarationName Name) { 3154 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name); 3155 } 3156 3157 UnresolvedUsingIfExistsDecl * 3158 UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) { 3159 return new (Ctx, ID) 3160 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName()); 3161 } 3162 3163 UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC, 3164 SourceLocation Loc, 3165 DeclarationName Name) 3166 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {} 3167 3168 void UnresolvedUsingIfExistsDecl::anchor() {} 3169 3170 void StaticAssertDecl::anchor() {} 3171 3172 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC, 3173 SourceLocation StaticAssertLoc, 3174 Expr *AssertExpr, 3175 StringLiteral *Message, 3176 SourceLocation RParenLoc, 3177 bool Failed) { 3178 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message, 3179 RParenLoc, Failed); 3180 } 3181 3182 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, 3183 unsigned ID) { 3184 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr, 3185 nullptr, SourceLocation(), false); 3186 } 3187 3188 void BindingDecl::anchor() {} 3189 3190 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC, 3191 SourceLocation IdLoc, IdentifierInfo *Id) { 3192 return new (C, DC) BindingDecl(DC, IdLoc, Id); 3193 } 3194 3195 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3196 return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr); 3197 } 3198 3199 VarDecl *BindingDecl::getHoldingVar() const { 3200 Expr *B = getBinding(); 3201 if (!B) 3202 return nullptr; 3203 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit()); 3204 if (!DRE) 3205 return nullptr; 3206 3207 auto *VD = cast<VarDecl>(DRE->getDecl()); 3208 assert(VD->isImplicit() && "holding var for binding decl not implicit"); 3209 return VD; 3210 } 3211 3212 void DecompositionDecl::anchor() {} 3213 3214 DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC, 3215 SourceLocation StartLoc, 3216 SourceLocation LSquareLoc, 3217 QualType T, TypeSourceInfo *TInfo, 3218 StorageClass SC, 3219 ArrayRef<BindingDecl *> Bindings) { 3220 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size()); 3221 return new (C, DC, Extra) 3222 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings); 3223 } 3224 3225 DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C, 3226 unsigned ID, 3227 unsigned NumBindings) { 3228 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings); 3229 auto *Result = new (C, ID, Extra) 3230 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(), 3231 QualType(), nullptr, StorageClass(), None); 3232 // Set up and clean out the bindings array. 3233 Result->NumBindings = NumBindings; 3234 auto *Trail = Result->getTrailingObjects<BindingDecl *>(); 3235 for (unsigned I = 0; I != NumBindings; ++I) 3236 new (Trail + I) BindingDecl*(nullptr); 3237 return Result; 3238 } 3239 3240 void DecompositionDecl::printName(llvm::raw_ostream &os) const { 3241 os << '['; 3242 bool Comma = false; 3243 for (const auto *B : bindings()) { 3244 if (Comma) 3245 os << ", "; 3246 B->printName(os); 3247 Comma = true; 3248 } 3249 os << ']'; 3250 } 3251 3252 void MSPropertyDecl::anchor() {} 3253 3254 MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC, 3255 SourceLocation L, DeclarationName N, 3256 QualType T, TypeSourceInfo *TInfo, 3257 SourceLocation StartL, 3258 IdentifierInfo *Getter, 3259 IdentifierInfo *Setter) { 3260 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter); 3261 } 3262 3263 MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, 3264 unsigned ID) { 3265 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(), 3266 DeclarationName(), QualType(), nullptr, 3267 SourceLocation(), nullptr, nullptr); 3268 } 3269 3270 void MSGuidDecl::anchor() {} 3271 3272 MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P) 3273 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T), 3274 PartVal(P) {} 3275 3276 MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) { 3277 DeclContext *DC = C.getTranslationUnitDecl(); 3278 return new (C, DC) MSGuidDecl(DC, T, P); 3279 } 3280 3281 MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3282 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts()); 3283 } 3284 3285 void MSGuidDecl::printName(llvm::raw_ostream &OS) const { 3286 OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-", 3287 PartVal.Part1, PartVal.Part2, PartVal.Part3); 3288 unsigned I = 0; 3289 for (uint8_t Byte : PartVal.Part4And5) { 3290 OS << llvm::format("%02" PRIx8, Byte); 3291 if (++I == 2) 3292 OS << '-'; 3293 } 3294 OS << '}'; 3295 } 3296 3297 /// Determine if T is a valid 'struct _GUID' of the shape that we expect. 3298 static bool isValidStructGUID(ASTContext &Ctx, QualType T) { 3299 // FIXME: We only need to check this once, not once each time we compute a 3300 // GUID APValue. 3301 using MatcherRef = llvm::function_ref<bool(QualType)>; 3302 3303 auto IsInt = [&Ctx](unsigned N) { 3304 return [&Ctx, N](QualType T) { 3305 return T->isUnsignedIntegerOrEnumerationType() && 3306 Ctx.getIntWidth(T) == N; 3307 }; 3308 }; 3309 3310 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) { 3311 return [&Ctx, Elem, N](QualType T) { 3312 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T); 3313 return CAT && CAT->getSize() == N && Elem(CAT->getElementType()); 3314 }; 3315 }; 3316 3317 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) { 3318 return [Fields](QualType T) { 3319 const RecordDecl *RD = T->getAsRecordDecl(); 3320 if (!RD || RD->isUnion()) 3321 return false; 3322 RD = RD->getDefinition(); 3323 if (!RD) 3324 return false; 3325 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 3326 if (CXXRD->getNumBases()) 3327 return false; 3328 auto MatcherIt = Fields.begin(); 3329 for (const FieldDecl *FD : RD->fields()) { 3330 if (FD->isUnnamedBitfield()) continue; 3331 if (FD->isBitField() || MatcherIt == Fields.end() || 3332 !(*MatcherIt)(FD->getType())) 3333 return false; 3334 ++MatcherIt; 3335 } 3336 return MatcherIt == Fields.end(); 3337 }; 3338 }; 3339 3340 // We expect an {i32, i16, i16, [8 x i8]}. 3341 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T); 3342 } 3343 3344 APValue &MSGuidDecl::getAsAPValue() const { 3345 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) { 3346 using llvm::APInt; 3347 using llvm::APSInt; 3348 APVal = APValue(APValue::UninitStruct(), 0, 4); 3349 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true)); 3350 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true)); 3351 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true)); 3352 APValue &Arr = APVal.getStructField(3) = 3353 APValue(APValue::UninitArray(), 8, 8); 3354 for (unsigned I = 0; I != 8; ++I) { 3355 Arr.getArrayInitializedElt(I) = 3356 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true)); 3357 } 3358 // Register this APValue to be destroyed if necessary. (Note that the 3359 // MSGuidDecl destructor is never run.) 3360 getASTContext().addDestruction(&APVal); 3361 } 3362 3363 return APVal; 3364 } 3365 3366 static const char *getAccessName(AccessSpecifier AS) { 3367 switch (AS) { 3368 case AS_none: 3369 llvm_unreachable("Invalid access specifier!"); 3370 case AS_public: 3371 return "public"; 3372 case AS_private: 3373 return "private"; 3374 case AS_protected: 3375 return "protected"; 3376 } 3377 llvm_unreachable("Invalid access specifier!"); 3378 } 3379 3380 const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB, 3381 AccessSpecifier AS) { 3382 return DB << getAccessName(AS); 3383 } 3384