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