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