1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Decl subclasses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/Decl.h" 14 #include "Linkage.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/CanonicalType.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclOpenMP.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/DeclarationName.h" 27 #include "clang/AST/Expr.h" 28 #include "clang/AST/ExprCXX.h" 29 #include "clang/AST/ExternalASTSource.h" 30 #include "clang/AST/ODRHash.h" 31 #include "clang/AST/PrettyDeclStackTrace.h" 32 #include "clang/AST/PrettyPrinter.h" 33 #include "clang/AST/Randstruct.h" 34 #include "clang/AST/RecordLayout.h" 35 #include "clang/AST/Redeclarable.h" 36 #include "clang/AST/Stmt.h" 37 #include "clang/AST/TemplateBase.h" 38 #include "clang/AST/Type.h" 39 #include "clang/AST/TypeLoc.h" 40 #include "clang/Basic/Builtins.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/Linkage.h" 45 #include "clang/Basic/Module.h" 46 #include "clang/Basic/NoSanitizeList.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/Sanitizers.h" 49 #include "clang/Basic/SourceLocation.h" 50 #include "clang/Basic/SourceManager.h" 51 #include "clang/Basic/Specifiers.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/Visibility.h" 55 #include "llvm/ADT/APSInt.h" 56 #include "llvm/ADT/ArrayRef.h" 57 #include "llvm/ADT/STLExtras.h" 58 #include "llvm/ADT/SmallVector.h" 59 #include "llvm/ADT/StringRef.h" 60 #include "llvm/ADT/StringSwitch.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/TargetParser/Triple.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <cstddef> 68 #include <cstring> 69 #include <memory> 70 #include <optional> 71 #include <string> 72 #include <tuple> 73 #include <type_traits> 74 75 using namespace clang; 76 77 Decl *clang::getPrimaryMergedDecl(Decl *D) { 78 return D->getASTContext().getPrimaryMergedDecl(D); 79 } 80 81 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 82 SourceLocation Loc = this->Loc; 83 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 84 if (Loc.isValid()) { 85 Loc.print(OS, Context.getSourceManager()); 86 OS << ": "; 87 } 88 OS << Message; 89 90 if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) { 91 OS << " '"; 92 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true); 93 OS << "'"; 94 } 95 96 OS << '\n'; 97 } 98 99 // Defined here so that it can be inlined into its direct callers. 100 bool Decl::isOutOfLine() const { 101 return !getLexicalDeclContext()->Equals(getDeclContext()); 102 } 103 104 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx) 105 : Decl(TranslationUnit, nullptr, SourceLocation()), 106 DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {} 107 108 //===----------------------------------------------------------------------===// 109 // NamedDecl Implementation 110 //===----------------------------------------------------------------------===// 111 112 // Visibility rules aren't rigorously externally specified, but here 113 // are the basic principles behind what we implement: 114 // 115 // 1. An explicit visibility attribute is generally a direct expression 116 // of the user's intent and should be honored. Only the innermost 117 // visibility attribute applies. If no visibility attribute applies, 118 // global visibility settings are considered. 119 // 120 // 2. There is one caveat to the above: on or in a template pattern, 121 // an explicit visibility attribute is just a default rule, and 122 // visibility can be decreased by the visibility of template 123 // arguments. But this, too, has an exception: an attribute on an 124 // explicit specialization or instantiation causes all the visibility 125 // restrictions of the template arguments to be ignored. 126 // 127 // 3. A variable that does not otherwise have explicit visibility can 128 // be restricted by the visibility of its type. 129 // 130 // 4. A visibility restriction is explicit if it comes from an 131 // attribute (or something like it), not a global visibility setting. 132 // When emitting a reference to an external symbol, visibility 133 // restrictions are ignored unless they are explicit. 134 // 135 // 5. When computing the visibility of a non-type, including a 136 // non-type member of a class, only non-type visibility restrictions 137 // are considered: the 'visibility' attribute, global value-visibility 138 // settings, and a few special cases like __private_extern. 139 // 140 // 6. When computing the visibility of a type, including a type member 141 // of a class, only type visibility restrictions are considered: 142 // the 'type_visibility' attribute and global type-visibility settings. 143 // However, a 'visibility' attribute counts as a 'type_visibility' 144 // attribute on any declaration that only has the former. 145 // 146 // The visibility of a "secondary" entity, like a template argument, 147 // is computed using the kind of that entity, not the kind of the 148 // primary entity for which we are computing visibility. For example, 149 // the visibility of a specialization of either of these templates: 150 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); 151 // template <class T, bool (&compare)(T, X)> class matcher; 152 // is restricted according to the type visibility of the argument 'T', 153 // the type visibility of 'bool(&)(T,X)', and the value visibility of 154 // the argument function 'compare'. That 'has_match' is a value 155 // and 'matcher' is a type only matters when looking for attributes 156 // and settings from the immediate context. 157 158 /// Does this computation kind permit us to consider additional 159 /// visibility settings from attributes and the like? 160 static bool hasExplicitVisibilityAlready(LVComputationKind computation) { 161 return computation.IgnoreExplicitVisibility; 162 } 163 164 /// Given an LVComputationKind, return one of the same type/value sort 165 /// that records that it already has explicit visibility. 166 static LVComputationKind 167 withExplicitVisibilityAlready(LVComputationKind Kind) { 168 Kind.IgnoreExplicitVisibility = true; 169 return Kind; 170 } 171 172 static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D, 173 LVComputationKind kind) { 174 assert(!kind.IgnoreExplicitVisibility && 175 "asking for explicit visibility when we shouldn't be"); 176 return D->getExplicitVisibility(kind.getExplicitVisibilityKind()); 177 } 178 179 /// Is the given declaration a "type" or a "value" for the purposes of 180 /// visibility computation? 181 static bool usesTypeVisibility(const NamedDecl *D) { 182 return isa<TypeDecl>(D) || 183 isa<ClassTemplateDecl>(D) || 184 isa<ObjCInterfaceDecl>(D); 185 } 186 187 /// Does the given declaration have member specialization information, 188 /// and if so, is it an explicit specialization? 189 template <class T> 190 static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool> 191 isExplicitMemberSpecialization(const T *D) { 192 if (const MemberSpecializationInfo *member = 193 D->getMemberSpecializationInfo()) { 194 return member->isExplicitSpecialization(); 195 } 196 return false; 197 } 198 199 /// For templates, this question is easier: a member template can't be 200 /// explicitly instantiated, so there's a single bit indicating whether 201 /// or not this is an explicit member specialization. 202 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { 203 return D->isMemberSpecialization(); 204 } 205 206 /// Given a visibility attribute, return the explicit visibility 207 /// associated with it. 208 template <class T> 209 static Visibility getVisibilityFromAttr(const T *attr) { 210 switch (attr->getVisibility()) { 211 case T::Default: 212 return DefaultVisibility; 213 case T::Hidden: 214 return HiddenVisibility; 215 case T::Protected: 216 return ProtectedVisibility; 217 } 218 llvm_unreachable("bad visibility kind"); 219 } 220 221 /// Return the explicit visibility of the given declaration. 222 static std::optional<Visibility> 223 getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) { 224 // If we're ultimately computing the visibility of a type, look for 225 // a 'type_visibility' attribute before looking for 'visibility'. 226 if (kind == NamedDecl::VisibilityForType) { 227 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) { 228 return getVisibilityFromAttr(A); 229 } 230 } 231 232 // If this declaration has an explicit visibility attribute, use it. 233 if (const auto *A = D->getAttr<VisibilityAttr>()) { 234 return getVisibilityFromAttr(A); 235 } 236 237 return std::nullopt; 238 } 239 240 LinkageInfo LinkageComputer::getLVForType(const Type &T, 241 LVComputationKind computation) { 242 if (computation.IgnoreAllVisibility) 243 return LinkageInfo(T.getLinkage(), DefaultVisibility, true); 244 return getTypeLinkageAndVisibility(&T); 245 } 246 247 /// Get the most restrictive linkage for the types in the given 248 /// template parameter list. For visibility purposes, template 249 /// parameters are part of the signature of a template. 250 LinkageInfo LinkageComputer::getLVForTemplateParameterList( 251 const TemplateParameterList *Params, LVComputationKind computation) { 252 LinkageInfo LV; 253 for (const NamedDecl *P : *Params) { 254 // Template type parameters are the most common and never 255 // contribute to visibility, pack or not. 256 if (isa<TemplateTypeParmDecl>(P)) 257 continue; 258 259 // Non-type template parameters can be restricted by the value type, e.g. 260 // template <enum X> class A { ... }; 261 // We have to be careful here, though, because we can be dealing with 262 // dependent types. 263 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 264 // Handle the non-pack case first. 265 if (!NTTP->isExpandedParameterPack()) { 266 if (!NTTP->getType()->isDependentType()) { 267 LV.merge(getLVForType(*NTTP->getType(), computation)); 268 } 269 continue; 270 } 271 272 // Look at all the types in an expanded pack. 273 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { 274 QualType type = NTTP->getExpansionType(i); 275 if (!type->isDependentType()) 276 LV.merge(getTypeLinkageAndVisibility(type)); 277 } 278 continue; 279 } 280 281 // Template template parameters can be restricted by their 282 // template parameters, recursively. 283 const auto *TTP = cast<TemplateTemplateParmDecl>(P); 284 285 // Handle the non-pack case first. 286 if (!TTP->isExpandedParameterPack()) { 287 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(), 288 computation)); 289 continue; 290 } 291 292 // Look at all expansions in an expanded pack. 293 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); 294 i != n; ++i) { 295 LV.merge(getLVForTemplateParameterList( 296 TTP->getExpansionTemplateParameters(i), computation)); 297 } 298 } 299 300 return LV; 301 } 302 303 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { 304 const Decl *Ret = nullptr; 305 const DeclContext *DC = D->getDeclContext(); 306 while (DC->getDeclKind() != Decl::TranslationUnit) { 307 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC)) 308 Ret = cast<Decl>(DC); 309 DC = DC->getParent(); 310 } 311 return Ret; 312 } 313 314 /// Get the most restrictive linkage for the types and 315 /// declarations in the given template argument list. 316 /// 317 /// Note that we don't take an LVComputationKind because we always 318 /// want to honor the visibility of template arguments in the same way. 319 LinkageInfo 320 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args, 321 LVComputationKind computation) { 322 LinkageInfo LV; 323 324 for (const TemplateArgument &Arg : Args) { 325 switch (Arg.getKind()) { 326 case TemplateArgument::Null: 327 case TemplateArgument::Integral: 328 case TemplateArgument::Expression: 329 continue; 330 331 case TemplateArgument::Type: 332 LV.merge(getLVForType(*Arg.getAsType(), computation)); 333 continue; 334 335 case TemplateArgument::Declaration: { 336 const NamedDecl *ND = Arg.getAsDecl(); 337 assert(!usesTypeVisibility(ND)); 338 LV.merge(getLVForDecl(ND, computation)); 339 continue; 340 } 341 342 case TemplateArgument::NullPtr: 343 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType())); 344 continue; 345 346 case TemplateArgument::StructuralValue: 347 LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation)); 348 continue; 349 350 case TemplateArgument::Template: 351 case TemplateArgument::TemplateExpansion: 352 if (TemplateDecl *Template = 353 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl( 354 /*IgnoreDeduced=*/true)) 355 LV.merge(getLVForDecl(Template, computation)); 356 continue; 357 358 case TemplateArgument::Pack: 359 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation)); 360 continue; 361 } 362 llvm_unreachable("bad template argument kind"); 363 } 364 365 return LV; 366 } 367 368 LinkageInfo 369 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 370 LVComputationKind computation) { 371 return getLVForTemplateArgumentList(TArgs.asArray(), computation); 372 } 373 374 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, 375 const FunctionTemplateSpecializationInfo *specInfo) { 376 // Include visibility from the template parameters and arguments 377 // only if this is not an explicit instantiation or specialization 378 // with direct explicit visibility. (Implicit instantiations won't 379 // have a direct attribute.) 380 if (!specInfo->isExplicitInstantiationOrSpecialization()) 381 return true; 382 383 return !fn->hasAttr<VisibilityAttr>(); 384 } 385 386 /// Merge in template-related linkage and visibility for the given 387 /// function template specialization. 388 /// 389 /// We don't need a computation kind here because we can assume 390 /// LVForValue. 391 /// 392 /// \param[out] LV the computation to use for the parent 393 void LinkageComputer::mergeTemplateLV( 394 LinkageInfo &LV, const FunctionDecl *fn, 395 const FunctionTemplateSpecializationInfo *specInfo, 396 LVComputationKind computation) { 397 bool considerVisibility = 398 shouldConsiderTemplateVisibility(fn, specInfo); 399 400 FunctionTemplateDecl *temp = specInfo->getTemplate(); 401 // Merge information from the template declaration. 402 LinkageInfo tempLV = getLVForDecl(temp, computation); 403 // The linkage of the specialization should be consistent with the 404 // template declaration. 405 LV.setLinkage(tempLV.getLinkage()); 406 407 // Merge information from the template parameters. 408 LinkageInfo paramsLV = 409 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 410 LV.mergeMaybeWithVisibility(paramsLV, considerVisibility); 411 412 // Merge information from the template arguments. 413 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 414 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 415 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 416 } 417 418 /// Does the given declaration have a direct visibility attribute 419 /// that would match the given rules? 420 static bool hasDirectVisibilityAttribute(const NamedDecl *D, 421 LVComputationKind computation) { 422 if (computation.IgnoreAllVisibility) 423 return false; 424 425 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) || 426 D->hasAttr<VisibilityAttr>(); 427 } 428 429 /// Should we consider visibility associated with the template 430 /// arguments and parameters of the given class template specialization? 431 static bool shouldConsiderTemplateVisibility( 432 const ClassTemplateSpecializationDecl *spec, 433 LVComputationKind computation) { 434 // Include visibility from the template parameters and arguments 435 // only if this is not an explicit instantiation or specialization 436 // with direct explicit visibility (and note that implicit 437 // instantiations won't have a direct attribute). 438 // 439 // Furthermore, we want to ignore template parameters and arguments 440 // for an explicit specialization when computing the visibility of a 441 // member thereof with explicit visibility. 442 // 443 // This is a bit complex; let's unpack it. 444 // 445 // An explicit class specialization is an independent, top-level 446 // declaration. As such, if it or any of its members has an 447 // explicit visibility attribute, that must directly express the 448 // user's intent, and we should honor it. The same logic applies to 449 // an explicit instantiation of a member of such a thing. 450 451 // Fast path: if this is not an explicit instantiation or 452 // specialization, we always want to consider template-related 453 // visibility restrictions. 454 if (!spec->isExplicitInstantiationOrSpecialization()) 455 return true; 456 457 // This is the 'member thereof' check. 458 if (spec->isExplicitSpecialization() && 459 hasExplicitVisibilityAlready(computation)) 460 return false; 461 462 return !hasDirectVisibilityAttribute(spec, computation); 463 } 464 465 /// Merge in template-related linkage and visibility for the given 466 /// class template specialization. 467 void LinkageComputer::mergeTemplateLV( 468 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec, 469 LVComputationKind computation) { 470 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 471 472 // Merge information from the template parameters, but ignore 473 // visibility if we're only considering template arguments. 474 ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 475 // Merge information from the template declaration. 476 LinkageInfo tempLV = getLVForDecl(temp, computation); 477 // The linkage of the specialization should be consistent with the 478 // template declaration. 479 LV.setLinkage(tempLV.getLinkage()); 480 481 LinkageInfo paramsLV = 482 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 483 LV.mergeMaybeWithVisibility(paramsLV, 484 considerVisibility && !hasExplicitVisibilityAlready(computation)); 485 486 // Merge information from the template arguments. We ignore 487 // template-argument visibility if we've got an explicit 488 // instantiation with a visibility attribute. 489 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 490 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 491 if (considerVisibility) 492 LV.mergeVisibility(argsLV); 493 LV.mergeExternalVisibility(argsLV); 494 } 495 496 /// Should we consider visibility associated with the template 497 /// arguments and parameters of the given variable template 498 /// specialization? As usual, follow class template specialization 499 /// logic up to initialization. 500 static bool shouldConsiderTemplateVisibility( 501 const VarTemplateSpecializationDecl *spec, 502 LVComputationKind computation) { 503 // Include visibility from the template parameters and arguments 504 // only if this is not an explicit instantiation or specialization 505 // with direct explicit visibility (and note that implicit 506 // instantiations won't have a direct attribute). 507 if (!spec->isExplicitInstantiationOrSpecialization()) 508 return true; 509 510 // An explicit variable specialization is an independent, top-level 511 // declaration. As such, if it has an explicit visibility attribute, 512 // that must directly express the user's intent, and we should honor 513 // it. 514 if (spec->isExplicitSpecialization() && 515 hasExplicitVisibilityAlready(computation)) 516 return false; 517 518 return !hasDirectVisibilityAttribute(spec, computation); 519 } 520 521 /// Merge in template-related linkage and visibility for the given 522 /// variable template specialization. As usual, follow class template 523 /// specialization logic up to initialization. 524 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV, 525 const VarTemplateSpecializationDecl *spec, 526 LVComputationKind computation) { 527 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 528 529 // Merge information from the template parameters, but ignore 530 // visibility if we're only considering template arguments. 531 VarTemplateDecl *temp = spec->getSpecializedTemplate(); 532 LinkageInfo tempLV = 533 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 534 LV.mergeMaybeWithVisibility(tempLV, 535 considerVisibility && !hasExplicitVisibilityAlready(computation)); 536 537 // Merge information from the template arguments. We ignore 538 // template-argument visibility if we've got an explicit 539 // instantiation with a visibility attribute. 540 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 541 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 542 if (considerVisibility) 543 LV.mergeVisibility(argsLV); 544 LV.mergeExternalVisibility(argsLV); 545 } 546 547 static bool useInlineVisibilityHidden(const NamedDecl *D) { 548 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 549 const LangOptions &Opts = D->getASTContext().getLangOpts(); 550 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 551 return false; 552 553 const auto *FD = dyn_cast<FunctionDecl>(D); 554 if (!FD) 555 return false; 556 557 TemplateSpecializationKind TSK = TSK_Undeclared; 558 if (FunctionTemplateSpecializationInfo *spec 559 = FD->getTemplateSpecializationInfo()) { 560 TSK = spec->getTemplateSpecializationKind(); 561 } else if (MemberSpecializationInfo *MSI = 562 FD->getMemberSpecializationInfo()) { 563 TSK = MSI->getTemplateSpecializationKind(); 564 } 565 566 const FunctionDecl *Def = nullptr; 567 // InlineVisibilityHidden only applies to definitions, and 568 // isInlined() only gives meaningful answers on definitions 569 // anyway. 570 return TSK != TSK_ExplicitInstantiationDeclaration && 571 TSK != TSK_ExplicitInstantiationDefinition && 572 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 573 } 574 575 template <typename T> static bool isFirstInExternCContext(T *D) { 576 const T *First = D->getFirstDecl(); 577 return First->isInExternCContext(); 578 } 579 580 static bool isSingleLineLanguageLinkage(const Decl &D) { 581 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext())) 582 if (!SD->hasBraces()) 583 return true; 584 return false; 585 } 586 587 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) { 588 return LinkageInfo::external(); 589 } 590 591 static StorageClass getStorageClass(const Decl *D) { 592 if (auto *TD = dyn_cast<TemplateDecl>(D)) 593 D = TD->getTemplatedDecl(); 594 if (D) { 595 if (auto *VD = dyn_cast<VarDecl>(D)) 596 return VD->getStorageClass(); 597 if (auto *FD = dyn_cast<FunctionDecl>(D)) 598 return FD->getStorageClass(); 599 } 600 return SC_None; 601 } 602 603 LinkageInfo 604 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, 605 LVComputationKind computation, 606 bool IgnoreVarTypeLinkage) { 607 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 608 "Not a name having namespace scope"); 609 ASTContext &Context = D->getASTContext(); 610 const auto *Var = dyn_cast<VarDecl>(D); 611 612 // C++ [basic.link]p3: 613 // A name having namespace scope (3.3.6) has internal linkage if it 614 // is the name of 615 616 if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) || 617 (Context.getLangOpts().C23 && Var && Var->isConstexpr())) { 618 // - a variable, variable template, function, or function template 619 // that is explicitly declared static; or 620 // (This bullet corresponds to C99 6.2.2p3.) 621 622 // C23 6.2.2p3 623 // If the declaration of a file scope identifier for 624 // an object contains any of the storage-class specifiers static or 625 // constexpr then the identifier has internal linkage. 626 return LinkageInfo::internal(); 627 } 628 629 if (Var) { 630 // - a non-template variable of non-volatile const-qualified type, unless 631 // - it is explicitly declared extern, or 632 // - it is declared in the purview of a module interface unit 633 // (outside the private-module-fragment, if any) or module partition, or 634 // - it is inline, or 635 // - it was previously declared and the prior declaration did not have 636 // internal linkage 637 // (There is no equivalent in C99.) 638 if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() && 639 !Var->getType().isVolatileQualified() && !Var->isInline() && 640 ![Var]() { 641 // Check if it is module purview except private module fragment 642 // and implementation unit. 643 if (auto *M = Var->getOwningModule()) 644 return M->isInterfaceOrPartition() || M->isImplicitGlobalModule(); 645 return false; 646 }() && 647 !isa<VarTemplateSpecializationDecl>(Var) && 648 !Var->getDescribedVarTemplate()) { 649 const VarDecl *PrevVar = Var->getPreviousDecl(); 650 if (PrevVar) 651 return getLVForDecl(PrevVar, computation); 652 653 if (Var->getStorageClass() != SC_Extern && 654 Var->getStorageClass() != SC_PrivateExtern && 655 !isSingleLineLanguageLinkage(*Var)) 656 return LinkageInfo::internal(); 657 } 658 659 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; 660 PrevVar = PrevVar->getPreviousDecl()) { 661 if (PrevVar->getStorageClass() == SC_PrivateExtern && 662 Var->getStorageClass() == SC_None) 663 return getDeclLinkageAndVisibility(PrevVar); 664 // Explicitly declared static. 665 if (PrevVar->getStorageClass() == SC_Static) 666 return LinkageInfo::internal(); 667 } 668 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) { 669 // - a data member of an anonymous union. 670 const VarDecl *VD = IFD->getVarDecl(); 671 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); 672 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage); 673 } 674 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"); 675 676 // FIXME: This gives internal linkage to names that should have no linkage 677 // (those not covered by [basic.link]p6). 678 if (D->isInAnonymousNamespace()) { 679 const auto *Var = dyn_cast<VarDecl>(D); 680 const auto *Func = dyn_cast<FunctionDecl>(D); 681 // FIXME: The check for extern "C" here is not justified by the standard 682 // wording, but we retain it from the pre-DR1113 model to avoid breaking 683 // code. 684 // 685 // C++11 [basic.link]p4: 686 // An unnamed namespace or a namespace declared directly or indirectly 687 // within an unnamed namespace has internal linkage. 688 if ((!Var || !isFirstInExternCContext(Var)) && 689 (!Func || !isFirstInExternCContext(Func))) 690 return LinkageInfo::internal(); 691 } 692 693 // Set up the defaults. 694 695 // C99 6.2.2p5: 696 // If the declaration of an identifier for an object has file 697 // scope and no storage-class specifier, its linkage is 698 // external. 699 LinkageInfo LV = getExternalLinkageFor(D); 700 701 if (!hasExplicitVisibilityAlready(computation)) { 702 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) { 703 LV.mergeVisibility(*Vis, true); 704 } else { 705 // If we're declared in a namespace with a visibility attribute, 706 // use that namespace's visibility, and it still counts as explicit. 707 for (const DeclContext *DC = D->getDeclContext(); 708 !isa<TranslationUnitDecl>(DC); 709 DC = DC->getParent()) { 710 const auto *ND = dyn_cast<NamespaceDecl>(DC); 711 if (!ND) continue; 712 if (std::optional<Visibility> Vis = 713 getExplicitVisibility(ND, computation)) { 714 LV.mergeVisibility(*Vis, true); 715 break; 716 } 717 } 718 } 719 720 // Add in global settings if the above didn't give us direct visibility. 721 if (!LV.isVisibilityExplicit()) { 722 // Use global type/value visibility as appropriate. 723 Visibility globalVisibility = 724 computation.isValueVisibility() 725 ? Context.getLangOpts().getValueVisibilityMode() 726 : Context.getLangOpts().getTypeVisibilityMode(); 727 LV.mergeVisibility(globalVisibility, /*explicit*/ false); 728 729 // If we're paying attention to global visibility, apply 730 // -finline-visibility-hidden if this is an inline method. 731 if (useInlineVisibilityHidden(D)) 732 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false); 733 } 734 } 735 736 // C++ [basic.link]p4: 737 738 // A name having namespace scope that has not been given internal linkage 739 // above and that is the name of 740 // [...bullets...] 741 // has its linkage determined as follows: 742 // - if the enclosing namespace has internal linkage, the name has 743 // internal linkage; [handled above] 744 // - otherwise, if the declaration of the name is attached to a named 745 // module and is not exported, the name has module linkage; 746 // - otherwise, the name has external linkage. 747 // LV is currently set up to handle the last two bullets. 748 // 749 // The bullets are: 750 751 // - a variable; or 752 if (const auto *Var = dyn_cast<VarDecl>(D)) { 753 // GCC applies the following optimization to variables and static 754 // data members, but not to functions: 755 // 756 // Modify the variable's LV by the LV of its type unless this is 757 // C or extern "C". This follows from [basic.link]p9: 758 // A type without linkage shall not be used as the type of a 759 // variable or function with external linkage unless 760 // - the entity has C language linkage, or 761 // - the entity is declared within an unnamed namespace, or 762 // - the entity is not used or is defined in the same 763 // translation unit. 764 // and [basic.link]p10: 765 // ...the types specified by all declarations referring to a 766 // given variable or function shall be identical... 767 // C does not have an equivalent rule. 768 // 769 // Ignore this if we've got an explicit attribute; the user 770 // probably knows what they're doing. 771 // 772 // Note that we don't want to make the variable non-external 773 // because of this, but unique-external linkage suits us. 774 775 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) && 776 !IgnoreVarTypeLinkage) { 777 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation); 778 if (!isExternallyVisible(TypeLV.getLinkage())) 779 return LinkageInfo::uniqueExternal(); 780 if (!LV.isVisibilityExplicit()) 781 LV.mergeVisibility(TypeLV); 782 } 783 784 if (Var->getStorageClass() == SC_PrivateExtern) 785 LV.mergeVisibility(HiddenVisibility, true); 786 787 // Note that Sema::MergeVarDecl already takes care of implementing 788 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 789 // to do it here. 790 791 // As per function and class template specializations (below), 792 // consider LV for the template and template arguments. We're at file 793 // scope, so we do not need to worry about nested specializations. 794 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 795 mergeTemplateLV(LV, spec, computation); 796 } 797 798 // - a function; or 799 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 800 // In theory, we can modify the function's LV by the LV of its 801 // type unless it has C linkage (see comment above about variables 802 // for justification). In practice, GCC doesn't do this, so it's 803 // just too painful to make work. 804 805 if (Function->getStorageClass() == SC_PrivateExtern) 806 LV.mergeVisibility(HiddenVisibility, true); 807 808 // OpenMP target declare device functions are not callable from the host so 809 // they should not be exported from the device image. This applies to all 810 // functions as the host-callable kernel functions are emitted at codegen. 811 if (Context.getLangOpts().OpenMP && 812 Context.getLangOpts().OpenMPIsTargetDevice && 813 ((Context.getTargetInfo().getTriple().isAMDGPU() || 814 Context.getTargetInfo().getTriple().isNVPTX()) || 815 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function))) 816 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false); 817 818 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 819 // merging storage classes and visibility attributes, so we don't have to 820 // look at previous decls in here. 821 822 // In C++, then if the type of the function uses a type with 823 // unique-external linkage, it's not legally usable from outside 824 // this translation unit. However, we should use the C linkage 825 // rules instead for extern "C" declarations. 826 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) { 827 // Only look at the type-as-written. Otherwise, deducing the return type 828 // of a function could change its linkage. 829 QualType TypeAsWritten = Function->getType(); 830 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo()) 831 TypeAsWritten = TSI->getType(); 832 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 833 return LinkageInfo::uniqueExternal(); 834 } 835 836 // Consider LV from the template and the template arguments. 837 // We're at file scope, so we do not need to worry about nested 838 // specializations. 839 if (FunctionTemplateSpecializationInfo *specInfo 840 = Function->getTemplateSpecializationInfo()) { 841 mergeTemplateLV(LV, Function, specInfo, computation); 842 } 843 844 // - a named class (Clause 9), or an unnamed class defined in a 845 // typedef declaration in which the class has the typedef name 846 // for linkage purposes (7.1.3); or 847 // - a named enumeration (7.2), or an unnamed enumeration 848 // defined in a typedef declaration in which the enumeration 849 // has the typedef name for linkage purposes (7.1.3); or 850 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) { 851 // Unnamed tags have no linkage. 852 if (!Tag->hasNameForLinkage()) 853 return LinkageInfo::none(); 854 855 // If this is a class template specialization, consider the 856 // linkage of the template and template arguments. We're at file 857 // scope, so we do not need to worry about nested specializations. 858 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 859 mergeTemplateLV(LV, spec, computation); 860 } 861 862 // FIXME: This is not part of the C++ standard any more. 863 // - an enumerator belonging to an enumeration with external linkage; or 864 } else if (isa<EnumConstantDecl>(D)) { 865 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 866 computation); 867 if (!isExternalFormalLinkage(EnumLV.getLinkage())) 868 return LinkageInfo::none(); 869 LV.merge(EnumLV); 870 871 // - a template 872 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 873 bool considerVisibility = !hasExplicitVisibilityAlready(computation); 874 LinkageInfo tempLV = 875 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 876 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 877 878 // An unnamed namespace or a namespace declared directly or indirectly 879 // within an unnamed namespace has internal linkage. All other namespaces 880 // have external linkage. 881 // 882 // We handled names in anonymous namespaces above. 883 } else if (isa<NamespaceDecl>(D)) { 884 return LV; 885 886 // By extension, we assign external linkage to Objective-C 887 // interfaces. 888 } else if (isa<ObjCInterfaceDecl>(D)) { 889 // fallout 890 891 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 892 // A typedef declaration has linkage if it gives a type a name for 893 // linkage purposes. 894 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 895 return LinkageInfo::none(); 896 897 } else if (isa<MSGuidDecl>(D)) { 898 // A GUID behaves like an inline variable with external linkage. Fall 899 // through. 900 901 // Everything not covered here has no linkage. 902 } else { 903 return LinkageInfo::none(); 904 } 905 906 // If we ended up with non-externally-visible linkage, visibility should 907 // always be default. 908 if (!isExternallyVisible(LV.getLinkage())) 909 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); 910 911 return LV; 912 } 913 914 LinkageInfo 915 LinkageComputer::getLVForClassMember(const NamedDecl *D, 916 LVComputationKind computation, 917 bool IgnoreVarTypeLinkage) { 918 // Only certain class members have linkage. Note that fields don't 919 // really have linkage, but it's convenient to say they do for the 920 // purposes of calculating linkage of pointer-to-data-member 921 // template arguments. 922 // 923 // Templates also don't officially have linkage, but since we ignore 924 // the C++ standard and look at template arguments when determining 925 // linkage and visibility of a template specialization, we might hit 926 // a template template argument that way. If we do, we need to 927 // consider its linkage. 928 if (!(isa<CXXMethodDecl>(D) || 929 isa<VarDecl>(D) || 930 isa<FieldDecl>(D) || 931 isa<IndirectFieldDecl>(D) || 932 isa<TagDecl>(D) || 933 isa<TemplateDecl>(D))) 934 return LinkageInfo::none(); 935 936 LinkageInfo LV; 937 938 // If we have an explicit visibility attribute, merge that in. 939 if (!hasExplicitVisibilityAlready(computation)) { 940 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) 941 LV.mergeVisibility(*Vis, true); 942 // If we're paying attention to global visibility, apply 943 // -finline-visibility-hidden if this is an inline method. 944 // 945 // Note that we do this before merging information about 946 // the class visibility. 947 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) 948 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false); 949 } 950 951 // If this class member has an explicit visibility attribute, the only 952 // thing that can change its visibility is the template arguments, so 953 // only look for them when processing the class. 954 LVComputationKind classComputation = computation; 955 if (LV.isVisibilityExplicit()) 956 classComputation = withExplicitVisibilityAlready(computation); 957 958 LinkageInfo classLV = 959 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation); 960 // The member has the same linkage as the class. If that's not externally 961 // visible, we don't need to compute anything about the linkage. 962 // FIXME: If we're only computing linkage, can we bail out here? 963 if (!isExternallyVisible(classLV.getLinkage())) 964 return classLV; 965 966 967 // Otherwise, don't merge in classLV yet, because in certain cases 968 // we need to completely ignore the visibility from it. 969 970 // Specifically, if this decl exists and has an explicit attribute. 971 const NamedDecl *explicitSpecSuppressor = nullptr; 972 973 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 974 // Only look at the type-as-written. Otherwise, deducing the return type 975 // of a function could change its linkage. 976 QualType TypeAsWritten = MD->getType(); 977 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 978 TypeAsWritten = TSI->getType(); 979 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 980 return LinkageInfo::uniqueExternal(); 981 982 // If this is a method template specialization, use the linkage for 983 // the template parameters and arguments. 984 if (FunctionTemplateSpecializationInfo *spec 985 = MD->getTemplateSpecializationInfo()) { 986 mergeTemplateLV(LV, MD, spec, computation); 987 if (spec->isExplicitSpecialization()) { 988 explicitSpecSuppressor = MD; 989 } else if (isExplicitMemberSpecialization(spec->getTemplate())) { 990 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); 991 } 992 } else if (isExplicitMemberSpecialization(MD)) { 993 explicitSpecSuppressor = MD; 994 } 995 996 // OpenMP target declare device functions are not callable from the host so 997 // they should not be exported from the device image. This applies to all 998 // functions as the host-callable kernel functions are emitted at codegen. 999 ASTContext &Context = D->getASTContext(); 1000 if (Context.getLangOpts().OpenMP && 1001 Context.getLangOpts().OpenMPIsTargetDevice && 1002 ((Context.getTargetInfo().getTriple().isAMDGPU() || 1003 Context.getTargetInfo().getTriple().isNVPTX()) || 1004 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD))) 1005 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false); 1006 1007 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 1008 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 1009 mergeTemplateLV(LV, spec, computation); 1010 if (spec->isExplicitSpecialization()) { 1011 explicitSpecSuppressor = spec; 1012 } else { 1013 const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 1014 if (isExplicitMemberSpecialization(temp)) { 1015 explicitSpecSuppressor = temp->getTemplatedDecl(); 1016 } 1017 } 1018 } else if (isExplicitMemberSpecialization(RD)) { 1019 explicitSpecSuppressor = RD; 1020 } 1021 1022 // Static data members. 1023 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 1024 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD)) 1025 mergeTemplateLV(LV, spec, computation); 1026 1027 // Modify the variable's linkage by its type, but ignore the 1028 // type's visibility unless it's a definition. 1029 if (!IgnoreVarTypeLinkage) { 1030 LinkageInfo typeLV = getLVForType(*VD->getType(), computation); 1031 // FIXME: If the type's linkage is not externally visible, we can 1032 // give this static data member UniqueExternalLinkage. 1033 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()) 1034 LV.mergeVisibility(typeLV); 1035 LV.mergeExternalVisibility(typeLV); 1036 } 1037 1038 if (isExplicitMemberSpecialization(VD)) { 1039 explicitSpecSuppressor = VD; 1040 } 1041 1042 // Template members. 1043 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 1044 bool considerVisibility = 1045 (!LV.isVisibilityExplicit() && 1046 !classLV.isVisibilityExplicit() && 1047 !hasExplicitVisibilityAlready(computation)); 1048 LinkageInfo tempLV = 1049 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 1050 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 1051 1052 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) { 1053 if (isExplicitMemberSpecialization(redeclTemp)) { 1054 explicitSpecSuppressor = temp->getTemplatedDecl(); 1055 } 1056 } 1057 } 1058 1059 // We should never be looking for an attribute directly on a template. 1060 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); 1061 1062 // If this member is an explicit member specialization, and it has 1063 // an explicit attribute, ignore visibility from the parent. 1064 bool considerClassVisibility = true; 1065 if (explicitSpecSuppressor && 1066 // optimization: hasDVA() is true only with explicit visibility. 1067 LV.isVisibilityExplicit() && 1068 classLV.getVisibility() != DefaultVisibility && 1069 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) { 1070 considerClassVisibility = false; 1071 } 1072 1073 // Finally, merge in information from the class. 1074 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility); 1075 return LV; 1076 } 1077 1078 void NamedDecl::anchor() {} 1079 1080 bool NamedDecl::isLinkageValid() const { 1081 if (!hasCachedLinkage()) 1082 return true; 1083 1084 Linkage L = LinkageComputer{} 1085 .computeLVForDecl(this, LVComputationKind::forLinkageOnly()) 1086 .getLinkage(); 1087 return L == getCachedLinkage(); 1088 } 1089 1090 bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const { 1091 // [C++2c] [basic.scope.scope]/p5 1092 // A declaration is name-independent if its name is _ and it declares 1093 // - a variable with automatic storage duration, 1094 // - a structured binding not inhabiting a namespace scope, 1095 // - the variable introduced by an init-capture 1096 // - or a non-static data member. 1097 1098 if (!LangOpts.CPlusPlus || !getIdentifier() || 1099 !getIdentifier()->isPlaceholder()) 1100 return false; 1101 if (isa<FieldDecl>(this)) 1102 return true; 1103 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) { 1104 if (!getDeclContext()->isFunctionOrMethod() && 1105 !getDeclContext()->isRecord()) 1106 return false; 1107 const VarDecl *VD = IFD->getVarDecl(); 1108 return !VD || VD->getStorageDuration() == SD_Automatic; 1109 } 1110 // and it declares a variable with automatic storage duration 1111 if (const auto *VD = dyn_cast<VarDecl>(this)) { 1112 if (isa<ParmVarDecl>(VD)) 1113 return false; 1114 if (VD->isInitCapture()) 1115 return true; 1116 return VD->getStorageDuration() == StorageDuration::SD_Automatic; 1117 } 1118 if (const auto *BD = dyn_cast<BindingDecl>(this); 1119 BD && getDeclContext()->isFunctionOrMethod()) { 1120 const VarDecl *VD = BD->getHoldingVar(); 1121 return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic; 1122 } 1123 return false; 1124 } 1125 1126 ReservedIdentifierStatus 1127 NamedDecl::isReserved(const LangOptions &LangOpts) const { 1128 const IdentifierInfo *II = getIdentifier(); 1129 1130 // This triggers at least for CXXLiteralIdentifiers, which we already checked 1131 // at lexing time. 1132 if (!II) 1133 return ReservedIdentifierStatus::NotReserved; 1134 1135 ReservedIdentifierStatus Status = II->isReserved(LangOpts); 1136 if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) { 1137 // This name is only reserved at global scope. Check if this declaration 1138 // conflicts with a global scope declaration. 1139 if (isa<ParmVarDecl>(this) || isTemplateParameter()) 1140 return ReservedIdentifierStatus::NotReserved; 1141 1142 // C++ [dcl.link]/7: 1143 // Two declarations [conflict] if [...] one declares a function or 1144 // variable with C language linkage, and the other declares [...] a 1145 // variable that belongs to the global scope. 1146 // 1147 // Therefore names that are reserved at global scope are also reserved as 1148 // names of variables and functions with C language linkage. 1149 const DeclContext *DC = getDeclContext()->getRedeclContext(); 1150 if (DC->isTranslationUnit()) 1151 return Status; 1152 if (auto *VD = dyn_cast<VarDecl>(this)) 1153 if (VD->isExternC()) 1154 return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; 1155 if (auto *FD = dyn_cast<FunctionDecl>(this)) 1156 if (FD->isExternC()) 1157 return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; 1158 return ReservedIdentifierStatus::NotReserved; 1159 } 1160 1161 return Status; 1162 } 1163 1164 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { 1165 StringRef name = getName(); 1166 if (name.empty()) return SFF_None; 1167 1168 if (name.front() == 'C') 1169 if (name == "CFStringCreateWithFormat" || 1170 name == "CFStringCreateWithFormatAndArguments" || 1171 name == "CFStringAppendFormat" || 1172 name == "CFStringAppendFormatAndArguments") 1173 return SFF_CFString; 1174 return SFF_None; 1175 } 1176 1177 Linkage NamedDecl::getLinkageInternal() const { 1178 // We don't care about visibility here, so ask for the cheapest 1179 // possible visibility analysis. 1180 return LinkageComputer{} 1181 .getLVForDecl(this, LVComputationKind::forLinkageOnly()) 1182 .getLinkage(); 1183 } 1184 1185 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) { 1186 // FIXME: Handle isModulePrivate. 1187 switch (D->getModuleOwnershipKind()) { 1188 case Decl::ModuleOwnershipKind::Unowned: 1189 case Decl::ModuleOwnershipKind::ReachableWhenImported: 1190 case Decl::ModuleOwnershipKind::ModulePrivate: 1191 return false; 1192 case Decl::ModuleOwnershipKind::Visible: 1193 case Decl::ModuleOwnershipKind::VisibleWhenImported: 1194 return D->isInNamedModule(); 1195 } 1196 llvm_unreachable("unexpected module ownership kind"); 1197 } 1198 1199 /// Get the linkage from a semantic point of view. Entities in 1200 /// anonymous namespaces are external (in c++98). 1201 Linkage NamedDecl::getFormalLinkage() const { 1202 Linkage InternalLinkage = getLinkageInternal(); 1203 1204 // C++ [basic.link]p4.8: 1205 // - if the declaration of the name is attached to a named module and is not 1206 // exported 1207 // the name has module linkage; 1208 // 1209 // [basic.namespace.general]/p2 1210 // A namespace is never attached to a named module and never has a name with 1211 // module linkage. 1212 if (isInNamedModule() && InternalLinkage == Linkage::External && 1213 !isExportedFromModuleInterfaceUnit( 1214 cast<NamedDecl>(this->getCanonicalDecl())) && 1215 !isa<NamespaceDecl>(this)) 1216 InternalLinkage = Linkage::Module; 1217 1218 return clang::getFormalLinkage(InternalLinkage); 1219 } 1220 1221 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 1222 return LinkageComputer{}.getDeclLinkageAndVisibility(this); 1223 } 1224 1225 static std::optional<Visibility> 1226 getExplicitVisibilityAux(const NamedDecl *ND, 1227 NamedDecl::ExplicitVisibilityKind kind, 1228 bool IsMostRecent) { 1229 assert(!IsMostRecent || ND == ND->getMostRecentDecl()); 1230 1231 // Check the declaration itself first. 1232 if (std::optional<Visibility> V = getVisibilityOf(ND, kind)) 1233 return V; 1234 1235 // If this is a member class of a specialization of a class template 1236 // and the corresponding decl has explicit visibility, use that. 1237 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 1238 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 1239 if (InstantiatedFrom) 1240 return getVisibilityOf(InstantiatedFrom, kind); 1241 } 1242 1243 // If there wasn't explicit visibility there, and this is a 1244 // specialization of a class template, check for visibility 1245 // on the pattern. 1246 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 1247 // Walk all the template decl till this point to see if there are 1248 // explicit visibility attributes. 1249 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl(); 1250 while (TD != nullptr) { 1251 auto Vis = getVisibilityOf(TD, kind); 1252 if (Vis != std::nullopt) 1253 return Vis; 1254 TD = TD->getPreviousDecl(); 1255 } 1256 return std::nullopt; 1257 } 1258 1259 // Use the most recent declaration. 1260 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) { 1261 const NamedDecl *MostRecent = ND->getMostRecentDecl(); 1262 if (MostRecent != ND) 1263 return getExplicitVisibilityAux(MostRecent, kind, true); 1264 } 1265 1266 if (const auto *Var = dyn_cast<VarDecl>(ND)) { 1267 if (Var->isStaticDataMember()) { 1268 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 1269 if (InstantiatedFrom) 1270 return getVisibilityOf(InstantiatedFrom, kind); 1271 } 1272 1273 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var)) 1274 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), 1275 kind); 1276 1277 return std::nullopt; 1278 } 1279 // Also handle function template specializations. 1280 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) { 1281 // If the function is a specialization of a template with an 1282 // explicit visibility attribute, use that. 1283 if (FunctionTemplateSpecializationInfo *templateInfo 1284 = fn->getTemplateSpecializationInfo()) 1285 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), 1286 kind); 1287 1288 // If the function is a member of a specialization of a class template 1289 // and the corresponding decl has explicit visibility, use that. 1290 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 1291 if (InstantiatedFrom) 1292 return getVisibilityOf(InstantiatedFrom, kind); 1293 1294 return std::nullopt; 1295 } 1296 1297 // The visibility of a template is stored in the templated decl. 1298 if (const auto *TD = dyn_cast<TemplateDecl>(ND)) 1299 return getVisibilityOf(TD->getTemplatedDecl(), kind); 1300 1301 return std::nullopt; 1302 } 1303 1304 std::optional<Visibility> 1305 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { 1306 return getExplicitVisibilityAux(this, kind, false); 1307 } 1308 1309 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC, 1310 Decl *ContextDecl, 1311 LVComputationKind computation) { 1312 // This lambda has its linkage/visibility determined by its owner. 1313 const NamedDecl *Owner; 1314 if (!ContextDecl) 1315 Owner = dyn_cast<NamedDecl>(DC); 1316 else if (isa<ParmVarDecl>(ContextDecl)) 1317 Owner = 1318 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext()); 1319 else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) { 1320 // Replace with the concept's owning decl, which is either a namespace or a 1321 // TU, so this needs a dyn_cast. 1322 Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext()); 1323 } else { 1324 Owner = cast<NamedDecl>(ContextDecl); 1325 } 1326 1327 if (!Owner) 1328 return LinkageInfo::none(); 1329 1330 // If the owner has a deduced type, we need to skip querying the linkage and 1331 // visibility of that type, because it might involve this closure type. The 1332 // only effect of this is that we might give a lambda VisibleNoLinkage rather 1333 // than NoLinkage when we don't strictly need to, which is benign. 1334 auto *VD = dyn_cast<VarDecl>(Owner); 1335 LinkageInfo OwnerLV = 1336 VD && VD->getType()->getContainedDeducedType() 1337 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true) 1338 : getLVForDecl(Owner, computation); 1339 1340 // A lambda never formally has linkage. But if the owner is externally 1341 // visible, then the lambda is too. We apply the same rules to blocks. 1342 if (!isExternallyVisible(OwnerLV.getLinkage())) 1343 return LinkageInfo::none(); 1344 return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(), 1345 OwnerLV.isVisibilityExplicit()); 1346 } 1347 1348 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, 1349 LVComputationKind computation) { 1350 if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 1351 if (Function->isInAnonymousNamespace() && 1352 !isFirstInExternCContext(Function)) 1353 return LinkageInfo::internal(); 1354 1355 // This is a "void f();" which got merged with a file static. 1356 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 1357 return LinkageInfo::internal(); 1358 1359 LinkageInfo LV; 1360 if (!hasExplicitVisibilityAlready(computation)) { 1361 if (std::optional<Visibility> Vis = 1362 getExplicitVisibility(Function, computation)) 1363 LV.mergeVisibility(*Vis, true); 1364 } 1365 1366 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 1367 // merging storage classes and visibility attributes, so we don't have to 1368 // look at previous decls in here. 1369 1370 return LV; 1371 } 1372 1373 if (const auto *Var = dyn_cast<VarDecl>(D)) { 1374 if (Var->hasExternalStorage()) { 1375 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var)) 1376 return LinkageInfo::internal(); 1377 1378 LinkageInfo LV; 1379 if (Var->getStorageClass() == SC_PrivateExtern) 1380 LV.mergeVisibility(HiddenVisibility, true); 1381 else if (!hasExplicitVisibilityAlready(computation)) { 1382 if (std::optional<Visibility> Vis = 1383 getExplicitVisibility(Var, computation)) 1384 LV.mergeVisibility(*Vis, true); 1385 } 1386 1387 if (const VarDecl *Prev = Var->getPreviousDecl()) { 1388 LinkageInfo PrevLV = getLVForDecl(Prev, computation); 1389 if (PrevLV.getLinkage() != Linkage::Invalid) 1390 LV.setLinkage(PrevLV.getLinkage()); 1391 LV.mergeVisibility(PrevLV); 1392 } 1393 1394 return LV; 1395 } 1396 1397 if (!Var->isStaticLocal()) 1398 return LinkageInfo::none(); 1399 } 1400 1401 ASTContext &Context = D->getASTContext(); 1402 if (!Context.getLangOpts().CPlusPlus) 1403 return LinkageInfo::none(); 1404 1405 const Decl *OuterD = getOutermostFuncOrBlockContext(D); 1406 if (!OuterD || OuterD->isInvalidDecl()) 1407 return LinkageInfo::none(); 1408 1409 LinkageInfo LV; 1410 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) { 1411 if (!BD->getBlockManglingNumber()) 1412 return LinkageInfo::none(); 1413 1414 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(), 1415 BD->getBlockManglingContextDecl(), computation); 1416 } else { 1417 const auto *FD = cast<FunctionDecl>(OuterD); 1418 if (!FD->isInlined() && 1419 !isTemplateInstantiation(FD->getTemplateSpecializationKind())) 1420 return LinkageInfo::none(); 1421 1422 // If a function is hidden by -fvisibility-inlines-hidden option and 1423 // is not explicitly attributed as a hidden function, 1424 // we should not make static local variables in the function hidden. 1425 LV = getLVForDecl(FD, computation); 1426 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) && 1427 !LV.isVisibilityExplicit() && 1428 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) { 1429 assert(cast<VarDecl>(D)->isStaticLocal()); 1430 // If this was an implicitly hidden inline method, check again for 1431 // explicit visibility on the parent class, and use that for static locals 1432 // if present. 1433 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1434 LV = getLVForDecl(MD->getParent(), computation); 1435 if (!LV.isVisibilityExplicit()) { 1436 Visibility globalVisibility = 1437 computation.isValueVisibility() 1438 ? Context.getLangOpts().getValueVisibilityMode() 1439 : Context.getLangOpts().getTypeVisibilityMode(); 1440 return LinkageInfo(Linkage::VisibleNone, globalVisibility, 1441 /*visibilityExplicit=*/false); 1442 } 1443 } 1444 } 1445 if (!isExternallyVisible(LV.getLinkage())) 1446 return LinkageInfo::none(); 1447 return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(), 1448 LV.isVisibilityExplicit()); 1449 } 1450 1451 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, 1452 LVComputationKind computation, 1453 bool IgnoreVarTypeLinkage) { 1454 // Internal_linkage attribute overrides other considerations. 1455 if (D->hasAttr<InternalLinkageAttr>()) 1456 return LinkageInfo::internal(); 1457 1458 // Objective-C: treat all Objective-C declarations as having external 1459 // linkage. 1460 switch (D->getKind()) { 1461 default: 1462 break; 1463 1464 // Per C++ [basic.link]p2, only the names of objects, references, 1465 // functions, types, templates, namespaces, and values ever have linkage. 1466 // 1467 // Note that the name of a typedef, namespace alias, using declaration, 1468 // and so on are not the name of the corresponding type, namespace, or 1469 // declaration, so they do *not* have linkage. 1470 case Decl::ImplicitParam: 1471 case Decl::Label: 1472 case Decl::NamespaceAlias: 1473 case Decl::ParmVar: 1474 case Decl::Using: 1475 case Decl::UsingEnum: 1476 case Decl::UsingShadow: 1477 case Decl::UsingDirective: 1478 return LinkageInfo::none(); 1479 1480 case Decl::EnumConstant: 1481 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. 1482 if (D->getASTContext().getLangOpts().CPlusPlus) 1483 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation); 1484 return LinkageInfo::visible_none(); 1485 1486 case Decl::Typedef: 1487 case Decl::TypeAlias: 1488 // A typedef declaration has linkage if it gives a type a name for 1489 // linkage purposes. 1490 if (!cast<TypedefNameDecl>(D) 1491 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 1492 return LinkageInfo::none(); 1493 break; 1494 1495 case Decl::TemplateTemplateParm: // count these as external 1496 case Decl::NonTypeTemplateParm: 1497 case Decl::ObjCAtDefsField: 1498 case Decl::ObjCCategory: 1499 case Decl::ObjCCategoryImpl: 1500 case Decl::ObjCCompatibleAlias: 1501 case Decl::ObjCImplementation: 1502 case Decl::ObjCMethod: 1503 case Decl::ObjCProperty: 1504 case Decl::ObjCPropertyImpl: 1505 case Decl::ObjCProtocol: 1506 return getExternalLinkageFor(D); 1507 1508 case Decl::CXXRecord: { 1509 const auto *Record = cast<CXXRecordDecl>(D); 1510 if (Record->isLambda()) { 1511 if (Record->hasKnownLambdaInternalLinkage() || 1512 !Record->getLambdaManglingNumber()) { 1513 // This lambda has no mangling number, so it's internal. 1514 return LinkageInfo::internal(); 1515 } 1516 1517 return getLVForClosure( 1518 Record->getDeclContext()->getRedeclContext(), 1519 Record->getLambdaContextDecl(), computation); 1520 } 1521 1522 break; 1523 } 1524 1525 case Decl::TemplateParamObject: { 1526 // The template parameter object can be referenced from anywhere its type 1527 // and value can be referenced. 1528 auto *TPO = cast<TemplateParamObjectDecl>(D); 1529 LinkageInfo LV = getLVForType(*TPO->getType(), computation); 1530 LV.merge(getLVForValue(TPO->getValue(), computation)); 1531 return LV; 1532 } 1533 } 1534 1535 // Handle linkage for namespace-scope names. 1536 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 1537 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); 1538 1539 // C++ [basic.link]p5: 1540 // In addition, a member function, static data member, a named 1541 // class or enumeration of class scope, or an unnamed class or 1542 // enumeration defined in a class-scope typedef declaration such 1543 // that the class or enumeration has the typedef name for linkage 1544 // purposes (7.1.3), has external linkage if the name of the class 1545 // has external linkage. 1546 if (D->getDeclContext()->isRecord()) 1547 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage); 1548 1549 // C++ [basic.link]p6: 1550 // The name of a function declared in block scope and the name of 1551 // an object declared by a block scope extern declaration have 1552 // linkage. If there is a visible declaration of an entity with 1553 // linkage having the same name and type, ignoring entities 1554 // declared outside the innermost enclosing namespace scope, the 1555 // block scope declaration declares that same entity and receives 1556 // the linkage of the previous declaration. If there is more than 1557 // one such matching entity, the program is ill-formed. Otherwise, 1558 // if no matching entity is found, the block scope entity receives 1559 // external linkage. 1560 if (D->getDeclContext()->isFunctionOrMethod()) 1561 return getLVForLocalDecl(D, computation); 1562 1563 // C++ [basic.link]p6: 1564 // Names not covered by these rules have no linkage. 1565 return LinkageInfo::none(); 1566 } 1567 1568 /// getLVForDecl - Get the linkage and visibility for the given declaration. 1569 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, 1570 LVComputationKind computation) { 1571 // Internal_linkage attribute overrides other considerations. 1572 if (D->hasAttr<InternalLinkageAttr>()) 1573 return LinkageInfo::internal(); 1574 1575 if (computation.IgnoreAllVisibility && D->hasCachedLinkage()) 1576 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); 1577 1578 if (std::optional<LinkageInfo> LI = lookup(D, computation)) 1579 return *LI; 1580 1581 LinkageInfo LV = computeLVForDecl(D, computation); 1582 if (D->hasCachedLinkage()) 1583 assert(D->getCachedLinkage() == LV.getLinkage()); 1584 1585 D->setCachedLinkage(LV.getLinkage()); 1586 cache(D, computation, LV); 1587 1588 #ifndef NDEBUG 1589 // In C (because of gnu inline) and in c++ with microsoft extensions an 1590 // static can follow an extern, so we can have two decls with different 1591 // linkages. 1592 const LangOptions &Opts = D->getASTContext().getLangOpts(); 1593 if (!Opts.CPlusPlus || Opts.MicrosoftExt) 1594 return LV; 1595 1596 // We have just computed the linkage for this decl. By induction we know 1597 // that all other computed linkages match, check that the one we just 1598 // computed also does. 1599 NamedDecl *Old = nullptr; 1600 for (auto *I : D->redecls()) { 1601 auto *T = cast<NamedDecl>(I); 1602 if (T == D) 1603 continue; 1604 if (!T->isInvalidDecl() && T->hasCachedLinkage()) { 1605 Old = T; 1606 break; 1607 } 1608 } 1609 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage()); 1610 #endif 1611 1612 return LV; 1613 } 1614 1615 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) { 1616 NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D) 1617 ? NamedDecl::VisibilityForType 1618 : NamedDecl::VisibilityForValue; 1619 LVComputationKind CK(EK); 1620 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility 1621 ? CK.forLinkageOnly() 1622 : CK); 1623 } 1624 1625 Module *Decl::getOwningModuleForLinkage() const { 1626 if (isa<NamespaceDecl>(this)) 1627 // Namespaces never have module linkage. It is the entities within them 1628 // that [may] do. 1629 return nullptr; 1630 1631 Module *M = getOwningModule(); 1632 if (!M) 1633 return nullptr; 1634 1635 switch (M->Kind) { 1636 case Module::ModuleMapModule: 1637 // Module map modules have no special linkage semantics. 1638 return nullptr; 1639 1640 case Module::ModuleInterfaceUnit: 1641 case Module::ModuleImplementationUnit: 1642 case Module::ModulePartitionInterface: 1643 case Module::ModulePartitionImplementation: 1644 return M; 1645 1646 case Module::ModuleHeaderUnit: 1647 case Module::ExplicitGlobalModuleFragment: 1648 case Module::ImplicitGlobalModuleFragment: 1649 // The global module shouldn't change the linkage. 1650 return nullptr; 1651 1652 case Module::PrivateModuleFragment: 1653 // The private module fragment is part of its containing module for linkage 1654 // purposes. 1655 return M->Parent; 1656 } 1657 1658 llvm_unreachable("unknown module kind"); 1659 } 1660 1661 void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 1662 Name.print(OS, Policy); 1663 } 1664 1665 void NamedDecl::printName(raw_ostream &OS) const { 1666 printName(OS, getASTContext().getPrintingPolicy()); 1667 } 1668 1669 std::string NamedDecl::getQualifiedNameAsString() const { 1670 std::string QualName; 1671 llvm::raw_string_ostream OS(QualName); 1672 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1673 return QualName; 1674 } 1675 1676 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1677 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1678 } 1679 1680 void NamedDecl::printQualifiedName(raw_ostream &OS, 1681 const PrintingPolicy &P) const { 1682 if (getDeclContext()->isFunctionOrMethod()) { 1683 // We do not print '(anonymous)' for function parameters without name. 1684 printName(OS, P); 1685 return; 1686 } 1687 printNestedNameSpecifier(OS, P); 1688 if (getDeclName()) 1689 OS << *this; 1690 else { 1691 // Give the printName override a chance to pick a different name before we 1692 // fall back to "(anonymous)". 1693 SmallString<64> NameBuffer; 1694 llvm::raw_svector_ostream NameOS(NameBuffer); 1695 printName(NameOS, P); 1696 if (NameBuffer.empty()) 1697 OS << "(anonymous)"; 1698 else 1699 OS << NameBuffer; 1700 } 1701 } 1702 1703 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const { 1704 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy()); 1705 } 1706 1707 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS, 1708 const PrintingPolicy &P) const { 1709 const DeclContext *Ctx = getDeclContext(); 1710 1711 // For ObjC methods and properties, look through categories and use the 1712 // interface as context. 1713 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) { 1714 if (auto *ID = MD->getClassInterface()) 1715 Ctx = ID; 1716 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) { 1717 if (auto *MD = PD->getGetterMethodDecl()) 1718 if (auto *ID = MD->getClassInterface()) 1719 Ctx = ID; 1720 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) { 1721 if (auto *CI = ID->getContainingInterface()) 1722 Ctx = CI; 1723 } 1724 1725 if (Ctx->isFunctionOrMethod()) 1726 return; 1727 1728 using ContextsTy = SmallVector<const DeclContext *, 8>; 1729 ContextsTy Contexts; 1730 1731 // Collect named contexts. 1732 DeclarationName NameInScope = getDeclName(); 1733 for (; Ctx; Ctx = Ctx->getParent()) { 1734 // Suppress anonymous namespace if requested. 1735 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) && 1736 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace()) 1737 continue; 1738 1739 // Suppress inline namespace if it doesn't make the result ambiguous. 1740 if (Ctx->isInlineNamespace() && NameInScope) { 1741 bool isRedundant = 1742 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope); 1743 if (P.SuppressInlineNamespace == 1744 PrintingPolicy::SuppressInlineNamespaceMode::All || 1745 (P.SuppressInlineNamespace == 1746 PrintingPolicy::SuppressInlineNamespaceMode::Redundant && 1747 isRedundant)) { 1748 continue; 1749 } 1750 } 1751 1752 // Skip non-named contexts such as linkage specifications and ExportDecls. 1753 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx); 1754 if (!ND) 1755 continue; 1756 1757 Contexts.push_back(Ctx); 1758 NameInScope = ND->getDeclName(); 1759 } 1760 1761 for (const DeclContext *DC : llvm::reverse(Contexts)) { 1762 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1763 OS << Spec->getName(); 1764 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1765 printTemplateArgumentList( 1766 OS, TemplateArgs.asArray(), P, 1767 Spec->getSpecializedTemplate()->getTemplateParameters()); 1768 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 1769 if (ND->isAnonymousNamespace()) { 1770 OS << (P.MSVCFormatting ? "`anonymous namespace\'" 1771 : "(anonymous namespace)"); 1772 } 1773 else 1774 OS << *ND; 1775 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { 1776 if (!RD->getIdentifier()) 1777 OS << "(anonymous " << RD->getKindName() << ')'; 1778 else 1779 OS << *RD; 1780 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1781 const FunctionProtoType *FT = nullptr; 1782 if (FD->hasWrittenPrototype()) 1783 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1784 1785 OS << *FD << '('; 1786 if (FT) { 1787 unsigned NumParams = FD->getNumParams(); 1788 for (unsigned i = 0; i < NumParams; ++i) { 1789 if (i) 1790 OS << ", "; 1791 OS << FD->getParamDecl(i)->getType().stream(P); 1792 } 1793 1794 if (FT->isVariadic()) { 1795 if (NumParams > 0) 1796 OS << ", "; 1797 OS << "..."; 1798 } 1799 } 1800 OS << ')'; 1801 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) { 1802 // C++ [dcl.enum]p10: Each enum-name and each unscoped 1803 // enumerator is declared in the scope that immediately contains 1804 // the enum-specifier. Each scoped enumerator is declared in the 1805 // scope of the enumeration. 1806 // For the case of unscoped enumerator, do not include in the qualified 1807 // name any information about its enum enclosing scope, as its visibility 1808 // is global. 1809 if (ED->isScoped()) 1810 OS << *ED; 1811 else 1812 continue; 1813 } else { 1814 OS << *cast<NamedDecl>(DC); 1815 } 1816 OS << "::"; 1817 } 1818 } 1819 1820 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1821 const PrintingPolicy &Policy, 1822 bool Qualified) const { 1823 if (Qualified) 1824 printQualifiedName(OS, Policy); 1825 else 1826 printName(OS, Policy); 1827 } 1828 1829 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1830 return true; 1831 } 1832 static bool isRedeclarableImpl(...) { return false; } 1833 static bool isRedeclarable(Decl::Kind K) { 1834 switch (K) { 1835 #define DECL(Type, Base) \ 1836 case Decl::Type: \ 1837 return isRedeclarableImpl((Type##Decl *)nullptr); 1838 #define ABSTRACT_DECL(DECL) 1839 #include "clang/AST/DeclNodes.inc" 1840 } 1841 llvm_unreachable("unknown decl kind"); 1842 } 1843 1844 bool NamedDecl::declarationReplaces(const NamedDecl *OldD, 1845 bool IsKnownNewer) const { 1846 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1847 1848 // Never replace one imported declaration with another; we need both results 1849 // when re-exporting. 1850 if (OldD->isFromASTFile() && isFromASTFile()) 1851 return false; 1852 1853 // A kind mismatch implies that the declaration is not replaced. 1854 if (OldD->getKind() != getKind()) 1855 return false; 1856 1857 // For method declarations, we never replace. (Why?) 1858 if (isa<ObjCMethodDecl>(this)) 1859 return false; 1860 1861 // For parameters, pick the newer one. This is either an error or (in 1862 // Objective-C) permitted as an extension. 1863 if (isa<ParmVarDecl>(this)) 1864 return true; 1865 1866 // Inline namespaces can give us two declarations with the same 1867 // name and kind in the same scope but different contexts; we should 1868 // keep both declarations in this case. 1869 if (!this->getDeclContext()->getRedeclContext()->Equals( 1870 OldD->getDeclContext()->getRedeclContext())) 1871 return false; 1872 1873 // Using declarations can be replaced if they import the same name from the 1874 // same context. 1875 if (const auto *UD = dyn_cast<UsingDecl>(this)) { 1876 ASTContext &Context = getASTContext(); 1877 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1878 Context.getCanonicalNestedNameSpecifier( 1879 cast<UsingDecl>(OldD)->getQualifier()); 1880 } 1881 if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1882 ASTContext &Context = getASTContext(); 1883 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1884 Context.getCanonicalNestedNameSpecifier( 1885 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1886 } 1887 1888 if (isRedeclarable(getKind())) { 1889 if (getCanonicalDecl() != OldD->getCanonicalDecl()) 1890 return false; 1891 1892 if (IsKnownNewer) 1893 return true; 1894 1895 // Check whether this is actually newer than OldD. We want to keep the 1896 // newer declaration. This loop will usually only iterate once, because 1897 // OldD is usually the previous declaration. 1898 for (const auto *D : redecls()) { 1899 if (D == OldD) 1900 break; 1901 1902 // If we reach the canonical declaration, then OldD is not actually older 1903 // than this one. 1904 // 1905 // FIXME: In this case, we should not add this decl to the lookup table. 1906 if (D->isCanonicalDecl()) 1907 return false; 1908 } 1909 1910 // It's a newer declaration of the same kind of declaration in the same 1911 // scope: we want this decl instead of the existing one. 1912 return true; 1913 } 1914 1915 // In all other cases, we need to keep both declarations in case they have 1916 // different visibility. Any attempt to use the name will result in an 1917 // ambiguity if more than one is visible. 1918 return false; 1919 } 1920 1921 bool NamedDecl::hasLinkage() const { 1922 switch (getFormalLinkage()) { 1923 case Linkage::Invalid: 1924 llvm_unreachable("Linkage hasn't been computed!"); 1925 case Linkage::None: 1926 return false; 1927 case Linkage::Internal: 1928 return true; 1929 case Linkage::UniqueExternal: 1930 case Linkage::VisibleNone: 1931 llvm_unreachable("Non-formal linkage is not allowed here!"); 1932 case Linkage::Module: 1933 case Linkage::External: 1934 return true; 1935 } 1936 llvm_unreachable("Unhandled Linkage enum"); 1937 } 1938 1939 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1940 NamedDecl *ND = this; 1941 if (auto *UD = dyn_cast<UsingShadowDecl>(ND)) 1942 ND = UD->getTargetDecl(); 1943 1944 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1945 return AD->getClassInterface(); 1946 1947 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND)) 1948 return AD->getNamespace(); 1949 1950 return ND; 1951 } 1952 1953 bool NamedDecl::isCXXInstanceMember() const { 1954 if (!isCXXClassMember()) 1955 return false; 1956 1957 const NamedDecl *D = this; 1958 if (isa<UsingShadowDecl>(D)) 1959 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1960 1961 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1962 return true; 1963 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction())) 1964 return MD->isInstance(); 1965 return false; 1966 } 1967 1968 //===----------------------------------------------------------------------===// 1969 // DeclaratorDecl Implementation 1970 //===----------------------------------------------------------------------===// 1971 1972 template <typename DeclT> 1973 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1974 if (decl->getNumTemplateParameterLists() > 0) 1975 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1976 return decl->getInnerLocStart(); 1977 } 1978 1979 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1980 TypeSourceInfo *TSI = getTypeSourceInfo(); 1981 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1982 return SourceLocation(); 1983 } 1984 1985 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const { 1986 TypeSourceInfo *TSI = getTypeSourceInfo(); 1987 if (TSI) return TSI->getTypeLoc().getEndLoc(); 1988 return SourceLocation(); 1989 } 1990 1991 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1992 if (QualifierLoc) { 1993 // Make sure the extended decl info is allocated. 1994 if (!hasExtInfo()) { 1995 // Save (non-extended) type source info pointer. 1996 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1997 // Allocate external info struct. 1998 DeclInfo = new (getASTContext()) ExtInfo; 1999 // Restore savedTInfo into (extended) decl info. 2000 getExtInfo()->TInfo = savedTInfo; 2001 } 2002 // Set qualifier info. 2003 getExtInfo()->QualifierLoc = QualifierLoc; 2004 } else if (hasExtInfo()) { 2005 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2006 getExtInfo()->QualifierLoc = QualifierLoc; 2007 } 2008 } 2009 2010 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) { 2011 assert(TrailingRequiresClause); 2012 // Make sure the extended decl info is allocated. 2013 if (!hasExtInfo()) { 2014 // Save (non-extended) type source info pointer. 2015 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 2016 // Allocate external info struct. 2017 DeclInfo = new (getASTContext()) ExtInfo; 2018 // Restore savedTInfo into (extended) decl info. 2019 getExtInfo()->TInfo = savedTInfo; 2020 } 2021 // Set requires clause info. 2022 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause; 2023 } 2024 2025 void DeclaratorDecl::setTemplateParameterListsInfo( 2026 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 2027 assert(!TPLists.empty()); 2028 // Make sure the extended decl info is allocated. 2029 if (!hasExtInfo()) { 2030 // Save (non-extended) type source info pointer. 2031 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 2032 // Allocate external info struct. 2033 DeclInfo = new (getASTContext()) ExtInfo; 2034 // Restore savedTInfo into (extended) decl info. 2035 getExtInfo()->TInfo = savedTInfo; 2036 } 2037 // Set the template parameter lists info. 2038 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 2039 } 2040 2041 SourceLocation DeclaratorDecl::getOuterLocStart() const { 2042 return getTemplateOrInnerLocStart(this); 2043 } 2044 2045 // Helper function: returns true if QT is or contains a type 2046 // having a postfix component. 2047 static bool typeIsPostfix(QualType QT) { 2048 while (true) { 2049 const Type* T = QT.getTypePtr(); 2050 switch (T->getTypeClass()) { 2051 default: 2052 return false; 2053 case Type::Pointer: 2054 QT = cast<PointerType>(T)->getPointeeType(); 2055 break; 2056 case Type::BlockPointer: 2057 QT = cast<BlockPointerType>(T)->getPointeeType(); 2058 break; 2059 case Type::MemberPointer: 2060 QT = cast<MemberPointerType>(T)->getPointeeType(); 2061 break; 2062 case Type::LValueReference: 2063 case Type::RValueReference: 2064 QT = cast<ReferenceType>(T)->getPointeeType(); 2065 break; 2066 case Type::PackExpansion: 2067 QT = cast<PackExpansionType>(T)->getPattern(); 2068 break; 2069 case Type::Paren: 2070 case Type::ConstantArray: 2071 case Type::DependentSizedArray: 2072 case Type::IncompleteArray: 2073 case Type::VariableArray: 2074 case Type::FunctionProto: 2075 case Type::FunctionNoProto: 2076 return true; 2077 } 2078 } 2079 } 2080 2081 SourceRange DeclaratorDecl::getSourceRange() const { 2082 SourceLocation RangeEnd = getLocation(); 2083 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 2084 // If the declaration has no name or the type extends past the name take the 2085 // end location of the type. 2086 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 2087 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 2088 } 2089 return SourceRange(getOuterLocStart(), RangeEnd); 2090 } 2091 2092 void QualifierInfo::setTemplateParameterListsInfo( 2093 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 2094 // Free previous template parameters (if any). 2095 if (NumTemplParamLists > 0) { 2096 Context.Deallocate(TemplParamLists); 2097 TemplParamLists = nullptr; 2098 NumTemplParamLists = 0; 2099 } 2100 // Set info on matched template parameter lists (if any). 2101 if (!TPLists.empty()) { 2102 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 2103 NumTemplParamLists = TPLists.size(); 2104 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 2105 } 2106 } 2107 2108 //===----------------------------------------------------------------------===// 2109 // VarDecl Implementation 2110 //===----------------------------------------------------------------------===// 2111 2112 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 2113 switch (SC) { 2114 case SC_None: break; 2115 case SC_Auto: return "auto"; 2116 case SC_Extern: return "extern"; 2117 case SC_PrivateExtern: return "__private_extern__"; 2118 case SC_Register: return "register"; 2119 case SC_Static: return "static"; 2120 } 2121 2122 llvm_unreachable("Invalid storage class"); 2123 } 2124 2125 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 2126 SourceLocation StartLoc, SourceLocation IdLoc, 2127 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 2128 StorageClass SC) 2129 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 2130 redeclarable_base(C) { 2131 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 2132 "VarDeclBitfields too large!"); 2133 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 2134 "ParmVarDeclBitfields too large!"); 2135 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 2136 "NonParmVarDeclBitfields too large!"); 2137 AllBits = 0; 2138 VarDeclBits.SClass = SC; 2139 // Everything else is implicitly initialized to false. 2140 } 2141 2142 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL, 2143 SourceLocation IdL, const IdentifierInfo *Id, 2144 QualType T, TypeSourceInfo *TInfo, StorageClass S) { 2145 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 2146 } 2147 2148 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 2149 return new (C, ID) 2150 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 2151 QualType(), nullptr, SC_None); 2152 } 2153 2154 void VarDecl::setStorageClass(StorageClass SC) { 2155 assert(isLegalForVariable(SC)); 2156 VarDeclBits.SClass = SC; 2157 } 2158 2159 VarDecl::TLSKind VarDecl::getTLSKind() const { 2160 switch (VarDeclBits.TSCSpec) { 2161 case TSCS_unspecified: 2162 if (!hasAttr<ThreadAttr>() && 2163 !(getASTContext().getLangOpts().OpenMPUseTLS && 2164 getASTContext().getTargetInfo().isTLSSupported() && 2165 hasAttr<OMPThreadPrivateDeclAttr>())) 2166 return TLS_None; 2167 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 2168 LangOptions::MSVC2015)) || 2169 hasAttr<OMPThreadPrivateDeclAttr>()) 2170 ? TLS_Dynamic 2171 : TLS_Static; 2172 case TSCS___thread: // Fall through. 2173 case TSCS__Thread_local: 2174 return TLS_Static; 2175 case TSCS_thread_local: 2176 return TLS_Dynamic; 2177 } 2178 llvm_unreachable("Unknown thread storage class specifier!"); 2179 } 2180 2181 SourceRange VarDecl::getSourceRange() const { 2182 if (const Expr *Init = getInit()) { 2183 SourceLocation InitEnd = Init->getEndLoc(); 2184 // If Init is implicit, ignore its source range and fallback on 2185 // DeclaratorDecl::getSourceRange() to handle postfix elements. 2186 if (InitEnd.isValid() && InitEnd != getLocation()) 2187 return SourceRange(getOuterLocStart(), InitEnd); 2188 } 2189 return DeclaratorDecl::getSourceRange(); 2190 } 2191 2192 template<typename T> 2193 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 2194 // C++ [dcl.link]p1: All function types, function names with external linkage, 2195 // and variable names with external linkage have a language linkage. 2196 if (!D.hasExternalFormalLinkage()) 2197 return NoLanguageLinkage; 2198 2199 // Language linkage is a C++ concept, but saying that everything else in C has 2200 // C language linkage fits the implementation nicely. 2201 if (!D.getASTContext().getLangOpts().CPlusPlus) 2202 return CLanguageLinkage; 2203 2204 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 2205 // language linkage of the names of class members and the function type of 2206 // class member functions. 2207 const DeclContext *DC = D.getDeclContext(); 2208 if (DC->isRecord()) 2209 return CXXLanguageLinkage; 2210 2211 // If the first decl is in an extern "C" context, any other redeclaration 2212 // will have C language linkage. If the first one is not in an extern "C" 2213 // context, we would have reported an error for any other decl being in one. 2214 if (isFirstInExternCContext(&D)) 2215 return CLanguageLinkage; 2216 return CXXLanguageLinkage; 2217 } 2218 2219 template<typename T> 2220 static bool isDeclExternC(const T &D) { 2221 // Since the context is ignored for class members, they can only have C++ 2222 // language linkage or no language linkage. 2223 const DeclContext *DC = D.getDeclContext(); 2224 if (DC->isRecord()) { 2225 assert(D.getASTContext().getLangOpts().CPlusPlus); 2226 return false; 2227 } 2228 2229 return D.getLanguageLinkage() == CLanguageLinkage; 2230 } 2231 2232 LanguageLinkage VarDecl::getLanguageLinkage() const { 2233 return getDeclLanguageLinkage(*this); 2234 } 2235 2236 bool VarDecl::isExternC() const { 2237 return isDeclExternC(*this); 2238 } 2239 2240 bool VarDecl::isInExternCContext() const { 2241 return getLexicalDeclContext()->isExternCContext(); 2242 } 2243 2244 bool VarDecl::isInExternCXXContext() const { 2245 return getLexicalDeclContext()->isExternCXXContext(); 2246 } 2247 2248 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 2249 2250 VarDecl::DefinitionKind 2251 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 2252 if (isThisDeclarationADemotedDefinition()) 2253 return DeclarationOnly; 2254 2255 // C++ [basic.def]p2: 2256 // A declaration is a definition unless [...] it contains the 'extern' 2257 // specifier or a linkage-specification and neither an initializer [...], 2258 // it declares a non-inline static data member in a class declaration [...], 2259 // it declares a static data member outside a class definition and the variable 2260 // was defined within the class with the constexpr specifier [...], 2261 // C++1y [temp.expl.spec]p15: 2262 // An explicit specialization of a static data member or an explicit 2263 // specialization of a static data member template is a definition if the 2264 // declaration includes an initializer; otherwise, it is a declaration. 2265 // 2266 // FIXME: How do you declare (but not define) a partial specialization of 2267 // a static data member template outside the containing class? 2268 if (isStaticDataMember()) { 2269 if (isOutOfLine() && 2270 !(getCanonicalDecl()->isInline() && 2271 getCanonicalDecl()->isConstexpr()) && 2272 (hasInit() || 2273 // If the first declaration is out-of-line, this may be an 2274 // instantiation of an out-of-line partial specialization of a variable 2275 // template for which we have not yet instantiated the initializer. 2276 (getFirstDecl()->isOutOfLine() 2277 ? getTemplateSpecializationKind() == TSK_Undeclared 2278 : getTemplateSpecializationKind() != 2279 TSK_ExplicitSpecialization) || 2280 isa<VarTemplatePartialSpecializationDecl>(this))) 2281 return Definition; 2282 if (!isOutOfLine() && isInline()) 2283 return Definition; 2284 return DeclarationOnly; 2285 } 2286 // C99 6.7p5: 2287 // A definition of an identifier is a declaration for that identifier that 2288 // [...] causes storage to be reserved for that object. 2289 // Note: that applies for all non-file-scope objects. 2290 // C99 6.9.2p1: 2291 // If the declaration of an identifier for an object has file scope and an 2292 // initializer, the declaration is an external definition for the identifier 2293 if (hasInit()) 2294 return Definition; 2295 2296 if (hasDefiningAttr()) 2297 return Definition; 2298 2299 if (const auto *SAA = getAttr<SelectAnyAttr>()) 2300 if (!SAA->isInherited()) 2301 return Definition; 2302 2303 // A variable template specialization (other than a static data member 2304 // template or an explicit specialization) is a declaration until we 2305 // instantiate its initializer. 2306 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2307 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2308 !isa<VarTemplatePartialSpecializationDecl>(VTSD) && 2309 !VTSD->IsCompleteDefinition) 2310 return DeclarationOnly; 2311 } 2312 2313 if (hasExternalStorage()) 2314 return DeclarationOnly; 2315 2316 // [dcl.link] p7: 2317 // A declaration directly contained in a linkage-specification is treated 2318 // as if it contains the extern specifier for the purpose of determining 2319 // the linkage of the declared name and whether it is a definition. 2320 if (isSingleLineLanguageLinkage(*this)) 2321 return DeclarationOnly; 2322 2323 // C99 6.9.2p2: 2324 // A declaration of an object that has file scope without an initializer, 2325 // and without a storage class specifier or the scs 'static', constitutes 2326 // a tentative definition. 2327 // No such thing in C++. 2328 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 2329 return TentativeDefinition; 2330 2331 // What's left is (in C, block-scope) declarations without initializers or 2332 // external storage. These are definitions. 2333 return Definition; 2334 } 2335 2336 VarDecl *VarDecl::getActingDefinition() { 2337 DefinitionKind Kind = isThisDeclarationADefinition(); 2338 if (Kind != TentativeDefinition) 2339 return nullptr; 2340 2341 VarDecl *LastTentative = nullptr; 2342 2343 // Loop through the declaration chain, starting with the most recent. 2344 for (VarDecl *Decl = getMostRecentDecl(); Decl; 2345 Decl = Decl->getPreviousDecl()) { 2346 Kind = Decl->isThisDeclarationADefinition(); 2347 if (Kind == Definition) 2348 return nullptr; 2349 // Record the first (most recent) TentativeDefinition that is encountered. 2350 if (Kind == TentativeDefinition && !LastTentative) 2351 LastTentative = Decl; 2352 } 2353 2354 return LastTentative; 2355 } 2356 2357 VarDecl *VarDecl::getDefinition(ASTContext &C) { 2358 VarDecl *First = getFirstDecl(); 2359 for (auto *I : First->redecls()) { 2360 if (I->isThisDeclarationADefinition(C) == Definition) 2361 return I; 2362 } 2363 return nullptr; 2364 } 2365 2366 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 2367 DefinitionKind Kind = DeclarationOnly; 2368 2369 const VarDecl *First = getFirstDecl(); 2370 for (auto *I : First->redecls()) { 2371 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 2372 if (Kind == Definition) 2373 break; 2374 } 2375 2376 return Kind; 2377 } 2378 2379 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2380 for (auto *I : redecls()) { 2381 if (auto Expr = I->getInit()) { 2382 D = I; 2383 return Expr; 2384 } 2385 } 2386 return nullptr; 2387 } 2388 2389 bool VarDecl::hasInit() const { 2390 if (auto *P = dyn_cast<ParmVarDecl>(this)) 2391 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) 2392 return false; 2393 2394 if (auto *Eval = getEvaluatedStmt()) 2395 return Eval->Value.isValid(); 2396 2397 return !Init.isNull(); 2398 } 2399 2400 Expr *VarDecl::getInit() { 2401 if (!hasInit()) 2402 return nullptr; 2403 2404 if (auto *S = Init.dyn_cast<Stmt *>()) 2405 return cast<Expr>(S); 2406 2407 auto *Eval = getEvaluatedStmt(); 2408 2409 return cast<Expr>(Eval->Value.get( 2410 Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr)); 2411 } 2412 2413 Stmt **VarDecl::getInitAddress() { 2414 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) 2415 return ES->Value.getAddressOfPointer(getASTContext().getExternalSource()); 2416 2417 return Init.getAddrOfPtr1(); 2418 } 2419 2420 VarDecl *VarDecl::getInitializingDeclaration() { 2421 VarDecl *Def = nullptr; 2422 for (auto *I : redecls()) { 2423 if (I->hasInit()) 2424 return I; 2425 2426 if (I->isThisDeclarationADefinition()) { 2427 if (isStaticDataMember()) 2428 return I; 2429 Def = I; 2430 } 2431 } 2432 return Def; 2433 } 2434 2435 bool VarDecl::isOutOfLine() const { 2436 if (Decl::isOutOfLine()) 2437 return true; 2438 2439 if (!isStaticDataMember()) 2440 return false; 2441 2442 // If this static data member was instantiated from a static data member of 2443 // a class template, check whether that static data member was defined 2444 // out-of-line. 2445 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2446 return VD->isOutOfLine(); 2447 2448 return false; 2449 } 2450 2451 void VarDecl::setInit(Expr *I) { 2452 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2453 Eval->~EvaluatedStmt(); 2454 getASTContext().Deallocate(Eval); 2455 } 2456 2457 Init = I; 2458 } 2459 2460 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const { 2461 const LangOptions &Lang = C.getLangOpts(); 2462 2463 // OpenCL permits const integral variables to be used in constant 2464 // expressions, like in C++98. 2465 if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23) 2466 return false; 2467 2468 // Function parameters are never usable in constant expressions. 2469 if (isa<ParmVarDecl>(this)) 2470 return false; 2471 2472 // The values of weak variables are never usable in constant expressions. 2473 if (isWeak()) 2474 return false; 2475 2476 // In C++11, any variable of reference type can be used in a constant 2477 // expression if it is initialized by a constant expression. 2478 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2479 return true; 2480 2481 // Only const objects can be used in constant expressions in C++. C++98 does 2482 // not require the variable to be non-volatile, but we consider this to be a 2483 // defect. 2484 if (!getType().isConstant(C) || getType().isVolatileQualified()) 2485 return false; 2486 2487 // In C++, but not in C, const, non-volatile variables of integral or 2488 // enumeration types can be used in constant expressions. 2489 if (getType()->isIntegralOrEnumerationType() && !Lang.C23) 2490 return true; 2491 2492 // C23 6.6p7: An identifier that is: 2493 // ... 2494 // - declared with storage-class specifier constexpr and has an object type, 2495 // is a named constant, ... such a named constant is a constant expression 2496 // with the type and value of the declared object. 2497 // Additionally, in C++11, non-volatile constexpr variables can be used in 2498 // constant expressions. 2499 return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr(); 2500 } 2501 2502 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const { 2503 // C++2a [expr.const]p3: 2504 // A variable is usable in constant expressions after its initializing 2505 // declaration is encountered... 2506 const VarDecl *DefVD = nullptr; 2507 const Expr *Init = getAnyInitializer(DefVD); 2508 if (!Init || Init->isValueDependent() || getType()->isDependentType()) 2509 return false; 2510 // ... if it is a constexpr variable, or it is of reference type or of 2511 // const-qualified integral or enumeration type, ... 2512 if (!DefVD->mightBeUsableInConstantExpressions(Context)) 2513 return false; 2514 // ... and its initializer is a constant initializer. 2515 if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) && 2516 !DefVD->hasConstantInitialization()) 2517 return false; 2518 // C++98 [expr.const]p1: 2519 // An integral constant-expression can involve only [...] const variables 2520 // or static data members of integral or enumeration types initialized with 2521 // [integer] constant expressions (dcl.init) 2522 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) && 2523 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context)) 2524 return false; 2525 return true; 2526 } 2527 2528 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2529 /// form, which contains extra information on the evaluated value of the 2530 /// initializer. 2531 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2532 auto *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2533 if (!Eval) { 2534 // Note: EvaluatedStmt contains an APValue, which usually holds 2535 // resources not allocated from the ASTContext. We need to do some 2536 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2537 // where we can detect whether there's anything to clean up or not. 2538 Eval = new (getASTContext()) EvaluatedStmt; 2539 Eval->Value = Init.get<Stmt *>(); 2540 Init = Eval; 2541 } 2542 return Eval; 2543 } 2544 2545 EvaluatedStmt *VarDecl::getEvaluatedStmt() const { 2546 return Init.dyn_cast<EvaluatedStmt *>(); 2547 } 2548 2549 APValue *VarDecl::evaluateValue() const { 2550 SmallVector<PartialDiagnosticAt, 8> Notes; 2551 return evaluateValueImpl(Notes, hasConstantInitialization()); 2552 } 2553 2554 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, 2555 bool IsConstantInitialization) const { 2556 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2557 2558 const auto *Init = getInit(); 2559 assert(!Init->isValueDependent()); 2560 2561 // We only produce notes indicating why an initializer is non-constant the 2562 // first time it is evaluated. FIXME: The notes won't always be emitted the 2563 // first time we try evaluation, so might not be produced at all. 2564 if (Eval->WasEvaluated) 2565 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated; 2566 2567 if (Eval->IsEvaluating) { 2568 // FIXME: Produce a diagnostic for self-initialization. 2569 return nullptr; 2570 } 2571 2572 Eval->IsEvaluating = true; 2573 2574 ASTContext &Ctx = getASTContext(); 2575 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes, 2576 IsConstantInitialization); 2577 2578 // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't 2579 // a constant initializer if we produced notes. In that case, we can't keep 2580 // the result, because it may only be correct under the assumption that the 2581 // initializer is a constant context. 2582 if (IsConstantInitialization && 2583 (Ctx.getLangOpts().CPlusPlus || 2584 (isConstexpr() && Ctx.getLangOpts().C23)) && 2585 !Notes.empty()) 2586 Result = false; 2587 2588 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2589 // or that it's empty (so that there's nothing to clean up) if evaluation 2590 // failed. 2591 if (!Result) 2592 Eval->Evaluated = APValue(); 2593 else if (Eval->Evaluated.needsCleanup()) 2594 Ctx.addDestruction(&Eval->Evaluated); 2595 2596 Eval->IsEvaluating = false; 2597 Eval->WasEvaluated = true; 2598 2599 return Result ? &Eval->Evaluated : nullptr; 2600 } 2601 2602 APValue *VarDecl::getEvaluatedValue() const { 2603 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2604 if (Eval->WasEvaluated) 2605 return &Eval->Evaluated; 2606 2607 return nullptr; 2608 } 2609 2610 bool VarDecl::hasICEInitializer(const ASTContext &Context) const { 2611 const Expr *Init = getInit(); 2612 assert(Init && "no initializer"); 2613 2614 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2615 if (!Eval->CheckedForICEInit) { 2616 Eval->CheckedForICEInit = true; 2617 Eval->HasICEInit = Init->isIntegerConstantExpr(Context); 2618 } 2619 return Eval->HasICEInit; 2620 } 2621 2622 bool VarDecl::hasConstantInitialization() const { 2623 // In C, all globals and constexpr variables should have constant 2624 // initialization. For constexpr variables in C check that initializer is a 2625 // constant initializer because they can be used in constant expressions. 2626 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus && 2627 !isConstexpr()) 2628 return true; 2629 2630 // In C++, it depends on whether the evaluation at the point of definition 2631 // was evaluatable as a constant initializer. 2632 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2633 return Eval->HasConstantInitialization; 2634 2635 return false; 2636 } 2637 2638 bool VarDecl::checkForConstantInitialization( 2639 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2640 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2641 // If we ask for the value before we know whether we have a constant 2642 // initializer, we can compute the wrong value (for example, due to 2643 // std::is_constant_evaluated()). 2644 assert(!Eval->WasEvaluated && 2645 "already evaluated var value before checking for constant init"); 2646 assert((getASTContext().getLangOpts().CPlusPlus || 2647 getASTContext().getLangOpts().C23) && 2648 "only meaningful in C++/C23"); 2649 2650 assert(!getInit()->isValueDependent()); 2651 2652 // Evaluate the initializer to check whether it's a constant expression. 2653 Eval->HasConstantInitialization = 2654 evaluateValueImpl(Notes, true) && Notes.empty(); 2655 2656 // If evaluation as a constant initializer failed, allow re-evaluation as a 2657 // non-constant initializer if we later find we want the value. 2658 if (!Eval->HasConstantInitialization) 2659 Eval->WasEvaluated = false; 2660 2661 return Eval->HasConstantInitialization; 2662 } 2663 2664 bool VarDecl::isParameterPack() const { 2665 return isa<PackExpansionType>(getType()); 2666 } 2667 2668 template<typename DeclT> 2669 static DeclT *getDefinitionOrSelf(DeclT *D) { 2670 assert(D); 2671 if (auto *Def = D->getDefinition()) 2672 return Def; 2673 return D; 2674 } 2675 2676 bool VarDecl::isEscapingByref() const { 2677 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref; 2678 } 2679 2680 bool VarDecl::isNonEscapingByref() const { 2681 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref; 2682 } 2683 2684 bool VarDecl::hasDependentAlignment() const { 2685 QualType T = getType(); 2686 return T->isDependentType() || T->isUndeducedType() || 2687 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) { 2688 return AA->isAlignmentDependent(); 2689 }); 2690 } 2691 2692 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2693 const VarDecl *VD = this; 2694 2695 // If this is an instantiated member, walk back to the template from which 2696 // it was instantiated. 2697 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) { 2698 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2699 VD = VD->getInstantiatedFromStaticDataMember(); 2700 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2701 VD = NewVD; 2702 } 2703 } 2704 2705 // If it's an instantiated variable template specialization, find the 2706 // template or partial specialization from which it was instantiated. 2707 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 2708 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) { 2709 auto From = VDTemplSpec->getInstantiatedFrom(); 2710 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2711 while (!VTD->hasMemberSpecialization()) { 2712 if (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) 2713 VTD = NewVTD; 2714 else 2715 break; 2716 } 2717 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2718 } 2719 if (auto *VTPSD = 2720 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2721 while (!VTPSD->hasMemberSpecialization()) { 2722 if (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) 2723 VTPSD = NewVTPSD; 2724 else 2725 break; 2726 } 2727 return getDefinitionOrSelf<VarDecl>(VTPSD); 2728 } 2729 } 2730 } 2731 2732 // If this is the pattern of a variable template, find where it was 2733 // instantiated from. FIXME: Is this necessary? 2734 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) { 2735 while (!VTD->hasMemberSpecialization()) { 2736 if (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) 2737 VTD = NewVTD; 2738 else 2739 break; 2740 } 2741 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2742 } 2743 2744 if (VD == this) 2745 return nullptr; 2746 return getDefinitionOrSelf(const_cast<VarDecl*>(VD)); 2747 } 2748 2749 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2750 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2751 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2752 2753 return nullptr; 2754 } 2755 2756 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2757 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2758 return Spec->getSpecializationKind(); 2759 2760 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2761 return MSI->getTemplateSpecializationKind(); 2762 2763 return TSK_Undeclared; 2764 } 2765 2766 TemplateSpecializationKind 2767 VarDecl::getTemplateSpecializationKindForInstantiation() const { 2768 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2769 return MSI->getTemplateSpecializationKind(); 2770 2771 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2772 return Spec->getSpecializationKind(); 2773 2774 return TSK_Undeclared; 2775 } 2776 2777 SourceLocation VarDecl::getPointOfInstantiation() const { 2778 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2779 return Spec->getPointOfInstantiation(); 2780 2781 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2782 return MSI->getPointOfInstantiation(); 2783 2784 return SourceLocation(); 2785 } 2786 2787 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2788 return getASTContext().getTemplateOrSpecializationInfo(this) 2789 .dyn_cast<VarTemplateDecl *>(); 2790 } 2791 2792 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2793 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2794 } 2795 2796 bool VarDecl::isKnownToBeDefined() const { 2797 const auto &LangOpts = getASTContext().getLangOpts(); 2798 // In CUDA mode without relocatable device code, variables of form 'extern 2799 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared 2800 // memory pool. These are never undefined variables, even if they appear 2801 // inside of an anon namespace or static function. 2802 // 2803 // With CUDA relocatable device code enabled, these variables don't get 2804 // special handling; they're treated like regular extern variables. 2805 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode && 2806 hasExternalStorage() && hasAttr<CUDASharedAttr>() && 2807 isa<IncompleteArrayType>(getType())) 2808 return true; 2809 2810 return hasDefinition(); 2811 } 2812 2813 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { 2814 if (!hasGlobalStorage()) 2815 return false; 2816 if (hasAttr<NoDestroyAttr>()) 2817 return true; 2818 if (hasAttr<AlwaysDestroyAttr>()) 2819 return false; 2820 2821 using RSDKind = LangOptions::RegisterStaticDestructorsKind; 2822 RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors(); 2823 return K == RSDKind::None || 2824 (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None); 2825 } 2826 2827 QualType::DestructionKind 2828 VarDecl::needsDestruction(const ASTContext &Ctx) const { 2829 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2830 if (Eval->HasConstantDestruction) 2831 return QualType::DK_none; 2832 2833 if (isNoDestroy(Ctx)) 2834 return QualType::DK_none; 2835 2836 return getType().isDestructedType(); 2837 } 2838 2839 bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const { 2840 assert(hasInit() && "Expect initializer to check for flexible array init"); 2841 auto *Ty = getType()->getAs<RecordType>(); 2842 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) 2843 return false; 2844 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2845 if (!List) 2846 return false; 2847 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2848 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2849 if (!InitTy) 2850 return false; 2851 return !InitTy->isZeroSize(); 2852 } 2853 2854 CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const { 2855 assert(hasInit() && "Expect initializer to check for flexible array init"); 2856 auto *Ty = getType()->getAs<RecordType>(); 2857 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) 2858 return CharUnits::Zero(); 2859 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2860 if (!List || List->getNumInits() == 0) 2861 return CharUnits::Zero(); 2862 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2863 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2864 if (!InitTy) 2865 return CharUnits::Zero(); 2866 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy); 2867 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl()); 2868 CharUnits FlexibleArrayOffset = 2869 Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1)); 2870 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize()) 2871 return CharUnits::Zero(); 2872 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize(); 2873 } 2874 2875 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2876 if (isStaticDataMember()) 2877 // FIXME: Remove ? 2878 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2879 return getASTContext().getTemplateOrSpecializationInfo(this) 2880 .dyn_cast<MemberSpecializationInfo *>(); 2881 return nullptr; 2882 } 2883 2884 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2885 SourceLocation PointOfInstantiation) { 2886 assert((isa<VarTemplateSpecializationDecl>(this) || 2887 getMemberSpecializationInfo()) && 2888 "not a variable or static data member template specialization"); 2889 2890 if (VarTemplateSpecializationDecl *Spec = 2891 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2892 Spec->setSpecializationKind(TSK); 2893 if (TSK != TSK_ExplicitSpecialization && 2894 PointOfInstantiation.isValid() && 2895 Spec->getPointOfInstantiation().isInvalid()) { 2896 Spec->setPointOfInstantiation(PointOfInstantiation); 2897 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2898 L->InstantiationRequested(this); 2899 } 2900 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2901 MSI->setTemplateSpecializationKind(TSK); 2902 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2903 MSI->getPointOfInstantiation().isInvalid()) { 2904 MSI->setPointOfInstantiation(PointOfInstantiation); 2905 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2906 L->InstantiationRequested(this); 2907 } 2908 } 2909 } 2910 2911 void 2912 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2913 TemplateSpecializationKind TSK) { 2914 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2915 "Previous template or instantiation?"); 2916 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2917 } 2918 2919 //===----------------------------------------------------------------------===// 2920 // ParmVarDecl Implementation 2921 //===----------------------------------------------------------------------===// 2922 2923 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2924 SourceLocation StartLoc, SourceLocation IdLoc, 2925 const IdentifierInfo *Id, QualType T, 2926 TypeSourceInfo *TInfo, StorageClass S, 2927 Expr *DefArg) { 2928 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2929 S, DefArg); 2930 } 2931 2932 QualType ParmVarDecl::getOriginalType() const { 2933 TypeSourceInfo *TSI = getTypeSourceInfo(); 2934 QualType T = TSI ? TSI->getType() : getType(); 2935 if (const auto *DT = dyn_cast<DecayedType>(T)) 2936 return DT->getOriginalType(); 2937 return T; 2938 } 2939 2940 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 2941 return new (C, ID) 2942 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2943 nullptr, QualType(), nullptr, SC_None, nullptr); 2944 } 2945 2946 SourceRange ParmVarDecl::getSourceRange() const { 2947 if (!hasInheritedDefaultArg()) { 2948 SourceRange ArgRange = getDefaultArgRange(); 2949 if (ArgRange.isValid()) 2950 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2951 } 2952 2953 // DeclaratorDecl considers the range of postfix types as overlapping with the 2954 // declaration name, but this is not the case with parameters in ObjC methods. 2955 if (isa<ObjCMethodDecl>(getDeclContext())) 2956 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation()); 2957 2958 return DeclaratorDecl::getSourceRange(); 2959 } 2960 2961 bool ParmVarDecl::isDestroyedInCallee() const { 2962 // ns_consumed only affects code generation in ARC 2963 if (hasAttr<NSConsumedAttr>()) 2964 return getASTContext().getLangOpts().ObjCAutoRefCount; 2965 2966 // FIXME: isParamDestroyedInCallee() should probably imply 2967 // isDestructedType() 2968 const auto *RT = getType()->getAs<RecordType>(); 2969 if (RT && RT->getDecl()->isParamDestroyedInCallee() && 2970 getType().isDestructedType()) 2971 return true; 2972 2973 return false; 2974 } 2975 2976 Expr *ParmVarDecl::getDefaultArg() { 2977 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2978 assert(!hasUninstantiatedDefaultArg() && 2979 "Default argument is not yet instantiated!"); 2980 2981 Expr *Arg = getInit(); 2982 if (auto *E = dyn_cast_if_present<FullExpr>(Arg)) 2983 return E->getSubExpr(); 2984 2985 return Arg; 2986 } 2987 2988 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2989 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2990 Init = defarg; 2991 } 2992 2993 SourceRange ParmVarDecl::getDefaultArgRange() const { 2994 switch (ParmVarDeclBits.DefaultArgKind) { 2995 case DAK_None: 2996 case DAK_Unparsed: 2997 // Nothing we can do here. 2998 return SourceRange(); 2999 3000 case DAK_Uninstantiated: 3001 return getUninstantiatedDefaultArg()->getSourceRange(); 3002 3003 case DAK_Normal: 3004 if (const Expr *E = getInit()) 3005 return E->getSourceRange(); 3006 3007 // Missing an actual expression, may be invalid. 3008 return SourceRange(); 3009 } 3010 llvm_unreachable("Invalid default argument kind."); 3011 } 3012 3013 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 3014 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 3015 Init = arg; 3016 } 3017 3018 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 3019 assert(hasUninstantiatedDefaultArg() && 3020 "Wrong kind of initialization expression!"); 3021 return cast_if_present<Expr>(Init.get<Stmt *>()); 3022 } 3023 3024 bool ParmVarDecl::hasDefaultArg() const { 3025 // FIXME: We should just return false for DAK_None here once callers are 3026 // prepared for the case that we encountered an invalid default argument and 3027 // were unable to even build an invalid expression. 3028 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 3029 !Init.isNull(); 3030 } 3031 3032 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 3033 getASTContext().setParameterIndex(this, parameterIndex); 3034 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 3035 } 3036 3037 unsigned ParmVarDecl::getParameterIndexLarge() const { 3038 return getASTContext().getParameterIndex(this); 3039 } 3040 3041 //===----------------------------------------------------------------------===// 3042 // FunctionDecl Implementation 3043 //===----------------------------------------------------------------------===// 3044 3045 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, 3046 SourceLocation StartLoc, 3047 const DeclarationNameInfo &NameInfo, QualType T, 3048 TypeSourceInfo *TInfo, StorageClass S, 3049 bool UsesFPIntrin, bool isInlineSpecified, 3050 ConstexprSpecKind ConstexprKind, 3051 Expr *TrailingRequiresClause) 3052 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 3053 StartLoc), 3054 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0), 3055 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) { 3056 assert(T.isNull() || T->isFunctionType()); 3057 FunctionDeclBits.SClass = S; 3058 FunctionDeclBits.IsInline = isInlineSpecified; 3059 FunctionDeclBits.IsInlineSpecified = isInlineSpecified; 3060 FunctionDeclBits.IsVirtualAsWritten = false; 3061 FunctionDeclBits.IsPureVirtual = false; 3062 FunctionDeclBits.HasInheritedPrototype = false; 3063 FunctionDeclBits.HasWrittenPrototype = true; 3064 FunctionDeclBits.IsDeleted = false; 3065 FunctionDeclBits.IsTrivial = false; 3066 FunctionDeclBits.IsTrivialForCall = false; 3067 FunctionDeclBits.IsDefaulted = false; 3068 FunctionDeclBits.IsExplicitlyDefaulted = false; 3069 FunctionDeclBits.HasDefaultedOrDeletedInfo = false; 3070 FunctionDeclBits.IsIneligibleOrNotSelected = false; 3071 FunctionDeclBits.HasImplicitReturnZero = false; 3072 FunctionDeclBits.IsLateTemplateParsed = false; 3073 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind); 3074 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false; 3075 FunctionDeclBits.InstantiationIsPending = false; 3076 FunctionDeclBits.UsesSEHTry = false; 3077 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin; 3078 FunctionDeclBits.HasSkippedBody = false; 3079 FunctionDeclBits.WillHaveBody = false; 3080 FunctionDeclBits.IsMultiVersion = false; 3081 FunctionDeclBits.DeductionCandidateKind = 3082 static_cast<unsigned char>(DeductionCandidate::Normal); 3083 FunctionDeclBits.HasODRHash = false; 3084 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false; 3085 if (TrailingRequiresClause) 3086 setTrailingRequiresClause(TrailingRequiresClause); 3087 } 3088 3089 void FunctionDecl::getNameForDiagnostic( 3090 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 3091 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 3092 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 3093 if (TemplateArgs) 3094 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 3095 } 3096 3097 bool FunctionDecl::isVariadic() const { 3098 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 3099 return FT->isVariadic(); 3100 return false; 3101 } 3102 3103 FunctionDecl::DefaultedOrDeletedFunctionInfo * 3104 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create( 3105 ASTContext &Context, ArrayRef<DeclAccessPair> Lookups, 3106 StringLiteral *DeletedMessage) { 3107 static constexpr size_t Alignment = 3108 std::max({alignof(DefaultedOrDeletedFunctionInfo), 3109 alignof(DeclAccessPair), alignof(StringLiteral *)}); 3110 size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>( 3111 Lookups.size(), DeletedMessage != nullptr); 3112 3113 DefaultedOrDeletedFunctionInfo *Info = 3114 new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo; 3115 Info->NumLookups = Lookups.size(); 3116 Info->HasDeletedMessage = DeletedMessage != nullptr; 3117 3118 std::uninitialized_copy(Lookups.begin(), Lookups.end(), 3119 Info->getTrailingObjects<DeclAccessPair>()); 3120 if (DeletedMessage) 3121 *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage; 3122 return Info; 3123 } 3124 3125 void FunctionDecl::setDefaultedOrDeletedInfo( 3126 DefaultedOrDeletedFunctionInfo *Info) { 3127 assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this"); 3128 assert(!Body && "can't replace function body with defaulted function info"); 3129 3130 FunctionDeclBits.HasDefaultedOrDeletedInfo = true; 3131 DefaultedOrDeletedInfo = Info; 3132 } 3133 3134 void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) { 3135 FunctionDeclBits.IsDeleted = D; 3136 3137 if (Message) { 3138 assert(isDeletedAsWritten() && "Function must be deleted"); 3139 if (FunctionDeclBits.HasDefaultedOrDeletedInfo) 3140 DefaultedOrDeletedInfo->setDeletedMessage(Message); 3141 else 3142 setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create( 3143 getASTContext(), /*Lookups=*/{}, Message)); 3144 } 3145 } 3146 3147 void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage( 3148 StringLiteral *Message) { 3149 // We should never get here with the DefaultedOrDeletedInfo populated, but 3150 // no space allocated for the deleted message, since that would require 3151 // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting 3152 // an already existing DefaultedOrDeletedFunctionInfo. 3153 assert(HasDeletedMessage && 3154 "No space to store a delete message in this DefaultedOrDeletedInfo"); 3155 *getTrailingObjects<StringLiteral *>() = Message; 3156 } 3157 3158 FunctionDecl::DefaultedOrDeletedFunctionInfo * 3159 FunctionDecl::getDefalutedOrDeletedInfo() const { 3160 return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo 3161 : nullptr; 3162 } 3163 3164 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 3165 for (const auto *I : redecls()) { 3166 if (I->doesThisDeclarationHaveABody()) { 3167 Definition = I; 3168 return true; 3169 } 3170 } 3171 3172 return false; 3173 } 3174 3175 bool FunctionDecl::hasTrivialBody() const { 3176 const Stmt *S = getBody(); 3177 if (!S) { 3178 // Since we don't have a body for this function, we don't know if it's 3179 // trivial or not. 3180 return false; 3181 } 3182 3183 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 3184 return true; 3185 return false; 3186 } 3187 3188 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const { 3189 if (!getFriendObjectKind()) 3190 return false; 3191 3192 // Check for a friend function instantiated from a friend function 3193 // definition in a templated class. 3194 if (const FunctionDecl *InstantiatedFrom = 3195 getInstantiatedFromMemberFunction()) 3196 return InstantiatedFrom->getFriendObjectKind() && 3197 InstantiatedFrom->isThisDeclarationADefinition(); 3198 3199 // Check for a friend function template instantiated from a friend 3200 // function template definition in a templated class. 3201 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { 3202 if (const FunctionTemplateDecl *InstantiatedFrom = 3203 Template->getInstantiatedFromMemberTemplate()) 3204 return InstantiatedFrom->getFriendObjectKind() && 3205 InstantiatedFrom->isThisDeclarationADefinition(); 3206 } 3207 3208 return false; 3209 } 3210 3211 bool FunctionDecl::isDefined(const FunctionDecl *&Definition, 3212 bool CheckForPendingFriendDefinition) const { 3213 for (const FunctionDecl *FD : redecls()) { 3214 if (FD->isThisDeclarationADefinition()) { 3215 Definition = FD; 3216 return true; 3217 } 3218 3219 // If this is a friend function defined in a class template, it does not 3220 // have a body until it is used, nevertheless it is a definition, see 3221 // [temp.inst]p2: 3222 // 3223 // ... for the purpose of determining whether an instantiated redeclaration 3224 // is valid according to [basic.def.odr] and [class.mem], a declaration that 3225 // corresponds to a definition in the template is considered to be a 3226 // definition. 3227 // 3228 // The following code must produce redefinition error: 3229 // 3230 // template<typename T> struct C20 { friend void func_20() {} }; 3231 // C20<int> c20i; 3232 // void func_20() {} 3233 // 3234 if (CheckForPendingFriendDefinition && 3235 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 3236 Definition = FD; 3237 return true; 3238 } 3239 } 3240 3241 return false; 3242 } 3243 3244 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 3245 if (!hasBody(Definition)) 3246 return nullptr; 3247 3248 assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo && 3249 "definition should not have a body"); 3250 if (Definition->Body) 3251 return Definition->Body.get(getASTContext().getExternalSource()); 3252 3253 return nullptr; 3254 } 3255 3256 void FunctionDecl::setBody(Stmt *B) { 3257 FunctionDeclBits.HasDefaultedOrDeletedInfo = false; 3258 Body = LazyDeclStmtPtr(B); 3259 if (B) 3260 EndRangeLoc = B->getEndLoc(); 3261 } 3262 3263 void FunctionDecl::setIsPureVirtual(bool P) { 3264 FunctionDeclBits.IsPureVirtual = P; 3265 if (P) 3266 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 3267 Parent->markedVirtualFunctionPure(); 3268 } 3269 3270 template<std::size_t Len> 3271 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 3272 const IdentifierInfo *II = ND->getIdentifier(); 3273 return II && II->isStr(Str); 3274 } 3275 3276 bool FunctionDecl::isImmediateEscalating() const { 3277 // C++23 [expr.const]/p17 3278 // An immediate-escalating function is 3279 // - the call operator of a lambda that is not declared with the consteval 3280 // specifier, 3281 if (isLambdaCallOperator(this) && !isConsteval()) 3282 return true; 3283 // - a defaulted special member function that is not declared with the 3284 // consteval specifier, 3285 if (isDefaulted() && !isConsteval()) 3286 return true; 3287 // - a function that results from the instantiation of a templated entity 3288 // defined with the constexpr specifier. 3289 TemplatedKind TK = getTemplatedKind(); 3290 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate && 3291 isConstexprSpecified()) 3292 return true; 3293 return false; 3294 } 3295 3296 bool FunctionDecl::isImmediateFunction() const { 3297 // C++23 [expr.const]/p18 3298 // An immediate function is a function or constructor that is 3299 // - declared with the consteval specifier 3300 if (isConsteval()) 3301 return true; 3302 // - an immediate-escalating function F whose function body contains an 3303 // immediate-escalating expression 3304 if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions()) 3305 return true; 3306 3307 if (const auto *MD = dyn_cast<CXXMethodDecl>(this); 3308 MD && MD->isLambdaStaticInvoker()) 3309 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction(); 3310 3311 return false; 3312 } 3313 3314 bool FunctionDecl::isMain() const { 3315 return isNamed(this, "main") && !getLangOpts().Freestanding && 3316 !getLangOpts().HLSL && 3317 (getDeclContext()->getRedeclContext()->isTranslationUnit() || 3318 isExternC()); 3319 } 3320 3321 bool FunctionDecl::isMSVCRTEntryPoint() const { 3322 const TranslationUnitDecl *TUnit = 3323 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3324 if (!TUnit) 3325 return false; 3326 3327 // Even though we aren't really targeting MSVCRT if we are freestanding, 3328 // semantic analysis for these functions remains the same. 3329 3330 // MSVCRT entry points only exist on MSVCRT targets. 3331 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 3332 return false; 3333 3334 // Nameless functions like constructors cannot be entry points. 3335 if (!getIdentifier()) 3336 return false; 3337 3338 return llvm::StringSwitch<bool>(getName()) 3339 .Cases("main", // an ANSI console app 3340 "wmain", // a Unicode console App 3341 "WinMain", // an ANSI GUI app 3342 "wWinMain", // a Unicode GUI app 3343 "DllMain", // a DLL 3344 true) 3345 .Default(false); 3346 } 3347 3348 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 3349 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3350 return false; 3351 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3352 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3353 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3354 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3355 return false; 3356 3357 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3358 return false; 3359 3360 const auto *proto = getType()->castAs<FunctionProtoType>(); 3361 if (proto->getNumParams() != 2 || proto->isVariadic()) 3362 return false; 3363 3364 const ASTContext &Context = 3365 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 3366 ->getASTContext(); 3367 3368 // The result type and first argument type are constant across all 3369 // these operators. The second argument must be exactly void*. 3370 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 3371 } 3372 3373 bool FunctionDecl::isReplaceableGlobalAllocationFunction( 3374 std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const { 3375 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3376 return false; 3377 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3378 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3379 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3380 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3381 return false; 3382 3383 if (isa<CXXRecordDecl>(getDeclContext())) 3384 return false; 3385 3386 // This can only fail for an invalid 'operator new' declaration. 3387 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3388 return false; 3389 3390 const auto *FPT = getType()->castAs<FunctionProtoType>(); 3391 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic()) 3392 return false; 3393 3394 // If this is a single-parameter function, it must be a replaceable global 3395 // allocation or deallocation function. 3396 if (FPT->getNumParams() == 1) 3397 return true; 3398 3399 unsigned Params = 1; 3400 QualType Ty = FPT->getParamType(Params); 3401 const ASTContext &Ctx = getASTContext(); 3402 3403 auto Consume = [&] { 3404 ++Params; 3405 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 3406 }; 3407 3408 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 3409 bool IsSizedDelete = false; 3410 if (Ctx.getLangOpts().SizedDeallocation && 3411 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 3412 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 3413 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 3414 IsSizedDelete = true; 3415 Consume(); 3416 } 3417 3418 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 3419 // new/delete. 3420 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 3421 Consume(); 3422 if (AlignmentParam) 3423 *AlignmentParam = Params; 3424 } 3425 3426 // If this is not a sized delete, the next parameter can be a 3427 // 'const std::nothrow_t&'. 3428 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 3429 Ty = Ty->getPointeeType(); 3430 if (Ty.getCVRQualifiers() != Qualifiers::Const) 3431 return false; 3432 if (Ty->isNothrowT()) { 3433 if (IsNothrow) 3434 *IsNothrow = true; 3435 Consume(); 3436 } 3437 } 3438 3439 // Finally, recognize the not yet standard versions of new that take a 3440 // hot/cold allocation hint (__hot_cold_t). These are currently supported by 3441 // tcmalloc (see 3442 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53). 3443 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) { 3444 QualType T = Ty; 3445 while (const auto *TD = T->getAs<TypedefType>()) 3446 T = TD->getDecl()->getUnderlyingType(); 3447 const IdentifierInfo *II = 3448 T->castAs<EnumType>()->getDecl()->getIdentifier(); 3449 if (II && II->isStr("__hot_cold_t")) 3450 Consume(); 3451 } 3452 3453 return Params == FPT->getNumParams(); 3454 } 3455 3456 bool FunctionDecl::isInlineBuiltinDeclaration() const { 3457 if (!getBuiltinID()) 3458 return false; 3459 3460 const FunctionDecl *Definition; 3461 if (!hasBody(Definition)) 3462 return false; 3463 3464 if (!Definition->isInlineSpecified() || 3465 !Definition->hasAttr<AlwaysInlineAttr>()) 3466 return false; 3467 3468 ASTContext &Context = getASTContext(); 3469 switch (Context.GetGVALinkageForFunction(Definition)) { 3470 case GVA_Internal: 3471 case GVA_DiscardableODR: 3472 case GVA_StrongODR: 3473 return false; 3474 case GVA_AvailableExternally: 3475 case GVA_StrongExternal: 3476 return true; 3477 } 3478 llvm_unreachable("Unknown GVALinkage"); 3479 } 3480 3481 bool FunctionDecl::isDestroyingOperatorDelete() const { 3482 // C++ P0722: 3483 // Within a class C, a single object deallocation function with signature 3484 // (T, std::destroying_delete_t, <more params>) 3485 // is a destroying operator delete. 3486 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 3487 getNumParams() < 2) 3488 return false; 3489 3490 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 3491 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 3492 RD->getIdentifier()->isStr("destroying_delete_t"); 3493 } 3494 3495 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 3496 return getDeclLanguageLinkage(*this); 3497 } 3498 3499 bool FunctionDecl::isExternC() const { 3500 return isDeclExternC(*this); 3501 } 3502 3503 bool FunctionDecl::isInExternCContext() const { 3504 if (hasAttr<OpenCLKernelAttr>()) 3505 return true; 3506 return getLexicalDeclContext()->isExternCContext(); 3507 } 3508 3509 bool FunctionDecl::isInExternCXXContext() const { 3510 return getLexicalDeclContext()->isExternCXXContext(); 3511 } 3512 3513 bool FunctionDecl::isGlobal() const { 3514 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 3515 return Method->isStatic(); 3516 3517 if (getCanonicalDecl()->getStorageClass() == SC_Static) 3518 return false; 3519 3520 for (const DeclContext *DC = getDeclContext(); 3521 DC->isNamespace(); 3522 DC = DC->getParent()) { 3523 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 3524 if (!Namespace->getDeclName()) 3525 return false; 3526 } 3527 } 3528 3529 return true; 3530 } 3531 3532 bool FunctionDecl::isNoReturn() const { 3533 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 3534 hasAttr<C11NoReturnAttr>()) 3535 return true; 3536 3537 if (auto *FnTy = getType()->getAs<FunctionType>()) 3538 return FnTy->getNoReturnAttr(); 3539 3540 return false; 3541 } 3542 3543 bool FunctionDecl::isMemberLikeConstrainedFriend() const { 3544 // C++20 [temp.friend]p9: 3545 // A non-template friend declaration with a requires-clause [or] 3546 // a friend function template with a constraint that depends on a template 3547 // parameter from an enclosing template [...] does not declare the same 3548 // function or function template as a declaration in any other scope. 3549 3550 // If this isn't a friend then it's not a member-like constrained friend. 3551 if (!getFriendObjectKind()) { 3552 return false; 3553 } 3554 3555 if (!getDescribedFunctionTemplate()) { 3556 // If these friends don't have constraints, they aren't constrained, and 3557 // thus don't fall under temp.friend p9. Else the simple presence of a 3558 // constraint makes them unique. 3559 return getTrailingRequiresClause(); 3560 } 3561 3562 return FriendConstraintRefersToEnclosingTemplate(); 3563 } 3564 3565 MultiVersionKind FunctionDecl::getMultiVersionKind() const { 3566 if (hasAttr<TargetAttr>()) 3567 return MultiVersionKind::Target; 3568 if (hasAttr<TargetVersionAttr>()) 3569 return MultiVersionKind::TargetVersion; 3570 if (hasAttr<CPUDispatchAttr>()) 3571 return MultiVersionKind::CPUDispatch; 3572 if (hasAttr<CPUSpecificAttr>()) 3573 return MultiVersionKind::CPUSpecific; 3574 if (hasAttr<TargetClonesAttr>()) 3575 return MultiVersionKind::TargetClones; 3576 return MultiVersionKind::None; 3577 } 3578 3579 bool FunctionDecl::isCPUDispatchMultiVersion() const { 3580 return isMultiVersion() && hasAttr<CPUDispatchAttr>(); 3581 } 3582 3583 bool FunctionDecl::isCPUSpecificMultiVersion() const { 3584 return isMultiVersion() && hasAttr<CPUSpecificAttr>(); 3585 } 3586 3587 bool FunctionDecl::isTargetMultiVersion() const { 3588 return isMultiVersion() && 3589 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>()); 3590 } 3591 3592 bool FunctionDecl::isTargetMultiVersionDefault() const { 3593 if (!isMultiVersion()) 3594 return false; 3595 if (hasAttr<TargetAttr>()) 3596 return getAttr<TargetAttr>()->isDefaultVersion(); 3597 return hasAttr<TargetVersionAttr>() && 3598 getAttr<TargetVersionAttr>()->isDefaultVersion(); 3599 } 3600 3601 bool FunctionDecl::isTargetClonesMultiVersion() const { 3602 return isMultiVersion() && hasAttr<TargetClonesAttr>(); 3603 } 3604 3605 bool FunctionDecl::isTargetVersionMultiVersion() const { 3606 return isMultiVersion() && hasAttr<TargetVersionAttr>(); 3607 } 3608 3609 void 3610 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 3611 redeclarable_base::setPreviousDecl(PrevDecl); 3612 3613 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 3614 FunctionTemplateDecl *PrevFunTmpl 3615 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 3616 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 3617 FunTmpl->setPreviousDecl(PrevFunTmpl); 3618 } 3619 3620 if (PrevDecl && PrevDecl->isInlined()) 3621 setImplicitlyInline(true); 3622 } 3623 3624 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 3625 3626 /// Returns a value indicating whether this function corresponds to a builtin 3627 /// function. 3628 /// 3629 /// The function corresponds to a built-in function if it is declared at 3630 /// translation scope or within an extern "C" block and its name matches with 3631 /// the name of a builtin. The returned value will be 0 for functions that do 3632 /// not correspond to a builtin, a value of type \c Builtin::ID if in the 3633 /// target-independent range \c [1,Builtin::First), or a target-specific builtin 3634 /// value. 3635 /// 3636 /// \param ConsiderWrapperFunctions If true, we should consider wrapper 3637 /// functions as their wrapped builtins. This shouldn't be done in general, but 3638 /// it's useful in Sema to diagnose calls to wrappers based on their semantics. 3639 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { 3640 unsigned BuiltinID = 0; 3641 3642 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) { 3643 BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); 3644 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) { 3645 BuiltinID = BAA->getBuiltinName()->getBuiltinID(); 3646 } else if (const auto *A = getAttr<BuiltinAttr>()) { 3647 BuiltinID = A->getID(); 3648 } 3649 3650 if (!BuiltinID) 3651 return 0; 3652 3653 // If the function is marked "overloadable", it has a different mangled name 3654 // and is not the C library function. 3655 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() && 3656 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>())) 3657 return 0; 3658 3659 const ASTContext &Context = getASTContext(); 3660 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3661 return BuiltinID; 3662 3663 // This function has the name of a known C library 3664 // function. Determine whether it actually refers to the C library 3665 // function or whether it just has the same name. 3666 3667 // If this is a static function, it's not a builtin. 3668 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static) 3669 return 0; 3670 3671 // OpenCL v1.2 s6.9.f - The library functions defined in 3672 // the C99 standard headers are not available. 3673 if (Context.getLangOpts().OpenCL && 3674 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3675 return 0; 3676 3677 // CUDA does not have device-side standard library. printf and malloc are the 3678 // only special cases that are supported by device-side runtime. 3679 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && 3680 !hasAttr<CUDAHostAttr>() && 3681 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3682 return 0; 3683 3684 // As AMDGCN implementation of OpenMP does not have a device-side standard 3685 // library, none of the predefined library functions except printf and malloc 3686 // should be treated as a builtin i.e. 0 should be returned for them. 3687 if (Context.getTargetInfo().getTriple().isAMDGCN() && 3688 Context.getLangOpts().OpenMPIsTargetDevice && 3689 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 3690 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3691 return 0; 3692 3693 return BuiltinID; 3694 } 3695 3696 /// getNumParams - Return the number of parameters this function must have 3697 /// based on its FunctionType. This is the length of the ParamInfo array 3698 /// after it has been created. 3699 unsigned FunctionDecl::getNumParams() const { 3700 const auto *FPT = getType()->getAs<FunctionProtoType>(); 3701 return FPT ? FPT->getNumParams() : 0; 3702 } 3703 3704 void FunctionDecl::setParams(ASTContext &C, 3705 ArrayRef<ParmVarDecl *> NewParamInfo) { 3706 assert(!ParamInfo && "Already has param info!"); 3707 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 3708 3709 // Zero params -> null pointer. 3710 if (!NewParamInfo.empty()) { 3711 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 3712 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3713 } 3714 } 3715 3716 /// getMinRequiredArguments - Returns the minimum number of arguments 3717 /// needed to call this function. This may be fewer than the number of 3718 /// function parameters, if some of the parameters have default 3719 /// arguments (in C++) or are parameter packs (C++11). 3720 unsigned FunctionDecl::getMinRequiredArguments() const { 3721 if (!getASTContext().getLangOpts().CPlusPlus) 3722 return getNumParams(); 3723 3724 // Note that it is possible for a parameter with no default argument to 3725 // follow a parameter with a default argument. 3726 unsigned NumRequiredArgs = 0; 3727 unsigned MinParamsSoFar = 0; 3728 for (auto *Param : parameters()) { 3729 if (!Param->isParameterPack()) { 3730 ++MinParamsSoFar; 3731 if (!Param->hasDefaultArg()) 3732 NumRequiredArgs = MinParamsSoFar; 3733 } 3734 } 3735 return NumRequiredArgs; 3736 } 3737 3738 bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const { 3739 return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter(); 3740 } 3741 3742 unsigned FunctionDecl::getNumNonObjectParams() const { 3743 return getNumParams() - 3744 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); 3745 } 3746 3747 unsigned FunctionDecl::getMinRequiredExplicitArguments() const { 3748 return getMinRequiredArguments() - 3749 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); 3750 } 3751 3752 bool FunctionDecl::hasOneParamOrDefaultArgs() const { 3753 return getNumParams() == 1 || 3754 (getNumParams() > 1 && 3755 llvm::all_of(llvm::drop_begin(parameters()), 3756 [](ParmVarDecl *P) { return P->hasDefaultArg(); })); 3757 } 3758 3759 /// The combination of the extern and inline keywords under MSVC forces 3760 /// the function to be required. 3761 /// 3762 /// Note: This function assumes that we will only get called when isInlined() 3763 /// would return true for this FunctionDecl. 3764 bool FunctionDecl::isMSExternInline() const { 3765 assert(isInlined() && "expected to get called on an inlined function!"); 3766 3767 const ASTContext &Context = getASTContext(); 3768 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 3769 !hasAttr<DLLExportAttr>()) 3770 return false; 3771 3772 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 3773 FD = FD->getPreviousDecl()) 3774 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3775 return true; 3776 3777 return false; 3778 } 3779 3780 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 3781 if (Redecl->getStorageClass() != SC_Extern) 3782 return false; 3783 3784 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 3785 FD = FD->getPreviousDecl()) 3786 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3787 return false; 3788 3789 return true; 3790 } 3791 3792 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 3793 // Only consider file-scope declarations in this test. 3794 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 3795 return false; 3796 3797 // Only consider explicit declarations; the presence of a builtin for a 3798 // libcall shouldn't affect whether a definition is externally visible. 3799 if (Redecl->isImplicit()) 3800 return false; 3801 3802 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 3803 return true; // Not an inline definition 3804 3805 return false; 3806 } 3807 3808 /// For a function declaration in C or C++, determine whether this 3809 /// declaration causes the definition to be externally visible. 3810 /// 3811 /// For instance, this determines if adding the current declaration to the set 3812 /// of redeclarations of the given functions causes 3813 /// isInlineDefinitionExternallyVisible to change from false to true. 3814 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 3815 assert(!doesThisDeclarationHaveABody() && 3816 "Must have a declaration without a body."); 3817 3818 const ASTContext &Context = getASTContext(); 3819 3820 if (Context.getLangOpts().MSVCCompat) { 3821 const FunctionDecl *Definition; 3822 if (hasBody(Definition) && Definition->isInlined() && 3823 redeclForcesDefMSVC(this)) 3824 return true; 3825 } 3826 3827 if (Context.getLangOpts().CPlusPlus) 3828 return false; 3829 3830 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3831 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3832 // an externally visible definition. 3833 // 3834 // FIXME: What happens if gnu_inline gets added on after the first 3835 // declaration? 3836 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3837 return false; 3838 3839 const FunctionDecl *Prev = this; 3840 bool FoundBody = false; 3841 while ((Prev = Prev->getPreviousDecl())) { 3842 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3843 3844 if (Prev->doesThisDeclarationHaveABody()) { 3845 // If it's not the case that both 'inline' and 'extern' are 3846 // specified on the definition, then it is always externally visible. 3847 if (!Prev->isInlineSpecified() || 3848 Prev->getStorageClass() != SC_Extern) 3849 return false; 3850 } else if (Prev->isInlineSpecified() && 3851 Prev->getStorageClass() != SC_Extern) { 3852 return false; 3853 } 3854 } 3855 return FoundBody; 3856 } 3857 3858 // C99 6.7.4p6: 3859 // [...] If all of the file scope declarations for a function in a 3860 // translation unit include the inline function specifier without extern, 3861 // then the definition in that translation unit is an inline definition. 3862 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3863 return false; 3864 const FunctionDecl *Prev = this; 3865 bool FoundBody = false; 3866 while ((Prev = Prev->getPreviousDecl())) { 3867 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3868 if (RedeclForcesDefC99(Prev)) 3869 return false; 3870 } 3871 return FoundBody; 3872 } 3873 3874 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { 3875 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3876 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>() 3877 : FunctionTypeLoc(); 3878 } 3879 3880 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3881 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3882 if (!FTL) 3883 return SourceRange(); 3884 3885 // Skip self-referential return types. 3886 const SourceManager &SM = getASTContext().getSourceManager(); 3887 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3888 SourceLocation Boundary = getNameInfo().getBeginLoc(); 3889 if (RTRange.isInvalid() || Boundary.isInvalid() || 3890 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3891 return SourceRange(); 3892 3893 return RTRange; 3894 } 3895 3896 SourceRange FunctionDecl::getParametersSourceRange() const { 3897 unsigned NP = getNumParams(); 3898 SourceLocation EllipsisLoc = getEllipsisLoc(); 3899 3900 if (NP == 0 && EllipsisLoc.isInvalid()) 3901 return SourceRange(); 3902 3903 SourceLocation Begin = 3904 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc; 3905 SourceLocation End = EllipsisLoc.isValid() 3906 ? EllipsisLoc 3907 : ParamInfo[NP - 1]->getSourceRange().getEnd(); 3908 3909 return SourceRange(Begin, End); 3910 } 3911 3912 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3913 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3914 return FTL ? FTL.getExceptionSpecRange() : SourceRange(); 3915 } 3916 3917 /// For an inline function definition in C, or for a gnu_inline function 3918 /// in C++, determine whether the definition will be externally visible. 3919 /// 3920 /// Inline function definitions are always available for inlining optimizations. 3921 /// However, depending on the language dialect, declaration specifiers, and 3922 /// attributes, the definition of an inline function may or may not be 3923 /// "externally" visible to other translation units in the program. 3924 /// 3925 /// In C99, inline definitions are not externally visible by default. However, 3926 /// if even one of the global-scope declarations is marked "extern inline", the 3927 /// inline definition becomes externally visible (C99 6.7.4p6). 3928 /// 3929 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3930 /// definition, we use the GNU semantics for inline, which are nearly the 3931 /// opposite of C99 semantics. In particular, "inline" by itself will create 3932 /// an externally visible symbol, but "extern inline" will not create an 3933 /// externally visible symbol. 3934 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3935 assert((doesThisDeclarationHaveABody() || willHaveBody() || 3936 hasAttr<AliasAttr>()) && 3937 "Must be a function definition"); 3938 assert(isInlined() && "Function must be inline"); 3939 ASTContext &Context = getASTContext(); 3940 3941 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3942 // Note: If you change the logic here, please change 3943 // doesDeclarationForceExternallyVisibleDefinition as well. 3944 // 3945 // If it's not the case that both 'inline' and 'extern' are 3946 // specified on the definition, then this inline definition is 3947 // externally visible. 3948 if (Context.getLangOpts().CPlusPlus) 3949 return false; 3950 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3951 return true; 3952 3953 // If any declaration is 'inline' but not 'extern', then this definition 3954 // is externally visible. 3955 for (auto *Redecl : redecls()) { 3956 if (Redecl->isInlineSpecified() && 3957 Redecl->getStorageClass() != SC_Extern) 3958 return true; 3959 } 3960 3961 return false; 3962 } 3963 3964 // The rest of this function is C-only. 3965 assert(!Context.getLangOpts().CPlusPlus && 3966 "should not use C inline rules in C++"); 3967 3968 // C99 6.7.4p6: 3969 // [...] If all of the file scope declarations for a function in a 3970 // translation unit include the inline function specifier without extern, 3971 // then the definition in that translation unit is an inline definition. 3972 for (auto *Redecl : redecls()) { 3973 if (RedeclForcesDefC99(Redecl)) 3974 return true; 3975 } 3976 3977 // C99 6.7.4p6: 3978 // An inline definition does not provide an external definition for the 3979 // function, and does not forbid an external definition in another 3980 // translation unit. 3981 return false; 3982 } 3983 3984 /// getOverloadedOperator - Which C++ overloaded operator this 3985 /// function represents, if any. 3986 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3987 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3988 return getDeclName().getCXXOverloadedOperator(); 3989 return OO_None; 3990 } 3991 3992 /// getLiteralIdentifier - The literal suffix identifier this function 3993 /// represents, if any. 3994 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3995 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3996 return getDeclName().getCXXLiteralIdentifier(); 3997 return nullptr; 3998 } 3999 4000 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 4001 if (TemplateOrSpecialization.isNull()) 4002 return TK_NonTemplate; 4003 if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) { 4004 if (isa<FunctionDecl>(ND)) 4005 return TK_DependentNonTemplate; 4006 assert(isa<FunctionTemplateDecl>(ND) && 4007 "No other valid types in NamedDecl"); 4008 return TK_FunctionTemplate; 4009 } 4010 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 4011 return TK_MemberSpecialization; 4012 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 4013 return TK_FunctionTemplateSpecialization; 4014 if (TemplateOrSpecialization.is 4015 <DependentFunctionTemplateSpecializationInfo*>()) 4016 return TK_DependentFunctionTemplateSpecialization; 4017 4018 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 4019 } 4020 4021 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 4022 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 4023 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 4024 4025 return nullptr; 4026 } 4027 4028 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 4029 if (auto *MSI = 4030 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4031 return MSI; 4032 if (auto *FTSI = TemplateOrSpecialization 4033 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 4034 return FTSI->getMemberSpecializationInfo(); 4035 return nullptr; 4036 } 4037 4038 void 4039 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 4040 FunctionDecl *FD, 4041 TemplateSpecializationKind TSK) { 4042 assert(TemplateOrSpecialization.isNull() && 4043 "Member function is already a specialization"); 4044 MemberSpecializationInfo *Info 4045 = new (C) MemberSpecializationInfo(FD, TSK); 4046 TemplateOrSpecialization = Info; 4047 } 4048 4049 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 4050 return dyn_cast_if_present<FunctionTemplateDecl>( 4051 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 4052 } 4053 4054 void FunctionDecl::setDescribedFunctionTemplate( 4055 FunctionTemplateDecl *Template) { 4056 assert(TemplateOrSpecialization.isNull() && 4057 "Member function is already a specialization"); 4058 TemplateOrSpecialization = Template; 4059 } 4060 4061 bool FunctionDecl::isFunctionTemplateSpecialization() const { 4062 return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() || 4063 TemplateOrSpecialization 4064 .is<DependentFunctionTemplateSpecializationInfo *>(); 4065 } 4066 4067 void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) { 4068 assert(TemplateOrSpecialization.isNull() && 4069 "Function is already a specialization"); 4070 TemplateOrSpecialization = FD; 4071 } 4072 4073 FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const { 4074 return dyn_cast_if_present<FunctionDecl>( 4075 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 4076 } 4077 4078 bool FunctionDecl::isImplicitlyInstantiable() const { 4079 // If the function is invalid, it can't be implicitly instantiated. 4080 if (isInvalidDecl()) 4081 return false; 4082 4083 switch (getTemplateSpecializationKindForInstantiation()) { 4084 case TSK_Undeclared: 4085 case TSK_ExplicitInstantiationDefinition: 4086 case TSK_ExplicitSpecialization: 4087 return false; 4088 4089 case TSK_ImplicitInstantiation: 4090 return true; 4091 4092 case TSK_ExplicitInstantiationDeclaration: 4093 // Handled below. 4094 break; 4095 } 4096 4097 // Find the actual template from which we will instantiate. 4098 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 4099 bool HasPattern = false; 4100 if (PatternDecl) 4101 HasPattern = PatternDecl->hasBody(PatternDecl); 4102 4103 // C++0x [temp.explicit]p9: 4104 // Except for inline functions, other explicit instantiation declarations 4105 // have the effect of suppressing the implicit instantiation of the entity 4106 // to which they refer. 4107 if (!HasPattern || !PatternDecl) 4108 return true; 4109 4110 return PatternDecl->isInlined(); 4111 } 4112 4113 bool FunctionDecl::isTemplateInstantiation() const { 4114 // FIXME: Remove this, it's not clear what it means. (Which template 4115 // specialization kind?) 4116 return clang::isTemplateInstantiation(getTemplateSpecializationKind()); 4117 } 4118 4119 FunctionDecl * 4120 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const { 4121 // If this is a generic lambda call operator specialization, its 4122 // instantiation pattern is always its primary template's pattern 4123 // even if its primary template was instantiated from another 4124 // member template (which happens with nested generic lambdas). 4125 // Since a lambda's call operator's body is transformed eagerly, 4126 // we don't have to go hunting for a prototype definition template 4127 // (i.e. instantiated-from-member-template) to use as an instantiation 4128 // pattern. 4129 4130 if (isGenericLambdaCallOperatorSpecialization( 4131 dyn_cast<CXXMethodDecl>(this))) { 4132 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 4133 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 4134 } 4135 4136 // Check for a declaration of this function that was instantiated from a 4137 // friend definition. 4138 const FunctionDecl *FD = nullptr; 4139 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true)) 4140 FD = this; 4141 4142 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) { 4143 if (ForDefinition && 4144 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind())) 4145 return nullptr; 4146 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom())); 4147 } 4148 4149 if (ForDefinition && 4150 !clang::isTemplateInstantiation(getTemplateSpecializationKind())) 4151 return nullptr; 4152 4153 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 4154 // If we hit a point where the user provided a specialization of this 4155 // template, we're done looking. 4156 while (!ForDefinition || !Primary->hasMemberSpecialization()) { 4157 if (auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate()) 4158 Primary = NewPrimary; 4159 else 4160 break; 4161 } 4162 4163 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 4164 } 4165 4166 return nullptr; 4167 } 4168 4169 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 4170 if (FunctionTemplateSpecializationInfo *Info 4171 = TemplateOrSpecialization 4172 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4173 return Info->getTemplate(); 4174 } 4175 return nullptr; 4176 } 4177 4178 FunctionTemplateSpecializationInfo * 4179 FunctionDecl::getTemplateSpecializationInfo() const { 4180 return TemplateOrSpecialization 4181 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 4182 } 4183 4184 const TemplateArgumentList * 4185 FunctionDecl::getTemplateSpecializationArgs() const { 4186 if (FunctionTemplateSpecializationInfo *Info 4187 = TemplateOrSpecialization 4188 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4189 return Info->TemplateArguments; 4190 } 4191 return nullptr; 4192 } 4193 4194 const ASTTemplateArgumentListInfo * 4195 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 4196 if (FunctionTemplateSpecializationInfo *Info 4197 = TemplateOrSpecialization 4198 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4199 return Info->TemplateArgumentsAsWritten; 4200 } 4201 if (DependentFunctionTemplateSpecializationInfo *Info = 4202 TemplateOrSpecialization 4203 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) { 4204 return Info->TemplateArgumentsAsWritten; 4205 } 4206 return nullptr; 4207 } 4208 4209 void FunctionDecl::setFunctionTemplateSpecialization( 4210 ASTContext &C, FunctionTemplateDecl *Template, 4211 TemplateArgumentList *TemplateArgs, void *InsertPos, 4212 TemplateSpecializationKind TSK, 4213 const TemplateArgumentListInfo *TemplateArgsAsWritten, 4214 SourceLocation PointOfInstantiation) { 4215 assert((TemplateOrSpecialization.isNull() || 4216 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && 4217 "Member function is already a specialization"); 4218 assert(TSK != TSK_Undeclared && 4219 "Must specify the type of function template specialization"); 4220 assert((TemplateOrSpecialization.isNull() || 4221 getFriendObjectKind() != FOK_None || 4222 TSK == TSK_ExplicitSpecialization) && 4223 "Member specialization must be an explicit specialization"); 4224 FunctionTemplateSpecializationInfo *Info = 4225 FunctionTemplateSpecializationInfo::Create( 4226 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten, 4227 PointOfInstantiation, 4228 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()); 4229 TemplateOrSpecialization = Info; 4230 Template->addSpecialization(Info, InsertPos); 4231 } 4232 4233 void FunctionDecl::setDependentTemplateSpecialization( 4234 ASTContext &Context, const UnresolvedSetImpl &Templates, 4235 const TemplateArgumentListInfo *TemplateArgs) { 4236 assert(TemplateOrSpecialization.isNull()); 4237 DependentFunctionTemplateSpecializationInfo *Info = 4238 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 4239 TemplateArgs); 4240 TemplateOrSpecialization = Info; 4241 } 4242 4243 DependentFunctionTemplateSpecializationInfo * 4244 FunctionDecl::getDependentSpecializationInfo() const { 4245 return TemplateOrSpecialization 4246 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 4247 } 4248 4249 DependentFunctionTemplateSpecializationInfo * 4250 DependentFunctionTemplateSpecializationInfo::Create( 4251 ASTContext &Context, const UnresolvedSetImpl &Candidates, 4252 const TemplateArgumentListInfo *TArgs) { 4253 const auto *TArgsWritten = 4254 TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr; 4255 return new (Context.Allocate( 4256 totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size()))) 4257 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten); 4258 } 4259 4260 DependentFunctionTemplateSpecializationInfo:: 4261 DependentFunctionTemplateSpecializationInfo( 4262 const UnresolvedSetImpl &Candidates, 4263 const ASTTemplateArgumentListInfo *TemplateArgsWritten) 4264 : NumCandidates(Candidates.size()), 4265 TemplateArgumentsAsWritten(TemplateArgsWritten) { 4266 std::transform(Candidates.begin(), Candidates.end(), 4267 getTrailingObjects<FunctionTemplateDecl *>(), 4268 [](NamedDecl *ND) { 4269 return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl()); 4270 }); 4271 } 4272 4273 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 4274 // For a function template specialization, query the specialization 4275 // information object. 4276 if (FunctionTemplateSpecializationInfo *FTSInfo = 4277 TemplateOrSpecialization 4278 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 4279 return FTSInfo->getTemplateSpecializationKind(); 4280 4281 if (MemberSpecializationInfo *MSInfo = 4282 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4283 return MSInfo->getTemplateSpecializationKind(); 4284 4285 // A dependent function template specialization is an explicit specialization, 4286 // except when it's a friend declaration. 4287 if (TemplateOrSpecialization 4288 .is<DependentFunctionTemplateSpecializationInfo *>() && 4289 getFriendObjectKind() == FOK_None) 4290 return TSK_ExplicitSpecialization; 4291 4292 return TSK_Undeclared; 4293 } 4294 4295 TemplateSpecializationKind 4296 FunctionDecl::getTemplateSpecializationKindForInstantiation() const { 4297 // This is the same as getTemplateSpecializationKind(), except that for a 4298 // function that is both a function template specialization and a member 4299 // specialization, we prefer the member specialization information. Eg: 4300 // 4301 // template<typename T> struct A { 4302 // template<typename U> void f() {} 4303 // template<> void f<int>() {} 4304 // }; 4305 // 4306 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function 4307 // template specialization; both getTemplateSpecializationKind() and 4308 // getTemplateSpecializationKindForInstantiation() will return 4309 // TSK_ExplicitSpecialization. 4310 // 4311 // For A<int>::f<int>(): 4312 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization 4313 // * getTemplateSpecializationKindForInstantiation() will return 4314 // TSK_ImplicitInstantiation 4315 // 4316 // This reflects the facts that A<int>::f<int> is an explicit specialization 4317 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated 4318 // from A::f<int> if a definition is needed. 4319 if (FunctionTemplateSpecializationInfo *FTSInfo = 4320 TemplateOrSpecialization 4321 .dyn_cast<FunctionTemplateSpecializationInfo *>()) { 4322 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo()) 4323 return MSInfo->getTemplateSpecializationKind(); 4324 return FTSInfo->getTemplateSpecializationKind(); 4325 } 4326 4327 if (MemberSpecializationInfo *MSInfo = 4328 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4329 return MSInfo->getTemplateSpecializationKind(); 4330 4331 if (TemplateOrSpecialization 4332 .is<DependentFunctionTemplateSpecializationInfo *>() && 4333 getFriendObjectKind() == FOK_None) 4334 return TSK_ExplicitSpecialization; 4335 4336 return TSK_Undeclared; 4337 } 4338 4339 void 4340 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4341 SourceLocation PointOfInstantiation) { 4342 if (FunctionTemplateSpecializationInfo *FTSInfo 4343 = TemplateOrSpecialization.dyn_cast< 4344 FunctionTemplateSpecializationInfo*>()) { 4345 FTSInfo->setTemplateSpecializationKind(TSK); 4346 if (TSK != TSK_ExplicitSpecialization && 4347 PointOfInstantiation.isValid() && 4348 FTSInfo->getPointOfInstantiation().isInvalid()) { 4349 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 4350 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4351 L->InstantiationRequested(this); 4352 } 4353 } else if (MemberSpecializationInfo *MSInfo 4354 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 4355 MSInfo->setTemplateSpecializationKind(TSK); 4356 if (TSK != TSK_ExplicitSpecialization && 4357 PointOfInstantiation.isValid() && 4358 MSInfo->getPointOfInstantiation().isInvalid()) { 4359 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4360 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4361 L->InstantiationRequested(this); 4362 } 4363 } else 4364 llvm_unreachable("Function cannot have a template specialization kind"); 4365 } 4366 4367 SourceLocation FunctionDecl::getPointOfInstantiation() const { 4368 if (FunctionTemplateSpecializationInfo *FTSInfo 4369 = TemplateOrSpecialization.dyn_cast< 4370 FunctionTemplateSpecializationInfo*>()) 4371 return FTSInfo->getPointOfInstantiation(); 4372 if (MemberSpecializationInfo *MSInfo = 4373 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4374 return MSInfo->getPointOfInstantiation(); 4375 4376 return SourceLocation(); 4377 } 4378 4379 bool FunctionDecl::isOutOfLine() const { 4380 if (Decl::isOutOfLine()) 4381 return true; 4382 4383 // If this function was instantiated from a member function of a 4384 // class template, check whether that member function was defined out-of-line. 4385 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 4386 const FunctionDecl *Definition; 4387 if (FD->hasBody(Definition)) 4388 return Definition->isOutOfLine(); 4389 } 4390 4391 // If this function was instantiated from a function template, 4392 // check whether that function template was defined out-of-line. 4393 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 4394 const FunctionDecl *Definition; 4395 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 4396 return Definition->isOutOfLine(); 4397 } 4398 4399 return false; 4400 } 4401 4402 SourceRange FunctionDecl::getSourceRange() const { 4403 return SourceRange(getOuterLocStart(), EndRangeLoc); 4404 } 4405 4406 unsigned FunctionDecl::getMemoryFunctionKind() const { 4407 IdentifierInfo *FnInfo = getIdentifier(); 4408 4409 if (!FnInfo) 4410 return 0; 4411 4412 // Builtin handling. 4413 switch (getBuiltinID()) { 4414 case Builtin::BI__builtin_memset: 4415 case Builtin::BI__builtin___memset_chk: 4416 case Builtin::BImemset: 4417 return Builtin::BImemset; 4418 4419 case Builtin::BI__builtin_memcpy: 4420 case Builtin::BI__builtin___memcpy_chk: 4421 case Builtin::BImemcpy: 4422 return Builtin::BImemcpy; 4423 4424 case Builtin::BI__builtin_mempcpy: 4425 case Builtin::BI__builtin___mempcpy_chk: 4426 case Builtin::BImempcpy: 4427 return Builtin::BImempcpy; 4428 4429 case Builtin::BI__builtin_memmove: 4430 case Builtin::BI__builtin___memmove_chk: 4431 case Builtin::BImemmove: 4432 return Builtin::BImemmove; 4433 4434 case Builtin::BIstrlcpy: 4435 case Builtin::BI__builtin___strlcpy_chk: 4436 return Builtin::BIstrlcpy; 4437 4438 case Builtin::BIstrlcat: 4439 case Builtin::BI__builtin___strlcat_chk: 4440 return Builtin::BIstrlcat; 4441 4442 case Builtin::BI__builtin_memcmp: 4443 case Builtin::BImemcmp: 4444 return Builtin::BImemcmp; 4445 4446 case Builtin::BI__builtin_bcmp: 4447 case Builtin::BIbcmp: 4448 return Builtin::BIbcmp; 4449 4450 case Builtin::BI__builtin_strncpy: 4451 case Builtin::BI__builtin___strncpy_chk: 4452 case Builtin::BIstrncpy: 4453 return Builtin::BIstrncpy; 4454 4455 case Builtin::BI__builtin_strncmp: 4456 case Builtin::BIstrncmp: 4457 return Builtin::BIstrncmp; 4458 4459 case Builtin::BI__builtin_strncasecmp: 4460 case Builtin::BIstrncasecmp: 4461 return Builtin::BIstrncasecmp; 4462 4463 case Builtin::BI__builtin_strncat: 4464 case Builtin::BI__builtin___strncat_chk: 4465 case Builtin::BIstrncat: 4466 return Builtin::BIstrncat; 4467 4468 case Builtin::BI__builtin_strndup: 4469 case Builtin::BIstrndup: 4470 return Builtin::BIstrndup; 4471 4472 case Builtin::BI__builtin_strlen: 4473 case Builtin::BIstrlen: 4474 return Builtin::BIstrlen; 4475 4476 case Builtin::BI__builtin_bzero: 4477 case Builtin::BIbzero: 4478 return Builtin::BIbzero; 4479 4480 case Builtin::BI__builtin_bcopy: 4481 case Builtin::BIbcopy: 4482 return Builtin::BIbcopy; 4483 4484 case Builtin::BIfree: 4485 return Builtin::BIfree; 4486 4487 default: 4488 if (isExternC()) { 4489 if (FnInfo->isStr("memset")) 4490 return Builtin::BImemset; 4491 if (FnInfo->isStr("memcpy")) 4492 return Builtin::BImemcpy; 4493 if (FnInfo->isStr("mempcpy")) 4494 return Builtin::BImempcpy; 4495 if (FnInfo->isStr("memmove")) 4496 return Builtin::BImemmove; 4497 if (FnInfo->isStr("memcmp")) 4498 return Builtin::BImemcmp; 4499 if (FnInfo->isStr("bcmp")) 4500 return Builtin::BIbcmp; 4501 if (FnInfo->isStr("strncpy")) 4502 return Builtin::BIstrncpy; 4503 if (FnInfo->isStr("strncmp")) 4504 return Builtin::BIstrncmp; 4505 if (FnInfo->isStr("strncasecmp")) 4506 return Builtin::BIstrncasecmp; 4507 if (FnInfo->isStr("strncat")) 4508 return Builtin::BIstrncat; 4509 if (FnInfo->isStr("strndup")) 4510 return Builtin::BIstrndup; 4511 if (FnInfo->isStr("strlen")) 4512 return Builtin::BIstrlen; 4513 if (FnInfo->isStr("bzero")) 4514 return Builtin::BIbzero; 4515 if (FnInfo->isStr("bcopy")) 4516 return Builtin::BIbcopy; 4517 } else if (isInStdNamespace()) { 4518 if (FnInfo->isStr("free")) 4519 return Builtin::BIfree; 4520 } 4521 break; 4522 } 4523 return 0; 4524 } 4525 4526 unsigned FunctionDecl::getODRHash() const { 4527 assert(hasODRHash()); 4528 return ODRHash; 4529 } 4530 4531 unsigned FunctionDecl::getODRHash() { 4532 if (hasODRHash()) 4533 return ODRHash; 4534 4535 if (auto *FT = getInstantiatedFromMemberFunction()) { 4536 setHasODRHash(true); 4537 ODRHash = FT->getODRHash(); 4538 return ODRHash; 4539 } 4540 4541 class ODRHash Hash; 4542 Hash.AddFunctionDecl(this); 4543 setHasODRHash(true); 4544 ODRHash = Hash.CalculateHash(); 4545 return ODRHash; 4546 } 4547 4548 //===----------------------------------------------------------------------===// 4549 // FieldDecl Implementation 4550 //===----------------------------------------------------------------------===// 4551 4552 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 4553 SourceLocation StartLoc, SourceLocation IdLoc, 4554 const IdentifierInfo *Id, QualType T, 4555 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 4556 InClassInitStyle InitStyle) { 4557 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 4558 BW, Mutable, InitStyle); 4559 } 4560 4561 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 4562 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 4563 SourceLocation(), nullptr, QualType(), nullptr, 4564 nullptr, false, ICIS_NoInit); 4565 } 4566 4567 bool FieldDecl::isAnonymousStructOrUnion() const { 4568 if (!isImplicit() || getDeclName()) 4569 return false; 4570 4571 if (const auto *Record = getType()->getAs<RecordType>()) 4572 return Record->getDecl()->isAnonymousStructOrUnion(); 4573 4574 return false; 4575 } 4576 4577 Expr *FieldDecl::getInClassInitializer() const { 4578 if (!hasInClassInitializer()) 4579 return nullptr; 4580 4581 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init; 4582 return cast_if_present<Expr>( 4583 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource()) 4584 : InitPtr.get(nullptr)); 4585 } 4586 4587 void FieldDecl::setInClassInitializer(Expr *NewInit) { 4588 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit)); 4589 } 4590 4591 void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) { 4592 assert(hasInClassInitializer() && !getInClassInitializer()); 4593 if (BitField) 4594 InitAndBitWidth->Init = NewInit; 4595 else 4596 Init = NewInit; 4597 } 4598 4599 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 4600 assert(isBitField() && "not a bitfield"); 4601 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 4602 } 4603 4604 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const { 4605 return isUnnamedBitField() && !getBitWidth()->isValueDependent() && 4606 getBitWidthValue(Ctx) == 0; 4607 } 4608 4609 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { 4610 if (isZeroLengthBitField(Ctx)) 4611 return true; 4612 4613 // C++2a [intro.object]p7: 4614 // An object has nonzero size if it 4615 // -- is not a potentially-overlapping subobject, or 4616 if (!hasAttr<NoUniqueAddressAttr>()) 4617 return false; 4618 4619 // -- is not of class type, or 4620 const auto *RT = getType()->getAs<RecordType>(); 4621 if (!RT) 4622 return false; 4623 const RecordDecl *RD = RT->getDecl()->getDefinition(); 4624 if (!RD) { 4625 assert(isInvalidDecl() && "valid field has incomplete type"); 4626 return false; 4627 } 4628 4629 // -- [has] virtual member functions or virtual base classes, or 4630 // -- has subobjects of nonzero size or bit-fields of nonzero length 4631 const auto *CXXRD = cast<CXXRecordDecl>(RD); 4632 if (!CXXRD->isEmpty()) 4633 return false; 4634 4635 // Otherwise, [...] the circumstances under which the object has zero size 4636 // are implementation-defined. 4637 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft()) 4638 return true; 4639 4640 // MS ABI: has nonzero size if it is a class type with class type fields, 4641 // whether or not they have nonzero size 4642 return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) { 4643 return Field->getType()->getAs<RecordType>(); 4644 }); 4645 } 4646 4647 bool FieldDecl::isPotentiallyOverlapping() const { 4648 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl(); 4649 } 4650 4651 unsigned FieldDecl::getFieldIndex() const { 4652 const FieldDecl *Canonical = getCanonicalDecl(); 4653 if (Canonical != this) 4654 return Canonical->getFieldIndex(); 4655 4656 if (CachedFieldIndex) return CachedFieldIndex - 1; 4657 4658 unsigned Index = 0; 4659 const RecordDecl *RD = getParent()->getDefinition(); 4660 assert(RD && "requested index for field of struct with no definition"); 4661 4662 for (auto *Field : RD->fields()) { 4663 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 4664 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 && 4665 "overflow in field numbering"); 4666 ++Index; 4667 } 4668 4669 assert(CachedFieldIndex && "failed to find field in parent"); 4670 return CachedFieldIndex - 1; 4671 } 4672 4673 SourceRange FieldDecl::getSourceRange() const { 4674 const Expr *FinalExpr = getInClassInitializer(); 4675 if (!FinalExpr) 4676 FinalExpr = getBitWidth(); 4677 if (FinalExpr) 4678 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc()); 4679 return DeclaratorDecl::getSourceRange(); 4680 } 4681 4682 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 4683 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 4684 "capturing type in non-lambda or captured record."); 4685 assert(StorageKind == ISK_NoInit && !BitField && 4686 "bit-field or field with default member initializer cannot capture " 4687 "VLA type"); 4688 StorageKind = ISK_CapturedVLAType; 4689 CapturedVLAType = VLAType; 4690 } 4691 4692 void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 4693 // Print unnamed members using name of their type. 4694 if (isAnonymousStructOrUnion()) { 4695 this->getType().print(OS, Policy); 4696 return; 4697 } 4698 // Otherwise, do the normal printing. 4699 DeclaratorDecl::printName(OS, Policy); 4700 } 4701 4702 const FieldDecl *FieldDecl::findCountedByField() const { 4703 const auto *CAT = getType()->getAs<CountAttributedType>(); 4704 if (!CAT) 4705 return nullptr; 4706 4707 const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr()); 4708 const auto *CountDecl = CountDRE->getDecl(); 4709 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) 4710 CountDecl = IFD->getAnonField(); 4711 4712 return dyn_cast<FieldDecl>(CountDecl); 4713 } 4714 4715 //===----------------------------------------------------------------------===// 4716 // TagDecl Implementation 4717 //===----------------------------------------------------------------------===// 4718 4719 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, 4720 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, 4721 SourceLocation StartL) 4722 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), 4723 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { 4724 assert((DK != Enum || TK == TagTypeKind::Enum) && 4725 "EnumDecl not matched with TagTypeKind::Enum"); 4726 setPreviousDecl(PrevDecl); 4727 setTagKind(TK); 4728 setCompleteDefinition(false); 4729 setBeingDefined(false); 4730 setEmbeddedInDeclarator(false); 4731 setFreeStanding(false); 4732 setCompleteDefinitionRequired(false); 4733 TagDeclBits.IsThisDeclarationADemotedDefinition = false; 4734 } 4735 4736 SourceLocation TagDecl::getOuterLocStart() const { 4737 return getTemplateOrInnerLocStart(this); 4738 } 4739 4740 SourceRange TagDecl::getSourceRange() const { 4741 SourceLocation RBraceLoc = BraceRange.getEnd(); 4742 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 4743 return SourceRange(getOuterLocStart(), E); 4744 } 4745 4746 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 4747 4748 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 4749 TypedefNameDeclOrQualifier = TDD; 4750 if (const Type *T = getTypeForDecl()) { 4751 (void)T; 4752 assert(T->isLinkageValid()); 4753 } 4754 assert(isLinkageValid()); 4755 } 4756 4757 void TagDecl::startDefinition() { 4758 setBeingDefined(true); 4759 4760 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 4761 struct CXXRecordDecl::DefinitionData *Data = 4762 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 4763 for (auto *I : redecls()) 4764 cast<CXXRecordDecl>(I)->DefinitionData = Data; 4765 } 4766 } 4767 4768 void TagDecl::completeDefinition() { 4769 assert((!isa<CXXRecordDecl>(this) || 4770 cast<CXXRecordDecl>(this)->hasDefinition()) && 4771 "definition completed but not started"); 4772 4773 setCompleteDefinition(true); 4774 setBeingDefined(false); 4775 4776 if (ASTMutationListener *L = getASTMutationListener()) 4777 L->CompletedTagDefinition(this); 4778 } 4779 4780 TagDecl *TagDecl::getDefinition() const { 4781 if (isCompleteDefinition()) 4782 return const_cast<TagDecl *>(this); 4783 4784 // If it's possible for us to have an out-of-date definition, check now. 4785 if (mayHaveOutOfDateDef()) { 4786 if (IdentifierInfo *II = getIdentifier()) { 4787 if (II->isOutOfDate()) { 4788 updateOutOfDate(*II); 4789 } 4790 } 4791 } 4792 4793 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 4794 return CXXRD->getDefinition(); 4795 4796 for (auto *R : redecls()) 4797 if (R->isCompleteDefinition()) 4798 return R; 4799 4800 return nullptr; 4801 } 4802 4803 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 4804 if (QualifierLoc) { 4805 // Make sure the extended qualifier info is allocated. 4806 if (!hasExtInfo()) 4807 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4808 // Set qualifier info. 4809 getExtInfo()->QualifierLoc = QualifierLoc; 4810 } else { 4811 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 4812 if (hasExtInfo()) { 4813 if (getExtInfo()->NumTemplParamLists == 0) { 4814 getASTContext().Deallocate(getExtInfo()); 4815 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 4816 } 4817 else 4818 getExtInfo()->QualifierLoc = QualifierLoc; 4819 } 4820 } 4821 } 4822 4823 void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 4824 DeclarationName Name = getDeclName(); 4825 // If the name is supposed to have an identifier but does not have one, then 4826 // the tag is anonymous and we should print it differently. 4827 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) { 4828 // If the caller wanted to print a qualified name, they've already printed 4829 // the scope. And if the caller doesn't want that, the scope information 4830 // is already printed as part of the type. 4831 PrintingPolicy Copy(Policy); 4832 Copy.SuppressScope = true; 4833 getASTContext().getTagDeclType(this).print(OS, Copy); 4834 return; 4835 } 4836 // Otherwise, do the normal printing. 4837 Name.print(OS, Policy); 4838 } 4839 4840 void TagDecl::setTemplateParameterListsInfo( 4841 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 4842 assert(!TPLists.empty()); 4843 // Make sure the extended decl info is allocated. 4844 if (!hasExtInfo()) 4845 // Allocate external info struct. 4846 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4847 // Set the template parameter lists info. 4848 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 4849 } 4850 4851 //===----------------------------------------------------------------------===// 4852 // EnumDecl Implementation 4853 //===----------------------------------------------------------------------===// 4854 4855 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4856 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, 4857 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 4858 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4859 assert(Scoped || !ScopedUsingClassTag); 4860 IntegerType = nullptr; 4861 setNumPositiveBits(0); 4862 setNumNegativeBits(0); 4863 setScoped(Scoped); 4864 setScopedUsingClassTag(ScopedUsingClassTag); 4865 setFixed(Fixed); 4866 setHasODRHash(false); 4867 ODRHash = 0; 4868 } 4869 4870 void EnumDecl::anchor() {} 4871 4872 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 4873 SourceLocation StartLoc, SourceLocation IdLoc, 4874 IdentifierInfo *Id, 4875 EnumDecl *PrevDecl, bool IsScoped, 4876 bool IsScopedUsingClassTag, bool IsFixed) { 4877 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 4878 IsScoped, IsScopedUsingClassTag, IsFixed); 4879 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4880 C.getTypeDeclType(Enum, PrevDecl); 4881 return Enum; 4882 } 4883 4884 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 4885 EnumDecl *Enum = 4886 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 4887 nullptr, nullptr, false, false, false); 4888 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4889 return Enum; 4890 } 4891 4892 SourceRange EnumDecl::getIntegerTypeRange() const { 4893 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 4894 return TI->getTypeLoc().getSourceRange(); 4895 return SourceRange(); 4896 } 4897 4898 void EnumDecl::completeDefinition(QualType NewType, 4899 QualType NewPromotionType, 4900 unsigned NumPositiveBits, 4901 unsigned NumNegativeBits) { 4902 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 4903 if (!IntegerType) 4904 IntegerType = NewType.getTypePtr(); 4905 PromotionType = NewPromotionType; 4906 setNumPositiveBits(NumPositiveBits); 4907 setNumNegativeBits(NumNegativeBits); 4908 TagDecl::completeDefinition(); 4909 } 4910 4911 bool EnumDecl::isClosed() const { 4912 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 4913 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 4914 return true; 4915 } 4916 4917 bool EnumDecl::isClosedFlag() const { 4918 return isClosed() && hasAttr<FlagEnumAttr>(); 4919 } 4920 4921 bool EnumDecl::isClosedNonFlag() const { 4922 return isClosed() && !hasAttr<FlagEnumAttr>(); 4923 } 4924 4925 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 4926 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 4927 return MSI->getTemplateSpecializationKind(); 4928 4929 return TSK_Undeclared; 4930 } 4931 4932 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4933 SourceLocation PointOfInstantiation) { 4934 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 4935 assert(MSI && "Not an instantiated member enumeration?"); 4936 MSI->setTemplateSpecializationKind(TSK); 4937 if (TSK != TSK_ExplicitSpecialization && 4938 PointOfInstantiation.isValid() && 4939 MSI->getPointOfInstantiation().isInvalid()) 4940 MSI->setPointOfInstantiation(PointOfInstantiation); 4941 } 4942 4943 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 4944 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 4945 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 4946 EnumDecl *ED = getInstantiatedFromMemberEnum(); 4947 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 4948 ED = NewED; 4949 return getDefinitionOrSelf(ED); 4950 } 4951 } 4952 4953 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 4954 "couldn't find pattern for enum instantiation"); 4955 return nullptr; 4956 } 4957 4958 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 4959 if (SpecializationInfo) 4960 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 4961 4962 return nullptr; 4963 } 4964 4965 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 4966 TemplateSpecializationKind TSK) { 4967 assert(!SpecializationInfo && "Member enum is already a specialization"); 4968 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 4969 } 4970 4971 unsigned EnumDecl::getODRHash() { 4972 if (hasODRHash()) 4973 return ODRHash; 4974 4975 class ODRHash Hash; 4976 Hash.AddEnumDecl(this); 4977 setHasODRHash(true); 4978 ODRHash = Hash.CalculateHash(); 4979 return ODRHash; 4980 } 4981 4982 SourceRange EnumDecl::getSourceRange() const { 4983 auto Res = TagDecl::getSourceRange(); 4984 // Set end-point to enum-base, e.g. enum foo : ^bar 4985 if (auto *TSI = getIntegerTypeSourceInfo()) { 4986 // TagDecl doesn't know about the enum base. 4987 if (!getBraceRange().getEnd().isValid()) 4988 Res.setEnd(TSI->getTypeLoc().getEndLoc()); 4989 } 4990 return Res; 4991 } 4992 4993 void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const { 4994 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType()); 4995 unsigned NumNegativeBits = getNumNegativeBits(); 4996 unsigned NumPositiveBits = getNumPositiveBits(); 4997 4998 if (NumNegativeBits) { 4999 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 5000 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 5001 Min = -Max; 5002 } else { 5003 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 5004 Min = llvm::APInt::getZero(Bitwidth); 5005 } 5006 } 5007 5008 //===----------------------------------------------------------------------===// 5009 // RecordDecl Implementation 5010 //===----------------------------------------------------------------------===// 5011 5012 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 5013 DeclContext *DC, SourceLocation StartLoc, 5014 SourceLocation IdLoc, IdentifierInfo *Id, 5015 RecordDecl *PrevDecl) 5016 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 5017 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!"); 5018 setHasFlexibleArrayMember(false); 5019 setAnonymousStructOrUnion(false); 5020 setHasObjectMember(false); 5021 setHasVolatileMember(false); 5022 setHasLoadedFieldsFromExternalStorage(false); 5023 setNonTrivialToPrimitiveDefaultInitialize(false); 5024 setNonTrivialToPrimitiveCopy(false); 5025 setNonTrivialToPrimitiveDestroy(false); 5026 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false); 5027 setHasNonTrivialToPrimitiveDestructCUnion(false); 5028 setHasNonTrivialToPrimitiveCopyCUnion(false); 5029 setParamDestroyedInCallee(false); 5030 setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs); 5031 setIsRandomized(false); 5032 setODRHash(0); 5033 } 5034 5035 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 5036 SourceLocation StartLoc, SourceLocation IdLoc, 5037 IdentifierInfo *Id, RecordDecl* PrevDecl) { 5038 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 5039 StartLoc, IdLoc, Id, PrevDecl); 5040 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 5041 5042 C.getTypeDeclType(R, PrevDecl); 5043 return R; 5044 } 5045 5046 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, 5047 GlobalDeclID ID) { 5048 RecordDecl *R = new (C, ID) 5049 RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(), 5050 SourceLocation(), nullptr, nullptr); 5051 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 5052 return R; 5053 } 5054 5055 bool RecordDecl::isInjectedClassName() const { 5056 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 5057 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 5058 } 5059 5060 bool RecordDecl::isLambda() const { 5061 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 5062 return RD->isLambda(); 5063 return false; 5064 } 5065 5066 bool RecordDecl::isCapturedRecord() const { 5067 return hasAttr<CapturedRecordAttr>(); 5068 } 5069 5070 void RecordDecl::setCapturedRecord() { 5071 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 5072 } 5073 5074 bool RecordDecl::isOrContainsUnion() const { 5075 if (isUnion()) 5076 return true; 5077 5078 if (const RecordDecl *Def = getDefinition()) { 5079 for (const FieldDecl *FD : Def->fields()) { 5080 const RecordType *RT = FD->getType()->getAs<RecordType>(); 5081 if (RT && RT->getDecl()->isOrContainsUnion()) 5082 return true; 5083 } 5084 } 5085 5086 return false; 5087 } 5088 5089 RecordDecl::field_iterator RecordDecl::field_begin() const { 5090 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage()) 5091 LoadFieldsFromExternalStorage(); 5092 // This is necessary for correctness for C++ with modules. 5093 // FIXME: Come up with a test case that breaks without definition. 5094 if (RecordDecl *D = getDefinition(); D && D != this) 5095 return D->field_begin(); 5096 return field_iterator(decl_iterator(FirstDecl)); 5097 } 5098 5099 /// completeDefinition - Notes that the definition of this type is now 5100 /// complete. 5101 void RecordDecl::completeDefinition() { 5102 assert(!isCompleteDefinition() && "Cannot redefine record!"); 5103 TagDecl::completeDefinition(); 5104 5105 ASTContext &Ctx = getASTContext(); 5106 5107 // Layouts are dumped when computed, so if we are dumping for all complete 5108 // types, we need to force usage to get types that wouldn't be used elsewhere. 5109 // 5110 // If the type is dependent, then we can't compute its layout because there 5111 // is no way for us to know the size or alignment of a dependent type. Also 5112 // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts 5113 // on that. 5114 if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() && 5115 !isInvalidDecl()) 5116 (void)Ctx.getASTRecordLayout(this); 5117 } 5118 5119 /// isMsStruct - Get whether or not this record uses ms_struct layout. 5120 /// This which can be turned on with an attribute, pragma, or the 5121 /// -mms-bitfields command-line option. 5122 bool RecordDecl::isMsStruct(const ASTContext &C) const { 5123 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 5124 } 5125 5126 void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) { 5127 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false); 5128 LastDecl->NextInContextAndBits.setPointer(nullptr); 5129 setIsRandomized(true); 5130 } 5131 5132 void RecordDecl::LoadFieldsFromExternalStorage() const { 5133 ExternalASTSource *Source = getASTContext().getExternalSource(); 5134 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 5135 5136 // Notify that we have a RecordDecl doing some initialization. 5137 ExternalASTSource::Deserializing TheFields(Source); 5138 5139 SmallVector<Decl*, 64> Decls; 5140 setHasLoadedFieldsFromExternalStorage(true); 5141 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 5142 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 5143 }, Decls); 5144 5145 #ifndef NDEBUG 5146 // Check that all decls we got were FieldDecls. 5147 for (unsigned i=0, e=Decls.size(); i != e; ++i) 5148 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 5149 #endif 5150 5151 if (Decls.empty()) 5152 return; 5153 5154 auto [ExternalFirst, ExternalLast] = 5155 BuildDeclChain(Decls, 5156 /*FieldsAlreadyLoaded=*/false); 5157 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 5158 FirstDecl = ExternalFirst; 5159 if (!LastDecl) 5160 LastDecl = ExternalLast; 5161 } 5162 5163 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 5164 ASTContext &Context = getASTContext(); 5165 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 5166 (SanitizerKind::Address | SanitizerKind::KernelAddress); 5167 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 5168 return false; 5169 const auto &NoSanitizeList = Context.getNoSanitizeList(); 5170 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 5171 // We may be able to relax some of these requirements. 5172 int ReasonToReject = -1; 5173 if (!CXXRD || CXXRD->isExternCContext()) 5174 ReasonToReject = 0; // is not C++. 5175 else if (CXXRD->hasAttr<PackedAttr>()) 5176 ReasonToReject = 1; // is packed. 5177 else if (CXXRD->isUnion()) 5178 ReasonToReject = 2; // is a union. 5179 else if (CXXRD->isTriviallyCopyable()) 5180 ReasonToReject = 3; // is trivially copyable. 5181 else if (CXXRD->hasTrivialDestructor()) 5182 ReasonToReject = 4; // has trivial destructor. 5183 else if (CXXRD->isStandardLayout()) 5184 ReasonToReject = 5; // is standard layout. 5185 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), 5186 "field-padding")) 5187 ReasonToReject = 6; // is in an excluded file. 5188 else if (NoSanitizeList.containsType( 5189 EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) 5190 ReasonToReject = 7; // The type is excluded. 5191 5192 if (EmitRemark) { 5193 if (ReasonToReject >= 0) 5194 Context.getDiagnostics().Report( 5195 getLocation(), 5196 diag::remark_sanitize_address_insert_extra_padding_rejected) 5197 << getQualifiedNameAsString() << ReasonToReject; 5198 else 5199 Context.getDiagnostics().Report( 5200 getLocation(), 5201 diag::remark_sanitize_address_insert_extra_padding_accepted) 5202 << getQualifiedNameAsString(); 5203 } 5204 return ReasonToReject < 0; 5205 } 5206 5207 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 5208 for (const auto *I : fields()) { 5209 if (I->getIdentifier()) 5210 return I; 5211 5212 if (const auto *RT = I->getType()->getAs<RecordType>()) 5213 if (const FieldDecl *NamedDataMember = 5214 RT->getDecl()->findFirstNamedDataMember()) 5215 return NamedDataMember; 5216 } 5217 5218 // We didn't find a named data member. 5219 return nullptr; 5220 } 5221 5222 unsigned RecordDecl::getODRHash() { 5223 if (hasODRHash()) 5224 return RecordDeclBits.ODRHash; 5225 5226 // Only calculate hash on first call of getODRHash per record. 5227 ODRHash Hash; 5228 Hash.AddRecordDecl(this); 5229 // For RecordDecl the ODRHash is stored in the remaining 26 5230 // bit of RecordDeclBits, adjust the hash to accomodate. 5231 setODRHash(Hash.CalculateHash() >> 6); 5232 return RecordDeclBits.ODRHash; 5233 } 5234 5235 //===----------------------------------------------------------------------===// 5236 // BlockDecl Implementation 5237 //===----------------------------------------------------------------------===// 5238 5239 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 5240 : Decl(Block, DC, CaretLoc), DeclContext(Block) { 5241 setIsVariadic(false); 5242 setCapturesCXXThis(false); 5243 setBlockMissingReturnType(true); 5244 setIsConversionFromLambda(false); 5245 setDoesNotEscape(false); 5246 setCanAvoidCopyToHeap(false); 5247 } 5248 5249 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 5250 assert(!ParamInfo && "Already has param info!"); 5251 5252 // Zero params -> null pointer. 5253 if (!NewParamInfo.empty()) { 5254 NumParams = NewParamInfo.size(); 5255 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 5256 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 5257 } 5258 } 5259 5260 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 5261 bool CapturesCXXThis) { 5262 this->setCapturesCXXThis(CapturesCXXThis); 5263 this->NumCaptures = Captures.size(); 5264 5265 if (Captures.empty()) { 5266 this->Captures = nullptr; 5267 return; 5268 } 5269 5270 this->Captures = Captures.copy(Context).data(); 5271 } 5272 5273 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 5274 for (const auto &I : captures()) 5275 // Only auto vars can be captured, so no redeclaration worries. 5276 if (I.getVariable() == variable) 5277 return true; 5278 5279 return false; 5280 } 5281 5282 SourceRange BlockDecl::getSourceRange() const { 5283 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation()); 5284 } 5285 5286 //===----------------------------------------------------------------------===// 5287 // Other Decl Allocation/Deallocation Method Implementations 5288 //===----------------------------------------------------------------------===// 5289 5290 void TranslationUnitDecl::anchor() {} 5291 5292 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 5293 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 5294 } 5295 5296 void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) { 5297 AnonymousNamespace = D; 5298 5299 if (ASTMutationListener *Listener = Ctx.getASTMutationListener()) 5300 Listener->AddedAnonymousNamespace(this, D); 5301 } 5302 5303 void PragmaCommentDecl::anchor() {} 5304 5305 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 5306 TranslationUnitDecl *DC, 5307 SourceLocation CommentLoc, 5308 PragmaMSCommentKind CommentKind, 5309 StringRef Arg) { 5310 PragmaCommentDecl *PCD = 5311 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 5312 PragmaCommentDecl(DC, CommentLoc, CommentKind); 5313 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 5314 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 5315 return PCD; 5316 } 5317 5318 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 5319 GlobalDeclID ID, 5320 unsigned ArgSize) { 5321 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 5322 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 5323 } 5324 5325 void PragmaDetectMismatchDecl::anchor() {} 5326 5327 PragmaDetectMismatchDecl * 5328 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 5329 SourceLocation Loc, StringRef Name, 5330 StringRef Value) { 5331 size_t ValueStart = Name.size() + 1; 5332 PragmaDetectMismatchDecl *PDMD = 5333 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 5334 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 5335 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 5336 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 5337 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 5338 Value.size()); 5339 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 5340 return PDMD; 5341 } 5342 5343 PragmaDetectMismatchDecl * 5344 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, 5345 unsigned NameValueSize) { 5346 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 5347 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 5348 } 5349 5350 void ExternCContextDecl::anchor() {} 5351 5352 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 5353 TranslationUnitDecl *DC) { 5354 return new (C, DC) ExternCContextDecl(DC); 5355 } 5356 5357 void LabelDecl::anchor() {} 5358 5359 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 5360 SourceLocation IdentL, IdentifierInfo *II) { 5361 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 5362 } 5363 5364 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 5365 SourceLocation IdentL, IdentifierInfo *II, 5366 SourceLocation GnuLabelL) { 5367 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 5368 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 5369 } 5370 5371 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5372 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 5373 SourceLocation()); 5374 } 5375 5376 void LabelDecl::setMSAsmLabel(StringRef Name) { 5377 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 5378 memcpy(Buffer, Name.data(), Name.size()); 5379 Buffer[Name.size()] = '\0'; 5380 MSAsmName = Buffer; 5381 } 5382 5383 void ValueDecl::anchor() {} 5384 5385 bool ValueDecl::isWeak() const { 5386 auto *MostRecent = getMostRecentDecl(); 5387 return MostRecent->hasAttr<WeakAttr>() || 5388 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported(); 5389 } 5390 5391 bool ValueDecl::isInitCapture() const { 5392 if (auto *Var = llvm::dyn_cast<VarDecl>(this)) 5393 return Var->isInitCapture(); 5394 return false; 5395 } 5396 5397 void ImplicitParamDecl::anchor() {} 5398 5399 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 5400 SourceLocation IdLoc, 5401 IdentifierInfo *Id, QualType Type, 5402 ImplicitParamKind ParamKind) { 5403 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 5404 } 5405 5406 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 5407 ImplicitParamKind ParamKind) { 5408 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 5409 } 5410 5411 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 5412 GlobalDeclID ID) { 5413 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 5414 } 5415 5416 FunctionDecl * 5417 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 5418 const DeclarationNameInfo &NameInfo, QualType T, 5419 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 5420 bool isInlineSpecified, bool hasWrittenPrototype, 5421 ConstexprSpecKind ConstexprKind, 5422 Expr *TrailingRequiresClause) { 5423 FunctionDecl *New = new (C, DC) FunctionDecl( 5424 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 5425 isInlineSpecified, ConstexprKind, TrailingRequiresClause); 5426 New->setHasWrittenPrototype(hasWrittenPrototype); 5427 return New; 5428 } 5429 5430 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5431 return new (C, ID) FunctionDecl( 5432 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), 5433 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr); 5434 } 5435 5436 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5437 return new (C, DC) BlockDecl(DC, L); 5438 } 5439 5440 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5441 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 5442 } 5443 5444 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 5445 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 5446 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 5447 5448 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 5449 unsigned NumParams) { 5450 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5451 CapturedDecl(DC, NumParams); 5452 } 5453 5454 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, 5455 unsigned NumParams) { 5456 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5457 CapturedDecl(nullptr, NumParams); 5458 } 5459 5460 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 5461 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 5462 5463 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 5464 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 5465 5466 EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC, 5467 SourceLocation L, IdentifierInfo *Id, 5468 QualType T, Expr *E, const llvm::APSInt &V) 5469 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) { 5470 setInitVal(C, V); 5471 } 5472 5473 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 5474 SourceLocation L, 5475 IdentifierInfo *Id, QualType T, 5476 Expr *E, const llvm::APSInt &V) { 5477 return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V); 5478 } 5479 5480 EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C, 5481 GlobalDeclID ID) { 5482 return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr, 5483 QualType(), nullptr, llvm::APSInt()); 5484 } 5485 5486 void IndirectFieldDecl::anchor() {} 5487 5488 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 5489 SourceLocation L, DeclarationName N, 5490 QualType T, 5491 MutableArrayRef<NamedDecl *> CH) 5492 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 5493 ChainingSize(CH.size()) { 5494 // In C++, indirect field declarations conflict with tag declarations in the 5495 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 5496 if (C.getLangOpts().CPlusPlus) 5497 IdentifierNamespace |= IDNS_Tag; 5498 } 5499 5500 IndirectFieldDecl * 5501 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 5502 const IdentifierInfo *Id, QualType T, 5503 llvm::MutableArrayRef<NamedDecl *> CH) { 5504 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 5505 } 5506 5507 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 5508 GlobalDeclID ID) { 5509 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), 5510 DeclarationName(), QualType(), {}); 5511 } 5512 5513 SourceRange EnumConstantDecl::getSourceRange() const { 5514 SourceLocation End = getLocation(); 5515 if (Init) 5516 End = Init->getEndLoc(); 5517 return SourceRange(getLocation(), End); 5518 } 5519 5520 void TypeDecl::anchor() {} 5521 5522 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 5523 SourceLocation StartLoc, SourceLocation IdLoc, 5524 const IdentifierInfo *Id, 5525 TypeSourceInfo *TInfo) { 5526 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5527 } 5528 5529 void TypedefNameDecl::anchor() {} 5530 5531 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 5532 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 5533 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 5534 auto *ThisTypedef = this; 5535 if (AnyRedecl && OwningTypedef) { 5536 OwningTypedef = OwningTypedef->getCanonicalDecl(); 5537 ThisTypedef = ThisTypedef->getCanonicalDecl(); 5538 } 5539 if (OwningTypedef == ThisTypedef) 5540 return TT->getDecl(); 5541 } 5542 5543 return nullptr; 5544 } 5545 5546 bool TypedefNameDecl::isTransparentTagSlow() const { 5547 auto determineIsTransparent = [&]() { 5548 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 5549 if (auto *TD = TT->getDecl()) { 5550 if (TD->getName() != getName()) 5551 return false; 5552 SourceLocation TTLoc = getLocation(); 5553 SourceLocation TDLoc = TD->getLocation(); 5554 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 5555 return false; 5556 SourceManager &SM = getASTContext().getSourceManager(); 5557 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 5558 } 5559 } 5560 return false; 5561 }; 5562 5563 bool isTransparent = determineIsTransparent(); 5564 MaybeModedTInfo.setInt((isTransparent << 1) | 1); 5565 return isTransparent; 5566 } 5567 5568 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5569 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 5570 nullptr, nullptr); 5571 } 5572 5573 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 5574 SourceLocation StartLoc, 5575 SourceLocation IdLoc, 5576 const IdentifierInfo *Id, 5577 TypeSourceInfo *TInfo) { 5578 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5579 } 5580 5581 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, 5582 GlobalDeclID ID) { 5583 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 5584 SourceLocation(), nullptr, nullptr); 5585 } 5586 5587 SourceRange TypedefDecl::getSourceRange() const { 5588 SourceLocation RangeEnd = getLocation(); 5589 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 5590 if (typeIsPostfix(TInfo->getType())) 5591 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5592 } 5593 return SourceRange(getBeginLoc(), RangeEnd); 5594 } 5595 5596 SourceRange TypeAliasDecl::getSourceRange() const { 5597 SourceLocation RangeEnd = getBeginLoc(); 5598 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 5599 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5600 return SourceRange(getBeginLoc(), RangeEnd); 5601 } 5602 5603 void FileScopeAsmDecl::anchor() {} 5604 5605 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 5606 StringLiteral *Str, 5607 SourceLocation AsmLoc, 5608 SourceLocation RParenLoc) { 5609 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 5610 } 5611 5612 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 5613 GlobalDeclID ID) { 5614 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 5615 SourceLocation()); 5616 } 5617 5618 void TopLevelStmtDecl::anchor() {} 5619 5620 TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) { 5621 assert(C.getLangOpts().IncrementalExtensions && 5622 "Must be used only in incremental mode"); 5623 5624 SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation(); 5625 DeclContext *DC = C.getTranslationUnitDecl(); 5626 5627 return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement); 5628 } 5629 5630 TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C, 5631 GlobalDeclID ID) { 5632 return new (C, ID) 5633 TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr); 5634 } 5635 5636 SourceRange TopLevelStmtDecl::getSourceRange() const { 5637 return SourceRange(getLocation(), Statement->getEndLoc()); 5638 } 5639 5640 void TopLevelStmtDecl::setStmt(Stmt *S) { 5641 assert(S); 5642 Statement = S; 5643 setLocation(Statement->getBeginLoc()); 5644 } 5645 5646 void EmptyDecl::anchor() {} 5647 5648 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5649 return new (C, DC) EmptyDecl(DC, L); 5650 } 5651 5652 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5653 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 5654 } 5655 5656 HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer, 5657 SourceLocation KwLoc, IdentifierInfo *ID, 5658 SourceLocation IDLoc, SourceLocation LBrace) 5659 : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)), 5660 DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc), 5661 IsCBuffer(CBuffer) {} 5662 5663 HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C, 5664 DeclContext *LexicalParent, bool CBuffer, 5665 SourceLocation KwLoc, IdentifierInfo *ID, 5666 SourceLocation IDLoc, 5667 SourceLocation LBrace) { 5668 // For hlsl like this 5669 // cbuffer A { 5670 // cbuffer B { 5671 // } 5672 // } 5673 // compiler should treat it as 5674 // cbuffer A { 5675 // } 5676 // cbuffer B { 5677 // } 5678 // FIXME: support nested buffers if required for back-compat. 5679 DeclContext *DC = LexicalParent; 5680 HLSLBufferDecl *Result = 5681 new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace); 5682 return Result; 5683 } 5684 5685 HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C, 5686 GlobalDeclID ID) { 5687 return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr, 5688 SourceLocation(), SourceLocation()); 5689 } 5690 5691 //===----------------------------------------------------------------------===// 5692 // ImportDecl Implementation 5693 //===----------------------------------------------------------------------===// 5694 5695 /// Retrieve the number of module identifiers needed to name the given 5696 /// module. 5697 static unsigned getNumModuleIdentifiers(Module *Mod) { 5698 unsigned Result = 1; 5699 while (Mod->Parent) { 5700 Mod = Mod->Parent; 5701 ++Result; 5702 } 5703 return Result; 5704 } 5705 5706 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5707 Module *Imported, 5708 ArrayRef<SourceLocation> IdentifierLocs) 5709 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5710 NextLocalImportAndComplete(nullptr, true) { 5711 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 5712 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5713 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 5714 StoredLocs); 5715 } 5716 5717 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5718 Module *Imported, SourceLocation EndLoc) 5719 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5720 NextLocalImportAndComplete(nullptr, false) { 5721 *getTrailingObjects<SourceLocation>() = EndLoc; 5722 } 5723 5724 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 5725 SourceLocation StartLoc, Module *Imported, 5726 ArrayRef<SourceLocation> IdentifierLocs) { 5727 return new (C, DC, 5728 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 5729 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 5730 } 5731 5732 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 5733 SourceLocation StartLoc, 5734 Module *Imported, 5735 SourceLocation EndLoc) { 5736 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 5737 ImportDecl(DC, StartLoc, Imported, EndLoc); 5738 Import->setImplicit(); 5739 return Import; 5740 } 5741 5742 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID, 5743 unsigned NumLocations) { 5744 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 5745 ImportDecl(EmptyShell()); 5746 } 5747 5748 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 5749 if (!isImportComplete()) 5750 return {}; 5751 5752 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5753 return llvm::ArrayRef(StoredLocs, 5754 getNumModuleIdentifiers(getImportedModule())); 5755 } 5756 5757 SourceRange ImportDecl::getSourceRange() const { 5758 if (!isImportComplete()) 5759 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 5760 5761 return SourceRange(getLocation(), getIdentifierLocs().back()); 5762 } 5763 5764 //===----------------------------------------------------------------------===// 5765 // ExportDecl Implementation 5766 //===----------------------------------------------------------------------===// 5767 5768 void ExportDecl::anchor() {} 5769 5770 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 5771 SourceLocation ExportLoc) { 5772 return new (C, DC) ExportDecl(DC, ExportLoc); 5773 } 5774 5775 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) { 5776 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 5777 } 5778 5779 bool clang::IsArmStreamingFunction(const FunctionDecl *FD, 5780 bool IncludeLocallyStreaming) { 5781 if (IncludeLocallyStreaming) 5782 if (FD->hasAttr<ArmLocallyStreamingAttr>()) 5783 return true; 5784 5785 if (const Type *Ty = FD->getType().getTypePtrOrNull()) 5786 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) 5787 if (FPT->getAArch64SMEAttributes() & 5788 FunctionType::SME_PStateSMEnabledMask) 5789 return true; 5790 5791 return false; 5792 } 5793