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