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