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 named contexts. 1501 while (Ctx) { 1502 if (isa<NamedDecl>(Ctx)) 1503 Contexts.push_back(Ctx); 1504 Ctx = Ctx->getParent(); 1505 } 1506 1507 for (const DeclContext *DC : llvm::reverse(Contexts)) { 1508 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1509 OS << Spec->getName(); 1510 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1511 printTemplateArgumentList(OS, TemplateArgs.asArray(), P); 1512 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 1513 if (P.SuppressUnwrittenScope && 1514 (ND->isAnonymousNamespace() || ND->isInline())) 1515 continue; 1516 if (ND->isAnonymousNamespace()) { 1517 OS << (P.MSVCFormatting ? "`anonymous namespace\'" 1518 : "(anonymous namespace)"); 1519 } 1520 else 1521 OS << *ND; 1522 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { 1523 if (!RD->getIdentifier()) 1524 OS << "(anonymous " << RD->getKindName() << ')'; 1525 else 1526 OS << *RD; 1527 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1528 const FunctionProtoType *FT = nullptr; 1529 if (FD->hasWrittenPrototype()) 1530 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1531 1532 OS << *FD << '('; 1533 if (FT) { 1534 unsigned NumParams = FD->getNumParams(); 1535 for (unsigned i = 0; i < NumParams; ++i) { 1536 if (i) 1537 OS << ", "; 1538 OS << FD->getParamDecl(i)->getType().stream(P); 1539 } 1540 1541 if (FT->isVariadic()) { 1542 if (NumParams > 0) 1543 OS << ", "; 1544 OS << "..."; 1545 } 1546 } 1547 OS << ')'; 1548 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) { 1549 // C++ [dcl.enum]p10: Each enum-name and each unscoped 1550 // enumerator is declared in the scope that immediately contains 1551 // the enum-specifier. Each scoped enumerator is declared in the 1552 // scope of the enumeration. 1553 // For the case of unscoped enumerator, do not include in the qualified 1554 // name any information about its enum enclosing scope, as its visibility 1555 // is global. 1556 if (ED->isScoped()) 1557 OS << *ED; 1558 else 1559 continue; 1560 } else { 1561 OS << *cast<NamedDecl>(DC); 1562 } 1563 OS << "::"; 1564 } 1565 1566 if (getDeclName() || isa<DecompositionDecl>(this)) 1567 OS << *this; 1568 else 1569 OS << "(anonymous)"; 1570 } 1571 1572 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1573 const PrintingPolicy &Policy, 1574 bool Qualified) const { 1575 if (Qualified) 1576 printQualifiedName(OS, Policy); 1577 else 1578 printName(OS); 1579 } 1580 1581 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1582 return true; 1583 } 1584 static bool isRedeclarableImpl(...) { return false; } 1585 static bool isRedeclarable(Decl::Kind K) { 1586 switch (K) { 1587 #define DECL(Type, Base) \ 1588 case Decl::Type: \ 1589 return isRedeclarableImpl((Type##Decl *)nullptr); 1590 #define ABSTRACT_DECL(DECL) 1591 #include "clang/AST/DeclNodes.inc" 1592 } 1593 llvm_unreachable("unknown decl kind"); 1594 } 1595 1596 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const { 1597 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1598 1599 // Never replace one imported declaration with another; we need both results 1600 // when re-exporting. 1601 if (OldD->isFromASTFile() && isFromASTFile()) 1602 return false; 1603 1604 // A kind mismatch implies that the declaration is not replaced. 1605 if (OldD->getKind() != getKind()) 1606 return false; 1607 1608 // For method declarations, we never replace. (Why?) 1609 if (isa<ObjCMethodDecl>(this)) 1610 return false; 1611 1612 // For parameters, pick the newer one. This is either an error or (in 1613 // Objective-C) permitted as an extension. 1614 if (isa<ParmVarDecl>(this)) 1615 return true; 1616 1617 // Inline namespaces can give us two declarations with the same 1618 // name and kind in the same scope but different contexts; we should 1619 // keep both declarations in this case. 1620 if (!this->getDeclContext()->getRedeclContext()->Equals( 1621 OldD->getDeclContext()->getRedeclContext())) 1622 return false; 1623 1624 // Using declarations can be replaced if they import the same name from the 1625 // same context. 1626 if (auto *UD = dyn_cast<UsingDecl>(this)) { 1627 ASTContext &Context = getASTContext(); 1628 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1629 Context.getCanonicalNestedNameSpecifier( 1630 cast<UsingDecl>(OldD)->getQualifier()); 1631 } 1632 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1633 ASTContext &Context = getASTContext(); 1634 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1635 Context.getCanonicalNestedNameSpecifier( 1636 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1637 } 1638 1639 if (isRedeclarable(getKind())) { 1640 if (getCanonicalDecl() != OldD->getCanonicalDecl()) 1641 return false; 1642 1643 if (IsKnownNewer) 1644 return true; 1645 1646 // Check whether this is actually newer than OldD. We want to keep the 1647 // newer declaration. This loop will usually only iterate once, because 1648 // OldD is usually the previous declaration. 1649 for (auto D : redecls()) { 1650 if (D == OldD) 1651 break; 1652 1653 // If we reach the canonical declaration, then OldD is not actually older 1654 // than this one. 1655 // 1656 // FIXME: In this case, we should not add this decl to the lookup table. 1657 if (D->isCanonicalDecl()) 1658 return false; 1659 } 1660 1661 // It's a newer declaration of the same kind of declaration in the same 1662 // scope: we want this decl instead of the existing one. 1663 return true; 1664 } 1665 1666 // In all other cases, we need to keep both declarations in case they have 1667 // different visibility. Any attempt to use the name will result in an 1668 // ambiguity if more than one is visible. 1669 return false; 1670 } 1671 1672 bool NamedDecl::hasLinkage() const { 1673 return getFormalLinkage() != NoLinkage; 1674 } 1675 1676 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1677 NamedDecl *ND = this; 1678 while (auto *UD = dyn_cast<UsingShadowDecl>(ND)) 1679 ND = UD->getTargetDecl(); 1680 1681 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1682 return AD->getClassInterface(); 1683 1684 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND)) 1685 return AD->getNamespace(); 1686 1687 return ND; 1688 } 1689 1690 bool NamedDecl::isCXXInstanceMember() const { 1691 if (!isCXXClassMember()) 1692 return false; 1693 1694 const NamedDecl *D = this; 1695 if (isa<UsingShadowDecl>(D)) 1696 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1697 1698 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1699 return true; 1700 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction())) 1701 return MD->isInstance(); 1702 return false; 1703 } 1704 1705 //===----------------------------------------------------------------------===// 1706 // DeclaratorDecl Implementation 1707 //===----------------------------------------------------------------------===// 1708 1709 template <typename DeclT> 1710 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1711 if (decl->getNumTemplateParameterLists() > 0) 1712 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1713 else 1714 return decl->getInnerLocStart(); 1715 } 1716 1717 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1718 TypeSourceInfo *TSI = getTypeSourceInfo(); 1719 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1720 return SourceLocation(); 1721 } 1722 1723 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1724 if (QualifierLoc) { 1725 // Make sure the extended decl info is allocated. 1726 if (!hasExtInfo()) { 1727 // Save (non-extended) type source info pointer. 1728 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1729 // Allocate external info struct. 1730 DeclInfo = new (getASTContext()) ExtInfo; 1731 // Restore savedTInfo into (extended) decl info. 1732 getExtInfo()->TInfo = savedTInfo; 1733 } 1734 // Set qualifier info. 1735 getExtInfo()->QualifierLoc = QualifierLoc; 1736 } else { 1737 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1738 if (hasExtInfo()) { 1739 if (getExtInfo()->NumTemplParamLists == 0) { 1740 // Save type source info pointer. 1741 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 1742 // Deallocate the extended decl info. 1743 getASTContext().Deallocate(getExtInfo()); 1744 // Restore savedTInfo into (non-extended) decl info. 1745 DeclInfo = savedTInfo; 1746 } 1747 else 1748 getExtInfo()->QualifierLoc = QualifierLoc; 1749 } 1750 } 1751 } 1752 1753 void DeclaratorDecl::setTemplateParameterListsInfo( 1754 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1755 assert(!TPLists.empty()); 1756 // Make sure the extended decl info is allocated. 1757 if (!hasExtInfo()) { 1758 // Save (non-extended) type source info pointer. 1759 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1760 // Allocate external info struct. 1761 DeclInfo = new (getASTContext()) ExtInfo; 1762 // Restore savedTInfo into (extended) decl info. 1763 getExtInfo()->TInfo = savedTInfo; 1764 } 1765 // Set the template parameter lists info. 1766 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 1767 } 1768 1769 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1770 return getTemplateOrInnerLocStart(this); 1771 } 1772 1773 // Helper function: returns true if QT is or contains a type 1774 // having a postfix component. 1775 static bool typeIsPostfix(QualType QT) { 1776 while (true) { 1777 const Type* T = QT.getTypePtr(); 1778 switch (T->getTypeClass()) { 1779 default: 1780 return false; 1781 case Type::Pointer: 1782 QT = cast<PointerType>(T)->getPointeeType(); 1783 break; 1784 case Type::BlockPointer: 1785 QT = cast<BlockPointerType>(T)->getPointeeType(); 1786 break; 1787 case Type::MemberPointer: 1788 QT = cast<MemberPointerType>(T)->getPointeeType(); 1789 break; 1790 case Type::LValueReference: 1791 case Type::RValueReference: 1792 QT = cast<ReferenceType>(T)->getPointeeType(); 1793 break; 1794 case Type::PackExpansion: 1795 QT = cast<PackExpansionType>(T)->getPattern(); 1796 break; 1797 case Type::Paren: 1798 case Type::ConstantArray: 1799 case Type::DependentSizedArray: 1800 case Type::IncompleteArray: 1801 case Type::VariableArray: 1802 case Type::FunctionProto: 1803 case Type::FunctionNoProto: 1804 return true; 1805 } 1806 } 1807 } 1808 1809 SourceRange DeclaratorDecl::getSourceRange() const { 1810 SourceLocation RangeEnd = getLocation(); 1811 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1812 // If the declaration has no name or the type extends past the name take the 1813 // end location of the type. 1814 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 1815 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1816 } 1817 return SourceRange(getOuterLocStart(), RangeEnd); 1818 } 1819 1820 void QualifierInfo::setTemplateParameterListsInfo( 1821 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1822 // Free previous template parameters (if any). 1823 if (NumTemplParamLists > 0) { 1824 Context.Deallocate(TemplParamLists); 1825 TemplParamLists = nullptr; 1826 NumTemplParamLists = 0; 1827 } 1828 // Set info on matched template parameter lists (if any). 1829 if (!TPLists.empty()) { 1830 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 1831 NumTemplParamLists = TPLists.size(); 1832 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 1833 } 1834 } 1835 1836 //===----------------------------------------------------------------------===// 1837 // VarDecl Implementation 1838 //===----------------------------------------------------------------------===// 1839 1840 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1841 switch (SC) { 1842 case SC_None: break; 1843 case SC_Auto: return "auto"; 1844 case SC_Extern: return "extern"; 1845 case SC_PrivateExtern: return "__private_extern__"; 1846 case SC_Register: return "register"; 1847 case SC_Static: return "static"; 1848 } 1849 1850 llvm_unreachable("Invalid storage class"); 1851 } 1852 1853 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 1854 SourceLocation StartLoc, SourceLocation IdLoc, 1855 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1856 StorageClass SC) 1857 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 1858 redeclarable_base(C) { 1859 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 1860 "VarDeclBitfields too large!"); 1861 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 1862 "ParmVarDeclBitfields too large!"); 1863 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 1864 "NonParmVarDeclBitfields too large!"); 1865 AllBits = 0; 1866 VarDeclBits.SClass = SC; 1867 // Everything else is implicitly initialized to false. 1868 } 1869 1870 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1871 SourceLocation StartL, SourceLocation IdL, 1872 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1873 StorageClass S) { 1874 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 1875 } 1876 1877 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1878 return new (C, ID) 1879 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 1880 QualType(), nullptr, SC_None); 1881 } 1882 1883 void VarDecl::setStorageClass(StorageClass SC) { 1884 assert(isLegalForVariable(SC)); 1885 VarDeclBits.SClass = SC; 1886 } 1887 1888 VarDecl::TLSKind VarDecl::getTLSKind() const { 1889 switch (VarDeclBits.TSCSpec) { 1890 case TSCS_unspecified: 1891 if (!hasAttr<ThreadAttr>() && 1892 !(getASTContext().getLangOpts().OpenMPUseTLS && 1893 getASTContext().getTargetInfo().isTLSSupported() && 1894 hasAttr<OMPThreadPrivateDeclAttr>())) 1895 return TLS_None; 1896 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 1897 LangOptions::MSVC2015)) || 1898 hasAttr<OMPThreadPrivateDeclAttr>()) 1899 ? TLS_Dynamic 1900 : TLS_Static; 1901 case TSCS___thread: // Fall through. 1902 case TSCS__Thread_local: 1903 return TLS_Static; 1904 case TSCS_thread_local: 1905 return TLS_Dynamic; 1906 } 1907 llvm_unreachable("Unknown thread storage class specifier!"); 1908 } 1909 1910 SourceRange VarDecl::getSourceRange() const { 1911 if (const Expr *Init = getInit()) { 1912 SourceLocation InitEnd = Init->getLocEnd(); 1913 // If Init is implicit, ignore its source range and fallback on 1914 // DeclaratorDecl::getSourceRange() to handle postfix elements. 1915 if (InitEnd.isValid() && InitEnd != getLocation()) 1916 return SourceRange(getOuterLocStart(), InitEnd); 1917 } 1918 return DeclaratorDecl::getSourceRange(); 1919 } 1920 1921 template<typename T> 1922 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 1923 // C++ [dcl.link]p1: All function types, function names with external linkage, 1924 // and variable names with external linkage have a language linkage. 1925 if (!D.hasExternalFormalLinkage()) 1926 return NoLanguageLinkage; 1927 1928 // Language linkage is a C++ concept, but saying that everything else in C has 1929 // C language linkage fits the implementation nicely. 1930 ASTContext &Context = D.getASTContext(); 1931 if (!Context.getLangOpts().CPlusPlus) 1932 return CLanguageLinkage; 1933 1934 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 1935 // language linkage of the names of class members and the function type of 1936 // class member functions. 1937 const DeclContext *DC = D.getDeclContext(); 1938 if (DC->isRecord()) 1939 return CXXLanguageLinkage; 1940 1941 // If the first decl is in an extern "C" context, any other redeclaration 1942 // will have C language linkage. If the first one is not in an extern "C" 1943 // context, we would have reported an error for any other decl being in one. 1944 if (isFirstInExternCContext(&D)) 1945 return CLanguageLinkage; 1946 return CXXLanguageLinkage; 1947 } 1948 1949 template<typename T> 1950 static bool isDeclExternC(const T &D) { 1951 // Since the context is ignored for class members, they can only have C++ 1952 // language linkage or no language linkage. 1953 const DeclContext *DC = D.getDeclContext(); 1954 if (DC->isRecord()) { 1955 assert(D.getASTContext().getLangOpts().CPlusPlus); 1956 return false; 1957 } 1958 1959 return D.getLanguageLinkage() == CLanguageLinkage; 1960 } 1961 1962 LanguageLinkage VarDecl::getLanguageLinkage() const { 1963 return getDeclLanguageLinkage(*this); 1964 } 1965 1966 bool VarDecl::isExternC() const { 1967 return isDeclExternC(*this); 1968 } 1969 1970 bool VarDecl::isInExternCContext() const { 1971 return getLexicalDeclContext()->isExternCContext(); 1972 } 1973 1974 bool VarDecl::isInExternCXXContext() const { 1975 return getLexicalDeclContext()->isExternCXXContext(); 1976 } 1977 1978 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 1979 1980 VarDecl::DefinitionKind 1981 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 1982 if (isThisDeclarationADemotedDefinition()) 1983 return DeclarationOnly; 1984 1985 // C++ [basic.def]p2: 1986 // A declaration is a definition unless [...] it contains the 'extern' 1987 // specifier or a linkage-specification and neither an initializer [...], 1988 // it declares a non-inline static data member in a class declaration [...], 1989 // it declares a static data member outside a class definition and the variable 1990 // was defined within the class with the constexpr specifier [...], 1991 // C++1y [temp.expl.spec]p15: 1992 // An explicit specialization of a static data member or an explicit 1993 // specialization of a static data member template is a definition if the 1994 // declaration includes an initializer; otherwise, it is a declaration. 1995 // 1996 // FIXME: How do you declare (but not define) a partial specialization of 1997 // a static data member template outside the containing class? 1998 if (isStaticDataMember()) { 1999 if (isOutOfLine() && 2000 !(getCanonicalDecl()->isInline() && 2001 getCanonicalDecl()->isConstexpr()) && 2002 (hasInit() || 2003 // If the first declaration is out-of-line, this may be an 2004 // instantiation of an out-of-line partial specialization of a variable 2005 // template for which we have not yet instantiated the initializer. 2006 (getFirstDecl()->isOutOfLine() 2007 ? getTemplateSpecializationKind() == TSK_Undeclared 2008 : getTemplateSpecializationKind() != 2009 TSK_ExplicitSpecialization) || 2010 isa<VarTemplatePartialSpecializationDecl>(this))) 2011 return Definition; 2012 else if (!isOutOfLine() && isInline()) 2013 return Definition; 2014 else 2015 return DeclarationOnly; 2016 } 2017 // C99 6.7p5: 2018 // A definition of an identifier is a declaration for that identifier that 2019 // [...] causes storage to be reserved for that object. 2020 // Note: that applies for all non-file-scope objects. 2021 // C99 6.9.2p1: 2022 // If the declaration of an identifier for an object has file scope and an 2023 // initializer, the declaration is an external definition for the identifier 2024 if (hasInit()) 2025 return Definition; 2026 2027 if (hasDefiningAttr()) 2028 return Definition; 2029 2030 if (const auto *SAA = getAttr<SelectAnyAttr>()) 2031 if (!SAA->isInherited()) 2032 return Definition; 2033 2034 // A variable template specialization (other than a static data member 2035 // template or an explicit specialization) is a declaration until we 2036 // instantiate its initializer. 2037 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2038 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2039 !isa<VarTemplatePartialSpecializationDecl>(VTSD) && 2040 !VTSD->IsCompleteDefinition) 2041 return DeclarationOnly; 2042 } 2043 2044 if (hasExternalStorage()) 2045 return DeclarationOnly; 2046 2047 // [dcl.link] p7: 2048 // A declaration directly contained in a linkage-specification is treated 2049 // as if it contains the extern specifier for the purpose of determining 2050 // the linkage of the declared name and whether it is a definition. 2051 if (isSingleLineLanguageLinkage(*this)) 2052 return DeclarationOnly; 2053 2054 // C99 6.9.2p2: 2055 // A declaration of an object that has file scope without an initializer, 2056 // and without a storage class specifier or the scs 'static', constitutes 2057 // a tentative definition. 2058 // No such thing in C++. 2059 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 2060 return TentativeDefinition; 2061 2062 // What's left is (in C, block-scope) declarations without initializers or 2063 // external storage. These are definitions. 2064 return Definition; 2065 } 2066 2067 VarDecl *VarDecl::getActingDefinition() { 2068 DefinitionKind Kind = isThisDeclarationADefinition(); 2069 if (Kind != TentativeDefinition) 2070 return nullptr; 2071 2072 VarDecl *LastTentative = nullptr; 2073 VarDecl *First = getFirstDecl(); 2074 for (auto I : First->redecls()) { 2075 Kind = I->isThisDeclarationADefinition(); 2076 if (Kind == Definition) 2077 return nullptr; 2078 else if (Kind == TentativeDefinition) 2079 LastTentative = I; 2080 } 2081 return LastTentative; 2082 } 2083 2084 VarDecl *VarDecl::getDefinition(ASTContext &C) { 2085 VarDecl *First = getFirstDecl(); 2086 for (auto I : First->redecls()) { 2087 if (I->isThisDeclarationADefinition(C) == Definition) 2088 return I; 2089 } 2090 return nullptr; 2091 } 2092 2093 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 2094 DefinitionKind Kind = DeclarationOnly; 2095 2096 const VarDecl *First = getFirstDecl(); 2097 for (auto I : First->redecls()) { 2098 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 2099 if (Kind == Definition) 2100 break; 2101 } 2102 2103 return Kind; 2104 } 2105 2106 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2107 for (auto I : redecls()) { 2108 if (auto Expr = I->getInit()) { 2109 D = I; 2110 return Expr; 2111 } 2112 } 2113 return nullptr; 2114 } 2115 2116 bool VarDecl::hasInit() const { 2117 if (auto *P = dyn_cast<ParmVarDecl>(this)) 2118 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) 2119 return false; 2120 2121 return !Init.isNull(); 2122 } 2123 2124 Expr *VarDecl::getInit() { 2125 if (!hasInit()) 2126 return nullptr; 2127 2128 if (auto *S = Init.dyn_cast<Stmt *>()) 2129 return cast<Expr>(S); 2130 2131 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value); 2132 } 2133 2134 Stmt **VarDecl::getInitAddress() { 2135 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) 2136 return &ES->Value; 2137 2138 return Init.getAddrOfPtr1(); 2139 } 2140 2141 bool VarDecl::isOutOfLine() const { 2142 if (Decl::isOutOfLine()) 2143 return true; 2144 2145 if (!isStaticDataMember()) 2146 return false; 2147 2148 // If this static data member was instantiated from a static data member of 2149 // a class template, check whether that static data member was defined 2150 // out-of-line. 2151 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2152 return VD->isOutOfLine(); 2153 2154 return false; 2155 } 2156 2157 void VarDecl::setInit(Expr *I) { 2158 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2159 Eval->~EvaluatedStmt(); 2160 getASTContext().Deallocate(Eval); 2161 } 2162 2163 Init = I; 2164 } 2165 2166 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const { 2167 const LangOptions &Lang = C.getLangOpts(); 2168 2169 if (!Lang.CPlusPlus) 2170 return false; 2171 2172 // In C++11, any variable of reference type can be used in a constant 2173 // expression if it is initialized by a constant expression. 2174 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2175 return true; 2176 2177 // Only const objects can be used in constant expressions in C++. C++98 does 2178 // not require the variable to be non-volatile, but we consider this to be a 2179 // defect. 2180 if (!getType().isConstQualified() || getType().isVolatileQualified()) 2181 return false; 2182 2183 // In C++, const, non-volatile variables of integral or enumeration types 2184 // can be used in constant expressions. 2185 if (getType()->isIntegralOrEnumerationType()) 2186 return true; 2187 2188 // Additionally, in C++11, non-volatile constexpr variables can be used in 2189 // constant expressions. 2190 return Lang.CPlusPlus11 && isConstexpr(); 2191 } 2192 2193 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2194 /// form, which contains extra information on the evaluated value of the 2195 /// initializer. 2196 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2197 auto *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2198 if (!Eval) { 2199 // Note: EvaluatedStmt contains an APValue, which usually holds 2200 // resources not allocated from the ASTContext. We need to do some 2201 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2202 // where we can detect whether there's anything to clean up or not. 2203 Eval = new (getASTContext()) EvaluatedStmt; 2204 Eval->Value = Init.get<Stmt *>(); 2205 Init = Eval; 2206 } 2207 return Eval; 2208 } 2209 2210 APValue *VarDecl::evaluateValue() const { 2211 SmallVector<PartialDiagnosticAt, 8> Notes; 2212 return evaluateValue(Notes); 2213 } 2214 2215 APValue *VarDecl::evaluateValue( 2216 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2217 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2218 2219 // We only produce notes indicating why an initializer is non-constant the 2220 // first time it is evaluated. FIXME: The notes won't always be emitted the 2221 // first time we try evaluation, so might not be produced at all. 2222 if (Eval->WasEvaluated) 2223 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated; 2224 2225 const auto *Init = cast<Expr>(Eval->Value); 2226 assert(!Init->isValueDependent()); 2227 2228 if (Eval->IsEvaluating) { 2229 // FIXME: Produce a diagnostic for self-initialization. 2230 Eval->CheckedICE = true; 2231 Eval->IsICE = false; 2232 return nullptr; 2233 } 2234 2235 Eval->IsEvaluating = true; 2236 2237 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 2238 this, Notes); 2239 2240 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2241 // or that it's empty (so that there's nothing to clean up) if evaluation 2242 // failed. 2243 if (!Result) 2244 Eval->Evaluated = APValue(); 2245 else if (Eval->Evaluated.needsCleanup()) 2246 getASTContext().addDestruction(&Eval->Evaluated); 2247 2248 Eval->IsEvaluating = false; 2249 Eval->WasEvaluated = true; 2250 2251 // In C++11, we have determined whether the initializer was a constant 2252 // expression as a side-effect. 2253 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) { 2254 Eval->CheckedICE = true; 2255 Eval->IsICE = Result && Notes.empty(); 2256 } 2257 2258 return Result ? &Eval->Evaluated : nullptr; 2259 } 2260 2261 APValue *VarDecl::getEvaluatedValue() const { 2262 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 2263 if (Eval->WasEvaluated) 2264 return &Eval->Evaluated; 2265 2266 return nullptr; 2267 } 2268 2269 bool VarDecl::isInitKnownICE() const { 2270 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 2271 return Eval->CheckedICE; 2272 2273 return false; 2274 } 2275 2276 bool VarDecl::isInitICE() const { 2277 assert(isInitKnownICE() && 2278 "Check whether we already know that the initializer is an ICE"); 2279 return Init.get<EvaluatedStmt *>()->IsICE; 2280 } 2281 2282 bool VarDecl::checkInitIsICE() const { 2283 // Initializers of weak variables are never ICEs. 2284 if (isWeak()) 2285 return false; 2286 2287 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2288 if (Eval->CheckedICE) 2289 // We have already checked whether this subexpression is an 2290 // integral constant expression. 2291 return Eval->IsICE; 2292 2293 const auto *Init = cast<Expr>(Eval->Value); 2294 assert(!Init->isValueDependent()); 2295 2296 // In C++11, evaluate the initializer to check whether it's a constant 2297 // expression. 2298 if (getASTContext().getLangOpts().CPlusPlus11) { 2299 SmallVector<PartialDiagnosticAt, 8> Notes; 2300 evaluateValue(Notes); 2301 return Eval->IsICE; 2302 } 2303 2304 // It's an ICE whether or not the definition we found is 2305 // out-of-line. See DR 721 and the discussion in Clang PR 2306 // 6206 for details. 2307 2308 if (Eval->CheckingICE) 2309 return false; 2310 Eval->CheckingICE = true; 2311 2312 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext()); 2313 Eval->CheckingICE = false; 2314 Eval->CheckedICE = true; 2315 return Eval->IsICE; 2316 } 2317 2318 template<typename DeclT> 2319 static DeclT *getDefinitionOrSelf(DeclT *D) { 2320 assert(D); 2321 if (auto *Def = D->getDefinition()) 2322 return Def; 2323 return D; 2324 } 2325 2326 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2327 // If it's a variable template specialization, find the template or partial 2328 // specialization from which it was instantiated. 2329 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2330 auto From = VDTemplSpec->getInstantiatedFrom(); 2331 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2332 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) { 2333 if (NewVTD->isMemberSpecialization()) 2334 break; 2335 VTD = NewVTD; 2336 } 2337 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2338 } 2339 if (auto *VTPSD = 2340 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2341 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) { 2342 if (NewVTPSD->isMemberSpecialization()) 2343 break; 2344 VTPSD = NewVTPSD; 2345 } 2346 return getDefinitionOrSelf<VarDecl>(VTPSD); 2347 } 2348 } 2349 2350 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 2351 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2352 VarDecl *VD = getInstantiatedFromStaticDataMember(); 2353 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2354 VD = NewVD; 2355 return getDefinitionOrSelf(VD); 2356 } 2357 } 2358 2359 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) { 2360 while (VarTemplate->getInstantiatedFromMemberTemplate()) { 2361 if (VarTemplate->isMemberSpecialization()) 2362 break; 2363 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate(); 2364 } 2365 2366 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl()); 2367 } 2368 return nullptr; 2369 } 2370 2371 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2372 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2373 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2374 2375 return nullptr; 2376 } 2377 2378 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2379 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2380 return Spec->getSpecializationKind(); 2381 2382 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2383 return MSI->getTemplateSpecializationKind(); 2384 2385 return TSK_Undeclared; 2386 } 2387 2388 SourceLocation VarDecl::getPointOfInstantiation() const { 2389 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2390 return Spec->getPointOfInstantiation(); 2391 2392 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2393 return MSI->getPointOfInstantiation(); 2394 2395 return SourceLocation(); 2396 } 2397 2398 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2399 return getASTContext().getTemplateOrSpecializationInfo(this) 2400 .dyn_cast<VarTemplateDecl *>(); 2401 } 2402 2403 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2404 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2405 } 2406 2407 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2408 if (isStaticDataMember()) 2409 // FIXME: Remove ? 2410 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2411 return getASTContext().getTemplateOrSpecializationInfo(this) 2412 .dyn_cast<MemberSpecializationInfo *>(); 2413 return nullptr; 2414 } 2415 2416 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2417 SourceLocation PointOfInstantiation) { 2418 assert((isa<VarTemplateSpecializationDecl>(this) || 2419 getMemberSpecializationInfo()) && 2420 "not a variable or static data member template specialization"); 2421 2422 if (VarTemplateSpecializationDecl *Spec = 2423 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2424 Spec->setSpecializationKind(TSK); 2425 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2426 Spec->getPointOfInstantiation().isInvalid()) { 2427 Spec->setPointOfInstantiation(PointOfInstantiation); 2428 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2429 L->InstantiationRequested(this); 2430 } 2431 } 2432 2433 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2434 MSI->setTemplateSpecializationKind(TSK); 2435 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2436 MSI->getPointOfInstantiation().isInvalid()) { 2437 MSI->setPointOfInstantiation(PointOfInstantiation); 2438 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2439 L->InstantiationRequested(this); 2440 } 2441 } 2442 } 2443 2444 void 2445 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2446 TemplateSpecializationKind TSK) { 2447 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2448 "Previous template or instantiation?"); 2449 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2450 } 2451 2452 //===----------------------------------------------------------------------===// 2453 // ParmVarDecl Implementation 2454 //===----------------------------------------------------------------------===// 2455 2456 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2457 SourceLocation StartLoc, 2458 SourceLocation IdLoc, IdentifierInfo *Id, 2459 QualType T, TypeSourceInfo *TInfo, 2460 StorageClass S, Expr *DefArg) { 2461 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2462 S, DefArg); 2463 } 2464 2465 QualType ParmVarDecl::getOriginalType() const { 2466 TypeSourceInfo *TSI = getTypeSourceInfo(); 2467 QualType T = TSI ? TSI->getType() : getType(); 2468 if (const auto *DT = dyn_cast<DecayedType>(T)) 2469 return DT->getOriginalType(); 2470 return T; 2471 } 2472 2473 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2474 return new (C, ID) 2475 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2476 nullptr, QualType(), nullptr, SC_None, nullptr); 2477 } 2478 2479 SourceRange ParmVarDecl::getSourceRange() const { 2480 if (!hasInheritedDefaultArg()) { 2481 SourceRange ArgRange = getDefaultArgRange(); 2482 if (ArgRange.isValid()) 2483 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2484 } 2485 2486 // DeclaratorDecl considers the range of postfix types as overlapping with the 2487 // declaration name, but this is not the case with parameters in ObjC methods. 2488 if (isa<ObjCMethodDecl>(getDeclContext())) 2489 return SourceRange(DeclaratorDecl::getLocStart(), getLocation()); 2490 2491 return DeclaratorDecl::getSourceRange(); 2492 } 2493 2494 Expr *ParmVarDecl::getDefaultArg() { 2495 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2496 assert(!hasUninstantiatedDefaultArg() && 2497 "Default argument is not yet instantiated!"); 2498 2499 Expr *Arg = getInit(); 2500 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 2501 return E->getSubExpr(); 2502 2503 return Arg; 2504 } 2505 2506 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2507 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2508 Init = defarg; 2509 } 2510 2511 SourceRange ParmVarDecl::getDefaultArgRange() const { 2512 switch (ParmVarDeclBits.DefaultArgKind) { 2513 case DAK_None: 2514 case DAK_Unparsed: 2515 // Nothing we can do here. 2516 return SourceRange(); 2517 2518 case DAK_Uninstantiated: 2519 return getUninstantiatedDefaultArg()->getSourceRange(); 2520 2521 case DAK_Normal: 2522 if (const Expr *E = getInit()) 2523 return E->getSourceRange(); 2524 2525 // Missing an actual expression, may be invalid. 2526 return SourceRange(); 2527 } 2528 llvm_unreachable("Invalid default argument kind."); 2529 } 2530 2531 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 2532 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 2533 Init = arg; 2534 } 2535 2536 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 2537 assert(hasUninstantiatedDefaultArg() && 2538 "Wrong kind of initialization expression!"); 2539 return cast_or_null<Expr>(Init.get<Stmt *>()); 2540 } 2541 2542 bool ParmVarDecl::hasDefaultArg() const { 2543 // FIXME: We should just return false for DAK_None here once callers are 2544 // prepared for the case that we encountered an invalid default argument and 2545 // were unable to even build an invalid expression. 2546 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 2547 !Init.isNull(); 2548 } 2549 2550 bool ParmVarDecl::isParameterPack() const { 2551 return isa<PackExpansionType>(getType()); 2552 } 2553 2554 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 2555 getASTContext().setParameterIndex(this, parameterIndex); 2556 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 2557 } 2558 2559 unsigned ParmVarDecl::getParameterIndexLarge() const { 2560 return getASTContext().getParameterIndex(this); 2561 } 2562 2563 //===----------------------------------------------------------------------===// 2564 // FunctionDecl Implementation 2565 //===----------------------------------------------------------------------===// 2566 2567 void FunctionDecl::getNameForDiagnostic( 2568 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 2569 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 2570 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 2571 if (TemplateArgs) 2572 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 2573 } 2574 2575 bool FunctionDecl::isVariadic() const { 2576 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 2577 return FT->isVariadic(); 2578 return false; 2579 } 2580 2581 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 2582 for (auto I : redecls()) { 2583 if (I->doesThisDeclarationHaveABody()) { 2584 Definition = I; 2585 return true; 2586 } 2587 } 2588 2589 return false; 2590 } 2591 2592 bool FunctionDecl::hasTrivialBody() const 2593 { 2594 Stmt *S = getBody(); 2595 if (!S) { 2596 // Since we don't have a body for this function, we don't know if it's 2597 // trivial or not. 2598 return false; 2599 } 2600 2601 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 2602 return true; 2603 return false; 2604 } 2605 2606 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const { 2607 for (auto I : redecls()) { 2608 if (I->isThisDeclarationADefinition()) { 2609 Definition = I; 2610 return true; 2611 } 2612 } 2613 2614 return false; 2615 } 2616 2617 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 2618 if (!hasBody(Definition)) 2619 return nullptr; 2620 2621 if (Definition->Body) 2622 return Definition->Body.get(getASTContext().getExternalSource()); 2623 2624 return nullptr; 2625 } 2626 2627 void FunctionDecl::setBody(Stmt *B) { 2628 Body = B; 2629 if (B) 2630 EndRangeLoc = B->getLocEnd(); 2631 } 2632 2633 void FunctionDecl::setPure(bool P) { 2634 IsPure = P; 2635 if (P) 2636 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 2637 Parent->markedVirtualFunctionPure(); 2638 } 2639 2640 template<std::size_t Len> 2641 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 2642 IdentifierInfo *II = ND->getIdentifier(); 2643 return II && II->isStr(Str); 2644 } 2645 2646 bool FunctionDecl::isMain() const { 2647 const TranslationUnitDecl *tunit = 2648 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2649 return tunit && 2650 !tunit->getASTContext().getLangOpts().Freestanding && 2651 isNamed(this, "main"); 2652 } 2653 2654 bool FunctionDecl::isMSVCRTEntryPoint() const { 2655 const TranslationUnitDecl *TUnit = 2656 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2657 if (!TUnit) 2658 return false; 2659 2660 // Even though we aren't really targeting MSVCRT if we are freestanding, 2661 // semantic analysis for these functions remains the same. 2662 2663 // MSVCRT entry points only exist on MSVCRT targets. 2664 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 2665 return false; 2666 2667 // Nameless functions like constructors cannot be entry points. 2668 if (!getIdentifier()) 2669 return false; 2670 2671 return llvm::StringSwitch<bool>(getName()) 2672 .Cases("main", // an ANSI console app 2673 "wmain", // a Unicode console App 2674 "WinMain", // an ANSI GUI app 2675 "wWinMain", // a Unicode GUI app 2676 "DllMain", // a DLL 2677 true) 2678 .Default(false); 2679 } 2680 2681 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 2682 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 2683 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 2684 getDeclName().getCXXOverloadedOperator() == OO_Delete || 2685 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 2686 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 2687 2688 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2689 return false; 2690 2691 const auto *proto = getType()->castAs<FunctionProtoType>(); 2692 if (proto->getNumParams() != 2 || proto->isVariadic()) 2693 return false; 2694 2695 ASTContext &Context = 2696 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 2697 ->getASTContext(); 2698 2699 // The result type and first argument type are constant across all 2700 // these operators. The second argument must be exactly void*. 2701 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 2702 } 2703 2704 bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const { 2705 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 2706 return false; 2707 if (getDeclName().getCXXOverloadedOperator() != OO_New && 2708 getDeclName().getCXXOverloadedOperator() != OO_Delete && 2709 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 2710 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 2711 return false; 2712 2713 if (isa<CXXRecordDecl>(getDeclContext())) 2714 return false; 2715 2716 // This can only fail for an invalid 'operator new' declaration. 2717 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2718 return false; 2719 2720 const auto *FPT = getType()->castAs<FunctionProtoType>(); 2721 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic()) 2722 return false; 2723 2724 // If this is a single-parameter function, it must be a replaceable global 2725 // allocation or deallocation function. 2726 if (FPT->getNumParams() == 1) 2727 return true; 2728 2729 unsigned Params = 1; 2730 QualType Ty = FPT->getParamType(Params); 2731 ASTContext &Ctx = getASTContext(); 2732 2733 auto Consume = [&] { 2734 ++Params; 2735 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 2736 }; 2737 2738 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 2739 bool IsSizedDelete = false; 2740 if (Ctx.getLangOpts().SizedDeallocation && 2741 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 2742 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 2743 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 2744 IsSizedDelete = true; 2745 Consume(); 2746 } 2747 2748 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 2749 // new/delete. 2750 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 2751 if (IsAligned) 2752 *IsAligned = true; 2753 Consume(); 2754 } 2755 2756 // Finally, if this is not a sized delete, the final parameter can 2757 // be a 'const std::nothrow_t&'. 2758 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 2759 Ty = Ty->getPointeeType(); 2760 if (Ty.getCVRQualifiers() != Qualifiers::Const) 2761 return false; 2762 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 2763 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace()) 2764 Consume(); 2765 } 2766 2767 return Params == FPT->getNumParams(); 2768 } 2769 2770 bool FunctionDecl::isDestroyingOperatorDelete() const { 2771 // C++ P0722: 2772 // Within a class C, a single object deallocation function with signature 2773 // (T, std::destroying_delete_t, <more params>) 2774 // is a destroying operator delete. 2775 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 2776 getNumParams() < 2) 2777 return false; 2778 2779 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 2780 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 2781 RD->getIdentifier()->isStr("destroying_delete_t"); 2782 } 2783 2784 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 2785 return getDeclLanguageLinkage(*this); 2786 } 2787 2788 bool FunctionDecl::isExternC() const { 2789 return isDeclExternC(*this); 2790 } 2791 2792 bool FunctionDecl::isInExternCContext() const { 2793 return getLexicalDeclContext()->isExternCContext(); 2794 } 2795 2796 bool FunctionDecl::isInExternCXXContext() const { 2797 return getLexicalDeclContext()->isExternCXXContext(); 2798 } 2799 2800 bool FunctionDecl::isGlobal() const { 2801 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 2802 return Method->isStatic(); 2803 2804 if (getCanonicalDecl()->getStorageClass() == SC_Static) 2805 return false; 2806 2807 for (const DeclContext *DC = getDeclContext(); 2808 DC->isNamespace(); 2809 DC = DC->getParent()) { 2810 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 2811 if (!Namespace->getDeclName()) 2812 return false; 2813 break; 2814 } 2815 } 2816 2817 return true; 2818 } 2819 2820 bool FunctionDecl::isNoReturn() const { 2821 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 2822 hasAttr<C11NoReturnAttr>()) 2823 return true; 2824 2825 if (auto *FnTy = getType()->getAs<FunctionType>()) 2826 return FnTy->getNoReturnAttr(); 2827 2828 return false; 2829 } 2830 2831 void 2832 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 2833 redeclarable_base::setPreviousDecl(PrevDecl); 2834 2835 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 2836 FunctionTemplateDecl *PrevFunTmpl 2837 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 2838 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 2839 FunTmpl->setPreviousDecl(PrevFunTmpl); 2840 } 2841 2842 if (PrevDecl && PrevDecl->IsInline) 2843 IsInline = true; 2844 } 2845 2846 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 2847 2848 /// \brief Returns a value indicating whether this function 2849 /// corresponds to a builtin function. 2850 /// 2851 /// The function corresponds to a built-in function if it is 2852 /// declared at translation scope or within an extern "C" block and 2853 /// its name matches with the name of a builtin. The returned value 2854 /// will be 0 for functions that do not correspond to a builtin, a 2855 /// value of type \c Builtin::ID if in the target-independent range 2856 /// \c [1,Builtin::First), or a target-specific builtin value. 2857 unsigned FunctionDecl::getBuiltinID() const { 2858 if (!getIdentifier()) 2859 return 0; 2860 2861 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 2862 if (!BuiltinID) 2863 return 0; 2864 2865 ASTContext &Context = getASTContext(); 2866 if (Context.getLangOpts().CPlusPlus) { 2867 const auto *LinkageDecl = 2868 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext()); 2869 // In C++, the first declaration of a builtin is always inside an implicit 2870 // extern "C". 2871 // FIXME: A recognised library function may not be directly in an extern "C" 2872 // declaration, for instance "extern "C" { namespace std { decl } }". 2873 if (!LinkageDecl) { 2874 if (BuiltinID == Builtin::BI__GetExceptionInfo && 2875 Context.getTargetInfo().getCXXABI().isMicrosoft()) 2876 return Builtin::BI__GetExceptionInfo; 2877 return 0; 2878 } 2879 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c) 2880 return 0; 2881 } 2882 2883 // If the function is marked "overloadable", it has a different mangled name 2884 // and is not the C library function. 2885 if (hasAttr<OverloadableAttr>()) 2886 return 0; 2887 2888 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2889 return BuiltinID; 2890 2891 // This function has the name of a known C library 2892 // function. Determine whether it actually refers to the C library 2893 // function or whether it just has the same name. 2894 2895 // If this is a static function, it's not a builtin. 2896 if (getStorageClass() == SC_Static) 2897 return 0; 2898 2899 // OpenCL v1.2 s6.9.f - The library functions defined in 2900 // the C99 standard headers are not available. 2901 if (Context.getLangOpts().OpenCL && 2902 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2903 return 0; 2904 2905 // CUDA does not have device-side standard library. printf and malloc are the 2906 // only special cases that are supported by device-side runtime. 2907 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && 2908 !hasAttr<CUDAHostAttr>() && 2909 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 2910 return 0; 2911 2912 return BuiltinID; 2913 } 2914 2915 /// getNumParams - Return the number of parameters this function must have 2916 /// based on its FunctionType. This is the length of the ParamInfo array 2917 /// after it has been created. 2918 unsigned FunctionDecl::getNumParams() const { 2919 const auto *FPT = getType()->getAs<FunctionProtoType>(); 2920 return FPT ? FPT->getNumParams() : 0; 2921 } 2922 2923 void FunctionDecl::setParams(ASTContext &C, 2924 ArrayRef<ParmVarDecl *> NewParamInfo) { 2925 assert(!ParamInfo && "Already has param info!"); 2926 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 2927 2928 // Zero params -> null pointer. 2929 if (!NewParamInfo.empty()) { 2930 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 2931 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 2932 } 2933 } 2934 2935 /// getMinRequiredArguments - Returns the minimum number of arguments 2936 /// needed to call this function. This may be fewer than the number of 2937 /// function parameters, if some of the parameters have default 2938 /// arguments (in C++) or are parameter packs (C++11). 2939 unsigned FunctionDecl::getMinRequiredArguments() const { 2940 if (!getASTContext().getLangOpts().CPlusPlus) 2941 return getNumParams(); 2942 2943 unsigned NumRequiredArgs = 0; 2944 for (auto *Param : parameters()) 2945 if (!Param->isParameterPack() && !Param->hasDefaultArg()) 2946 ++NumRequiredArgs; 2947 return NumRequiredArgs; 2948 } 2949 2950 /// \brief The combination of the extern and inline keywords under MSVC forces 2951 /// the function to be required. 2952 /// 2953 /// Note: This function assumes that we will only get called when isInlined() 2954 /// would return true for this FunctionDecl. 2955 bool FunctionDecl::isMSExternInline() const { 2956 assert(isInlined() && "expected to get called on an inlined function!"); 2957 2958 const ASTContext &Context = getASTContext(); 2959 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 2960 !hasAttr<DLLExportAttr>()) 2961 return false; 2962 2963 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 2964 FD = FD->getPreviousDecl()) 2965 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2966 return true; 2967 2968 return false; 2969 } 2970 2971 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 2972 if (Redecl->getStorageClass() != SC_Extern) 2973 return false; 2974 2975 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 2976 FD = FD->getPreviousDecl()) 2977 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2978 return false; 2979 2980 return true; 2981 } 2982 2983 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 2984 // Only consider file-scope declarations in this test. 2985 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 2986 return false; 2987 2988 // Only consider explicit declarations; the presence of a builtin for a 2989 // libcall shouldn't affect whether a definition is externally visible. 2990 if (Redecl->isImplicit()) 2991 return false; 2992 2993 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 2994 return true; // Not an inline definition 2995 2996 return false; 2997 } 2998 2999 /// \brief For a function declaration in C or C++, determine whether this 3000 /// declaration causes the definition to be externally visible. 3001 /// 3002 /// For instance, this determines if adding the current declaration to the set 3003 /// of redeclarations of the given functions causes 3004 /// isInlineDefinitionExternallyVisible to change from false to true. 3005 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 3006 assert(!doesThisDeclarationHaveABody() && 3007 "Must have a declaration without a body."); 3008 3009 ASTContext &Context = getASTContext(); 3010 3011 if (Context.getLangOpts().MSVCCompat) { 3012 const FunctionDecl *Definition; 3013 if (hasBody(Definition) && Definition->isInlined() && 3014 redeclForcesDefMSVC(this)) 3015 return true; 3016 } 3017 3018 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3019 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3020 // an externally visible definition. 3021 // 3022 // FIXME: What happens if gnu_inline gets added on after the first 3023 // declaration? 3024 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3025 return false; 3026 3027 const FunctionDecl *Prev = this; 3028 bool FoundBody = false; 3029 while ((Prev = Prev->getPreviousDecl())) { 3030 FoundBody |= Prev->Body.isValid(); 3031 3032 if (Prev->Body) { 3033 // If it's not the case that both 'inline' and 'extern' are 3034 // specified on the definition, then it is always externally visible. 3035 if (!Prev->isInlineSpecified() || 3036 Prev->getStorageClass() != SC_Extern) 3037 return false; 3038 } else if (Prev->isInlineSpecified() && 3039 Prev->getStorageClass() != SC_Extern) { 3040 return false; 3041 } 3042 } 3043 return FoundBody; 3044 } 3045 3046 if (Context.getLangOpts().CPlusPlus) 3047 return false; 3048 3049 // C99 6.7.4p6: 3050 // [...] If all of the file scope declarations for a function in a 3051 // translation unit include the inline function specifier without extern, 3052 // then the definition in that translation unit is an inline definition. 3053 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3054 return false; 3055 const FunctionDecl *Prev = this; 3056 bool FoundBody = false; 3057 while ((Prev = Prev->getPreviousDecl())) { 3058 FoundBody |= Prev->Body.isValid(); 3059 if (RedeclForcesDefC99(Prev)) 3060 return false; 3061 } 3062 return FoundBody; 3063 } 3064 3065 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3066 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3067 if (!TSI) 3068 return SourceRange(); 3069 FunctionTypeLoc FTL = 3070 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>(); 3071 if (!FTL) 3072 return SourceRange(); 3073 3074 // Skip self-referential return types. 3075 const SourceManager &SM = getASTContext().getSourceManager(); 3076 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3077 SourceLocation Boundary = getNameInfo().getLocStart(); 3078 if (RTRange.isInvalid() || Boundary.isInvalid() || 3079 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3080 return SourceRange(); 3081 3082 return RTRange; 3083 } 3084 3085 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3086 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3087 if (!TSI) 3088 return SourceRange(); 3089 FunctionTypeLoc FTL = 3090 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>(); 3091 if (!FTL) 3092 return SourceRange(); 3093 3094 return FTL.getExceptionSpecRange(); 3095 } 3096 3097 const Attr *FunctionDecl::getUnusedResultAttr() const { 3098 QualType RetType = getReturnType(); 3099 if (RetType->isRecordType()) { 3100 if (const auto *Ret = 3101 dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) { 3102 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) 3103 return R; 3104 } 3105 } else if (const auto *ET = RetType->getAs<EnumType>()) { 3106 if (const EnumDecl *ED = ET->getDecl()) { 3107 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>()) 3108 return R; 3109 } 3110 } 3111 return getAttr<WarnUnusedResultAttr>(); 3112 } 3113 3114 /// \brief For an inline function definition in C, or for a gnu_inline function 3115 /// in C++, determine whether the definition will be externally visible. 3116 /// 3117 /// Inline function definitions are always available for inlining optimizations. 3118 /// However, depending on the language dialect, declaration specifiers, and 3119 /// attributes, the definition of an inline function may or may not be 3120 /// "externally" visible to other translation units in the program. 3121 /// 3122 /// In C99, inline definitions are not externally visible by default. However, 3123 /// if even one of the global-scope declarations is marked "extern inline", the 3124 /// inline definition becomes externally visible (C99 6.7.4p6). 3125 /// 3126 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3127 /// definition, we use the GNU semantics for inline, which are nearly the 3128 /// opposite of C99 semantics. In particular, "inline" by itself will create 3129 /// an externally visible symbol, but "extern inline" will not create an 3130 /// externally visible symbol. 3131 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3132 assert((doesThisDeclarationHaveABody() || willHaveBody()) && 3133 "Must be a function definition"); 3134 assert(isInlined() && "Function must be inline"); 3135 ASTContext &Context = getASTContext(); 3136 3137 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3138 // Note: If you change the logic here, please change 3139 // doesDeclarationForceExternallyVisibleDefinition as well. 3140 // 3141 // If it's not the case that both 'inline' and 'extern' are 3142 // specified on the definition, then this inline definition is 3143 // externally visible. 3144 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3145 return true; 3146 3147 // If any declaration is 'inline' but not 'extern', then this definition 3148 // is externally visible. 3149 for (auto Redecl : redecls()) { 3150 if (Redecl->isInlineSpecified() && 3151 Redecl->getStorageClass() != SC_Extern) 3152 return true; 3153 } 3154 3155 return false; 3156 } 3157 3158 // The rest of this function is C-only. 3159 assert(!Context.getLangOpts().CPlusPlus && 3160 "should not use C inline rules in C++"); 3161 3162 // C99 6.7.4p6: 3163 // [...] If all of the file scope declarations for a function in a 3164 // translation unit include the inline function specifier without extern, 3165 // then the definition in that translation unit is an inline definition. 3166 for (auto Redecl : redecls()) { 3167 if (RedeclForcesDefC99(Redecl)) 3168 return true; 3169 } 3170 3171 // C99 6.7.4p6: 3172 // An inline definition does not provide an external definition for the 3173 // function, and does not forbid an external definition in another 3174 // translation unit. 3175 return false; 3176 } 3177 3178 /// getOverloadedOperator - Which C++ overloaded operator this 3179 /// function represents, if any. 3180 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3181 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3182 return getDeclName().getCXXOverloadedOperator(); 3183 else 3184 return OO_None; 3185 } 3186 3187 /// getLiteralIdentifier - The literal suffix identifier this function 3188 /// represents, if any. 3189 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3190 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3191 return getDeclName().getCXXLiteralIdentifier(); 3192 else 3193 return nullptr; 3194 } 3195 3196 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 3197 if (TemplateOrSpecialization.isNull()) 3198 return TK_NonTemplate; 3199 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 3200 return TK_FunctionTemplate; 3201 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 3202 return TK_MemberSpecialization; 3203 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 3204 return TK_FunctionTemplateSpecialization; 3205 if (TemplateOrSpecialization.is 3206 <DependentFunctionTemplateSpecializationInfo*>()) 3207 return TK_DependentFunctionTemplateSpecialization; 3208 3209 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 3210 } 3211 3212 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 3213 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 3214 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 3215 3216 return nullptr; 3217 } 3218 3219 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 3220 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>(); 3221 } 3222 3223 void 3224 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 3225 FunctionDecl *FD, 3226 TemplateSpecializationKind TSK) { 3227 assert(TemplateOrSpecialization.isNull() && 3228 "Member function is already a specialization"); 3229 MemberSpecializationInfo *Info 3230 = new (C) MemberSpecializationInfo(FD, TSK); 3231 TemplateOrSpecialization = Info; 3232 } 3233 3234 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 3235 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>(); 3236 } 3237 3238 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { 3239 TemplateOrSpecialization = Template; 3240 } 3241 3242 bool FunctionDecl::isImplicitlyInstantiable() const { 3243 // If the function is invalid, it can't be implicitly instantiated. 3244 if (isInvalidDecl()) 3245 return false; 3246 3247 switch (getTemplateSpecializationKind()) { 3248 case TSK_Undeclared: 3249 case TSK_ExplicitInstantiationDefinition: 3250 return false; 3251 3252 case TSK_ImplicitInstantiation: 3253 return true; 3254 3255 // It is possible to instantiate TSK_ExplicitSpecialization kind 3256 // if the FunctionDecl has a class scope specialization pattern. 3257 case TSK_ExplicitSpecialization: 3258 return getClassScopeSpecializationPattern() != nullptr; 3259 3260 case TSK_ExplicitInstantiationDeclaration: 3261 // Handled below. 3262 break; 3263 } 3264 3265 // Find the actual template from which we will instantiate. 3266 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 3267 bool HasPattern = false; 3268 if (PatternDecl) 3269 HasPattern = PatternDecl->hasBody(PatternDecl); 3270 3271 // C++0x [temp.explicit]p9: 3272 // Except for inline functions, other explicit instantiation declarations 3273 // have the effect of suppressing the implicit instantiation of the entity 3274 // to which they refer. 3275 if (!HasPattern || !PatternDecl) 3276 return true; 3277 3278 return PatternDecl->isInlined(); 3279 } 3280 3281 bool FunctionDecl::isTemplateInstantiation() const { 3282 switch (getTemplateSpecializationKind()) { 3283 case TSK_Undeclared: 3284 case TSK_ExplicitSpecialization: 3285 return false; 3286 case TSK_ImplicitInstantiation: 3287 case TSK_ExplicitInstantiationDeclaration: 3288 case TSK_ExplicitInstantiationDefinition: 3289 return true; 3290 } 3291 llvm_unreachable("All TSK values handled."); 3292 } 3293 3294 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 3295 // Handle class scope explicit specialization special case. 3296 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 3297 if (auto *Spec = getClassScopeSpecializationPattern()) 3298 return getDefinitionOrSelf(Spec); 3299 return nullptr; 3300 } 3301 3302 // If this is a generic lambda call operator specialization, its 3303 // instantiation pattern is always its primary template's pattern 3304 // even if its primary template was instantiated from another 3305 // member template (which happens with nested generic lambdas). 3306 // Since a lambda's call operator's body is transformed eagerly, 3307 // we don't have to go hunting for a prototype definition template 3308 // (i.e. instantiated-from-member-template) to use as an instantiation 3309 // pattern. 3310 3311 if (isGenericLambdaCallOperatorSpecialization( 3312 dyn_cast<CXXMethodDecl>(this))) { 3313 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 3314 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 3315 } 3316 3317 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 3318 while (Primary->getInstantiatedFromMemberTemplate()) { 3319 // If we have hit a point where the user provided a specialization of 3320 // this template, we're done looking. 3321 if (Primary->isMemberSpecialization()) 3322 break; 3323 Primary = Primary->getInstantiatedFromMemberTemplate(); 3324 } 3325 3326 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 3327 } 3328 3329 if (auto *MFD = getInstantiatedFromMemberFunction()) 3330 return getDefinitionOrSelf(MFD); 3331 3332 return nullptr; 3333 } 3334 3335 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 3336 if (FunctionTemplateSpecializationInfo *Info 3337 = TemplateOrSpecialization 3338 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3339 return Info->Template.getPointer(); 3340 } 3341 return nullptr; 3342 } 3343 3344 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const { 3345 return getASTContext().getClassScopeSpecializationPattern(this); 3346 } 3347 3348 FunctionTemplateSpecializationInfo * 3349 FunctionDecl::getTemplateSpecializationInfo() const { 3350 return TemplateOrSpecialization 3351 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 3352 } 3353 3354 const TemplateArgumentList * 3355 FunctionDecl::getTemplateSpecializationArgs() const { 3356 if (FunctionTemplateSpecializationInfo *Info 3357 = TemplateOrSpecialization 3358 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3359 return Info->TemplateArguments; 3360 } 3361 return nullptr; 3362 } 3363 3364 const ASTTemplateArgumentListInfo * 3365 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 3366 if (FunctionTemplateSpecializationInfo *Info 3367 = TemplateOrSpecialization 3368 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3369 return Info->TemplateArgumentsAsWritten; 3370 } 3371 return nullptr; 3372 } 3373 3374 void 3375 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 3376 FunctionTemplateDecl *Template, 3377 const TemplateArgumentList *TemplateArgs, 3378 void *InsertPos, 3379 TemplateSpecializationKind TSK, 3380 const TemplateArgumentListInfo *TemplateArgsAsWritten, 3381 SourceLocation PointOfInstantiation) { 3382 assert(TSK != TSK_Undeclared && 3383 "Must specify the type of function template specialization"); 3384 FunctionTemplateSpecializationInfo *Info 3385 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3386 if (!Info) 3387 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 3388 TemplateArgs, 3389 TemplateArgsAsWritten, 3390 PointOfInstantiation); 3391 TemplateOrSpecialization = Info; 3392 Template->addSpecialization(Info, InsertPos); 3393 } 3394 3395 void 3396 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 3397 const UnresolvedSetImpl &Templates, 3398 const TemplateArgumentListInfo &TemplateArgs) { 3399 assert(TemplateOrSpecialization.isNull()); 3400 DependentFunctionTemplateSpecializationInfo *Info = 3401 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 3402 TemplateArgs); 3403 TemplateOrSpecialization = Info; 3404 } 3405 3406 DependentFunctionTemplateSpecializationInfo * 3407 FunctionDecl::getDependentSpecializationInfo() const { 3408 return TemplateOrSpecialization 3409 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 3410 } 3411 3412 DependentFunctionTemplateSpecializationInfo * 3413 DependentFunctionTemplateSpecializationInfo::Create( 3414 ASTContext &Context, const UnresolvedSetImpl &Ts, 3415 const TemplateArgumentListInfo &TArgs) { 3416 void *Buffer = Context.Allocate( 3417 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>( 3418 TArgs.size(), Ts.size())); 3419 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs); 3420 } 3421 3422 DependentFunctionTemplateSpecializationInfo:: 3423 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 3424 const TemplateArgumentListInfo &TArgs) 3425 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 3426 NumTemplates = Ts.size(); 3427 NumArgs = TArgs.size(); 3428 3429 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>(); 3430 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 3431 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 3432 3433 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>(); 3434 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 3435 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 3436 } 3437 3438 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 3439 // For a function template specialization, query the specialization 3440 // information object. 3441 FunctionTemplateSpecializationInfo *FTSInfo 3442 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3443 if (FTSInfo) 3444 return FTSInfo->getTemplateSpecializationKind(); 3445 3446 MemberSpecializationInfo *MSInfo 3447 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 3448 if (MSInfo) 3449 return MSInfo->getTemplateSpecializationKind(); 3450 3451 return TSK_Undeclared; 3452 } 3453 3454 void 3455 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3456 SourceLocation PointOfInstantiation) { 3457 if (FunctionTemplateSpecializationInfo *FTSInfo 3458 = TemplateOrSpecialization.dyn_cast< 3459 FunctionTemplateSpecializationInfo*>()) { 3460 FTSInfo->setTemplateSpecializationKind(TSK); 3461 if (TSK != TSK_ExplicitSpecialization && 3462 PointOfInstantiation.isValid() && 3463 FTSInfo->getPointOfInstantiation().isInvalid()) { 3464 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 3465 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 3466 L->InstantiationRequested(this); 3467 } 3468 } else if (MemberSpecializationInfo *MSInfo 3469 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 3470 MSInfo->setTemplateSpecializationKind(TSK); 3471 if (TSK != TSK_ExplicitSpecialization && 3472 PointOfInstantiation.isValid() && 3473 MSInfo->getPointOfInstantiation().isInvalid()) { 3474 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3475 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 3476 L->InstantiationRequested(this); 3477 } 3478 } else 3479 llvm_unreachable("Function cannot have a template specialization kind"); 3480 } 3481 3482 SourceLocation FunctionDecl::getPointOfInstantiation() const { 3483 if (FunctionTemplateSpecializationInfo *FTSInfo 3484 = TemplateOrSpecialization.dyn_cast< 3485 FunctionTemplateSpecializationInfo*>()) 3486 return FTSInfo->getPointOfInstantiation(); 3487 else if (MemberSpecializationInfo *MSInfo 3488 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 3489 return MSInfo->getPointOfInstantiation(); 3490 3491 return SourceLocation(); 3492 } 3493 3494 bool FunctionDecl::isOutOfLine() const { 3495 if (Decl::isOutOfLine()) 3496 return true; 3497 3498 // If this function was instantiated from a member function of a 3499 // class template, check whether that member function was defined out-of-line. 3500 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 3501 const FunctionDecl *Definition; 3502 if (FD->hasBody(Definition)) 3503 return Definition->isOutOfLine(); 3504 } 3505 3506 // If this function was instantiated from a function template, 3507 // check whether that function template was defined out-of-line. 3508 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 3509 const FunctionDecl *Definition; 3510 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 3511 return Definition->isOutOfLine(); 3512 } 3513 3514 return false; 3515 } 3516 3517 SourceRange FunctionDecl::getSourceRange() const { 3518 return SourceRange(getOuterLocStart(), EndRangeLoc); 3519 } 3520 3521 unsigned FunctionDecl::getMemoryFunctionKind() const { 3522 IdentifierInfo *FnInfo = getIdentifier(); 3523 3524 if (!FnInfo) 3525 return 0; 3526 3527 // Builtin handling. 3528 switch (getBuiltinID()) { 3529 case Builtin::BI__builtin_memset: 3530 case Builtin::BI__builtin___memset_chk: 3531 case Builtin::BImemset: 3532 return Builtin::BImemset; 3533 3534 case Builtin::BI__builtin_memcpy: 3535 case Builtin::BI__builtin___memcpy_chk: 3536 case Builtin::BImemcpy: 3537 return Builtin::BImemcpy; 3538 3539 case Builtin::BI__builtin_memmove: 3540 case Builtin::BI__builtin___memmove_chk: 3541 case Builtin::BImemmove: 3542 return Builtin::BImemmove; 3543 3544 case Builtin::BIstrlcpy: 3545 case Builtin::BI__builtin___strlcpy_chk: 3546 return Builtin::BIstrlcpy; 3547 3548 case Builtin::BIstrlcat: 3549 case Builtin::BI__builtin___strlcat_chk: 3550 return Builtin::BIstrlcat; 3551 3552 case Builtin::BI__builtin_memcmp: 3553 case Builtin::BImemcmp: 3554 return Builtin::BImemcmp; 3555 3556 case Builtin::BI__builtin_strncpy: 3557 case Builtin::BI__builtin___strncpy_chk: 3558 case Builtin::BIstrncpy: 3559 return Builtin::BIstrncpy; 3560 3561 case Builtin::BI__builtin_strncmp: 3562 case Builtin::BIstrncmp: 3563 return Builtin::BIstrncmp; 3564 3565 case Builtin::BI__builtin_strncasecmp: 3566 case Builtin::BIstrncasecmp: 3567 return Builtin::BIstrncasecmp; 3568 3569 case Builtin::BI__builtin_strncat: 3570 case Builtin::BI__builtin___strncat_chk: 3571 case Builtin::BIstrncat: 3572 return Builtin::BIstrncat; 3573 3574 case Builtin::BI__builtin_strndup: 3575 case Builtin::BIstrndup: 3576 return Builtin::BIstrndup; 3577 3578 case Builtin::BI__builtin_strlen: 3579 case Builtin::BIstrlen: 3580 return Builtin::BIstrlen; 3581 3582 case Builtin::BI__builtin_bzero: 3583 case Builtin::BIbzero: 3584 return Builtin::BIbzero; 3585 3586 default: 3587 if (isExternC()) { 3588 if (FnInfo->isStr("memset")) 3589 return Builtin::BImemset; 3590 else if (FnInfo->isStr("memcpy")) 3591 return Builtin::BImemcpy; 3592 else if (FnInfo->isStr("memmove")) 3593 return Builtin::BImemmove; 3594 else if (FnInfo->isStr("memcmp")) 3595 return Builtin::BImemcmp; 3596 else if (FnInfo->isStr("strncpy")) 3597 return Builtin::BIstrncpy; 3598 else if (FnInfo->isStr("strncmp")) 3599 return Builtin::BIstrncmp; 3600 else if (FnInfo->isStr("strncasecmp")) 3601 return Builtin::BIstrncasecmp; 3602 else if (FnInfo->isStr("strncat")) 3603 return Builtin::BIstrncat; 3604 else if (FnInfo->isStr("strndup")) 3605 return Builtin::BIstrndup; 3606 else if (FnInfo->isStr("strlen")) 3607 return Builtin::BIstrlen; 3608 else if (FnInfo->isStr("bzero")) 3609 return Builtin::BIbzero; 3610 } 3611 break; 3612 } 3613 return 0; 3614 } 3615 3616 unsigned FunctionDecl::getODRHash() { 3617 if (HasODRHash) 3618 return ODRHash; 3619 3620 if (FunctionDecl *Definition = getDefinition()) { 3621 if (Definition != this) { 3622 HasODRHash = true; 3623 ODRHash = Definition->getODRHash(); 3624 return ODRHash; 3625 } 3626 } 3627 3628 class ODRHash Hash; 3629 Hash.AddFunctionDecl(this); 3630 HasODRHash = true; 3631 ODRHash = Hash.CalculateHash(); 3632 return ODRHash; 3633 } 3634 3635 //===----------------------------------------------------------------------===// 3636 // FieldDecl Implementation 3637 //===----------------------------------------------------------------------===// 3638 3639 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 3640 SourceLocation StartLoc, SourceLocation IdLoc, 3641 IdentifierInfo *Id, QualType T, 3642 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 3643 InClassInitStyle InitStyle) { 3644 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 3645 BW, Mutable, InitStyle); 3646 } 3647 3648 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3649 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 3650 SourceLocation(), nullptr, QualType(), nullptr, 3651 nullptr, false, ICIS_NoInit); 3652 } 3653 3654 bool FieldDecl::isAnonymousStructOrUnion() const { 3655 if (!isImplicit() || getDeclName()) 3656 return false; 3657 3658 if (const auto *Record = getType()->getAs<RecordType>()) 3659 return Record->getDecl()->isAnonymousStructOrUnion(); 3660 3661 return false; 3662 } 3663 3664 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 3665 assert(isBitField() && "not a bitfield"); 3666 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 3667 } 3668 3669 unsigned FieldDecl::getFieldIndex() const { 3670 const FieldDecl *Canonical = getCanonicalDecl(); 3671 if (Canonical != this) 3672 return Canonical->getFieldIndex(); 3673 3674 if (CachedFieldIndex) return CachedFieldIndex - 1; 3675 3676 unsigned Index = 0; 3677 const RecordDecl *RD = getParent()->getDefinition(); 3678 assert(RD && "requested index for field of struct with no definition"); 3679 3680 for (auto *Field : RD->fields()) { 3681 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 3682 ++Index; 3683 } 3684 3685 assert(CachedFieldIndex && "failed to find field in parent"); 3686 return CachedFieldIndex - 1; 3687 } 3688 3689 SourceRange FieldDecl::getSourceRange() const { 3690 const Expr *FinalExpr = getInClassInitializer(); 3691 if (!FinalExpr) 3692 FinalExpr = getBitWidth(); 3693 if (FinalExpr) 3694 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd()); 3695 return DeclaratorDecl::getSourceRange(); 3696 } 3697 3698 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 3699 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 3700 "capturing type in non-lambda or captured record."); 3701 assert(InitStorage.getInt() == ISK_NoInit && 3702 InitStorage.getPointer() == nullptr && 3703 "bit width, initializer or captured type already set"); 3704 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType), 3705 ISK_CapturedVLAType); 3706 } 3707 3708 //===----------------------------------------------------------------------===// 3709 // TagDecl Implementation 3710 //===----------------------------------------------------------------------===// 3711 3712 SourceLocation TagDecl::getOuterLocStart() const { 3713 return getTemplateOrInnerLocStart(this); 3714 } 3715 3716 SourceRange TagDecl::getSourceRange() const { 3717 SourceLocation RBraceLoc = BraceRange.getEnd(); 3718 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 3719 return SourceRange(getOuterLocStart(), E); 3720 } 3721 3722 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 3723 3724 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 3725 TypedefNameDeclOrQualifier = TDD; 3726 if (const Type *T = getTypeForDecl()) { 3727 (void)T; 3728 assert(T->isLinkageValid()); 3729 } 3730 assert(isLinkageValid()); 3731 } 3732 3733 void TagDecl::startDefinition() { 3734 IsBeingDefined = true; 3735 3736 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 3737 struct CXXRecordDecl::DefinitionData *Data = 3738 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 3739 for (auto I : redecls()) 3740 cast<CXXRecordDecl>(I)->DefinitionData = Data; 3741 } 3742 } 3743 3744 void TagDecl::completeDefinition() { 3745 assert((!isa<CXXRecordDecl>(this) || 3746 cast<CXXRecordDecl>(this)->hasDefinition()) && 3747 "definition completed but not started"); 3748 3749 IsCompleteDefinition = true; 3750 IsBeingDefined = false; 3751 3752 if (ASTMutationListener *L = getASTMutationListener()) 3753 L->CompletedTagDefinition(this); 3754 } 3755 3756 TagDecl *TagDecl::getDefinition() const { 3757 if (isCompleteDefinition()) 3758 return const_cast<TagDecl *>(this); 3759 3760 // If it's possible for us to have an out-of-date definition, check now. 3761 if (MayHaveOutOfDateDef) { 3762 if (IdentifierInfo *II = getIdentifier()) { 3763 if (II->isOutOfDate()) { 3764 updateOutOfDate(*II); 3765 } 3766 } 3767 } 3768 3769 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 3770 return CXXRD->getDefinition(); 3771 3772 for (auto R : redecls()) 3773 if (R->isCompleteDefinition()) 3774 return R; 3775 3776 return nullptr; 3777 } 3778 3779 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 3780 if (QualifierLoc) { 3781 // Make sure the extended qualifier info is allocated. 3782 if (!hasExtInfo()) 3783 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3784 // Set qualifier info. 3785 getExtInfo()->QualifierLoc = QualifierLoc; 3786 } else { 3787 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 3788 if (hasExtInfo()) { 3789 if (getExtInfo()->NumTemplParamLists == 0) { 3790 getASTContext().Deallocate(getExtInfo()); 3791 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 3792 } 3793 else 3794 getExtInfo()->QualifierLoc = QualifierLoc; 3795 } 3796 } 3797 } 3798 3799 void TagDecl::setTemplateParameterListsInfo( 3800 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 3801 assert(!TPLists.empty()); 3802 // Make sure the extended decl info is allocated. 3803 if (!hasExtInfo()) 3804 // Allocate external info struct. 3805 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3806 // Set the template parameter lists info. 3807 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 3808 } 3809 3810 //===----------------------------------------------------------------------===// 3811 // EnumDecl Implementation 3812 //===----------------------------------------------------------------------===// 3813 3814 void EnumDecl::anchor() {} 3815 3816 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 3817 SourceLocation StartLoc, SourceLocation IdLoc, 3818 IdentifierInfo *Id, 3819 EnumDecl *PrevDecl, bool IsScoped, 3820 bool IsScopedUsingClassTag, bool IsFixed) { 3821 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 3822 IsScoped, IsScopedUsingClassTag, IsFixed); 3823 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3824 C.getTypeDeclType(Enum, PrevDecl); 3825 return Enum; 3826 } 3827 3828 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3829 EnumDecl *Enum = 3830 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 3831 nullptr, nullptr, false, false, false); 3832 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3833 return Enum; 3834 } 3835 3836 SourceRange EnumDecl::getIntegerTypeRange() const { 3837 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 3838 return TI->getTypeLoc().getSourceRange(); 3839 return SourceRange(); 3840 } 3841 3842 void EnumDecl::completeDefinition(QualType NewType, 3843 QualType NewPromotionType, 3844 unsigned NumPositiveBits, 3845 unsigned NumNegativeBits) { 3846 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 3847 if (!IntegerType) 3848 IntegerType = NewType.getTypePtr(); 3849 PromotionType = NewPromotionType; 3850 setNumPositiveBits(NumPositiveBits); 3851 setNumNegativeBits(NumNegativeBits); 3852 TagDecl::completeDefinition(); 3853 } 3854 3855 bool EnumDecl::isClosed() const { 3856 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 3857 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 3858 return true; 3859 } 3860 3861 bool EnumDecl::isClosedFlag() const { 3862 return isClosed() && hasAttr<FlagEnumAttr>(); 3863 } 3864 3865 bool EnumDecl::isClosedNonFlag() const { 3866 return isClosed() && !hasAttr<FlagEnumAttr>(); 3867 } 3868 3869 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 3870 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 3871 return MSI->getTemplateSpecializationKind(); 3872 3873 return TSK_Undeclared; 3874 } 3875 3876 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3877 SourceLocation PointOfInstantiation) { 3878 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 3879 assert(MSI && "Not an instantiated member enumeration?"); 3880 MSI->setTemplateSpecializationKind(TSK); 3881 if (TSK != TSK_ExplicitSpecialization && 3882 PointOfInstantiation.isValid() && 3883 MSI->getPointOfInstantiation().isInvalid()) 3884 MSI->setPointOfInstantiation(PointOfInstantiation); 3885 } 3886 3887 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 3888 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 3889 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 3890 EnumDecl *ED = getInstantiatedFromMemberEnum(); 3891 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 3892 ED = NewED; 3893 return getDefinitionOrSelf(ED); 3894 } 3895 } 3896 3897 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 3898 "couldn't find pattern for enum instantiation"); 3899 return nullptr; 3900 } 3901 3902 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 3903 if (SpecializationInfo) 3904 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 3905 3906 return nullptr; 3907 } 3908 3909 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 3910 TemplateSpecializationKind TSK) { 3911 assert(!SpecializationInfo && "Member enum is already a specialization"); 3912 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 3913 } 3914 3915 //===----------------------------------------------------------------------===// 3916 // RecordDecl Implementation 3917 //===----------------------------------------------------------------------===// 3918 3919 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 3920 DeclContext *DC, SourceLocation StartLoc, 3921 SourceLocation IdLoc, IdentifierInfo *Id, 3922 RecordDecl *PrevDecl) 3923 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc), 3924 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false), 3925 HasObjectMember(false), HasVolatileMember(false), 3926 LoadedFieldsFromExternalStorage(false) { 3927 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 3928 } 3929 3930 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 3931 SourceLocation StartLoc, SourceLocation IdLoc, 3932 IdentifierInfo *Id, RecordDecl* PrevDecl) { 3933 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 3934 StartLoc, IdLoc, Id, PrevDecl); 3935 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3936 3937 C.getTypeDeclType(R, PrevDecl); 3938 return R; 3939 } 3940 3941 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 3942 RecordDecl *R = 3943 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), 3944 SourceLocation(), nullptr, nullptr); 3945 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3946 return R; 3947 } 3948 3949 bool RecordDecl::isInjectedClassName() const { 3950 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 3951 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 3952 } 3953 3954 bool RecordDecl::isLambda() const { 3955 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 3956 return RD->isLambda(); 3957 return false; 3958 } 3959 3960 bool RecordDecl::isCapturedRecord() const { 3961 return hasAttr<CapturedRecordAttr>(); 3962 } 3963 3964 void RecordDecl::setCapturedRecord() { 3965 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 3966 } 3967 3968 RecordDecl::field_iterator RecordDecl::field_begin() const { 3969 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 3970 LoadFieldsFromExternalStorage(); 3971 3972 return field_iterator(decl_iterator(FirstDecl)); 3973 } 3974 3975 /// completeDefinition - Notes that the definition of this type is now 3976 /// complete. 3977 void RecordDecl::completeDefinition() { 3978 assert(!isCompleteDefinition() && "Cannot redefine record!"); 3979 TagDecl::completeDefinition(); 3980 } 3981 3982 /// isMsStruct - Get whether or not this record uses ms_struct layout. 3983 /// This which can be turned on with an attribute, pragma, or the 3984 /// -mms-bitfields command-line option. 3985 bool RecordDecl::isMsStruct(const ASTContext &C) const { 3986 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 3987 } 3988 3989 void RecordDecl::LoadFieldsFromExternalStorage() const { 3990 ExternalASTSource *Source = getASTContext().getExternalSource(); 3991 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 3992 3993 // Notify that we have a RecordDecl doing some initialization. 3994 ExternalASTSource::Deserializing TheFields(Source); 3995 3996 SmallVector<Decl*, 64> Decls; 3997 LoadedFieldsFromExternalStorage = true; 3998 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 3999 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 4000 }, Decls); 4001 4002 #ifndef NDEBUG 4003 // Check that all decls we got were FieldDecls. 4004 for (unsigned i=0, e=Decls.size(); i != e; ++i) 4005 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 4006 #endif 4007 4008 if (Decls.empty()) 4009 return; 4010 4011 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 4012 /*FieldsAlreadyLoaded=*/false); 4013 } 4014 4015 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 4016 ASTContext &Context = getASTContext(); 4017 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 4018 (SanitizerKind::Address | SanitizerKind::KernelAddress); 4019 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 4020 return false; 4021 const auto &Blacklist = Context.getSanitizerBlacklist(); 4022 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 4023 // We may be able to relax some of these requirements. 4024 int ReasonToReject = -1; 4025 if (!CXXRD || CXXRD->isExternCContext()) 4026 ReasonToReject = 0; // is not C++. 4027 else if (CXXRD->hasAttr<PackedAttr>()) 4028 ReasonToReject = 1; // is packed. 4029 else if (CXXRD->isUnion()) 4030 ReasonToReject = 2; // is a union. 4031 else if (CXXRD->isTriviallyCopyable()) 4032 ReasonToReject = 3; // is trivially copyable. 4033 else if (CXXRD->hasTrivialDestructor()) 4034 ReasonToReject = 4; // has trivial destructor. 4035 else if (CXXRD->isStandardLayout()) 4036 ReasonToReject = 5; // is standard layout. 4037 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(), 4038 "field-padding")) 4039 ReasonToReject = 6; // is in a blacklisted file. 4040 else if (Blacklist.isBlacklistedType(EnabledAsanMask, 4041 getQualifiedNameAsString(), 4042 "field-padding")) 4043 ReasonToReject = 7; // is blacklisted. 4044 4045 if (EmitRemark) { 4046 if (ReasonToReject >= 0) 4047 Context.getDiagnostics().Report( 4048 getLocation(), 4049 diag::remark_sanitize_address_insert_extra_padding_rejected) 4050 << getQualifiedNameAsString() << ReasonToReject; 4051 else 4052 Context.getDiagnostics().Report( 4053 getLocation(), 4054 diag::remark_sanitize_address_insert_extra_padding_accepted) 4055 << getQualifiedNameAsString(); 4056 } 4057 return ReasonToReject < 0; 4058 } 4059 4060 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 4061 for (const auto *I : fields()) { 4062 if (I->getIdentifier()) 4063 return I; 4064 4065 if (const auto *RT = I->getType()->getAs<RecordType>()) 4066 if (const FieldDecl *NamedDataMember = 4067 RT->getDecl()->findFirstNamedDataMember()) 4068 return NamedDataMember; 4069 } 4070 4071 // We didn't find a named data member. 4072 return nullptr; 4073 } 4074 4075 //===----------------------------------------------------------------------===// 4076 // BlockDecl Implementation 4077 //===----------------------------------------------------------------------===// 4078 4079 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 4080 assert(!ParamInfo && "Already has param info!"); 4081 4082 // Zero params -> null pointer. 4083 if (!NewParamInfo.empty()) { 4084 NumParams = NewParamInfo.size(); 4085 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 4086 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 4087 } 4088 } 4089 4090 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 4091 bool CapturesCXXThis) { 4092 this->CapturesCXXThis = CapturesCXXThis; 4093 this->NumCaptures = Captures.size(); 4094 4095 if (Captures.empty()) { 4096 this->Captures = nullptr; 4097 return; 4098 } 4099 4100 this->Captures = Captures.copy(Context).data(); 4101 } 4102 4103 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 4104 for (const auto &I : captures()) 4105 // Only auto vars can be captured, so no redeclaration worries. 4106 if (I.getVariable() == variable) 4107 return true; 4108 4109 return false; 4110 } 4111 4112 SourceRange BlockDecl::getSourceRange() const { 4113 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 4114 } 4115 4116 //===----------------------------------------------------------------------===// 4117 // Other Decl Allocation/Deallocation Method Implementations 4118 //===----------------------------------------------------------------------===// 4119 4120 void TranslationUnitDecl::anchor() {} 4121 4122 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 4123 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 4124 } 4125 4126 void PragmaCommentDecl::anchor() {} 4127 4128 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 4129 TranslationUnitDecl *DC, 4130 SourceLocation CommentLoc, 4131 PragmaMSCommentKind CommentKind, 4132 StringRef Arg) { 4133 PragmaCommentDecl *PCD = 4134 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 4135 PragmaCommentDecl(DC, CommentLoc, CommentKind); 4136 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 4137 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 4138 return PCD; 4139 } 4140 4141 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 4142 unsigned ID, 4143 unsigned ArgSize) { 4144 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 4145 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 4146 } 4147 4148 void PragmaDetectMismatchDecl::anchor() {} 4149 4150 PragmaDetectMismatchDecl * 4151 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 4152 SourceLocation Loc, StringRef Name, 4153 StringRef Value) { 4154 size_t ValueStart = Name.size() + 1; 4155 PragmaDetectMismatchDecl *PDMD = 4156 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 4157 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 4158 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 4159 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 4160 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 4161 Value.size()); 4162 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 4163 return PDMD; 4164 } 4165 4166 PragmaDetectMismatchDecl * 4167 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4168 unsigned NameValueSize) { 4169 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 4170 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 4171 } 4172 4173 void ExternCContextDecl::anchor() {} 4174 4175 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 4176 TranslationUnitDecl *DC) { 4177 return new (C, DC) ExternCContextDecl(DC); 4178 } 4179 4180 void LabelDecl::anchor() {} 4181 4182 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4183 SourceLocation IdentL, IdentifierInfo *II) { 4184 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 4185 } 4186 4187 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4188 SourceLocation IdentL, IdentifierInfo *II, 4189 SourceLocation GnuLabelL) { 4190 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 4191 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 4192 } 4193 4194 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4195 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 4196 SourceLocation()); 4197 } 4198 4199 void LabelDecl::setMSAsmLabel(StringRef Name) { 4200 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 4201 memcpy(Buffer, Name.data(), Name.size()); 4202 Buffer[Name.size()] = '\0'; 4203 MSAsmName = Buffer; 4204 } 4205 4206 void ValueDecl::anchor() {} 4207 4208 bool ValueDecl::isWeak() const { 4209 for (const auto *I : attrs()) 4210 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I)) 4211 return true; 4212 4213 return isWeakImported(); 4214 } 4215 4216 void ImplicitParamDecl::anchor() {} 4217 4218 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 4219 SourceLocation IdLoc, 4220 IdentifierInfo *Id, QualType Type, 4221 ImplicitParamKind ParamKind) { 4222 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 4223 } 4224 4225 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 4226 ImplicitParamKind ParamKind) { 4227 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 4228 } 4229 4230 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 4231 unsigned ID) { 4232 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 4233 } 4234 4235 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 4236 SourceLocation StartLoc, 4237 const DeclarationNameInfo &NameInfo, 4238 QualType T, TypeSourceInfo *TInfo, 4239 StorageClass SC, 4240 bool isInlineSpecified, 4241 bool hasWrittenPrototype, 4242 bool isConstexprSpecified) { 4243 FunctionDecl *New = 4244 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo, 4245 SC, isInlineSpecified, isConstexprSpecified); 4246 New->HasWrittenPrototype = hasWrittenPrototype; 4247 return New; 4248 } 4249 4250 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4251 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(), 4252 DeclarationNameInfo(), QualType(), nullptr, 4253 SC_None, false, false); 4254 } 4255 4256 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4257 return new (C, DC) BlockDecl(DC, L); 4258 } 4259 4260 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4261 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 4262 } 4263 4264 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 4265 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 4266 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 4267 4268 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 4269 unsigned NumParams) { 4270 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4271 CapturedDecl(DC, NumParams); 4272 } 4273 4274 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4275 unsigned NumParams) { 4276 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4277 CapturedDecl(nullptr, NumParams); 4278 } 4279 4280 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 4281 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 4282 4283 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 4284 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 4285 4286 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 4287 SourceLocation L, 4288 IdentifierInfo *Id, QualType T, 4289 Expr *E, const llvm::APSInt &V) { 4290 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 4291 } 4292 4293 EnumConstantDecl * 4294 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4295 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 4296 QualType(), nullptr, llvm::APSInt()); 4297 } 4298 4299 void IndirectFieldDecl::anchor() {} 4300 4301 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 4302 SourceLocation L, DeclarationName N, 4303 QualType T, 4304 MutableArrayRef<NamedDecl *> CH) 4305 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 4306 ChainingSize(CH.size()) { 4307 // In C++, indirect field declarations conflict with tag declarations in the 4308 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 4309 if (C.getLangOpts().CPlusPlus) 4310 IdentifierNamespace |= IDNS_Tag; 4311 } 4312 4313 IndirectFieldDecl * 4314 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 4315 IdentifierInfo *Id, QualType T, 4316 llvm::MutableArrayRef<NamedDecl *> CH) { 4317 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 4318 } 4319 4320 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 4321 unsigned ID) { 4322 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), 4323 DeclarationName(), QualType(), None); 4324 } 4325 4326 SourceRange EnumConstantDecl::getSourceRange() const { 4327 SourceLocation End = getLocation(); 4328 if (Init) 4329 End = Init->getLocEnd(); 4330 return SourceRange(getLocation(), End); 4331 } 4332 4333 void TypeDecl::anchor() {} 4334 4335 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 4336 SourceLocation StartLoc, SourceLocation IdLoc, 4337 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 4338 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 4339 } 4340 4341 void TypedefNameDecl::anchor() {} 4342 4343 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 4344 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 4345 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 4346 auto *ThisTypedef = this; 4347 if (AnyRedecl && OwningTypedef) { 4348 OwningTypedef = OwningTypedef->getCanonicalDecl(); 4349 ThisTypedef = ThisTypedef->getCanonicalDecl(); 4350 } 4351 if (OwningTypedef == ThisTypedef) 4352 return TT->getDecl(); 4353 } 4354 4355 return nullptr; 4356 } 4357 4358 bool TypedefNameDecl::isTransparentTagSlow() const { 4359 auto determineIsTransparent = [&]() { 4360 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 4361 if (auto *TD = TT->getDecl()) { 4362 if (TD->getName() != getName()) 4363 return false; 4364 SourceLocation TTLoc = getLocation(); 4365 SourceLocation TDLoc = TD->getLocation(); 4366 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 4367 return false; 4368 SourceManager &SM = getASTContext().getSourceManager(); 4369 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 4370 } 4371 } 4372 return false; 4373 }; 4374 4375 bool isTransparent = determineIsTransparent(); 4376 MaybeModedTInfo.setInt((isTransparent << 1) | 1); 4377 return isTransparent; 4378 } 4379 4380 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4381 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 4382 nullptr, nullptr); 4383 } 4384 4385 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 4386 SourceLocation StartLoc, 4387 SourceLocation IdLoc, IdentifierInfo *Id, 4388 TypeSourceInfo *TInfo) { 4389 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 4390 } 4391 4392 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4393 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 4394 SourceLocation(), nullptr, nullptr); 4395 } 4396 4397 SourceRange TypedefDecl::getSourceRange() const { 4398 SourceLocation RangeEnd = getLocation(); 4399 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 4400 if (typeIsPostfix(TInfo->getType())) 4401 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 4402 } 4403 return SourceRange(getLocStart(), RangeEnd); 4404 } 4405 4406 SourceRange TypeAliasDecl::getSourceRange() const { 4407 SourceLocation RangeEnd = getLocStart(); 4408 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 4409 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 4410 return SourceRange(getLocStart(), RangeEnd); 4411 } 4412 4413 void FileScopeAsmDecl::anchor() {} 4414 4415 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 4416 StringLiteral *Str, 4417 SourceLocation AsmLoc, 4418 SourceLocation RParenLoc) { 4419 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 4420 } 4421 4422 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 4423 unsigned ID) { 4424 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 4425 SourceLocation()); 4426 } 4427 4428 void EmptyDecl::anchor() {} 4429 4430 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4431 return new (C, DC) EmptyDecl(DC, L); 4432 } 4433 4434 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4435 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 4436 } 4437 4438 //===----------------------------------------------------------------------===// 4439 // ImportDecl Implementation 4440 //===----------------------------------------------------------------------===// 4441 4442 /// \brief Retrieve the number of module identifiers needed to name the given 4443 /// module. 4444 static unsigned getNumModuleIdentifiers(Module *Mod) { 4445 unsigned Result = 1; 4446 while (Mod->Parent) { 4447 Mod = Mod->Parent; 4448 ++Result; 4449 } 4450 return Result; 4451 } 4452 4453 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4454 Module *Imported, 4455 ArrayRef<SourceLocation> IdentifierLocs) 4456 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) { 4457 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 4458 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 4459 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 4460 StoredLocs); 4461 } 4462 4463 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4464 Module *Imported, SourceLocation EndLoc) 4465 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) { 4466 *getTrailingObjects<SourceLocation>() = EndLoc; 4467 } 4468 4469 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 4470 SourceLocation StartLoc, Module *Imported, 4471 ArrayRef<SourceLocation> IdentifierLocs) { 4472 return new (C, DC, 4473 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 4474 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 4475 } 4476 4477 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 4478 SourceLocation StartLoc, 4479 Module *Imported, 4480 SourceLocation EndLoc) { 4481 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 4482 ImportDecl(DC, StartLoc, Imported, EndLoc); 4483 Import->setImplicit(); 4484 return Import; 4485 } 4486 4487 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4488 unsigned NumLocations) { 4489 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 4490 ImportDecl(EmptyShell()); 4491 } 4492 4493 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 4494 if (!ImportedAndComplete.getInt()) 4495 return None; 4496 4497 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 4498 return llvm::makeArrayRef(StoredLocs, 4499 getNumModuleIdentifiers(getImportedModule())); 4500 } 4501 4502 SourceRange ImportDecl::getSourceRange() const { 4503 if (!ImportedAndComplete.getInt()) 4504 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 4505 4506 return SourceRange(getLocation(), getIdentifierLocs().back()); 4507 } 4508 4509 //===----------------------------------------------------------------------===// 4510 // ExportDecl Implementation 4511 //===----------------------------------------------------------------------===// 4512 4513 void ExportDecl::anchor() {} 4514 4515 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 4516 SourceLocation ExportLoc) { 4517 return new (C, DC) ExportDecl(DC, ExportLoc); 4518 } 4519 4520 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4521 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 4522 } 4523