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