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