1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl subclasses.
12 //===----------------------------------------------------------------------===//
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"
36 using namespace clang;
38 Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
42 // Defined here so that it can be inlined into its direct callers.
43 bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
47 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
48 : Decl(TranslationUnit, nullptr, SourceLocation()),
49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
53 //===----------------------------------------------------------------------===//
54 // NamedDecl Implementation
55 //===----------------------------------------------------------------------===//
57 // Visibility rules aren't rigorously externally specified, but here
58 // are the basic principles behind what we implement:
60 // 1. An explicit visibility attribute is generally a direct expression
61 // of the user's intent and should be honored. Only the innermost
62 // visibility attribute applies. If no visibility attribute applies,
63 // global visibility settings are considered.
65 // 2. There is one caveat to the above: on or in a template pattern,
66 // an explicit visibility attribute is just a default rule, and
67 // visibility can be decreased by the visibility of template
68 // arguments. But this, too, has an exception: an attribute on an
69 // explicit specialization or instantiation causes all the visibility
70 // restrictions of the template arguments to be ignored.
72 // 3. A variable that does not otherwise have explicit visibility can
73 // be restricted by the visibility of its type.
75 // 4. A visibility restriction is explicit if it comes from an
76 // attribute (or something like it), not a global visibility setting.
77 // When emitting a reference to an external symbol, visibility
78 // restrictions are ignored unless they are explicit.
80 // 5. When computing the visibility of a non-type, including a
81 // non-type member of a class, only non-type visibility restrictions
82 // are considered: the 'visibility' attribute, global value-visibility
83 // settings, and a few special cases like __private_extern.
85 // 6. When computing the visibility of a type, including a type member
86 // of a class, only type visibility restrictions are considered:
87 // the 'type_visibility' attribute and global type-visibility settings.
88 // However, a 'visibility' attribute counts as a 'type_visibility'
89 // attribute on any declaration that only has the former.
91 // The visibility of a "secondary" entity, like a template argument,
92 // is computed using the kind of that entity, not the kind of the
93 // primary entity for which we are computing visibility. For example,
94 // the visibility of a specialization of either of these templates:
95 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96 // template <class T, bool (&compare)(T, X)> class matcher;
97 // is restricted according to the type visibility of the argument 'T',
98 // the type visibility of 'bool(&)(T,X)', and the value visibility of
99 // the argument function 'compare'. That 'has_match' is a value
100 // and 'matcher' is a type only matters when looking for attributes
101 // and settings from the immediate context.
103 const unsigned IgnoreExplicitVisibilityBit = 2;
104 const unsigned IgnoreAllVisibilityBit = 4;
106 /// Kinds of LV computation. The linkage side of the computation is
107 /// always the same, but different things can change how visibility is
109 enum LVComputationKind {
110 /// Do an LV computation for, ultimately, a type.
111 /// Visibility may be restricted by type visibility settings and
112 /// the visibility of template arguments.
113 LVForType = NamedDecl::VisibilityForType,
115 /// Do an LV computation for, ultimately, a non-type declaration.
116 /// Visibility may be restricted by value visibility settings and
117 /// the visibility of template arguments.
118 LVForValue = NamedDecl::VisibilityForValue,
120 /// Do an LV computation for, ultimately, a type that already has
121 /// some sort of explicit visibility. Visibility may only be
122 /// restricted by the visibility of template arguments.
123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
125 /// Do an LV computation for, ultimately, a non-type declaration
126 /// that already has some sort of explicit visibility. Visibility
127 /// may only be restricted by the visibility of template arguments.
128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
130 /// Do an LV computation when we only care about the linkage.
132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
135 /// Does this computation kind permit us to consider additional
136 /// visibility settings from attributes and the like?
137 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
141 /// Given an LVComputationKind, return one of the same type/value sort
142 /// that records that it already has explicit visibility.
143 static LVComputationKind
144 withExplicitVisibilityAlready(LVComputationKind oldKind) {
145 LVComputationKind newKind =
146 static_cast<LVComputationKind>(unsigned(oldKind) |
147 IgnoreExplicitVisibilityBit);
148 assert(oldKind != LVForType || newKind == LVForExplicitType);
149 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
155 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
156 LVComputationKind kind) {
157 assert(!hasExplicitVisibilityAlready(kind) &&
158 "asking for explicit visibility when we shouldn't be");
159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
162 /// Is the given declaration a "type" or a "value" for the purposes of
163 /// visibility computation?
164 static bool usesTypeVisibility(const NamedDecl *D) {
165 return isa<TypeDecl>(D) ||
166 isa<ClassTemplateDecl>(D) ||
167 isa<ObjCInterfaceDecl>(D);
170 /// Does the given declaration have member specialization information,
171 /// and if so, is it an explicit specialization?
172 template <class T> static typename
173 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
174 isExplicitMemberSpecialization(const T *D) {
175 if (const MemberSpecializationInfo *member =
176 D->getMemberSpecializationInfo()) {
177 return member->isExplicitSpecialization();
182 /// For templates, this question is easier: a member template can't be
183 /// explicitly instantiated, so there's a single bit indicating whether
184 /// or not this is an explicit member specialization.
185 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
186 return D->isMemberSpecialization();
189 /// Given a visibility attribute, return the explicit visibility
190 /// associated with it.
192 static Visibility getVisibilityFromAttr(const T *attr) {
193 switch (attr->getVisibility()) {
195 return DefaultVisibility;
197 return HiddenVisibility;
199 return ProtectedVisibility;
201 llvm_unreachable("bad visibility kind");
204 /// Return the explicit visibility of the given declaration.
205 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
206 NamedDecl::ExplicitVisibilityKind kind) {
207 // If we're ultimately computing the visibility of a type, look for
208 // a 'type_visibility' attribute before looking for 'visibility'.
209 if (kind == NamedDecl::VisibilityForType) {
210 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
211 return getVisibilityFromAttr(A);
215 // If this declaration has an explicit visibility attribute, use it.
216 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
217 return getVisibilityFromAttr(A);
220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
221 // implies visibility(default).
222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
223 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
224 if (A->getPlatform()->getName().equals("macosx"))
225 return DefaultVisibility;
232 getLVForType(const Type &T, LVComputationKind computation) {
233 if (computation == LVForLinkageOnly)
234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
235 return T.getLinkageAndVisibility();
238 /// \brief Get the most restrictive linkage for the types in the given
239 /// template parameter list. For visibility purposes, template
240 /// parameters are part of the signature of a template.
242 getLVForTemplateParameterList(const TemplateParameterList *Params,
243 LVComputationKind computation) {
245 for (const NamedDecl *P : *Params) {
246 // Template type parameters are the most common and never
247 // contribute to visibility, pack or not.
248 if (isa<TemplateTypeParmDecl>(P))
251 // Non-type template parameters can be restricted by the value type, e.g.
252 // template <enum X> class A { ... };
253 // We have to be careful here, though, because we can be dealing with
255 if (const NonTypeTemplateParmDecl *NTTP =
256 dyn_cast<NonTypeTemplateParmDecl>(P)) {
257 // Handle the non-pack case first.
258 if (!NTTP->isExpandedParameterPack()) {
259 if (!NTTP->getType()->isDependentType()) {
260 LV.merge(getLVForType(*NTTP->getType(), computation));
265 // Look at all the types in an expanded pack.
266 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
267 QualType type = NTTP->getExpansionType(i);
268 if (!type->isDependentType())
269 LV.merge(type->getLinkageAndVisibility());
274 // Template template parameters can be restricted by their
275 // template parameters, recursively.
276 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
278 // Handle the non-pack case first.
279 if (!TTP->isExpandedParameterPack()) {
280 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
285 // Look at all expansions in an expanded pack.
286 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
288 LV.merge(getLVForTemplateParameterList(
289 TTP->getExpansionTemplateParameters(i), computation));
296 /// getLVForDecl - Get the linkage and visibility for the given declaration.
297 static LinkageInfo getLVForDecl(const NamedDecl *D,
298 LVComputationKind computation);
300 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
301 const Decl *Ret = nullptr;
302 const DeclContext *DC = D->getDeclContext();
303 while (DC->getDeclKind() != Decl::TranslationUnit) {
304 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
305 Ret = cast<Decl>(DC);
306 DC = DC->getParent();
311 /// \brief Get the most restrictive linkage for the types and
312 /// declarations in the given template argument list.
314 /// Note that we don't take an LVComputationKind because we always
315 /// want to honor the visibility of template arguments in the same way.
316 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
317 LVComputationKind computation) {
320 for (const TemplateArgument &Arg : Args) {
321 switch (Arg.getKind()) {
322 case TemplateArgument::Null:
323 case TemplateArgument::Integral:
324 case TemplateArgument::Expression:
327 case TemplateArgument::Type:
328 LV.merge(getLVForType(*Arg.getAsType(), computation));
331 case TemplateArgument::Declaration:
332 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
333 assert(!usesTypeVisibility(ND));
334 LV.merge(getLVForDecl(ND, computation));
338 case TemplateArgument::NullPtr:
339 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
342 case TemplateArgument::Template:
343 case TemplateArgument::TemplateExpansion:
344 if (TemplateDecl *Template =
345 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
346 LV.merge(getLVForDecl(Template, computation));
349 case TemplateArgument::Pack:
350 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
353 llvm_unreachable("bad template argument kind");
360 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
361 LVComputationKind computation) {
362 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
365 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
366 const FunctionTemplateSpecializationInfo *specInfo) {
367 // Include visibility from the template parameters and arguments
368 // only if this is not an explicit instantiation or specialization
369 // with direct explicit visibility. (Implicit instantiations won't
370 // have a direct attribute.)
371 if (!specInfo->isExplicitInstantiationOrSpecialization())
374 return !fn->hasAttr<VisibilityAttr>();
377 /// Merge in template-related linkage and visibility for the given
378 /// function template specialization.
380 /// We don't need a computation kind here because we can assume
383 /// \param[out] LV the computation to use for the parent
385 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
386 const FunctionTemplateSpecializationInfo *specInfo,
387 LVComputationKind computation) {
388 bool considerVisibility =
389 shouldConsiderTemplateVisibility(fn, specInfo);
391 // Merge information from the template parameters.
392 FunctionTemplateDecl *temp = specInfo->getTemplate();
394 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
395 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
397 // Merge information from the template arguments.
398 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
399 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
400 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
403 /// Does the given declaration have a direct visibility attribute
404 /// that would match the given rules?
405 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
406 LVComputationKind computation) {
407 switch (computation) {
409 case LVForExplicitType:
410 if (D->hasAttr<TypeVisibilityAttr>())
414 case LVForExplicitValue:
415 if (D->hasAttr<VisibilityAttr>())
418 case LVForLinkageOnly:
421 llvm_unreachable("bad visibility computation kind");
424 /// Should we consider visibility associated with the template
425 /// arguments and parameters of the given class template specialization?
426 static bool shouldConsiderTemplateVisibility(
427 const ClassTemplateSpecializationDecl *spec,
428 LVComputationKind computation) {
429 // Include visibility from the template parameters and arguments
430 // only if this is not an explicit instantiation or specialization
431 // with direct explicit visibility (and note that implicit
432 // instantiations won't have a direct attribute).
434 // Furthermore, we want to ignore template parameters and arguments
435 // for an explicit specialization when computing the visibility of a
436 // member thereof with explicit visibility.
438 // This is a bit complex; let's unpack it.
440 // An explicit class specialization is an independent, top-level
441 // declaration. As such, if it or any of its members has an
442 // explicit visibility attribute, that must directly express the
443 // user's intent, and we should honor it. The same logic applies to
444 // an explicit instantiation of a member of such a thing.
446 // Fast path: if this is not an explicit instantiation or
447 // specialization, we always want to consider template-related
448 // visibility restrictions.
449 if (!spec->isExplicitInstantiationOrSpecialization())
452 // This is the 'member thereof' check.
453 if (spec->isExplicitSpecialization() &&
454 hasExplicitVisibilityAlready(computation))
457 return !hasDirectVisibilityAttribute(spec, computation);
460 /// Merge in template-related linkage and visibility for the given
461 /// class template specialization.
462 static void mergeTemplateLV(LinkageInfo &LV,
463 const ClassTemplateSpecializationDecl *spec,
464 LVComputationKind computation) {
465 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
467 // Merge information from the template parameters, but ignore
468 // visibility if we're only considering template arguments.
470 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
472 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
473 LV.mergeMaybeWithVisibility(tempLV,
474 considerVisibility && !hasExplicitVisibilityAlready(computation));
476 // Merge information from the template arguments. We ignore
477 // template-argument visibility if we've got an explicit
478 // instantiation with a visibility attribute.
479 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
480 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
481 if (considerVisibility)
482 LV.mergeVisibility(argsLV);
483 LV.mergeExternalVisibility(argsLV);
486 /// Should we consider visibility associated with the template
487 /// arguments and parameters of the given variable template
488 /// specialization? As usual, follow class template specialization
489 /// logic up to initialization.
490 static bool shouldConsiderTemplateVisibility(
491 const VarTemplateSpecializationDecl *spec,
492 LVComputationKind computation) {
493 // Include visibility from the template parameters and arguments
494 // only if this is not an explicit instantiation or specialization
495 // with direct explicit visibility (and note that implicit
496 // instantiations won't have a direct attribute).
497 if (!spec->isExplicitInstantiationOrSpecialization())
500 // An explicit variable specialization is an independent, top-level
501 // declaration. As such, if it has an explicit visibility attribute,
502 // that must directly express the user's intent, and we should honor
504 if (spec->isExplicitSpecialization() &&
505 hasExplicitVisibilityAlready(computation))
508 return !hasDirectVisibilityAttribute(spec, computation);
511 /// Merge in template-related linkage and visibility for the given
512 /// variable template specialization. As usual, follow class template
513 /// specialization logic up to initialization.
514 static void mergeTemplateLV(LinkageInfo &LV,
515 const VarTemplateSpecializationDecl *spec,
516 LVComputationKind computation) {
517 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
519 // Merge information from the template parameters, but ignore
520 // visibility if we're only considering template arguments.
522 VarTemplateDecl *temp = spec->getSpecializedTemplate();
524 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
525 LV.mergeMaybeWithVisibility(tempLV,
526 considerVisibility && !hasExplicitVisibilityAlready(computation));
528 // Merge information from the template arguments. We ignore
529 // template-argument visibility if we've got an explicit
530 // instantiation with a visibility attribute.
531 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
532 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
533 if (considerVisibility)
534 LV.mergeVisibility(argsLV);
535 LV.mergeExternalVisibility(argsLV);
538 static bool useInlineVisibilityHidden(const NamedDecl *D) {
539 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
540 const LangOptions &Opts = D->getASTContext().getLangOpts();
541 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
544 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
548 TemplateSpecializationKind TSK = TSK_Undeclared;
549 if (FunctionTemplateSpecializationInfo *spec
550 = FD->getTemplateSpecializationInfo()) {
551 TSK = spec->getTemplateSpecializationKind();
552 } else if (MemberSpecializationInfo *MSI =
553 FD->getMemberSpecializationInfo()) {
554 TSK = MSI->getTemplateSpecializationKind();
557 const FunctionDecl *Def = nullptr;
558 // InlineVisibilityHidden only applies to definitions, and
559 // isInlined() only gives meaningful answers on definitions
561 return TSK != TSK_ExplicitInstantiationDeclaration &&
562 TSK != TSK_ExplicitInstantiationDefinition &&
563 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
566 template <typename T> static bool isFirstInExternCContext(T *D) {
567 const T *First = D->getFirstDecl();
568 return First->isInExternCContext();
571 static bool isSingleLineLanguageLinkage(const Decl &D) {
572 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
573 if (!SD->hasBraces())
578 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
579 LVComputationKind computation) {
580 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
581 "Not a name having namespace scope");
582 ASTContext &Context = D->getASTContext();
584 // C++ [basic.link]p3:
585 // A name having namespace scope (3.3.6) has internal linkage if it
587 // - an object, reference, function or function template that is
588 // explicitly declared static; or,
589 // (This bullet corresponds to C99 6.2.2p3.)
590 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
591 // Explicitly declared static.
592 if (Var->getStorageClass() == SC_Static)
593 return LinkageInfo::internal();
595 // - a non-volatile object or reference that is explicitly declared const
596 // or constexpr and neither explicitly declared extern nor previously
597 // declared to have external linkage; or (there is no equivalent in C99)
598 if (Context.getLangOpts().CPlusPlus &&
599 Var->getType().isConstQualified() &&
600 !Var->getType().isVolatileQualified()) {
601 const VarDecl *PrevVar = Var->getPreviousDecl();
603 return getLVForDecl(PrevVar, computation);
605 if (Var->getStorageClass() != SC_Extern &&
606 Var->getStorageClass() != SC_PrivateExtern &&
607 !isSingleLineLanguageLinkage(*Var))
608 return LinkageInfo::internal();
611 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
612 PrevVar = PrevVar->getPreviousDecl()) {
613 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
614 Var->getStorageClass() == SC_None)
615 return PrevVar->getLinkageAndVisibility();
616 // Explicitly declared static.
617 if (PrevVar->getStorageClass() == SC_Static)
618 return LinkageInfo::internal();
620 } else if (const FunctionDecl *Function = D->getAsFunction()) {
622 // A non-member function template can have internal linkage; any
623 // other template name shall have external linkage.
625 // Explicitly declared static.
626 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
627 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
628 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
629 // - a data member of an anonymous union.
630 const VarDecl *VD = IFD->getVarDecl();
631 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
632 return getLVForNamespaceScopeDecl(VD, computation);
634 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
636 if (D->isInAnonymousNamespace()) {
637 const VarDecl *Var = dyn_cast<VarDecl>(D);
638 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
639 if ((!Var || !isFirstInExternCContext(Var)) &&
640 (!Func || !isFirstInExternCContext(Func)))
641 return LinkageInfo::uniqueExternal();
644 // Set up the defaults.
647 // If the declaration of an identifier for an object has file
648 // scope and no storage-class specifier, its linkage is
652 if (!hasExplicitVisibilityAlready(computation)) {
653 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
654 LV.mergeVisibility(*Vis, true);
656 // If we're declared in a namespace with a visibility attribute,
657 // use that namespace's visibility, and it still counts as explicit.
658 for (const DeclContext *DC = D->getDeclContext();
659 !isa<TranslationUnitDecl>(DC);
660 DC = DC->getParent()) {
661 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
663 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
664 LV.mergeVisibility(*Vis, true);
670 // Add in global settings if the above didn't give us direct visibility.
671 if (!LV.isVisibilityExplicit()) {
672 // Use global type/value visibility as appropriate.
673 Visibility globalVisibility;
674 if (computation == LVForValue) {
675 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
677 assert(computation == LVForType);
678 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
680 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
682 // If we're paying attention to global visibility, apply
683 // -finline-visibility-hidden if this is an inline method.
684 if (useInlineVisibilityHidden(D))
685 LV.mergeVisibility(HiddenVisibility, true);
689 // C++ [basic.link]p4:
691 // A name having namespace scope has external linkage if it is the
694 // - an object or reference, unless it has internal linkage; or
695 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
696 // GCC applies the following optimization to variables and static
697 // data members, but not to functions:
699 // Modify the variable's LV by the LV of its type unless this is
700 // C or extern "C". This follows from [basic.link]p9:
701 // A type without linkage shall not be used as the type of a
702 // variable or function with external linkage unless
703 // - the entity has C language linkage, or
704 // - the entity is declared within an unnamed namespace, or
705 // - the entity is not used or is defined in the same
707 // and [basic.link]p10:
708 // ...the types specified by all declarations referring to a
709 // given variable or function shall be identical...
710 // C does not have an equivalent rule.
712 // Ignore this if we've got an explicit attribute; the user
713 // probably knows what they're doing.
715 // Note that we don't want to make the variable non-external
716 // because of this, but unique-external linkage suits us.
717 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
718 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
719 if (TypeLV.getLinkage() != ExternalLinkage)
720 return LinkageInfo::uniqueExternal();
721 if (!LV.isVisibilityExplicit())
722 LV.mergeVisibility(TypeLV);
725 if (Var->getStorageClass() == SC_PrivateExtern)
726 LV.mergeVisibility(HiddenVisibility, true);
728 // Note that Sema::MergeVarDecl already takes care of implementing
729 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
732 // As per function and class template specializations (below),
733 // consider LV for the template and template arguments. We're at file
734 // scope, so we do not need to worry about nested specializations.
735 if (const VarTemplateSpecializationDecl *spec
736 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
737 mergeTemplateLV(LV, spec, computation);
740 // - a function, unless it has internal linkage; or
741 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
742 // In theory, we can modify the function's LV by the LV of its
743 // type unless it has C linkage (see comment above about variables
744 // for justification). In practice, GCC doesn't do this, so it's
745 // just too painful to make work.
747 if (Function->getStorageClass() == SC_PrivateExtern)
748 LV.mergeVisibility(HiddenVisibility, true);
750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
751 // merging storage classes and visibility attributes, so we don't have to
752 // look at previous decls in here.
754 // In C++, then if the type of the function uses a type with
755 // unique-external linkage, it's not legally usable from outside
756 // this translation unit. However, we should use the C linkage
757 // rules instead for extern "C" declarations.
758 if (Context.getLangOpts().CPlusPlus &&
759 !Function->isInExternCContext()) {
760 // Only look at the type-as-written. If this function has an auto-deduced
761 // return type, we can't compute the linkage of that type because it could
762 // require looking at the linkage of this function, and we don't need this
763 // for correctness because the type is not part of the function's
765 // FIXME: This is a hack. We should be able to solve this circularity and
766 // the one in getLVForClassMember for Functions some other way.
767 QualType TypeAsWritten = Function->getType();
768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
769 TypeAsWritten = TSI->getType();
770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
771 return LinkageInfo::uniqueExternal();
774 // Consider LV from the template and the template arguments.
775 // We're at file scope, so we do not need to worry about nested
777 if (FunctionTemplateSpecializationInfo *specInfo
778 = Function->getTemplateSpecializationInfo()) {
779 mergeTemplateLV(LV, Function, specInfo, computation);
782 // - a named class (Clause 9), or an unnamed class defined in a
783 // typedef declaration in which the class has the typedef name
784 // for linkage purposes (7.1.3); or
785 // - a named enumeration (7.2), or an unnamed enumeration
786 // defined in a typedef declaration in which the enumeration
787 // has the typedef name for linkage purposes (7.1.3); or
788 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
789 // Unnamed tags have no linkage.
790 if (!Tag->hasNameForLinkage())
791 return LinkageInfo::none();
793 // If this is a class template specialization, consider the
794 // linkage of the template and template arguments. We're at file
795 // scope, so we do not need to worry about nested specializations.
796 if (const ClassTemplateSpecializationDecl *spec
797 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
798 mergeTemplateLV(LV, spec, computation);
801 // - an enumerator belonging to an enumeration with external linkage;
802 } else if (isa<EnumConstantDecl>(D)) {
803 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
805 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
806 return LinkageInfo::none();
809 // - a template, unless it is a function template that has
810 // internal linkage (Clause 14);
811 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
812 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
814 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
815 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
817 // - a namespace (7.3), unless it is declared within an unnamed
819 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
822 // By extension, we assign external linkage to Objective-C
824 } else if (isa<ObjCInterfaceDecl>(D)) {
827 // Everything not covered here has no linkage.
829 // FIXME: A typedef declaration has linkage if it gives a type a name for
831 return LinkageInfo::none();
834 // If we ended up with non-external linkage, visibility should
835 // always be default.
836 if (LV.getLinkage() != ExternalLinkage)
837 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
842 static LinkageInfo getLVForClassMember(const NamedDecl *D,
843 LVComputationKind computation) {
844 // Only certain class members have linkage. Note that fields don't
845 // really have linkage, but it's convenient to say they do for the
846 // purposes of calculating linkage of pointer-to-data-member
847 // template arguments.
849 // Templates also don't officially have linkage, but since we ignore
850 // the C++ standard and look at template arguments when determining
851 // linkage and visibility of a template specialization, we might hit
852 // a template template argument that way. If we do, we need to
853 // consider its linkage.
854 if (!(isa<CXXMethodDecl>(D) ||
857 isa<IndirectFieldDecl>(D) ||
859 isa<TemplateDecl>(D)))
860 return LinkageInfo::none();
864 // If we have an explicit visibility attribute, merge that in.
865 if (!hasExplicitVisibilityAlready(computation)) {
866 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
867 LV.mergeVisibility(*Vis, true);
868 // If we're paying attention to global visibility, apply
869 // -finline-visibility-hidden if this is an inline method.
871 // Note that we do this before merging information about
872 // the class visibility.
873 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
874 LV.mergeVisibility(HiddenVisibility, true);
877 // If this class member has an explicit visibility attribute, the only
878 // thing that can change its visibility is the template arguments, so
879 // only look for them when processing the class.
880 LVComputationKind classComputation = computation;
881 if (LV.isVisibilityExplicit())
882 classComputation = withExplicitVisibilityAlready(computation);
884 LinkageInfo classLV =
885 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
886 // If the class already has unique-external linkage, we can't improve.
887 if (classLV.getLinkage() == UniqueExternalLinkage)
888 return LinkageInfo::uniqueExternal();
890 if (!isExternallyVisible(classLV.getLinkage()))
891 return LinkageInfo::none();
894 // Otherwise, don't merge in classLV yet, because in certain cases
895 // we need to completely ignore the visibility from it.
897 // Specifically, if this decl exists and has an explicit attribute.
898 const NamedDecl *explicitSpecSuppressor = nullptr;
900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
901 // If the type of the function uses a type with unique-external
902 // linkage, it's not legally usable from outside this translation unit.
903 // But only look at the type-as-written. If this function has an
904 // auto-deduced return type, we can't compute the linkage of that type
905 // because it could require looking at the linkage of this function, and we
906 // don't need this for correctness because the type is not part of the
907 // function's signature.
908 // FIXME: This is a hack. We should be able to solve this circularity and
909 // the one in getLVForNamespaceScopeDecl for Functions some other way.
911 QualType TypeAsWritten = MD->getType();
912 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
913 TypeAsWritten = TSI->getType();
914 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
915 return LinkageInfo::uniqueExternal();
917 // If this is a method template specialization, use the linkage for
918 // the template parameters and arguments.
919 if (FunctionTemplateSpecializationInfo *spec
920 = MD->getTemplateSpecializationInfo()) {
921 mergeTemplateLV(LV, MD, spec, computation);
922 if (spec->isExplicitSpecialization()) {
923 explicitSpecSuppressor = MD;
924 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
925 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
927 } else if (isExplicitMemberSpecialization(MD)) {
928 explicitSpecSuppressor = MD;
931 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
932 if (const ClassTemplateSpecializationDecl *spec
933 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
934 mergeTemplateLV(LV, spec, computation);
935 if (spec->isExplicitSpecialization()) {
936 explicitSpecSuppressor = spec;
938 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
939 if (isExplicitMemberSpecialization(temp)) {
940 explicitSpecSuppressor = temp->getTemplatedDecl();
943 } else if (isExplicitMemberSpecialization(RD)) {
944 explicitSpecSuppressor = RD;
947 // Static data members.
948 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
949 if (const VarTemplateSpecializationDecl *spec
950 = dyn_cast<VarTemplateSpecializationDecl>(VD))
951 mergeTemplateLV(LV, spec, computation);
953 // Modify the variable's linkage by its type, but ignore the
954 // type's visibility unless it's a definition.
955 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
956 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
957 LV.mergeVisibility(typeLV);
958 LV.mergeExternalVisibility(typeLV);
960 if (isExplicitMemberSpecialization(VD)) {
961 explicitSpecSuppressor = VD;
965 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
966 bool considerVisibility =
967 (!LV.isVisibilityExplicit() &&
968 !classLV.isVisibilityExplicit() &&
969 !hasExplicitVisibilityAlready(computation));
971 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
972 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
974 if (const RedeclarableTemplateDecl *redeclTemp =
975 dyn_cast<RedeclarableTemplateDecl>(temp)) {
976 if (isExplicitMemberSpecialization(redeclTemp)) {
977 explicitSpecSuppressor = temp->getTemplatedDecl();
982 // We should never be looking for an attribute directly on a template.
983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
985 // If this member is an explicit member specialization, and it has
986 // an explicit attribute, ignore visibility from the parent.
987 bool considerClassVisibility = true;
988 if (explicitSpecSuppressor &&
989 // optimization: hasDVA() is true only with explicit visibility.
990 LV.isVisibilityExplicit() &&
991 classLV.getVisibility() != DefaultVisibility &&
992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
993 considerClassVisibility = false;
996 // Finally, merge in information from the class.
997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1001 void NamedDecl::anchor() { }
1003 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1004 LVComputationKind computation);
1006 bool NamedDecl::isLinkageValid() const {
1007 if (!hasCachedLinkage())
1010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
1014 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1015 StringRef name = getName();
1016 if (name.empty()) return SFF_None;
1018 if (name.front() == 'C')
1019 if (name == "CFStringCreateWithFormat" ||
1020 name == "CFStringCreateWithFormatAndArguments" ||
1021 name == "CFStringAppendFormat" ||
1022 name == "CFStringAppendFormatAndArguments")
1023 return SFF_CFString;
1027 Linkage NamedDecl::getLinkageInternal() const {
1028 // We don't care about visibility here, so ask for the cheapest
1029 // possible visibility analysis.
1030 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
1033 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1034 LVComputationKind computation =
1035 (usesTypeVisibility(this) ? LVForType : LVForValue);
1036 return getLVForDecl(this, computation);
1039 static Optional<Visibility>
1040 getExplicitVisibilityAux(const NamedDecl *ND,
1041 NamedDecl::ExplicitVisibilityKind kind,
1042 bool IsMostRecent) {
1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1045 // Check the declaration itself first.
1046 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1049 // If this is a member class of a specialization of a class template
1050 // and the corresponding decl has explicit visibility, use that.
1051 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
1052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1053 if (InstantiatedFrom)
1054 return getVisibilityOf(InstantiatedFrom, kind);
1057 // If there wasn't explicit visibility there, and this is a
1058 // specialization of a class template, check for visibility
1060 if (const ClassTemplateSpecializationDecl *spec
1061 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1062 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1065 // Use the most recent declaration.
1066 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1067 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1068 if (MostRecent != ND)
1069 return getExplicitVisibilityAux(MostRecent, kind, true);
1072 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
1073 if (Var->isStaticDataMember()) {
1074 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1075 if (InstantiatedFrom)
1076 return getVisibilityOf(InstantiatedFrom, kind);
1079 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1080 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1085 // Also handle function template specializations.
1086 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
1087 // If the function is a specialization of a template with an
1088 // explicit visibility attribute, use that.
1089 if (FunctionTemplateSpecializationInfo *templateInfo
1090 = fn->getTemplateSpecializationInfo())
1091 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1094 // If the function is a member of a specialization of a class template
1095 // and the corresponding decl has explicit visibility, use that.
1096 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1097 if (InstantiatedFrom)
1098 return getVisibilityOf(InstantiatedFrom, kind);
1103 // The visibility of a template is stored in the templated decl.
1104 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1105 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1110 Optional<Visibility>
1111 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1112 return getExplicitVisibilityAux(this, kind, false);
1115 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1116 LVComputationKind computation) {
1117 // This lambda has its linkage/visibility determined by its owner.
1119 if (isa<ParmVarDecl>(ContextDecl))
1120 DC = ContextDecl->getDeclContext()->getRedeclContext();
1122 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1125 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1126 return getLVForDecl(ND, computation);
1128 return LinkageInfo::external();
1131 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1132 LVComputationKind computation) {
1133 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1134 if (Function->isInAnonymousNamespace() &&
1135 !Function->isInExternCContext())
1136 return LinkageInfo::uniqueExternal();
1138 // This is a "void f();" which got merged with a file static.
1139 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1140 return LinkageInfo::internal();
1143 if (!hasExplicitVisibilityAlready(computation)) {
1144 if (Optional<Visibility> Vis =
1145 getExplicitVisibility(Function, computation))
1146 LV.mergeVisibility(*Vis, true);
1149 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1150 // merging storage classes and visibility attributes, so we don't have to
1151 // look at previous decls in here.
1156 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1157 if (Var->hasExternalStorage()) {
1158 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1159 return LinkageInfo::uniqueExternal();
1162 if (Var->getStorageClass() == SC_PrivateExtern)
1163 LV.mergeVisibility(HiddenVisibility, true);
1164 else if (!hasExplicitVisibilityAlready(computation)) {
1165 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1166 LV.mergeVisibility(*Vis, true);
1169 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1170 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1171 if (PrevLV.getLinkage())
1172 LV.setLinkage(PrevLV.getLinkage());
1173 LV.mergeVisibility(PrevLV);
1179 if (!Var->isStaticLocal())
1180 return LinkageInfo::none();
1183 ASTContext &Context = D->getASTContext();
1184 if (!Context.getLangOpts().CPlusPlus)
1185 return LinkageInfo::none();
1187 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1189 return LinkageInfo::none();
1192 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1193 if (!BD->getBlockManglingNumber())
1194 return LinkageInfo::none();
1196 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1197 BD->getBlockManglingContextDecl(), computation);
1199 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1200 if (!FD->isInlined() &&
1201 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1202 return LinkageInfo::none();
1204 LV = getLVForDecl(FD, computation);
1206 if (!isExternallyVisible(LV.getLinkage()))
1207 return LinkageInfo::none();
1208 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1209 LV.isVisibilityExplicit());
1212 static inline const CXXRecordDecl*
1213 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1214 const CXXRecordDecl *Ret = Record;
1215 while (Record && Record->isLambda()) {
1217 if (!Record->getParent()) break;
1218 // Get the Containing Class of this Lambda Class
1219 Record = dyn_cast_or_null<CXXRecordDecl>(
1220 Record->getParent()->getParent());
1225 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1226 LVComputationKind computation) {
1227 // Objective-C: treat all Objective-C declarations as having external
1229 switch (D->getKind()) {
1233 return LinkageInfo::none();
1234 case Decl::TemplateTemplateParm: // count these as external
1235 case Decl::NonTypeTemplateParm:
1236 case Decl::ObjCAtDefsField:
1237 case Decl::ObjCCategory:
1238 case Decl::ObjCCategoryImpl:
1239 case Decl::ObjCCompatibleAlias:
1240 case Decl::ObjCImplementation:
1241 case Decl::ObjCMethod:
1242 case Decl::ObjCProperty:
1243 case Decl::ObjCPropertyImpl:
1244 case Decl::ObjCProtocol:
1245 return LinkageInfo::external();
1247 case Decl::CXXRecord: {
1248 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1249 if (Record->isLambda()) {
1250 if (!Record->getLambdaManglingNumber()) {
1251 // This lambda has no mangling number, so it's internal.
1252 return LinkageInfo::internal();
1255 // This lambda has its linkage/visibility determined:
1256 // - either by the outermost lambda if that lambda has no mangling
1258 // - or by the parent of the outer most lambda
1259 // This prevents infinite recursion in settings such as nested lambdas
1260 // used in NSDMI's, for e.g.
1263 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1265 const CXXRecordDecl *OuterMostLambda =
1266 getOutermostEnclosingLambda(Record);
1267 if (!OuterMostLambda->getLambdaManglingNumber())
1268 return LinkageInfo::internal();
1270 return getLVForClosure(
1271 OuterMostLambda->getDeclContext()->getRedeclContext(),
1272 OuterMostLambda->getLambdaContextDecl(), computation);
1279 // Handle linkage for namespace-scope names.
1280 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1281 return getLVForNamespaceScopeDecl(D, computation);
1283 // C++ [basic.link]p5:
1284 // In addition, a member function, static data member, a named
1285 // class or enumeration of class scope, or an unnamed class or
1286 // enumeration defined in a class-scope typedef declaration such
1287 // that the class or enumeration has the typedef name for linkage
1288 // purposes (7.1.3), has external linkage if the name of the class
1289 // has external linkage.
1290 if (D->getDeclContext()->isRecord())
1291 return getLVForClassMember(D, computation);
1293 // C++ [basic.link]p6:
1294 // The name of a function declared in block scope and the name of
1295 // an object declared by a block scope extern declaration have
1296 // linkage. If there is a visible declaration of an entity with
1297 // linkage having the same name and type, ignoring entities
1298 // declared outside the innermost enclosing namespace scope, the
1299 // block scope declaration declares that same entity and receives
1300 // the linkage of the previous declaration. If there is more than
1301 // one such matching entity, the program is ill-formed. Otherwise,
1302 // if no matching entity is found, the block scope entity receives
1303 // external linkage.
1304 if (D->getDeclContext()->isFunctionOrMethod())
1305 return getLVForLocalDecl(D, computation);
1307 // C++ [basic.link]p6:
1308 // Names not covered by these rules have no linkage.
1309 return LinkageInfo::none();
1313 class LinkageComputer {
1315 static LinkageInfo getLVForDecl(const NamedDecl *D,
1316 LVComputationKind computation) {
1317 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1318 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1320 LinkageInfo LV = computeLVForDecl(D, computation);
1321 if (D->hasCachedLinkage())
1322 assert(D->getCachedLinkage() == LV.getLinkage());
1324 D->setCachedLinkage(LV.getLinkage());
1327 // In C (because of gnu inline) and in c++ with microsoft extensions an
1328 // static can follow an extern, so we can have two decls with different
1330 const LangOptions &Opts = D->getASTContext().getLangOpts();
1331 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1334 // We have just computed the linkage for this decl. By induction we know
1335 // that all other computed linkages match, check that the one we just
1336 // computed also does.
1337 NamedDecl *Old = nullptr;
1338 for (auto I : D->redecls()) {
1339 NamedDecl *T = cast<NamedDecl>(I);
1342 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1347 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1355 static LinkageInfo getLVForDecl(const NamedDecl *D,
1356 LVComputationKind computation) {
1357 return clang::LinkageComputer::getLVForDecl(D, computation);
1360 std::string NamedDecl::getQualifiedNameAsString() const {
1361 std::string QualName;
1362 llvm::raw_string_ostream OS(QualName);
1363 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1367 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1368 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1371 void NamedDecl::printQualifiedName(raw_ostream &OS,
1372 const PrintingPolicy &P) const {
1373 const DeclContext *Ctx = getDeclContext();
1375 if (Ctx->isFunctionOrMethod()) {
1380 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1381 ContextsTy Contexts;
1383 // Collect contexts.
1384 while (Ctx && isa<NamedDecl>(Ctx)) {
1385 Contexts.push_back(Ctx);
1386 Ctx = Ctx->getParent();
1389 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1391 if (const ClassTemplateSpecializationDecl *Spec
1392 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1393 OS << Spec->getName();
1394 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1395 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1396 TemplateArgs.data(),
1397 TemplateArgs.size(),
1399 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1400 if (P.SuppressUnwrittenScope &&
1401 (ND->isAnonymousNamespace() || ND->isInline()))
1403 if (ND->isAnonymousNamespace())
1404 OS << "(anonymous namespace)";
1407 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1408 if (!RD->getIdentifier())
1409 OS << "(anonymous " << RD->getKindName() << ')';
1412 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1413 const FunctionProtoType *FT = nullptr;
1414 if (FD->hasWrittenPrototype())
1415 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1419 unsigned NumParams = FD->getNumParams();
1420 for (unsigned i = 0; i < NumParams; ++i) {
1423 OS << FD->getParamDecl(i)->getType().stream(P);
1426 if (FT->isVariadic()) {
1434 OS << *cast<NamedDecl>(*I);
1442 OS << "(anonymous)";
1445 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1446 const PrintingPolicy &Policy,
1447 bool Qualified) const {
1449 printQualifiedName(OS, Policy);
1454 static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
1455 // For method declarations, we never replace.
1456 if (ObjCMethodDecl::classofKind(NewK))
1462 // A compatibility alias for a class can be replaced by an interface.
1463 if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
1464 ObjCInterfaceDecl::classofKind(NewK))
1467 // A typedef-declaration, alias-declaration, or Objective-C class declaration
1468 // can replace another declaration of the same type. Semantic analysis checks
1469 // that we have matching types.
1470 if ((TypedefNameDecl::classofKind(OldK) ||
1471 ObjCInterfaceDecl::classofKind(OldK)) &&
1472 (TypedefNameDecl::classofKind(NewK) ||
1473 ObjCInterfaceDecl::classofKind(NewK)))
1476 // Otherwise, a kind mismatch implies that the declaration is not replaced.
1480 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1483 static bool isRedeclarableImpl(...) { return false; }
1484 static bool isRedeclarable(Decl::Kind K) {
1486 #define DECL(Type, Base) \
1488 return isRedeclarableImpl((Type##Decl *)nullptr);
1489 #define ABSTRACT_DECL(DECL)
1490 #include "clang/AST/DeclNodes.inc"
1492 llvm_unreachable("unknown decl kind");
1495 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1496 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1498 // Never replace one imported declaration with another; we need both results
1499 // when re-exporting.
1500 if (OldD->isFromASTFile() && isFromASTFile())
1503 if (!isKindReplaceableBy(OldD->getKind(), getKind()))
1506 // Inline namespaces can give us two declarations with the same
1507 // name and kind in the same scope but different contexts; we should
1508 // keep both declarations in this case.
1509 if (!this->getDeclContext()->getRedeclContext()->Equals(
1510 OldD->getDeclContext()->getRedeclContext()))
1513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1514 // For function declarations, we keep track of redeclarations.
1515 // FIXME: This returns false for functions that should in fact be replaced.
1516 // Instead, perform some kind of type check?
1517 if (FD->getPreviousDecl() != OldD)
1520 // For function templates, the underlying function declarations are linked.
1521 if (const FunctionTemplateDecl *FunctionTemplate =
1522 dyn_cast<FunctionTemplateDecl>(this))
1523 return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
1524 cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
1526 // Using shadow declarations can be overloaded on their target declarations
1527 // if they introduce functions.
1528 // FIXME: If our target replaces the old target, can we replace the old
1529 // shadow declaration?
1530 if (auto *USD = dyn_cast<UsingShadowDecl>(this))
1531 if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
1534 // Using declarations can be overloaded if they introduce functions.
1535 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1536 ASTContext &Context = getASTContext();
1537 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1538 Context.getCanonicalNestedNameSpecifier(
1539 cast<UsingDecl>(OldD)->getQualifier());
1541 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1542 ASTContext &Context = getASTContext();
1543 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1544 Context.getCanonicalNestedNameSpecifier(
1545 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1548 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1549 // We want to keep it, unless it nominates same namespace.
1550 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1551 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1552 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1553 ->getOriginalNamespace();
1555 if (!IsKnownNewer && isRedeclarable(getKind())) {
1556 // Check whether this is actually newer than OldD. We want to keep the
1557 // newer declaration. This loop will usually only iterate once, because
1558 // OldD is usually the previous declaration.
1559 for (auto D : redecls()) {
1563 // If we reach the canonical declaration, then OldD is not actually older
1566 // FIXME: In this case, we should not add this decl to the lookup table.
1567 if (D->isCanonicalDecl())
1572 // It's a newer declaration of the same kind of declaration in the same scope,
1573 // and not an overload: we want this decl instead of the existing one.
1577 bool NamedDecl::hasLinkage() const {
1578 return getFormalLinkage() != NoLinkage;
1581 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1582 NamedDecl *ND = this;
1583 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1584 ND = UD->getTargetDecl();
1586 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1587 return AD->getClassInterface();
1592 bool NamedDecl::isCXXInstanceMember() const {
1593 if (!isCXXClassMember())
1596 const NamedDecl *D = this;
1597 if (isa<UsingShadowDecl>(D))
1598 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1600 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1602 if (const CXXMethodDecl *MD =
1603 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1604 return MD->isInstance();
1608 //===----------------------------------------------------------------------===//
1609 // DeclaratorDecl Implementation
1610 //===----------------------------------------------------------------------===//
1612 template <typename DeclT>
1613 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1614 if (decl->getNumTemplateParameterLists() > 0)
1615 return decl->getTemplateParameterList(0)->getTemplateLoc();
1617 return decl->getInnerLocStart();
1620 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1621 TypeSourceInfo *TSI = getTypeSourceInfo();
1622 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1623 return SourceLocation();
1626 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1628 // Make sure the extended decl info is allocated.
1629 if (!hasExtInfo()) {
1630 // Save (non-extended) type source info pointer.
1631 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1632 // Allocate external info struct.
1633 DeclInfo = new (getASTContext()) ExtInfo;
1634 // Restore savedTInfo into (extended) decl info.
1635 getExtInfo()->TInfo = savedTInfo;
1637 // Set qualifier info.
1638 getExtInfo()->QualifierLoc = QualifierLoc;
1640 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1642 if (getExtInfo()->NumTemplParamLists == 0) {
1643 // Save type source info pointer.
1644 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1645 // Deallocate the extended decl info.
1646 getASTContext().Deallocate(getExtInfo());
1647 // Restore savedTInfo into (non-extended) decl info.
1648 DeclInfo = savedTInfo;
1651 getExtInfo()->QualifierLoc = QualifierLoc;
1657 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1658 unsigned NumTPLists,
1659 TemplateParameterList **TPLists) {
1660 assert(NumTPLists > 0);
1661 // Make sure the extended decl info is allocated.
1662 if (!hasExtInfo()) {
1663 // Save (non-extended) type source info pointer.
1664 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1665 // Allocate external info struct.
1666 DeclInfo = new (getASTContext()) ExtInfo;
1667 // Restore savedTInfo into (extended) decl info.
1668 getExtInfo()->TInfo = savedTInfo;
1670 // Set the template parameter lists info.
1671 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1674 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1675 return getTemplateOrInnerLocStart(this);
1680 // Helper function: returns true if QT is or contains a type
1681 // having a postfix component.
1682 bool typeIsPostfix(clang::QualType QT) {
1684 const Type* T = QT.getTypePtr();
1685 switch (T->getTypeClass()) {
1689 QT = cast<PointerType>(T)->getPointeeType();
1691 case Type::BlockPointer:
1692 QT = cast<BlockPointerType>(T)->getPointeeType();
1694 case Type::MemberPointer:
1695 QT = cast<MemberPointerType>(T)->getPointeeType();
1697 case Type::LValueReference:
1698 case Type::RValueReference:
1699 QT = cast<ReferenceType>(T)->getPointeeType();
1701 case Type::PackExpansion:
1702 QT = cast<PackExpansionType>(T)->getPattern();
1705 case Type::ConstantArray:
1706 case Type::DependentSizedArray:
1707 case Type::IncompleteArray:
1708 case Type::VariableArray:
1709 case Type::FunctionProto:
1710 case Type::FunctionNoProto:
1718 SourceRange DeclaratorDecl::getSourceRange() const {
1719 SourceLocation RangeEnd = getLocation();
1720 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1721 // If the declaration has no name or the type extends past the name take the
1722 // end location of the type.
1723 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1724 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1726 return SourceRange(getOuterLocStart(), RangeEnd);
1730 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1731 unsigned NumTPLists,
1732 TemplateParameterList **TPLists) {
1733 assert((NumTPLists == 0 || TPLists != nullptr) &&
1734 "Empty array of template parameters with positive size!");
1736 // Free previous template parameters (if any).
1737 if (NumTemplParamLists > 0) {
1738 Context.Deallocate(TemplParamLists);
1739 TemplParamLists = nullptr;
1740 NumTemplParamLists = 0;
1742 // Set info on matched template parameter lists (if any).
1743 if (NumTPLists > 0) {
1744 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1745 NumTemplParamLists = NumTPLists;
1746 std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
1750 //===----------------------------------------------------------------------===//
1751 // VarDecl Implementation
1752 //===----------------------------------------------------------------------===//
1754 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1756 case SC_None: break;
1757 case SC_Auto: return "auto";
1758 case SC_Extern: return "extern";
1759 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1760 case SC_PrivateExtern: return "__private_extern__";
1761 case SC_Register: return "register";
1762 case SC_Static: return "static";
1765 llvm_unreachable("Invalid storage class");
1768 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1769 SourceLocation StartLoc, SourceLocation IdLoc,
1770 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1772 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1773 redeclarable_base(C), Init() {
1774 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1775 "VarDeclBitfields too large!");
1776 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1777 "ParmVarDeclBitfields too large!");
1778 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1779 "NonParmVarDeclBitfields too large!");
1781 VarDeclBits.SClass = SC;
1782 // Everything else is implicitly initialized to false.
1785 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1786 SourceLocation StartL, SourceLocation IdL,
1787 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1789 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1792 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1794 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1795 QualType(), nullptr, SC_None);
1798 void VarDecl::setStorageClass(StorageClass SC) {
1799 assert(isLegalForVariable(SC));
1800 VarDeclBits.SClass = SC;
1803 VarDecl::TLSKind VarDecl::getTLSKind() const {
1804 switch (VarDeclBits.TSCSpec) {
1805 case TSCS_unspecified:
1806 if (!hasAttr<ThreadAttr>())
1808 return getASTContext().getLangOpts().isCompatibleWithMSVC(
1809 LangOptions::MSVC2015)
1812 case TSCS___thread: // Fall through.
1813 case TSCS__Thread_local:
1815 case TSCS_thread_local:
1818 llvm_unreachable("Unknown thread storage class specifier!");
1821 SourceRange VarDecl::getSourceRange() const {
1822 if (const Expr *Init = getInit()) {
1823 SourceLocation InitEnd = Init->getLocEnd();
1824 // If Init is implicit, ignore its source range and fallback on
1825 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1826 if (InitEnd.isValid() && InitEnd != getLocation())
1827 return SourceRange(getOuterLocStart(), InitEnd);
1829 return DeclaratorDecl::getSourceRange();
1832 template<typename T>
1833 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1834 // C++ [dcl.link]p1: All function types, function names with external linkage,
1835 // and variable names with external linkage have a language linkage.
1836 if (!D.hasExternalFormalLinkage())
1837 return NoLanguageLinkage;
1839 // Language linkage is a C++ concept, but saying that everything else in C has
1840 // C language linkage fits the implementation nicely.
1841 ASTContext &Context = D.getASTContext();
1842 if (!Context.getLangOpts().CPlusPlus)
1843 return CLanguageLinkage;
1845 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1846 // language linkage of the names of class members and the function type of
1847 // class member functions.
1848 const DeclContext *DC = D.getDeclContext();
1850 return CXXLanguageLinkage;
1852 // If the first decl is in an extern "C" context, any other redeclaration
1853 // will have C language linkage. If the first one is not in an extern "C"
1854 // context, we would have reported an error for any other decl being in one.
1855 if (isFirstInExternCContext(&D))
1856 return CLanguageLinkage;
1857 return CXXLanguageLinkage;
1860 template<typename T>
1861 static bool isDeclExternC(const T &D) {
1862 // Since the context is ignored for class members, they can only have C++
1863 // language linkage or no language linkage.
1864 const DeclContext *DC = D.getDeclContext();
1865 if (DC->isRecord()) {
1866 assert(D.getASTContext().getLangOpts().CPlusPlus);
1870 return D.getLanguageLinkage() == CLanguageLinkage;
1873 LanguageLinkage VarDecl::getLanguageLinkage() const {
1874 return getDeclLanguageLinkage(*this);
1877 bool VarDecl::isExternC() const {
1878 return isDeclExternC(*this);
1881 bool VarDecl::isInExternCContext() const {
1882 return getLexicalDeclContext()->isExternCContext();
1885 bool VarDecl::isInExternCXXContext() const {
1886 return getLexicalDeclContext()->isExternCXXContext();
1889 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1891 VarDecl::DefinitionKind
1892 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
1893 // C++ [basic.def]p2:
1894 // A declaration is a definition unless [...] it contains the 'extern'
1895 // specifier or a linkage-specification and neither an initializer [...],
1896 // it declares a static data member in a class declaration [...].
1897 // C++1y [temp.expl.spec]p15:
1898 // An explicit specialization of a static data member or an explicit
1899 // specialization of a static data member template is a definition if the
1900 // declaration includes an initializer; otherwise, it is a declaration.
1902 // FIXME: How do you declare (but not define) a partial specialization of
1903 // a static data member template outside the containing class?
1904 if (isStaticDataMember()) {
1905 if (isOutOfLine() &&
1907 // If the first declaration is out-of-line, this may be an
1908 // instantiation of an out-of-line partial specialization of a variable
1909 // template for which we have not yet instantiated the initializer.
1910 (getFirstDecl()->isOutOfLine()
1911 ? getTemplateSpecializationKind() == TSK_Undeclared
1912 : getTemplateSpecializationKind() !=
1913 TSK_ExplicitSpecialization) ||
1914 isa<VarTemplatePartialSpecializationDecl>(this)))
1917 return DeclarationOnly;
1920 // A definition of an identifier is a declaration for that identifier that
1921 // [...] causes storage to be reserved for that object.
1922 // Note: that applies for all non-file-scope objects.
1924 // If the declaration of an identifier for an object has file scope and an
1925 // initializer, the declaration is an external definition for the identifier
1929 if (hasAttr<AliasAttr>())
1932 if (const auto *SAA = getAttr<SelectAnyAttr>())
1933 if (!SAA->isInherited())
1936 // A variable template specialization (other than a static data member
1937 // template or an explicit specialization) is a declaration until we
1938 // instantiate its initializer.
1939 if (isa<VarTemplateSpecializationDecl>(this) &&
1940 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1941 return DeclarationOnly;
1943 if (hasExternalStorage())
1944 return DeclarationOnly;
1947 // A declaration directly contained in a linkage-specification is treated
1948 // as if it contains the extern specifier for the purpose of determining
1949 // the linkage of the declared name and whether it is a definition.
1950 if (isSingleLineLanguageLinkage(*this))
1951 return DeclarationOnly;
1954 // A declaration of an object that has file scope without an initializer,
1955 // and without a storage class specifier or the scs 'static', constitutes
1956 // a tentative definition.
1957 // No such thing in C++.
1958 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1959 return TentativeDefinition;
1961 // What's left is (in C, block-scope) declarations without initializers or
1962 // external storage. These are definitions.
1966 VarDecl *VarDecl::getActingDefinition() {
1967 DefinitionKind Kind = isThisDeclarationADefinition();
1968 if (Kind != TentativeDefinition)
1971 VarDecl *LastTentative = nullptr;
1972 VarDecl *First = getFirstDecl();
1973 for (auto I : First->redecls()) {
1974 Kind = I->isThisDeclarationADefinition();
1975 if (Kind == Definition)
1977 else if (Kind == TentativeDefinition)
1980 return LastTentative;
1983 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1984 VarDecl *First = getFirstDecl();
1985 for (auto I : First->redecls()) {
1986 if (I->isThisDeclarationADefinition(C) == Definition)
1992 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1993 DefinitionKind Kind = DeclarationOnly;
1995 const VarDecl *First = getFirstDecl();
1996 for (auto I : First->redecls()) {
1997 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1998 if (Kind == Definition)
2005 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2006 for (auto I : redecls()) {
2007 if (auto Expr = I->getInit()) {
2015 bool VarDecl::isOutOfLine() const {
2016 if (Decl::isOutOfLine())
2019 if (!isStaticDataMember())
2022 // If this static data member was instantiated from a static data member of
2023 // a class template, check whether that static data member was defined
2025 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2026 return VD->isOutOfLine();
2031 VarDecl *VarDecl::getOutOfLineDefinition() {
2032 if (!isStaticDataMember())
2035 for (auto RD : redecls()) {
2036 if (RD->getLexicalDeclContext()->isFileContext())
2043 void VarDecl::setInit(Expr *I) {
2044 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2045 Eval->~EvaluatedStmt();
2046 getASTContext().Deallocate(Eval);
2052 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
2053 const LangOptions &Lang = C.getLangOpts();
2055 if (!Lang.CPlusPlus)
2058 // In C++11, any variable of reference type can be used in a constant
2059 // expression if it is initialized by a constant expression.
2060 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2063 // Only const objects can be used in constant expressions in C++. C++98 does
2064 // not require the variable to be non-volatile, but we consider this to be a
2066 if (!getType().isConstQualified() || getType().isVolatileQualified())
2069 // In C++, const, non-volatile variables of integral or enumeration types
2070 // can be used in constant expressions.
2071 if (getType()->isIntegralOrEnumerationType())
2074 // Additionally, in C++11, non-volatile constexpr variables can be used in
2075 // constant expressions.
2076 return Lang.CPlusPlus11 && isConstexpr();
2079 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2080 /// form, which contains extra information on the evaluated value of the
2082 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2083 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2085 Stmt *S = Init.get<Stmt *>();
2086 // Note: EvaluatedStmt contains an APValue, which usually holds
2087 // resources not allocated from the ASTContext. We need to do some
2088 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2089 // where we can detect whether there's anything to clean up or not.
2090 Eval = new (getASTContext()) EvaluatedStmt;
2097 APValue *VarDecl::evaluateValue() const {
2098 SmallVector<PartialDiagnosticAt, 8> Notes;
2099 return evaluateValue(Notes);
2103 // Destroy an APValue that was allocated in an ASTContext.
2104 void DestroyAPValue(void* UntypedValue) {
2105 static_cast<APValue*>(UntypedValue)->~APValue();
2109 APValue *VarDecl::evaluateValue(
2110 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2111 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2113 // We only produce notes indicating why an initializer is non-constant the
2114 // first time it is evaluated. FIXME: The notes won't always be emitted the
2115 // first time we try evaluation, so might not be produced at all.
2116 if (Eval->WasEvaluated)
2117 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2119 const Expr *Init = cast<Expr>(Eval->Value);
2120 assert(!Init->isValueDependent());
2122 if (Eval->IsEvaluating) {
2123 // FIXME: Produce a diagnostic for self-initialization.
2124 Eval->CheckedICE = true;
2125 Eval->IsICE = false;
2129 Eval->IsEvaluating = true;
2131 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2134 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2135 // or that it's empty (so that there's nothing to clean up) if evaluation
2138 Eval->Evaluated = APValue();
2139 else if (Eval->Evaluated.needsCleanup())
2140 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
2142 Eval->IsEvaluating = false;
2143 Eval->WasEvaluated = true;
2145 // In C++11, we have determined whether the initializer was a constant
2146 // expression as a side-effect.
2147 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2148 Eval->CheckedICE = true;
2149 Eval->IsICE = Result && Notes.empty();
2152 return Result ? &Eval->Evaluated : nullptr;
2155 bool VarDecl::checkInitIsICE() const {
2156 // Initializers of weak variables are never ICEs.
2160 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2161 if (Eval->CheckedICE)
2162 // We have already checked whether this subexpression is an
2163 // integral constant expression.
2166 const Expr *Init = cast<Expr>(Eval->Value);
2167 assert(!Init->isValueDependent());
2169 // In C++11, evaluate the initializer to check whether it's a constant
2171 if (getASTContext().getLangOpts().CPlusPlus11) {
2172 SmallVector<PartialDiagnosticAt, 8> Notes;
2173 evaluateValue(Notes);
2177 // It's an ICE whether or not the definition we found is
2178 // out-of-line. See DR 721 and the discussion in Clang PR
2179 // 6206 for details.
2181 if (Eval->CheckingICE)
2183 Eval->CheckingICE = true;
2185 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2186 Eval->CheckingICE = false;
2187 Eval->CheckedICE = true;
2191 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2192 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2193 return cast<VarDecl>(MSI->getInstantiatedFrom());
2198 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2199 if (const VarTemplateSpecializationDecl *Spec =
2200 dyn_cast<VarTemplateSpecializationDecl>(this))
2201 return Spec->getSpecializationKind();
2203 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2204 return MSI->getTemplateSpecializationKind();
2206 return TSK_Undeclared;
2209 SourceLocation VarDecl::getPointOfInstantiation() const {
2210 if (const VarTemplateSpecializationDecl *Spec =
2211 dyn_cast<VarTemplateSpecializationDecl>(this))
2212 return Spec->getPointOfInstantiation();
2214 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2215 return MSI->getPointOfInstantiation();
2217 return SourceLocation();
2220 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2221 return getASTContext().getTemplateOrSpecializationInfo(this)
2222 .dyn_cast<VarTemplateDecl *>();
2225 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2226 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2229 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2230 if (isStaticDataMember())
2232 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2233 return getASTContext().getTemplateOrSpecializationInfo(this)
2234 .dyn_cast<MemberSpecializationInfo *>();
2238 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2239 SourceLocation PointOfInstantiation) {
2240 assert((isa<VarTemplateSpecializationDecl>(this) ||
2241 getMemberSpecializationInfo()) &&
2242 "not a variable or static data member template specialization");
2244 if (VarTemplateSpecializationDecl *Spec =
2245 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2246 Spec->setSpecializationKind(TSK);
2247 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2248 Spec->getPointOfInstantiation().isInvalid())
2249 Spec->setPointOfInstantiation(PointOfInstantiation);
2252 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2253 MSI->setTemplateSpecializationKind(TSK);
2254 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2255 MSI->getPointOfInstantiation().isInvalid())
2256 MSI->setPointOfInstantiation(PointOfInstantiation);
2261 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2262 TemplateSpecializationKind TSK) {
2263 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2264 "Previous template or instantiation?");
2265 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2268 //===----------------------------------------------------------------------===//
2269 // ParmVarDecl Implementation
2270 //===----------------------------------------------------------------------===//
2272 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2273 SourceLocation StartLoc,
2274 SourceLocation IdLoc, IdentifierInfo *Id,
2275 QualType T, TypeSourceInfo *TInfo,
2276 StorageClass S, Expr *DefArg) {
2277 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2281 QualType ParmVarDecl::getOriginalType() const {
2282 TypeSourceInfo *TSI = getTypeSourceInfo();
2283 QualType T = TSI ? TSI->getType() : getType();
2284 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2285 return DT->getOriginalType();
2289 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2291 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2292 nullptr, QualType(), nullptr, SC_None, nullptr);
2295 SourceRange ParmVarDecl::getSourceRange() const {
2296 if (!hasInheritedDefaultArg()) {
2297 SourceRange ArgRange = getDefaultArgRange();
2298 if (ArgRange.isValid())
2299 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2302 // DeclaratorDecl considers the range of postfix types as overlapping with the
2303 // declaration name, but this is not the case with parameters in ObjC methods.
2304 if (isa<ObjCMethodDecl>(getDeclContext()))
2305 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2307 return DeclaratorDecl::getSourceRange();
2310 Expr *ParmVarDecl::getDefaultArg() {
2311 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2312 assert(!hasUninstantiatedDefaultArg() &&
2313 "Default argument is not yet instantiated!");
2315 Expr *Arg = getInit();
2316 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2317 return E->getSubExpr();
2322 SourceRange ParmVarDecl::getDefaultArgRange() const {
2323 if (const Expr *E = getInit())
2324 return E->getSourceRange();
2326 if (hasUninstantiatedDefaultArg())
2327 return getUninstantiatedDefaultArg()->getSourceRange();
2329 return SourceRange();
2332 bool ParmVarDecl::isParameterPack() const {
2333 return isa<PackExpansionType>(getType());
2336 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2337 getASTContext().setParameterIndex(this, parameterIndex);
2338 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2341 unsigned ParmVarDecl::getParameterIndexLarge() const {
2342 return getASTContext().getParameterIndex(this);
2345 //===----------------------------------------------------------------------===//
2346 // FunctionDecl Implementation
2347 //===----------------------------------------------------------------------===//
2349 void FunctionDecl::getNameForDiagnostic(
2350 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2351 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2352 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2354 TemplateSpecializationType::PrintTemplateArgumentList(
2355 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2358 bool FunctionDecl::isVariadic() const {
2359 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2360 return FT->isVariadic();
2364 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2365 for (auto I : redecls()) {
2366 if (I->Body || I->IsLateTemplateParsed) {
2375 bool FunctionDecl::hasTrivialBody() const
2377 Stmt *S = getBody();
2379 // Since we don't have a body for this function, we don't know if it's
2384 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2389 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2390 for (auto I : redecls()) {
2391 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2392 I->hasAttr<AliasAttr>()) {
2393 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2401 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2402 if (!hasBody(Definition))
2405 if (Definition->Body)
2406 return Definition->Body.get(getASTContext().getExternalSource());
2411 void FunctionDecl::setBody(Stmt *B) {
2414 EndRangeLoc = B->getLocEnd();
2417 void FunctionDecl::setPure(bool P) {
2420 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2421 Parent->markedVirtualFunctionPure();
2424 template<std::size_t Len>
2425 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2426 IdentifierInfo *II = ND->getIdentifier();
2427 return II && II->isStr(Str);
2430 bool FunctionDecl::isMain() const {
2431 const TranslationUnitDecl *tunit =
2432 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2434 !tunit->getASTContext().getLangOpts().Freestanding &&
2435 isNamed(this, "main");
2438 bool FunctionDecl::isMSVCRTEntryPoint() const {
2439 const TranslationUnitDecl *TUnit =
2440 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2444 // Even though we aren't really targeting MSVCRT if we are freestanding,
2445 // semantic analysis for these functions remains the same.
2447 // MSVCRT entry points only exist on MSVCRT targets.
2448 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2451 // Nameless functions like constructors cannot be entry points.
2452 if (!getIdentifier())
2455 return llvm::StringSwitch<bool>(getName())
2456 .Cases("main", // an ANSI console app
2457 "wmain", // a Unicode console App
2458 "WinMain", // an ANSI GUI app
2459 "wWinMain", // a Unicode GUI app
2465 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2466 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2467 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2468 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2469 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2470 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2472 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2475 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2476 if (proto->getNumParams() != 2 || proto->isVariadic())
2479 ASTContext &Context =
2480 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2483 // The result type and first argument type are constant across all
2484 // these operators. The second argument must be exactly void*.
2485 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2488 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2489 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2491 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2492 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2493 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2494 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2497 if (isa<CXXRecordDecl>(getDeclContext()))
2500 // This can only fail for an invalid 'operator new' declaration.
2501 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2504 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2505 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
2508 // If this is a single-parameter function, it must be a replaceable global
2509 // allocation or deallocation function.
2510 if (FPT->getNumParams() == 1)
2513 // Otherwise, we're looking for a second parameter whose type is
2514 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2515 QualType Ty = FPT->getParamType(1);
2516 ASTContext &Ctx = getASTContext();
2517 if (Ctx.getLangOpts().SizedDeallocation &&
2518 Ctx.hasSameType(Ty, Ctx.getSizeType()))
2520 if (!Ty->isReferenceType())
2522 Ty = Ty->getPointeeType();
2523 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2525 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2526 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
2529 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2530 return getDeclLanguageLinkage(*this);
2533 bool FunctionDecl::isExternC() const {
2534 return isDeclExternC(*this);
2537 bool FunctionDecl::isInExternCContext() const {
2538 return getLexicalDeclContext()->isExternCContext();
2541 bool FunctionDecl::isInExternCXXContext() const {
2542 return getLexicalDeclContext()->isExternCXXContext();
2545 bool FunctionDecl::isGlobal() const {
2546 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2547 return Method->isStatic();
2549 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2552 for (const DeclContext *DC = getDeclContext();
2554 DC = DC->getParent()) {
2555 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2556 if (!Namespace->getDeclName())
2565 bool FunctionDecl::isNoReturn() const {
2566 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2567 hasAttr<C11NoReturnAttr>() ||
2568 getType()->getAs<FunctionType>()->getNoReturnAttr();
2572 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2573 redeclarable_base::setPreviousDecl(PrevDecl);
2575 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2576 FunctionTemplateDecl *PrevFunTmpl
2577 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2578 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2579 FunTmpl->setPreviousDecl(PrevFunTmpl);
2582 if (PrevDecl && PrevDecl->IsInline)
2586 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2588 /// \brief Returns a value indicating whether this function
2589 /// corresponds to a builtin function.
2591 /// The function corresponds to a built-in function if it is
2592 /// declared at translation scope or within an extern "C" block and
2593 /// its name matches with the name of a builtin. The returned value
2594 /// will be 0 for functions that do not correspond to a builtin, a
2595 /// value of type \c Builtin::ID if in the target-independent range
2596 /// \c [1,Builtin::First), or a target-specific builtin value.
2597 unsigned FunctionDecl::getBuiltinID() const {
2598 if (!getIdentifier())
2601 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2605 ASTContext &Context = getASTContext();
2606 if (Context.getLangOpts().CPlusPlus) {
2607 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2608 getFirstDecl()->getDeclContext());
2609 // In C++, the first declaration of a builtin is always inside an implicit
2611 // FIXME: A recognised library function may not be directly in an extern "C"
2612 // declaration, for instance "extern "C" { namespace std { decl } }".
2614 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2615 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2617 return Builtin::BI__GetExceptionInfo;
2620 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2624 // If the function is marked "overloadable", it has a different mangled name
2625 // and is not the C library function.
2626 if (hasAttr<OverloadableAttr>())
2629 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2632 // This function has the name of a known C library
2633 // function. Determine whether it actually refers to the C library
2634 // function or whether it just has the same name.
2636 // If this is a static function, it's not a builtin.
2637 if (getStorageClass() == SC_Static)
2644 /// getNumParams - Return the number of parameters this function must have
2645 /// based on its FunctionType. This is the length of the ParamInfo array
2646 /// after it has been created.
2647 unsigned FunctionDecl::getNumParams() const {
2648 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2649 return FPT ? FPT->getNumParams() : 0;
2652 void FunctionDecl::setParams(ASTContext &C,
2653 ArrayRef<ParmVarDecl *> NewParamInfo) {
2654 assert(!ParamInfo && "Already has param info!");
2655 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2657 // Zero params -> null pointer.
2658 if (!NewParamInfo.empty()) {
2659 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2660 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2664 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2665 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2667 if (!NewDecls.empty()) {
2668 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2669 std::copy(NewDecls.begin(), NewDecls.end(), A);
2670 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
2671 // Move declarations introduced in prototype to the function context.
2672 for (auto I : NewDecls) {
2673 DeclContext *DC = I->getDeclContext();
2674 // Forward-declared reference to an enumeration is not added to
2675 // declaration scope, so skip declaration that is absent from its
2676 // declaration contexts.
2677 if (DC->containsDecl(I)) {
2679 I->setDeclContext(this);
2686 /// getMinRequiredArguments - Returns the minimum number of arguments
2687 /// needed to call this function. This may be fewer than the number of
2688 /// function parameters, if some of the parameters have default
2689 /// arguments (in C++) or are parameter packs (C++11).
2690 unsigned FunctionDecl::getMinRequiredArguments() const {
2691 if (!getASTContext().getLangOpts().CPlusPlus)
2692 return getNumParams();
2694 unsigned NumRequiredArgs = 0;
2695 for (auto *Param : params())
2696 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2698 return NumRequiredArgs;
2701 /// \brief The combination of the extern and inline keywords under MSVC forces
2702 /// the function to be required.
2704 /// Note: This function assumes that we will only get called when isInlined()
2705 /// would return true for this FunctionDecl.
2706 bool FunctionDecl::isMSExternInline() const {
2707 assert(isInlined() && "expected to get called on an inlined function!");
2709 const ASTContext &Context = getASTContext();
2710 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
2713 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2714 FD = FD->getPreviousDecl())
2715 if (FD->getStorageClass() == SC_Extern)
2721 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2722 if (Redecl->getStorageClass() != SC_Extern)
2725 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2726 FD = FD->getPreviousDecl())
2727 if (FD->getStorageClass() == SC_Extern)
2733 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2734 // Only consider file-scope declarations in this test.
2735 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2738 // Only consider explicit declarations; the presence of a builtin for a
2739 // libcall shouldn't affect whether a definition is externally visible.
2740 if (Redecl->isImplicit())
2743 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2744 return true; // Not an inline definition
2749 /// \brief For a function declaration in C or C++, determine whether this
2750 /// declaration causes the definition to be externally visible.
2752 /// For instance, this determines if adding the current declaration to the set
2753 /// of redeclarations of the given functions causes
2754 /// isInlineDefinitionExternallyVisible to change from false to true.
2755 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2756 assert(!doesThisDeclarationHaveABody() &&
2757 "Must have a declaration without a body.");
2759 ASTContext &Context = getASTContext();
2761 if (Context.getLangOpts().MSVCCompat) {
2762 const FunctionDecl *Definition;
2763 if (hasBody(Definition) && Definition->isInlined() &&
2764 redeclForcesDefMSVC(this))
2768 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2769 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2770 // an externally visible definition.
2772 // FIXME: What happens if gnu_inline gets added on after the first
2774 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2777 const FunctionDecl *Prev = this;
2778 bool FoundBody = false;
2779 while ((Prev = Prev->getPreviousDecl())) {
2780 FoundBody |= Prev->Body.isValid();
2783 // If it's not the case that both 'inline' and 'extern' are
2784 // specified on the definition, then it is always externally visible.
2785 if (!Prev->isInlineSpecified() ||
2786 Prev->getStorageClass() != SC_Extern)
2788 } else if (Prev->isInlineSpecified() &&
2789 Prev->getStorageClass() != SC_Extern) {
2796 if (Context.getLangOpts().CPlusPlus)
2800 // [...] If all of the file scope declarations for a function in a
2801 // translation unit include the inline function specifier without extern,
2802 // then the definition in that translation unit is an inline definition.
2803 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2805 const FunctionDecl *Prev = this;
2806 bool FoundBody = false;
2807 while ((Prev = Prev->getPreviousDecl())) {
2808 FoundBody |= Prev->Body.isValid();
2809 if (RedeclForcesDefC99(Prev))
2815 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2816 const TypeSourceInfo *TSI = getTypeSourceInfo();
2818 return SourceRange();
2819 FunctionTypeLoc FTL =
2820 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2822 return SourceRange();
2824 // Skip self-referential return types.
2825 const SourceManager &SM = getASTContext().getSourceManager();
2826 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2827 SourceLocation Boundary = getNameInfo().getLocStart();
2828 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2829 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2830 return SourceRange();
2835 bool FunctionDecl::hasUnusedResultAttr() const {
2836 QualType RetType = getReturnType();
2837 if (RetType->isRecordType()) {
2838 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2839 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
2840 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2841 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2844 return hasAttr<WarnUnusedResultAttr>();
2847 /// \brief For an inline function definition in C, or for a gnu_inline function
2848 /// in C++, determine whether the definition will be externally visible.
2850 /// Inline function definitions are always available for inlining optimizations.
2851 /// However, depending on the language dialect, declaration specifiers, and
2852 /// attributes, the definition of an inline function may or may not be
2853 /// "externally" visible to other translation units in the program.
2855 /// In C99, inline definitions are not externally visible by default. However,
2856 /// if even one of the global-scope declarations is marked "extern inline", the
2857 /// inline definition becomes externally visible (C99 6.7.4p6).
2859 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2860 /// definition, we use the GNU semantics for inline, which are nearly the
2861 /// opposite of C99 semantics. In particular, "inline" by itself will create
2862 /// an externally visible symbol, but "extern inline" will not create an
2863 /// externally visible symbol.
2864 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2865 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2866 assert(isInlined() && "Function must be inline");
2867 ASTContext &Context = getASTContext();
2869 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2870 // Note: If you change the logic here, please change
2871 // doesDeclarationForceExternallyVisibleDefinition as well.
2873 // If it's not the case that both 'inline' and 'extern' are
2874 // specified on the definition, then this inline definition is
2875 // externally visible.
2876 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2879 // If any declaration is 'inline' but not 'extern', then this definition
2880 // is externally visible.
2881 for (auto Redecl : redecls()) {
2882 if (Redecl->isInlineSpecified() &&
2883 Redecl->getStorageClass() != SC_Extern)
2890 // The rest of this function is C-only.
2891 assert(!Context.getLangOpts().CPlusPlus &&
2892 "should not use C inline rules in C++");
2895 // [...] If all of the file scope declarations for a function in a
2896 // translation unit include the inline function specifier without extern,
2897 // then the definition in that translation unit is an inline definition.
2898 for (auto Redecl : redecls()) {
2899 if (RedeclForcesDefC99(Redecl))
2904 // An inline definition does not provide an external definition for the
2905 // function, and does not forbid an external definition in another
2906 // translation unit.
2910 /// getOverloadedOperator - Which C++ overloaded operator this
2911 /// function represents, if any.
2912 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2913 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2914 return getDeclName().getCXXOverloadedOperator();
2919 /// getLiteralIdentifier - The literal suffix identifier this function
2920 /// represents, if any.
2921 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2922 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2923 return getDeclName().getCXXLiteralIdentifier();
2928 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2929 if (TemplateOrSpecialization.isNull())
2930 return TK_NonTemplate;
2931 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2932 return TK_FunctionTemplate;
2933 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2934 return TK_MemberSpecialization;
2935 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2936 return TK_FunctionTemplateSpecialization;
2937 if (TemplateOrSpecialization.is
2938 <DependentFunctionTemplateSpecializationInfo*>())
2939 return TK_DependentFunctionTemplateSpecialization;
2941 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2944 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2945 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2946 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2952 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2954 TemplateSpecializationKind TSK) {
2955 assert(TemplateOrSpecialization.isNull() &&
2956 "Member function is already a specialization");
2957 MemberSpecializationInfo *Info
2958 = new (C) MemberSpecializationInfo(FD, TSK);
2959 TemplateOrSpecialization = Info;
2962 bool FunctionDecl::isImplicitlyInstantiable() const {
2963 // If the function is invalid, it can't be implicitly instantiated.
2964 if (isInvalidDecl())
2967 switch (getTemplateSpecializationKind()) {
2968 case TSK_Undeclared:
2969 case TSK_ExplicitInstantiationDefinition:
2972 case TSK_ImplicitInstantiation:
2975 // It is possible to instantiate TSK_ExplicitSpecialization kind
2976 // if the FunctionDecl has a class scope specialization pattern.
2977 case TSK_ExplicitSpecialization:
2978 return getClassScopeSpecializationPattern() != nullptr;
2980 case TSK_ExplicitInstantiationDeclaration:
2985 // Find the actual template from which we will instantiate.
2986 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2987 bool HasPattern = false;
2989 HasPattern = PatternDecl->hasBody(PatternDecl);
2991 // C++0x [temp.explicit]p9:
2992 // Except for inline functions, other explicit instantiation declarations
2993 // have the effect of suppressing the implicit instantiation of the entity
2994 // to which they refer.
2995 if (!HasPattern || !PatternDecl)
2998 return PatternDecl->isInlined();
3001 bool FunctionDecl::isTemplateInstantiation() const {
3002 switch (getTemplateSpecializationKind()) {
3003 case TSK_Undeclared:
3004 case TSK_ExplicitSpecialization:
3006 case TSK_ImplicitInstantiation:
3007 case TSK_ExplicitInstantiationDeclaration:
3008 case TSK_ExplicitInstantiationDefinition:
3011 llvm_unreachable("All TSK values handled.");
3014 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3015 // Handle class scope explicit specialization special case.
3016 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3017 return getClassScopeSpecializationPattern();
3019 // If this is a generic lambda call operator specialization, its
3020 // instantiation pattern is always its primary template's pattern
3021 // even if its primary template was instantiated from another
3022 // member template (which happens with nested generic lambdas).
3023 // Since a lambda's call operator's body is transformed eagerly,
3024 // we don't have to go hunting for a prototype definition template
3025 // (i.e. instantiated-from-member-template) to use as an instantiation
3028 if (isGenericLambdaCallOperatorSpecialization(
3029 dyn_cast<CXXMethodDecl>(this))) {
3030 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3031 "generated from a primary call operator "
3033 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3034 "A generic lambda call operator template must always have a body - "
3035 "even if instantiated from a prototype (i.e. as written) member "
3037 return getPrimaryTemplate()->getTemplatedDecl();
3040 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3041 while (Primary->getInstantiatedFromMemberTemplate()) {
3042 // If we have hit a point where the user provided a specialization of
3043 // this template, we're done looking.
3044 if (Primary->isMemberSpecialization())
3046 Primary = Primary->getInstantiatedFromMemberTemplate();
3049 return Primary->getTemplatedDecl();
3052 return getInstantiatedFromMemberFunction();
3055 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3056 if (FunctionTemplateSpecializationInfo *Info
3057 = TemplateOrSpecialization
3058 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3059 return Info->Template.getPointer();
3064 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3065 return getASTContext().getClassScopeSpecializationPattern(this);
3068 const TemplateArgumentList *
3069 FunctionDecl::getTemplateSpecializationArgs() const {
3070 if (FunctionTemplateSpecializationInfo *Info
3071 = TemplateOrSpecialization
3072 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3073 return Info->TemplateArguments;
3078 const ASTTemplateArgumentListInfo *
3079 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3080 if (FunctionTemplateSpecializationInfo *Info
3081 = TemplateOrSpecialization
3082 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3083 return Info->TemplateArgumentsAsWritten;
3089 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3090 FunctionTemplateDecl *Template,
3091 const TemplateArgumentList *TemplateArgs,
3093 TemplateSpecializationKind TSK,
3094 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3095 SourceLocation PointOfInstantiation) {
3096 assert(TSK != TSK_Undeclared &&
3097 "Must specify the type of function template specialization");
3098 FunctionTemplateSpecializationInfo *Info
3099 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3101 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3103 TemplateArgsAsWritten,
3104 PointOfInstantiation);
3105 TemplateOrSpecialization = Info;
3106 Template->addSpecialization(Info, InsertPos);
3110 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3111 const UnresolvedSetImpl &Templates,
3112 const TemplateArgumentListInfo &TemplateArgs) {
3113 assert(TemplateOrSpecialization.isNull());
3114 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3115 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
3116 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
3117 void *Buffer = Context.Allocate(Size);
3118 DependentFunctionTemplateSpecializationInfo *Info =
3119 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3121 TemplateOrSpecialization = Info;
3124 DependentFunctionTemplateSpecializationInfo::
3125 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3126 const TemplateArgumentListInfo &TArgs)
3127 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3128 static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
3129 "Trailing data is unaligned!");
3131 d.NumTemplates = Ts.size();
3132 d.NumArgs = TArgs.size();
3134 FunctionTemplateDecl **TsArray =
3135 const_cast<FunctionTemplateDecl**>(getTemplates());
3136 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3137 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3139 TemplateArgumentLoc *ArgsArray =
3140 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3141 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3142 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3145 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3146 // For a function template specialization, query the specialization
3147 // information object.
3148 FunctionTemplateSpecializationInfo *FTSInfo
3149 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3151 return FTSInfo->getTemplateSpecializationKind();
3153 MemberSpecializationInfo *MSInfo
3154 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3156 return MSInfo->getTemplateSpecializationKind();
3158 return TSK_Undeclared;
3162 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3163 SourceLocation PointOfInstantiation) {
3164 if (FunctionTemplateSpecializationInfo *FTSInfo
3165 = TemplateOrSpecialization.dyn_cast<
3166 FunctionTemplateSpecializationInfo*>()) {
3167 FTSInfo->setTemplateSpecializationKind(TSK);
3168 if (TSK != TSK_ExplicitSpecialization &&
3169 PointOfInstantiation.isValid() &&
3170 FTSInfo->getPointOfInstantiation().isInvalid())
3171 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3172 } else if (MemberSpecializationInfo *MSInfo
3173 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3174 MSInfo->setTemplateSpecializationKind(TSK);
3175 if (TSK != TSK_ExplicitSpecialization &&
3176 PointOfInstantiation.isValid() &&
3177 MSInfo->getPointOfInstantiation().isInvalid())
3178 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3180 llvm_unreachable("Function cannot have a template specialization kind");
3183 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3184 if (FunctionTemplateSpecializationInfo *FTSInfo
3185 = TemplateOrSpecialization.dyn_cast<
3186 FunctionTemplateSpecializationInfo*>())
3187 return FTSInfo->getPointOfInstantiation();
3188 else if (MemberSpecializationInfo *MSInfo
3189 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3190 return MSInfo->getPointOfInstantiation();
3192 return SourceLocation();
3195 bool FunctionDecl::isOutOfLine() const {
3196 if (Decl::isOutOfLine())
3199 // If this function was instantiated from a member function of a
3200 // class template, check whether that member function was defined out-of-line.
3201 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3202 const FunctionDecl *Definition;
3203 if (FD->hasBody(Definition))
3204 return Definition->isOutOfLine();
3207 // If this function was instantiated from a function template,
3208 // check whether that function template was defined out-of-line.
3209 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3210 const FunctionDecl *Definition;
3211 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3212 return Definition->isOutOfLine();
3218 SourceRange FunctionDecl::getSourceRange() const {
3219 return SourceRange(getOuterLocStart(), EndRangeLoc);
3222 unsigned FunctionDecl::getMemoryFunctionKind() const {
3223 IdentifierInfo *FnInfo = getIdentifier();
3228 // Builtin handling.
3229 switch (getBuiltinID()) {
3230 case Builtin::BI__builtin_memset:
3231 case Builtin::BI__builtin___memset_chk:
3232 case Builtin::BImemset:
3233 return Builtin::BImemset;
3235 case Builtin::BI__builtin_memcpy:
3236 case Builtin::BI__builtin___memcpy_chk:
3237 case Builtin::BImemcpy:
3238 return Builtin::BImemcpy;
3240 case Builtin::BI__builtin_memmove:
3241 case Builtin::BI__builtin___memmove_chk:
3242 case Builtin::BImemmove:
3243 return Builtin::BImemmove;
3245 case Builtin::BIstrlcpy:
3246 case Builtin::BI__builtin___strlcpy_chk:
3247 return Builtin::BIstrlcpy;
3249 case Builtin::BIstrlcat:
3250 case Builtin::BI__builtin___strlcat_chk:
3251 return Builtin::BIstrlcat;
3253 case Builtin::BI__builtin_memcmp:
3254 case Builtin::BImemcmp:
3255 return Builtin::BImemcmp;
3257 case Builtin::BI__builtin_strncpy:
3258 case Builtin::BI__builtin___strncpy_chk:
3259 case Builtin::BIstrncpy:
3260 return Builtin::BIstrncpy;
3262 case Builtin::BI__builtin_strncmp:
3263 case Builtin::BIstrncmp:
3264 return Builtin::BIstrncmp;
3266 case Builtin::BI__builtin_strncasecmp:
3267 case Builtin::BIstrncasecmp:
3268 return Builtin::BIstrncasecmp;
3270 case Builtin::BI__builtin_strncat:
3271 case Builtin::BI__builtin___strncat_chk:
3272 case Builtin::BIstrncat:
3273 return Builtin::BIstrncat;
3275 case Builtin::BI__builtin_strndup:
3276 case Builtin::BIstrndup:
3277 return Builtin::BIstrndup;
3279 case Builtin::BI__builtin_strlen:
3280 case Builtin::BIstrlen:
3281 return Builtin::BIstrlen;
3285 if (FnInfo->isStr("memset"))
3286 return Builtin::BImemset;
3287 else if (FnInfo->isStr("memcpy"))
3288 return Builtin::BImemcpy;
3289 else if (FnInfo->isStr("memmove"))
3290 return Builtin::BImemmove;
3291 else if (FnInfo->isStr("memcmp"))
3292 return Builtin::BImemcmp;
3293 else if (FnInfo->isStr("strncpy"))
3294 return Builtin::BIstrncpy;
3295 else if (FnInfo->isStr("strncmp"))
3296 return Builtin::BIstrncmp;
3297 else if (FnInfo->isStr("strncasecmp"))
3298 return Builtin::BIstrncasecmp;
3299 else if (FnInfo->isStr("strncat"))
3300 return Builtin::BIstrncat;
3301 else if (FnInfo->isStr("strndup"))
3302 return Builtin::BIstrndup;
3303 else if (FnInfo->isStr("strlen"))
3304 return Builtin::BIstrlen;
3311 //===----------------------------------------------------------------------===//
3312 // FieldDecl Implementation
3313 //===----------------------------------------------------------------------===//
3315 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3316 SourceLocation StartLoc, SourceLocation IdLoc,
3317 IdentifierInfo *Id, QualType T,
3318 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3319 InClassInitStyle InitStyle) {
3320 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3321 BW, Mutable, InitStyle);
3324 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3325 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3326 SourceLocation(), nullptr, QualType(), nullptr,
3327 nullptr, false, ICIS_NoInit);
3330 bool FieldDecl::isAnonymousStructOrUnion() const {
3331 if (!isImplicit() || getDeclName())
3334 if (const RecordType *Record = getType()->getAs<RecordType>())
3335 return Record->getDecl()->isAnonymousStructOrUnion();
3340 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3341 assert(isBitField() && "not a bitfield");
3342 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
3343 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3346 unsigned FieldDecl::getFieldIndex() const {
3347 const FieldDecl *Canonical = getCanonicalDecl();
3348 if (Canonical != this)
3349 return Canonical->getFieldIndex();
3351 if (CachedFieldIndex) return CachedFieldIndex - 1;
3354 const RecordDecl *RD = getParent();
3356 for (auto *Field : RD->fields()) {
3357 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3361 assert(CachedFieldIndex && "failed to find field in parent");
3362 return CachedFieldIndex - 1;
3365 SourceRange FieldDecl::getSourceRange() const {
3366 switch (InitStorage.getInt()) {
3367 // All three of these cases store an optional Expr*.
3368 case ISK_BitWidthOrNothing:
3369 case ISK_InClassCopyInit:
3370 case ISK_InClassListInit:
3371 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3372 return SourceRange(getInnerLocStart(), E->getLocEnd());
3375 case ISK_CapturedVLAType:
3376 return DeclaratorDecl::getSourceRange();
3378 llvm_unreachable("bad init storage kind");
3381 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3382 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3383 "capturing type in non-lambda or captured record.");
3384 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3385 InitStorage.getPointer() == nullptr &&
3386 "bit width, initializer or captured type already set");
3387 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3388 ISK_CapturedVLAType);
3391 //===----------------------------------------------------------------------===//
3392 // TagDecl Implementation
3393 //===----------------------------------------------------------------------===//
3395 SourceLocation TagDecl::getOuterLocStart() const {
3396 return getTemplateOrInnerLocStart(this);
3399 SourceRange TagDecl::getSourceRange() const {
3400 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3401 return SourceRange(getOuterLocStart(), E);
3404 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3406 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3407 NamedDeclOrQualifier = TDD;
3408 if (const Type *T = getTypeForDecl()) {
3410 assert(T->isLinkageValid());
3412 assert(isLinkageValid());
3415 void TagDecl::startDefinition() {
3416 IsBeingDefined = true;
3418 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3419 struct CXXRecordDecl::DefinitionData *Data =
3420 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3421 for (auto I : redecls())
3422 cast<CXXRecordDecl>(I)->DefinitionData = Data;
3426 void TagDecl::completeDefinition() {
3427 assert((!isa<CXXRecordDecl>(this) ||
3428 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3429 "definition completed but not started");
3431 IsCompleteDefinition = true;
3432 IsBeingDefined = false;
3434 if (ASTMutationListener *L = getASTMutationListener())
3435 L->CompletedTagDefinition(this);
3438 TagDecl *TagDecl::getDefinition() const {
3439 if (isCompleteDefinition())
3440 return const_cast<TagDecl *>(this);
3442 // If it's possible for us to have an out-of-date definition, check now.
3443 if (MayHaveOutOfDateDef) {
3444 if (IdentifierInfo *II = getIdentifier()) {
3445 if (II->isOutOfDate()) {
3446 updateOutOfDate(*II);
3451 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3452 return CXXRD->getDefinition();
3454 for (auto R : redecls())
3455 if (R->isCompleteDefinition())
3461 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3463 // Make sure the extended qualifier info is allocated.
3465 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3466 // Set qualifier info.
3467 getExtInfo()->QualifierLoc = QualifierLoc;
3469 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3471 if (getExtInfo()->NumTemplParamLists == 0) {
3472 getASTContext().Deallocate(getExtInfo());
3473 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
3476 getExtInfo()->QualifierLoc = QualifierLoc;
3481 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3482 unsigned NumTPLists,
3483 TemplateParameterList **TPLists) {
3484 assert(NumTPLists > 0);
3485 // Make sure the extended decl info is allocated.
3487 // Allocate external info struct.
3488 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3489 // Set the template parameter lists info.
3490 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3493 //===----------------------------------------------------------------------===//
3494 // EnumDecl Implementation
3495 //===----------------------------------------------------------------------===//
3497 void EnumDecl::anchor() { }
3499 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3500 SourceLocation StartLoc, SourceLocation IdLoc,
3502 EnumDecl *PrevDecl, bool IsScoped,
3503 bool IsScopedUsingClassTag, bool IsFixed) {
3504 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3505 IsScoped, IsScopedUsingClassTag,
3507 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3508 C.getTypeDeclType(Enum, PrevDecl);
3512 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3514 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3515 nullptr, nullptr, false, false, false);
3516 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3520 SourceRange EnumDecl::getIntegerTypeRange() const {
3521 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3522 return TI->getTypeLoc().getSourceRange();
3523 return SourceRange();
3526 void EnumDecl::completeDefinition(QualType NewType,
3527 QualType NewPromotionType,
3528 unsigned NumPositiveBits,
3529 unsigned NumNegativeBits) {
3530 assert(!isCompleteDefinition() && "Cannot redefine enums!");
3532 IntegerType = NewType.getTypePtr();
3533 PromotionType = NewPromotionType;
3534 setNumPositiveBits(NumPositiveBits);
3535 setNumNegativeBits(NumNegativeBits);
3536 TagDecl::completeDefinition();
3539 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3540 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3541 return MSI->getTemplateSpecializationKind();
3543 return TSK_Undeclared;
3546 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3547 SourceLocation PointOfInstantiation) {
3548 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3549 assert(MSI && "Not an instantiated member enumeration?");
3550 MSI->setTemplateSpecializationKind(TSK);
3551 if (TSK != TSK_ExplicitSpecialization &&
3552 PointOfInstantiation.isValid() &&
3553 MSI->getPointOfInstantiation().isInvalid())
3554 MSI->setPointOfInstantiation(PointOfInstantiation);
3557 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3558 if (SpecializationInfo)
3559 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3564 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3565 TemplateSpecializationKind TSK) {
3566 assert(!SpecializationInfo && "Member enum is already a specialization");
3567 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3570 //===----------------------------------------------------------------------===//
3571 // RecordDecl Implementation
3572 //===----------------------------------------------------------------------===//
3574 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3575 DeclContext *DC, SourceLocation StartLoc,
3576 SourceLocation IdLoc, IdentifierInfo *Id,
3577 RecordDecl *PrevDecl)
3578 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3579 HasFlexibleArrayMember = false;
3580 AnonymousStructOrUnion = false;
3581 HasObjectMember = false;
3582 HasVolatileMember = false;
3583 LoadedFieldsFromExternalStorage = false;
3584 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3587 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3588 SourceLocation StartLoc, SourceLocation IdLoc,
3589 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3590 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3591 StartLoc, IdLoc, Id, PrevDecl);
3592 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3594 C.getTypeDeclType(R, PrevDecl);
3598 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3600 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3601 SourceLocation(), nullptr, nullptr);
3602 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3606 bool RecordDecl::isInjectedClassName() const {
3607 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3608 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3611 bool RecordDecl::isLambda() const {
3612 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3613 return RD->isLambda();
3617 bool RecordDecl::isCapturedRecord() const {
3618 return hasAttr<CapturedRecordAttr>();
3621 void RecordDecl::setCapturedRecord() {
3622 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3625 RecordDecl::field_iterator RecordDecl::field_begin() const {
3626 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3627 LoadFieldsFromExternalStorage();
3629 return field_iterator(decl_iterator(FirstDecl));
3632 /// completeDefinition - Notes that the definition of this type is now
3634 void RecordDecl::completeDefinition() {
3635 assert(!isCompleteDefinition() && "Cannot redefine record!");
3636 TagDecl::completeDefinition();
3639 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3640 /// This which can be turned on with an attribute, pragma, or the
3641 /// -mms-bitfields command-line option.
3642 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3643 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
3646 static bool isFieldOrIndirectField(Decl::Kind K) {
3647 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3650 void RecordDecl::LoadFieldsFromExternalStorage() const {
3651 ExternalASTSource *Source = getASTContext().getExternalSource();
3652 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3654 // Notify that we have a RecordDecl doing some initialization.
3655 ExternalASTSource::Deserializing TheFields(Source);
3657 SmallVector<Decl*, 64> Decls;
3658 LoadedFieldsFromExternalStorage = true;
3659 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3664 case ELR_AlreadyLoaded:
3670 // Check that all decls we got were FieldDecls.
3671 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3672 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3678 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3679 /*FieldsAlreadyLoaded=*/false);
3682 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3683 ASTContext &Context = getASTContext();
3684 if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
3685 !Context.getLangOpts().SanitizeAddressFieldPadding)
3687 const auto &Blacklist = Context.getSanitizerBlacklist();
3688 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
3689 // We may be able to relax some of these requirements.
3690 int ReasonToReject = -1;
3691 if (!CXXRD || CXXRD->isExternCContext())
3692 ReasonToReject = 0; // is not C++.
3693 else if (CXXRD->hasAttr<PackedAttr>())
3694 ReasonToReject = 1; // is packed.
3695 else if (CXXRD->isUnion())
3696 ReasonToReject = 2; // is a union.
3697 else if (CXXRD->isTriviallyCopyable())
3698 ReasonToReject = 3; // is trivially copyable.
3699 else if (CXXRD->hasTrivialDestructor())
3700 ReasonToReject = 4; // has trivial destructor.
3701 else if (CXXRD->isStandardLayout())
3702 ReasonToReject = 5; // is standard layout.
3703 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3704 ReasonToReject = 6; // is in a blacklisted file.
3705 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3707 ReasonToReject = 7; // is blacklisted.
3710 if (ReasonToReject >= 0)
3711 Context.getDiagnostics().Report(
3713 diag::remark_sanitize_address_insert_extra_padding_rejected)
3714 << getQualifiedNameAsString() << ReasonToReject;
3716 Context.getDiagnostics().Report(
3718 diag::remark_sanitize_address_insert_extra_padding_accepted)
3719 << getQualifiedNameAsString();
3721 return ReasonToReject < 0;
3724 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3725 for (const auto *I : fields()) {
3726 if (I->getIdentifier())
3729 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3730 if (const FieldDecl *NamedDataMember =
3731 RT->getDecl()->findFirstNamedDataMember())
3732 return NamedDataMember;
3735 // We didn't find a named data member.
3740 //===----------------------------------------------------------------------===//
3741 // BlockDecl Implementation
3742 //===----------------------------------------------------------------------===//
3744 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3745 assert(!ParamInfo && "Already has param info!");
3747 // Zero params -> null pointer.
3748 if (!NewParamInfo.empty()) {
3749 NumParams = NewParamInfo.size();
3750 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3751 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3755 void BlockDecl::setCaptures(ASTContext &Context,
3756 const Capture *begin,
3758 bool capturesCXXThis) {
3759 CapturesCXXThis = capturesCXXThis;
3767 NumCaptures = end - begin;
3769 // Avoid new Capture[] because we don't want to provide a default
3771 size_t allocationSize = NumCaptures * sizeof(Capture);
3772 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3773 memcpy(buffer, begin, allocationSize);
3774 Captures = static_cast<Capture*>(buffer);
3777 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3778 for (const auto &I : captures())
3779 // Only auto vars can be captured, so no redeclaration worries.
3780 if (I.getVariable() == variable)
3786 SourceRange BlockDecl::getSourceRange() const {
3787 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3790 //===----------------------------------------------------------------------===//
3791 // Other Decl Allocation/Deallocation Method Implementations
3792 //===----------------------------------------------------------------------===//
3794 void TranslationUnitDecl::anchor() { }
3796 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3797 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
3800 void ExternCContextDecl::anchor() { }
3802 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3803 TranslationUnitDecl *DC) {
3804 return new (C, DC) ExternCContextDecl(DC);
3807 void LabelDecl::anchor() { }
3809 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3810 SourceLocation IdentL, IdentifierInfo *II) {
3811 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
3814 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3815 SourceLocation IdentL, IdentifierInfo *II,
3816 SourceLocation GnuLabelL) {
3817 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3818 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
3821 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3822 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3826 void LabelDecl::setMSAsmLabel(StringRef Name) {
3827 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3828 memcpy(Buffer, Name.data(), Name.size());
3829 Buffer[Name.size()] = '\0';
3833 void ValueDecl::anchor() { }
3835 bool ValueDecl::isWeak() const {
3836 for (const auto *I : attrs())
3837 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3840 return isWeakImported();
3843 void ImplicitParamDecl::anchor() { }
3845 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3846 SourceLocation IdLoc,
3849 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
3852 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3854 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
3858 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3859 SourceLocation StartLoc,
3860 const DeclarationNameInfo &NameInfo,
3861 QualType T, TypeSourceInfo *TInfo,
3863 bool isInlineSpecified,
3864 bool hasWrittenPrototype,
3865 bool isConstexprSpecified) {
3867 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3868 SC, isInlineSpecified, isConstexprSpecified);
3869 New->HasWrittenPrototype = hasWrittenPrototype;
3873 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3874 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
3875 DeclarationNameInfo(), QualType(), nullptr,
3876 SC_None, false, false);
3879 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3880 return new (C, DC) BlockDecl(DC, L);
3883 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3884 return new (C, ID) BlockDecl(nullptr, SourceLocation());
3887 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3888 unsigned NumParams) {
3889 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3890 CapturedDecl(DC, NumParams);
3893 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3894 unsigned NumParams) {
3895 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3896 CapturedDecl(nullptr, NumParams);
3899 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3901 IdentifierInfo *Id, QualType T,
3902 Expr *E, const llvm::APSInt &V) {
3903 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3907 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3908 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3909 QualType(), nullptr, llvm::APSInt());
3912 void IndirectFieldDecl::anchor() { }
3915 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3916 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3918 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3921 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3923 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3924 DeclarationName(), QualType(), nullptr,
3928 SourceRange EnumConstantDecl::getSourceRange() const {
3929 SourceLocation End = getLocation();
3931 End = Init->getLocEnd();
3932 return SourceRange(getLocation(), End);
3935 void TypeDecl::anchor() { }
3937 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3938 SourceLocation StartLoc, SourceLocation IdLoc,
3939 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3940 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3943 void TypedefNameDecl::anchor() { }
3945 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
3946 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
3947 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
3948 auto *ThisTypedef = this;
3949 if (AnyRedecl && OwningTypedef) {
3950 OwningTypedef = OwningTypedef->getCanonicalDecl();
3951 ThisTypedef = ThisTypedef->getCanonicalDecl();
3953 if (OwningTypedef == ThisTypedef)
3954 return TT->getDecl();
3960 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3961 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
3965 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3966 SourceLocation StartLoc,
3967 SourceLocation IdLoc, IdentifierInfo *Id,
3968 TypeSourceInfo *TInfo) {
3969 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
3972 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3973 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3974 SourceLocation(), nullptr, nullptr);
3977 SourceRange TypedefDecl::getSourceRange() const {
3978 SourceLocation RangeEnd = getLocation();
3979 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3980 if (typeIsPostfix(TInfo->getType()))
3981 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3983 return SourceRange(getLocStart(), RangeEnd);
3986 SourceRange TypeAliasDecl::getSourceRange() const {
3987 SourceLocation RangeEnd = getLocStart();
3988 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3989 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3990 return SourceRange(getLocStart(), RangeEnd);
3993 void FileScopeAsmDecl::anchor() { }
3995 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3997 SourceLocation AsmLoc,
3998 SourceLocation RParenLoc) {
3999 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4002 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4004 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4008 void EmptyDecl::anchor() {}
4010 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4011 return new (C, DC) EmptyDecl(DC, L);
4014 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4015 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4018 //===----------------------------------------------------------------------===//
4019 // ImportDecl Implementation
4020 //===----------------------------------------------------------------------===//
4022 /// \brief Retrieve the number of module identifiers needed to name the given
4024 static unsigned getNumModuleIdentifiers(Module *Mod) {
4025 unsigned Result = 1;
4026 while (Mod->Parent) {
4033 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4035 ArrayRef<SourceLocation> IdentifierLocs)
4036 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
4039 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4040 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
4041 memcpy(StoredLocs, IdentifierLocs.data(),
4042 IdentifierLocs.size() * sizeof(SourceLocation));
4045 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4046 Module *Imported, SourceLocation EndLoc)
4047 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
4050 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
4053 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4054 SourceLocation StartLoc, Module *Imported,
4055 ArrayRef<SourceLocation> IdentifierLocs) {
4056 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
4057 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4060 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4061 SourceLocation StartLoc,
4063 SourceLocation EndLoc) {
4064 ImportDecl *Import =
4065 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
4067 Import->setImplicit();
4071 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4072 unsigned NumLocations) {
4073 return new (C, ID, NumLocations * sizeof(SourceLocation))
4074 ImportDecl(EmptyShell());
4077 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4078 if (!ImportedAndComplete.getInt())
4081 const SourceLocation *StoredLocs
4082 = reinterpret_cast<const SourceLocation *>(this + 1);
4083 return llvm::makeArrayRef(StoredLocs,
4084 getNumModuleIdentifiers(getImportedModule()));
4087 SourceRange ImportDecl::getSourceRange() const {
4088 if (!ImportedAndComplete.getInt())
4089 return SourceRange(getLocation(),
4090 *reinterpret_cast<const SourceLocation *>(this + 1));
4092 return SourceRange(getLocation(), getIdentifierLocs().back());