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