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