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