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