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