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