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