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