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