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