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/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/type_traits.h"
35 using namespace clang;
37 //===----------------------------------------------------------------------===//
38 // NamedDecl Implementation
39 //===----------------------------------------------------------------------===//
41 // Visibility rules aren't rigorously externally specified, but here
42 // are the basic principles behind what we implement:
44 // 1. An explicit visibility attribute is generally a direct expression
45 // of the user's intent and should be honored. Only the innermost
46 // visibility attribute applies. If no visibility attribute applies,
47 // global visibility settings are considered.
49 // 2. There is one caveat to the above: on or in a template pattern,
50 // an explicit visibility attribute is just a default rule, and
51 // visibility can be decreased by the visibility of template
52 // arguments. But this, too, has an exception: an attribute on an
53 // explicit specialization or instantiation causes all the visibility
54 // restrictions of the template arguments to be ignored.
56 // 3. A variable that does not otherwise have explicit visibility can
57 // be restricted by the visibility of its type.
59 // 4. A visibility restriction is explicit if it comes from an
60 // attribute (or something like it), not a global visibility setting.
61 // When emitting a reference to an external symbol, visibility
62 // restrictions are ignored unless they are explicit.
64 // 5. When computing the visibility of a non-type, including a
65 // non-type member of a class, only non-type visibility restrictions
66 // are considered: the 'visibility' attribute, global value-visibility
67 // settings, and a few special cases like __private_extern.
69 // 6. When computing the visibility of a type, including a type member
70 // of a class, only type visibility restrictions are considered:
71 // the 'type_visibility' attribute and global type-visibility settings.
72 // However, a 'visibility' attribute counts as a 'type_visibility'
73 // attribute on any declaration that only has the former.
75 // The visibility of a "secondary" entity, like a template argument,
76 // is computed using the kind of that entity, not the kind of the
77 // primary entity for which we are computing visibility. For example,
78 // the visibility of a specialization of either of these templates:
79 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
80 // template <class T, bool (&compare)(T, X)> class matcher;
81 // is restricted according to the type visibility of the argument 'T',
82 // the type visibility of 'bool(&)(T,X)', and the value visibility of
83 // the argument function 'compare'. That 'has_match' is a value
84 // and 'matcher' is a type only matters when looking for attributes
85 // and settings from the immediate context.
87 const unsigned IgnoreExplicitVisibilityBit = 2;
89 /// Kinds of LV computation. The linkage side of the computation is
90 /// always the same, but different things can change how visibility is
92 enum LVComputationKind {
93 /// Do an LV computation for, ultimately, a type.
94 /// Visibility may be restricted by type visibility settings and
95 /// the visibility of template arguments.
96 LVForType = NamedDecl::VisibilityForType,
98 /// Do an LV computation for, ultimately, a non-type declaration.
99 /// Visibility may be restricted by value visibility settings and
100 /// the visibility of template arguments.
101 LVForValue = NamedDecl::VisibilityForValue,
103 /// Do an LV computation for, ultimately, a type that already has
104 /// some sort of explicit visibility. Visibility may only be
105 /// restricted by the visibility of template arguments.
106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
108 /// Do an LV computation for, ultimately, a non-type declaration
109 /// that already has some sort of explicit visibility. Visibility
110 /// may only be restricted by the visibility of template arguments.
111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit)
114 /// Does this computation kind permit us to consider additional
115 /// visibility settings from attributes and the like?
116 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
120 /// Given an LVComputationKind, return one of the same type/value sort
121 /// that records that it already has explicit visibility.
122 static LVComputationKind
123 withExplicitVisibilityAlready(LVComputationKind oldKind) {
124 LVComputationKind newKind =
125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
127 assert(oldKind != LVForType || newKind == LVForExplicitType);
128 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
134 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
136 assert(!hasExplicitVisibilityAlready(kind) &&
137 "asking for explicit visibility when we shouldn't be");
138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
141 /// Is the given declaration a "type" or a "value" for the purposes of
142 /// visibility computation?
143 static bool usesTypeVisibility(const NamedDecl *D) {
144 return isa<TypeDecl>(D) ||
145 isa<ClassTemplateDecl>(D) ||
146 isa<ObjCInterfaceDecl>(D);
149 /// Does the given declaration have member specialization information,
150 /// and if so, is it an explicit specialization?
151 template <class T> static typename
152 llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
154 isExplicitMemberSpecialization(const T *D) {
155 if (const MemberSpecializationInfo *member =
156 D->getMemberSpecializationInfo()) {
157 return member->isExplicitSpecialization();
162 /// For templates, this question is easier: a member template can't be
163 /// explicitly instantiated, so there's a single bit indicating whether
164 /// or not this is an explicit member specialization.
165 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
166 return D->isMemberSpecialization();
169 /// Given a visibility attribute, return the explicit visibility
170 /// associated with it.
172 static Visibility getVisibilityFromAttr(const T *attr) {
173 switch (attr->getVisibility()) {
175 return DefaultVisibility;
177 return HiddenVisibility;
179 return ProtectedVisibility;
181 llvm_unreachable("bad visibility kind");
184 /// Return the explicit visibility of the given declaration.
185 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
186 NamedDecl::ExplicitVisibilityKind kind) {
187 // If we're ultimately computing the visibility of a type, look for
188 // a 'type_visibility' attribute before looking for 'visibility'.
189 if (kind == NamedDecl::VisibilityForType) {
190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
191 return getVisibilityFromAttr(A);
195 // If this declaration has an explicit visibility attribute, use it.
196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
197 return getVisibilityFromAttr(A);
200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
201 // implies visibility(default).
202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
203 for (specific_attr_iterator<AvailabilityAttr>
204 A = D->specific_attr_begin<AvailabilityAttr>(),
205 AEnd = D->specific_attr_end<AvailabilityAttr>();
207 if ((*A)->getPlatform()->getName().equals("macosx"))
208 return DefaultVisibility;
214 /// \brief Get the most restrictive linkage for the types in the given
215 /// template parameter list. For visibility purposes, template
216 /// parameters are part of the signature of a template.
218 getLVForTemplateParameterList(const TemplateParameterList *params) {
220 for (TemplateParameterList::const_iterator P = params->begin(),
221 PEnd = params->end();
224 // Template type parameters are the most common and never
225 // contribute to visibility, pack or not.
226 if (isa<TemplateTypeParmDecl>(*P))
229 // Non-type template parameters can be restricted by the value type, e.g.
230 // template <enum X> class A { ... };
231 // We have to be careful here, though, because we can be dealing with
233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
234 // Handle the non-pack case first.
235 if (!NTTP->isExpandedParameterPack()) {
236 if (!NTTP->getType()->isDependentType()) {
237 LV.merge(NTTP->getType()->getLinkageAndVisibility());
242 // Look at all the types in an expanded pack.
243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
244 QualType type = NTTP->getExpansionType(i);
245 if (!type->isDependentType())
246 LV.merge(type->getLinkageAndVisibility());
251 // Template template parameters can be restricted by their
252 // template parameters, recursively.
253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
255 // Handle the non-pack case first.
256 if (!TTP->isExpandedParameterPack()) {
257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
261 // Look at all expansions in an expanded pack.
262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
264 LV.merge(getLVForTemplateParameterList(
265 TTP->getExpansionTemplateParameters(i)));
272 /// getLVForDecl - Get the linkage and visibility for the given declaration.
273 static LinkageInfo getLVForDecl(const NamedDecl *D,
274 LVComputationKind computation);
276 /// \brief Get the most restrictive linkage for the types and
277 /// declarations in the given template argument list.
279 /// Note that we don't take an LVComputationKind because we always
280 /// want to honor the visibility of template arguments in the same way.
282 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
285 for (unsigned i = 0, e = args.size(); i != e; ++i) {
286 const TemplateArgument &arg = args[i];
287 switch (arg.getKind()) {
288 case TemplateArgument::Null:
289 case TemplateArgument::Integral:
290 case TemplateArgument::Expression:
293 case TemplateArgument::Type:
294 LV.merge(arg.getAsType()->getLinkageAndVisibility());
297 case TemplateArgument::Declaration:
298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
299 assert(!usesTypeVisibility(ND));
300 LV.merge(getLVForDecl(ND, LVForValue));
304 case TemplateArgument::NullPtr:
305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
308 case TemplateArgument::Template:
309 case TemplateArgument::TemplateExpansion:
310 if (TemplateDecl *Template
311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
312 LV.merge(getLVForDecl(Template, LVForValue));
315 case TemplateArgument::Pack:
316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
319 llvm_unreachable("bad template argument kind");
326 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
327 return getLVForTemplateArgumentList(TArgs.asArray());
330 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
331 const FunctionTemplateSpecializationInfo *specInfo) {
332 // Include visibility from the template parameters and arguments
333 // only if this is not an explicit instantiation or specialization
334 // with direct explicit visibility. (Implicit instantiations won't
335 // have a direct attribute.)
336 if (!specInfo->isExplicitInstantiationOrSpecialization())
339 return !fn->hasAttr<VisibilityAttr>();
342 /// Merge in template-related linkage and visibility for the given
343 /// function template specialization.
345 /// We don't need a computation kind here because we can assume
348 /// \param[out] LV the computation to use for the parent
350 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
351 const FunctionTemplateSpecializationInfo *specInfo) {
352 bool considerVisibility =
353 shouldConsiderTemplateVisibility(fn, specInfo);
355 // Merge information from the template parameters.
356 FunctionTemplateDecl *temp = specInfo->getTemplate();
358 getLVForTemplateParameterList(temp->getTemplateParameters());
359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
361 // Merge information from the template arguments.
362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
367 /// Does the given declaration have a direct visibility attribute
368 /// that would match the given rules?
369 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
370 LVComputationKind computation) {
371 switch (computation) {
373 case LVForExplicitType:
374 if (D->hasAttr<TypeVisibilityAttr>())
378 case LVForExplicitValue:
379 if (D->hasAttr<VisibilityAttr>())
383 llvm_unreachable("bad visibility computation kind");
386 /// Should we consider visibility associated with the template
387 /// arguments and parameters of the given class template specialization?
388 static bool shouldConsiderTemplateVisibility(
389 const ClassTemplateSpecializationDecl *spec,
390 LVComputationKind computation) {
391 // Include visibility from the template parameters and arguments
392 // only if this is not an explicit instantiation or specialization
393 // with direct explicit visibility (and note that implicit
394 // instantiations won't have a direct attribute).
396 // Furthermore, we want to ignore template parameters and arguments
397 // for an explicit specialization when computing the visibility of a
398 // member thereof with explicit visibility.
400 // This is a bit complex; let's unpack it.
402 // An explicit class specialization is an independent, top-level
403 // declaration. As such, if it or any of its members has an
404 // explicit visibility attribute, that must directly express the
405 // user's intent, and we should honor it. The same logic applies to
406 // an explicit instantiation of a member of such a thing.
408 // Fast path: if this is not an explicit instantiation or
409 // specialization, we always want to consider template-related
410 // visibility restrictions.
411 if (!spec->isExplicitInstantiationOrSpecialization())
414 // This is the 'member thereof' check.
415 if (spec->isExplicitSpecialization() &&
416 hasExplicitVisibilityAlready(computation))
419 return !hasDirectVisibilityAttribute(spec, computation);
422 /// Merge in template-related linkage and visibility for the given
423 /// class template specialization.
424 static void mergeTemplateLV(LinkageInfo &LV,
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
429 // Merge information from the template parameters, but ignore
430 // visibility if we're only considering template arguments.
432 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
434 getLVForTemplateParameterList(temp->getTemplateParameters());
435 LV.mergeMaybeWithVisibility(tempLV,
436 considerVisibility && !hasExplicitVisibilityAlready(computation));
438 // Merge information from the template arguments. We ignore
439 // template-argument visibility if we've got an explicit
440 // instantiation with a visibility attribute.
441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
446 static bool useInlineVisibilityHidden(const NamedDecl *D) {
447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
448 const LangOptions &Opts = D->getASTContext().getLangOpts();
449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
456 TemplateSpecializationKind TSK = TSK_Undeclared;
457 if (FunctionTemplateSpecializationInfo *spec
458 = FD->getTemplateSpecializationInfo()) {
459 TSK = spec->getTemplateSpecializationKind();
460 } else if (MemberSpecializationInfo *MSI =
461 FD->getMemberSpecializationInfo()) {
462 TSK = MSI->getTemplateSpecializationKind();
465 const FunctionDecl *Def = 0;
466 // InlineVisibilityHidden only applies to definitions, and
467 // isInlined() only gives meaningful answers on definitions
469 return TSK != TSK_ExplicitInstantiationDeclaration &&
470 TSK != TSK_ExplicitInstantiationDefinition &&
471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
474 template <typename T> static bool isFirstInExternCContext(T *D) {
475 const T *First = D->getFirstDeclaration();
476 return First->isInExternCContext();
479 static bool isSingleLineExternC(const Decl &D) {
480 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
481 if (SD->getLanguage() == LinkageSpecDecl::lang_c && !SD->hasBraces())
486 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
487 LVComputationKind computation) {
488 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
489 "Not a name having namespace scope");
490 ASTContext &Context = D->getASTContext();
492 // C++ [basic.link]p3:
493 // A name having namespace scope (3.3.6) has internal linkage if it
495 // - an object, reference, function or function template that is
496 // explicitly declared static; or,
497 // (This bullet corresponds to C99 6.2.2p3.)
498 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
499 // Explicitly declared static.
500 if (Var->getStorageClass() == SC_Static)
501 return LinkageInfo::internal();
503 // - a non-volatile object or reference that is explicitly declared const
504 // or constexpr and neither explicitly declared extern nor previously
505 // declared to have external linkage; or (there is no equivalent in C99)
506 if (Context.getLangOpts().CPlusPlus &&
507 Var->getType().isConstQualified() &&
508 !Var->getType().isVolatileQualified()) {
509 const VarDecl *PrevVar = Var->getPreviousDecl();
511 return PrevVar->getLinkageAndVisibility();
513 if (Var->getStorageClass() != SC_Extern &&
514 Var->getStorageClass() != SC_PrivateExtern &&
515 !isSingleLineExternC(*Var))
516 return LinkageInfo::internal();
519 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
520 PrevVar = PrevVar->getPreviousDecl()) {
521 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
522 Var->getStorageClass() == SC_None)
523 return PrevVar->getLinkageAndVisibility();
524 // Explicitly declared static.
525 if (PrevVar->getStorageClass() == SC_Static)
526 return LinkageInfo::internal();
528 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
530 // A non-member function template can have internal linkage; any
531 // other template name shall have external linkage.
532 const FunctionDecl *Function = 0;
533 if (const FunctionTemplateDecl *FunTmpl
534 = dyn_cast<FunctionTemplateDecl>(D))
535 Function = FunTmpl->getTemplatedDecl();
537 Function = cast<FunctionDecl>(D);
539 // Explicitly declared static.
540 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
541 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
542 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
543 // - a data member of an anonymous union.
544 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
545 return LinkageInfo::internal();
548 if (D->isInAnonymousNamespace()) {
549 const VarDecl *Var = dyn_cast<VarDecl>(D);
550 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
551 if ((!Var || !isFirstInExternCContext(Var)) &&
552 (!Func || !isFirstInExternCContext(Func)))
553 return LinkageInfo::uniqueExternal();
556 // Set up the defaults.
559 // If the declaration of an identifier for an object has file
560 // scope and no storage-class specifier, its linkage is
564 if (!hasExplicitVisibilityAlready(computation)) {
565 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
566 LV.mergeVisibility(*Vis, true);
568 // If we're declared in a namespace with a visibility attribute,
569 // use that namespace's visibility, and it still counts as explicit.
570 for (const DeclContext *DC = D->getDeclContext();
571 !isa<TranslationUnitDecl>(DC);
572 DC = DC->getParent()) {
573 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
575 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
576 LV.mergeVisibility(*Vis, true);
582 // Add in global settings if the above didn't give us direct visibility.
583 if (!LV.isVisibilityExplicit()) {
584 // Use global type/value visibility as appropriate.
585 Visibility globalVisibility;
586 if (computation == LVForValue) {
587 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
589 assert(computation == LVForType);
590 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
592 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
594 // If we're paying attention to global visibility, apply
595 // -finline-visibility-hidden if this is an inline method.
596 if (useInlineVisibilityHidden(D))
597 LV.mergeVisibility(HiddenVisibility, true);
601 // C++ [basic.link]p4:
603 // A name having namespace scope has external linkage if it is the
606 // - an object or reference, unless it has internal linkage; or
607 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
608 // GCC applies the following optimization to variables and static
609 // data members, but not to functions:
611 // Modify the variable's LV by the LV of its type unless this is
612 // C or extern "C". This follows from [basic.link]p9:
613 // A type without linkage shall not be used as the type of a
614 // variable or function with external linkage unless
615 // - the entity has C language linkage, or
616 // - the entity is declared within an unnamed namespace, or
617 // - the entity is not used or is defined in the same
619 // and [basic.link]p10:
620 // ...the types specified by all declarations referring to a
621 // given variable or function shall be identical...
622 // C does not have an equivalent rule.
624 // Ignore this if we've got an explicit attribute; the user
625 // probably knows what they're doing.
627 // Note that we don't want to make the variable non-external
628 // because of this, but unique-external linkage suits us.
629 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
630 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
631 if (TypeLV.getLinkage() != ExternalLinkage)
632 return LinkageInfo::uniqueExternal();
633 if (!LV.isVisibilityExplicit())
634 LV.mergeVisibility(TypeLV);
637 if (Var->getStorageClass() == SC_PrivateExtern)
638 LV.mergeVisibility(HiddenVisibility, true);
640 // Note that Sema::MergeVarDecl already takes care of implementing
641 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
644 // - a function, unless it has internal linkage; or
645 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
646 // In theory, we can modify the function's LV by the LV of its
647 // type unless it has C linkage (see comment above about variables
648 // for justification). In practice, GCC doesn't do this, so it's
649 // just too painful to make work.
651 if (Function->getStorageClass() == SC_PrivateExtern)
652 LV.mergeVisibility(HiddenVisibility, true);
654 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
655 // merging storage classes and visibility attributes, so we don't have to
656 // look at previous decls in here.
658 // In C++, then if the type of the function uses a type with
659 // unique-external linkage, it's not legally usable from outside
660 // this translation unit. However, we should use the C linkage
661 // rules instead for extern "C" declarations.
662 if (Context.getLangOpts().CPlusPlus &&
663 !Function->isInExternCContext() &&
664 Function->getType()->getLinkage() == UniqueExternalLinkage)
665 return LinkageInfo::uniqueExternal();
667 // Consider LV from the template and the template arguments.
668 // We're at file scope, so we do not need to worry about nested
670 if (FunctionTemplateSpecializationInfo *specInfo
671 = Function->getTemplateSpecializationInfo()) {
672 mergeTemplateLV(LV, Function, specInfo);
675 // - a named class (Clause 9), or an unnamed class defined in a
676 // typedef declaration in which the class has the typedef name
677 // for linkage purposes (7.1.3); or
678 // - a named enumeration (7.2), or an unnamed enumeration
679 // defined in a typedef declaration in which the enumeration
680 // has the typedef name for linkage purposes (7.1.3); or
681 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
682 // Unnamed tags have no linkage.
683 if (!Tag->hasNameForLinkage())
684 return LinkageInfo::none();
686 // If this is a class template specialization, consider the
687 // linkage of the template and template arguments. We're at file
688 // scope, so we do not need to worry about nested specializations.
689 if (const ClassTemplateSpecializationDecl *spec
690 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
691 mergeTemplateLV(LV, spec, computation);
694 // - an enumerator belonging to an enumeration with external linkage;
695 } else if (isa<EnumConstantDecl>(D)) {
696 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
698 if (!isExternalLinkage(EnumLV.getLinkage()))
699 return LinkageInfo::none();
702 // - a template, unless it is a function template that has
703 // internal linkage (Clause 14);
704 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
705 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
707 getLVForTemplateParameterList(temp->getTemplateParameters());
708 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
710 // - a namespace (7.3), unless it is declared within an unnamed
712 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
715 // By extension, we assign external linkage to Objective-C
717 } else if (isa<ObjCInterfaceDecl>(D)) {
720 // Everything not covered here has no linkage.
722 return LinkageInfo::none();
725 // If we ended up with non-external linkage, visibility should
726 // always be default.
727 if (LV.getLinkage() != ExternalLinkage)
728 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
733 static LinkageInfo getLVForClassMember(const NamedDecl *D,
734 LVComputationKind computation) {
735 // Only certain class members have linkage. Note that fields don't
736 // really have linkage, but it's convenient to say they do for the
737 // purposes of calculating linkage of pointer-to-data-member
738 // template arguments.
739 if (!(isa<CXXMethodDecl>(D) ||
743 return LinkageInfo::none();
747 // If we have an explicit visibility attribute, merge that in.
748 if (!hasExplicitVisibilityAlready(computation)) {
749 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
750 LV.mergeVisibility(*Vis, true);
751 // If we're paying attention to global visibility, apply
752 // -finline-visibility-hidden if this is an inline method.
754 // Note that we do this before merging information about
755 // the class visibility.
756 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
757 LV.mergeVisibility(HiddenVisibility, true);
760 // If this class member has an explicit visibility attribute, the only
761 // thing that can change its visibility is the template arguments, so
762 // only look for them when processing the class.
763 LVComputationKind classComputation = computation;
764 if (LV.isVisibilityExplicit())
765 classComputation = withExplicitVisibilityAlready(computation);
767 LinkageInfo classLV =
768 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
769 if (!isExternalLinkage(classLV.getLinkage()))
770 return LinkageInfo::none();
772 // If the class already has unique-external linkage, we can't improve.
773 if (classLV.getLinkage() == UniqueExternalLinkage)
774 return LinkageInfo::uniqueExternal();
776 // Otherwise, don't merge in classLV yet, because in certain cases
777 // we need to completely ignore the visibility from it.
779 // Specifically, if this decl exists and has an explicit attribute.
780 const NamedDecl *explicitSpecSuppressor = 0;
782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
783 // If the type of the function uses a type with unique-external
784 // linkage, it's not legally usable from outside this translation unit.
785 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
786 return LinkageInfo::uniqueExternal();
788 // If this is a method template specialization, use the linkage for
789 // the template parameters and arguments.
790 if (FunctionTemplateSpecializationInfo *spec
791 = MD->getTemplateSpecializationInfo()) {
792 mergeTemplateLV(LV, MD, spec);
793 if (spec->isExplicitSpecialization()) {
794 explicitSpecSuppressor = MD;
795 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
796 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
798 } else if (isExplicitMemberSpecialization(MD)) {
799 explicitSpecSuppressor = MD;
802 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
803 if (const ClassTemplateSpecializationDecl *spec
804 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
805 mergeTemplateLV(LV, spec, computation);
806 if (spec->isExplicitSpecialization()) {
807 explicitSpecSuppressor = spec;
809 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
810 if (isExplicitMemberSpecialization(temp)) {
811 explicitSpecSuppressor = temp->getTemplatedDecl();
814 } else if (isExplicitMemberSpecialization(RD)) {
815 explicitSpecSuppressor = RD;
818 // Static data members.
819 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
820 // Modify the variable's linkage by its type, but ignore the
821 // type's visibility unless it's a definition.
822 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility();
823 LV.mergeMaybeWithVisibility(typeLV,
824 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit());
826 if (isExplicitMemberSpecialization(VD)) {
827 explicitSpecSuppressor = VD;
831 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
832 bool considerVisibility =
833 (!LV.isVisibilityExplicit() &&
834 !classLV.isVisibilityExplicit() &&
835 !hasExplicitVisibilityAlready(computation));
837 getLVForTemplateParameterList(temp->getTemplateParameters());
838 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
840 if (const RedeclarableTemplateDecl *redeclTemp =
841 dyn_cast<RedeclarableTemplateDecl>(temp)) {
842 if (isExplicitMemberSpecialization(redeclTemp)) {
843 explicitSpecSuppressor = temp->getTemplatedDecl();
848 // We should never be looking for an attribute directly on a template.
849 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
851 // If this member is an explicit member specialization, and it has
852 // an explicit attribute, ignore visibility from the parent.
853 bool considerClassVisibility = true;
854 if (explicitSpecSuppressor &&
855 // optimization: hasDVA() is true only with explicit visibility.
856 LV.isVisibilityExplicit() &&
857 classLV.getVisibility() != DefaultVisibility &&
858 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
859 considerClassVisibility = false;
862 // Finally, merge in information from the class.
863 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
867 void NamedDecl::anchor() { }
869 bool NamedDecl::isLinkageValid() const {
870 if (!HasCachedLinkage)
873 return getLVForDecl(this, LVForExplicitValue).getLinkage() ==
874 Linkage(CachedLinkage);
877 Linkage NamedDecl::getLinkage() const {
878 if (HasCachedLinkage)
879 return Linkage(CachedLinkage);
881 // We don't care about visibility here, so ask for the cheapest
882 // possible visibility analysis.
883 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage();
884 HasCachedLinkage = 1;
890 return Linkage(CachedLinkage);
893 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
894 LVComputationKind computation =
895 (usesTypeVisibility(this) ? LVForType : LVForValue);
896 LinkageInfo LI = getLVForDecl(this, computation);
897 if (HasCachedLinkage) {
898 assert(Linkage(CachedLinkage) == LI.getLinkage());
901 HasCachedLinkage = 1;
902 CachedLinkage = LI.getLinkage();
911 void NamedDecl::verifyLinkage() const {
912 // In C (because of gnu inline) and in c++ with microsoft extensions an
913 // static can follow an extern, so we can have two decls with different
915 const LangOptions &Opts = getASTContext().getLangOpts();
916 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
919 // We have just computed the linkage for this decl. By induction we know
920 // that all other computed linkages match, check that the one we just computed
923 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
924 NamedDecl *T = cast<NamedDecl>(*I);
927 if (T->HasCachedLinkage != 0) {
932 assert(!D || D->CachedLinkage == CachedLinkage);
936 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
937 // Check the declaration itself first.
938 if (Optional<Visibility> V = getVisibilityOf(this, kind))
941 // If this is a member class of a specialization of a class template
942 // and the corresponding decl has explicit visibility, use that.
943 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
944 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
945 if (InstantiatedFrom)
946 return getVisibilityOf(InstantiatedFrom, kind);
949 // If there wasn't explicit visibility there, and this is a
950 // specialization of a class template, check for visibility
952 if (const ClassTemplateSpecializationDecl *spec
953 = dyn_cast<ClassTemplateSpecializationDecl>(this))
954 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
957 // Use the most recent declaration.
958 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
959 if (MostRecent != this)
960 return MostRecent->getExplicitVisibility(kind);
962 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
963 if (Var->isStaticDataMember()) {
964 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
965 if (InstantiatedFrom)
966 return getVisibilityOf(InstantiatedFrom, kind);
971 // Also handle function template specializations.
972 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
973 // If the function is a specialization of a template with an
974 // explicit visibility attribute, use that.
975 if (FunctionTemplateSpecializationInfo *templateInfo
976 = fn->getTemplateSpecializationInfo())
977 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
980 // If the function is a member of a specialization of a class template
981 // and the corresponding decl has explicit visibility, use that.
982 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
983 if (InstantiatedFrom)
984 return getVisibilityOf(InstantiatedFrom, kind);
989 // The visibility of a template is stored in the templated decl.
990 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
991 return getVisibilityOf(TD->getTemplatedDecl(), kind);
996 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
997 LVComputationKind computation) {
998 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
999 if (Function->isInAnonymousNamespace() &&
1000 !Function->isInExternCContext())
1001 return LinkageInfo::uniqueExternal();
1003 // This is a "void f();" which got merged with a file static.
1004 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1005 return LinkageInfo::internal();
1008 if (!hasExplicitVisibilityAlready(computation)) {
1009 if (Optional<Visibility> Vis =
1010 getExplicitVisibility(Function, computation))
1011 LV.mergeVisibility(*Vis, true);
1014 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1015 // merging storage classes and visibility attributes, so we don't have to
1016 // look at previous decls in here.
1021 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1022 if (Var->hasExternalStorage()) {
1023 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1024 return LinkageInfo::uniqueExternal();
1027 if (Var->getStorageClass() == SC_PrivateExtern)
1028 LV.mergeVisibility(HiddenVisibility, true);
1029 else if (!hasExplicitVisibilityAlready(computation)) {
1030 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1031 LV.mergeVisibility(*Vis, true);
1034 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1035 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1036 if (PrevLV.getLinkage())
1037 LV.setLinkage(PrevLV.getLinkage());
1038 LV.mergeVisibility(PrevLV);
1045 return LinkageInfo::none();
1048 static LinkageInfo getLVForDecl(const NamedDecl *D,
1049 LVComputationKind computation) {
1050 // Objective-C: treat all Objective-C declarations as having external
1052 switch (D->getKind()) {
1056 return LinkageInfo::none();
1057 case Decl::TemplateTemplateParm: // count these as external
1058 case Decl::NonTypeTemplateParm:
1059 case Decl::ObjCAtDefsField:
1060 case Decl::ObjCCategory:
1061 case Decl::ObjCCategoryImpl:
1062 case Decl::ObjCCompatibleAlias:
1063 case Decl::ObjCImplementation:
1064 case Decl::ObjCMethod:
1065 case Decl::ObjCProperty:
1066 case Decl::ObjCPropertyImpl:
1067 case Decl::ObjCProtocol:
1068 return LinkageInfo::external();
1070 case Decl::CXXRecord: {
1071 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1072 if (Record->isLambda()) {
1073 if (!Record->getLambdaManglingNumber()) {
1074 // This lambda has no mangling number, so it's internal.
1075 return LinkageInfo::internal();
1078 // This lambda has its linkage/visibility determined by its owner.
1079 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1080 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1081 if (isa<ParmVarDecl>(ContextDecl))
1082 DC = ContextDecl->getDeclContext()->getRedeclContext();
1084 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1087 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1088 return getLVForDecl(ND, computation);
1090 return LinkageInfo::external();
1097 // Handle linkage for namespace-scope names.
1098 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1099 return getLVForNamespaceScopeDecl(D, computation);
1101 // C++ [basic.link]p5:
1102 // In addition, a member function, static data member, a named
1103 // class or enumeration of class scope, or an unnamed class or
1104 // enumeration defined in a class-scope typedef declaration such
1105 // that the class or enumeration has the typedef name for linkage
1106 // purposes (7.1.3), has external linkage if the name of the class
1107 // has external linkage.
1108 if (D->getDeclContext()->isRecord())
1109 return getLVForClassMember(D, computation);
1111 // C++ [basic.link]p6:
1112 // The name of a function declared in block scope and the name of
1113 // an object declared by a block scope extern declaration have
1114 // linkage. If there is a visible declaration of an entity with
1115 // linkage having the same name and type, ignoring entities
1116 // declared outside the innermost enclosing namespace scope, the
1117 // block scope declaration declares that same entity and receives
1118 // the linkage of the previous declaration. If there is more than
1119 // one such matching entity, the program is ill-formed. Otherwise,
1120 // if no matching entity is found, the block scope entity receives
1121 // external linkage.
1122 if (D->getDeclContext()->isFunctionOrMethod())
1123 return getLVForLocalDecl(D, computation);
1125 // C++ [basic.link]p6:
1126 // Names not covered by these rules have no linkage.
1127 return LinkageInfo::none();
1130 std::string NamedDecl::getQualifiedNameAsString() const {
1131 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
1134 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
1135 std::string QualName;
1136 llvm::raw_string_ostream OS(QualName);
1137 printQualifiedName(OS, P);
1141 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1142 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1145 void NamedDecl::printQualifiedName(raw_ostream &OS,
1146 const PrintingPolicy &P) const {
1147 const DeclContext *Ctx = getDeclContext();
1149 if (Ctx->isFunctionOrMethod()) {
1154 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1155 ContextsTy Contexts;
1157 // Collect contexts.
1158 while (Ctx && isa<NamedDecl>(Ctx)) {
1159 Contexts.push_back(Ctx);
1160 Ctx = Ctx->getParent();
1163 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1165 if (const ClassTemplateSpecializationDecl *Spec
1166 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1167 OS << Spec->getName();
1168 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1169 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1170 TemplateArgs.data(),
1171 TemplateArgs.size(),
1173 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1174 if (ND->isAnonymousNamespace())
1175 OS << "<anonymous namespace>";
1178 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1179 if (!RD->getIdentifier())
1180 OS << "<anonymous " << RD->getKindName() << '>';
1183 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1184 const FunctionProtoType *FT = 0;
1185 if (FD->hasWrittenPrototype())
1186 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1190 unsigned NumParams = FD->getNumParams();
1191 for (unsigned i = 0; i < NumParams; ++i) {
1194 OS << FD->getParamDecl(i)->getType().stream(P);
1197 if (FT->isVariadic()) {
1205 OS << *cast<NamedDecl>(*I);
1213 OS << "<anonymous>";
1216 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1217 const PrintingPolicy &Policy,
1218 bool Qualified) const {
1220 printQualifiedName(OS, Policy);
1225 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1226 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1228 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1229 // We want to keep it, unless it nominates same namespace.
1230 if (getKind() == Decl::UsingDirective) {
1231 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1232 ->getOriginalNamespace() ==
1233 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1234 ->getOriginalNamespace();
1237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1238 // For function declarations, we keep track of redeclarations.
1239 return FD->getPreviousDecl() == OldD;
1241 // For function templates, the underlying function declarations are linked.
1242 if (const FunctionTemplateDecl *FunctionTemplate
1243 = dyn_cast<FunctionTemplateDecl>(this))
1244 if (const FunctionTemplateDecl *OldFunctionTemplate
1245 = dyn_cast<FunctionTemplateDecl>(OldD))
1246 return FunctionTemplate->getTemplatedDecl()
1247 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1249 // For method declarations, we keep track of redeclarations.
1250 if (isa<ObjCMethodDecl>(this))
1253 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1256 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1257 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1258 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1260 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1261 ASTContext &Context = getASTContext();
1262 return Context.getCanonicalNestedNameSpecifier(
1263 cast<UsingDecl>(this)->getQualifier()) ==
1264 Context.getCanonicalNestedNameSpecifier(
1265 cast<UsingDecl>(OldD)->getQualifier());
1268 // A typedef of an Objective-C class type can replace an Objective-C class
1269 // declaration or definition, and vice versa.
1270 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1271 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1274 // For non-function declarations, if the declarations are of the
1275 // same kind then this must be a redeclaration, or semantic analysis
1276 // would not have given us the new declaration.
1277 return this->getKind() == OldD->getKind();
1280 bool NamedDecl::hasLinkage() const {
1281 return getLinkage() != NoLinkage;
1284 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1285 NamedDecl *ND = this;
1286 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1287 ND = UD->getTargetDecl();
1289 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1290 return AD->getClassInterface();
1295 bool NamedDecl::isCXXInstanceMember() const {
1296 if (!isCXXClassMember())
1299 const NamedDecl *D = this;
1300 if (isa<UsingShadowDecl>(D))
1301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1303 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1305 if (isa<CXXMethodDecl>(D))
1306 return cast<CXXMethodDecl>(D)->isInstance();
1307 if (isa<FunctionTemplateDecl>(D))
1308 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1309 ->getTemplatedDecl())->isInstance();
1313 //===----------------------------------------------------------------------===//
1314 // DeclaratorDecl Implementation
1315 //===----------------------------------------------------------------------===//
1317 template <typename DeclT>
1318 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1319 if (decl->getNumTemplateParameterLists() > 0)
1320 return decl->getTemplateParameterList(0)->getTemplateLoc();
1322 return decl->getInnerLocStart();
1325 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1326 TypeSourceInfo *TSI = getTypeSourceInfo();
1327 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1328 return SourceLocation();
1331 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1333 // Make sure the extended decl info is allocated.
1334 if (!hasExtInfo()) {
1335 // Save (non-extended) type source info pointer.
1336 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1337 // Allocate external info struct.
1338 DeclInfo = new (getASTContext()) ExtInfo;
1339 // Restore savedTInfo into (extended) decl info.
1340 getExtInfo()->TInfo = savedTInfo;
1342 // Set qualifier info.
1343 getExtInfo()->QualifierLoc = QualifierLoc;
1345 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1347 if (getExtInfo()->NumTemplParamLists == 0) {
1348 // Save type source info pointer.
1349 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1350 // Deallocate the extended decl info.
1351 getASTContext().Deallocate(getExtInfo());
1352 // Restore savedTInfo into (non-extended) decl info.
1353 DeclInfo = savedTInfo;
1356 getExtInfo()->QualifierLoc = QualifierLoc;
1362 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1363 unsigned NumTPLists,
1364 TemplateParameterList **TPLists) {
1365 assert(NumTPLists > 0);
1366 // Make sure the extended decl info is allocated.
1367 if (!hasExtInfo()) {
1368 // Save (non-extended) type source info pointer.
1369 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1370 // Allocate external info struct.
1371 DeclInfo = new (getASTContext()) ExtInfo;
1372 // Restore savedTInfo into (extended) decl info.
1373 getExtInfo()->TInfo = savedTInfo;
1375 // Set the template parameter lists info.
1376 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1379 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1380 return getTemplateOrInnerLocStart(this);
1385 // Helper function: returns true if QT is or contains a type
1386 // having a postfix component.
1387 bool typeIsPostfix(clang::QualType QT) {
1389 const Type* T = QT.getTypePtr();
1390 switch (T->getTypeClass()) {
1394 QT = cast<PointerType>(T)->getPointeeType();
1396 case Type::BlockPointer:
1397 QT = cast<BlockPointerType>(T)->getPointeeType();
1399 case Type::MemberPointer:
1400 QT = cast<MemberPointerType>(T)->getPointeeType();
1402 case Type::LValueReference:
1403 case Type::RValueReference:
1404 QT = cast<ReferenceType>(T)->getPointeeType();
1406 case Type::PackExpansion:
1407 QT = cast<PackExpansionType>(T)->getPattern();
1410 case Type::ConstantArray:
1411 case Type::DependentSizedArray:
1412 case Type::IncompleteArray:
1413 case Type::VariableArray:
1414 case Type::FunctionProto:
1415 case Type::FunctionNoProto:
1423 SourceRange DeclaratorDecl::getSourceRange() const {
1424 SourceLocation RangeEnd = getLocation();
1425 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1426 if (typeIsPostfix(TInfo->getType()))
1427 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1429 return SourceRange(getOuterLocStart(), RangeEnd);
1433 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1434 unsigned NumTPLists,
1435 TemplateParameterList **TPLists) {
1436 assert((NumTPLists == 0 || TPLists != 0) &&
1437 "Empty array of template parameters with positive size!");
1439 // Free previous template parameters (if any).
1440 if (NumTemplParamLists > 0) {
1441 Context.Deallocate(TemplParamLists);
1442 TemplParamLists = 0;
1443 NumTemplParamLists = 0;
1445 // Set info on matched template parameter lists (if any).
1446 if (NumTPLists > 0) {
1447 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1448 NumTemplParamLists = NumTPLists;
1449 for (unsigned i = NumTPLists; i-- > 0; )
1450 TemplParamLists[i] = TPLists[i];
1454 //===----------------------------------------------------------------------===//
1455 // VarDecl Implementation
1456 //===----------------------------------------------------------------------===//
1458 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1460 case SC_None: break;
1461 case SC_Auto: return "auto";
1462 case SC_Extern: return "extern";
1463 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1464 case SC_PrivateExtern: return "__private_extern__";
1465 case SC_Register: return "register";
1466 case SC_Static: return "static";
1469 llvm_unreachable("Invalid storage class");
1472 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1473 SourceLocation StartL, SourceLocation IdL,
1474 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1476 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1479 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1480 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1481 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1482 QualType(), 0, SC_None);
1485 void VarDecl::setStorageClass(StorageClass SC) {
1486 assert(isLegalForVariable(SC));
1487 VarDeclBits.SClass = SC;
1490 SourceRange VarDecl::getSourceRange() const {
1491 if (const Expr *Init = getInit()) {
1492 SourceLocation InitEnd = Init->getLocEnd();
1493 // If Init is implicit, ignore its source range and fallback on
1494 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1495 if (InitEnd.isValid() && InitEnd != getLocation())
1496 return SourceRange(getOuterLocStart(), InitEnd);
1498 return DeclaratorDecl::getSourceRange();
1501 template<typename T>
1502 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1503 // C++ [dcl.link]p1: All function types, function names with external linkage,
1504 // and variable names with external linkage have a language linkage.
1505 if (!isExternalLinkage(D.getLinkage()))
1506 return NoLanguageLinkage;
1508 // Language linkage is a C++ concept, but saying that everything else in C has
1509 // C language linkage fits the implementation nicely.
1510 ASTContext &Context = D.getASTContext();
1511 if (!Context.getLangOpts().CPlusPlus)
1512 return CLanguageLinkage;
1514 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1515 // language linkage of the names of class members and the function type of
1516 // class member functions.
1517 const DeclContext *DC = D.getDeclContext();
1519 return CXXLanguageLinkage;
1521 // If the first decl is in an extern "C" context, any other redeclaration
1522 // will have C language linkage. If the first one is not in an extern "C"
1523 // context, we would have reported an error for any other decl being in one.
1524 if (isFirstInExternCContext(&D))
1525 return CLanguageLinkage;
1526 return CXXLanguageLinkage;
1529 template<typename T>
1530 static bool isExternCTemplate(const T &D) {
1531 // Since the context is ignored for class members, they can only have C++
1532 // language linkage or no language linkage.
1533 const DeclContext *DC = D.getDeclContext();
1534 if (DC->isRecord()) {
1535 assert(D.getASTContext().getLangOpts().CPlusPlus);
1539 return D.getLanguageLinkage() == CLanguageLinkage;
1542 LanguageLinkage VarDecl::getLanguageLinkage() const {
1543 return getLanguageLinkageTemplate(*this);
1546 bool VarDecl::isExternC() const {
1547 return isExternCTemplate(*this);
1550 static bool isLinkageSpecContext(const DeclContext *DC,
1551 LinkageSpecDecl::LanguageIDs ID) {
1552 while (DC->getDeclKind() != Decl::TranslationUnit) {
1553 if (DC->getDeclKind() == Decl::LinkageSpec)
1554 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1555 DC = DC->getParent();
1560 template <typename T>
1561 static bool isInLanguageSpecContext(T *D, LinkageSpecDecl::LanguageIDs ID) {
1562 return isLinkageSpecContext(D->getLexicalDeclContext(), ID);
1565 bool VarDecl::isInExternCContext() const {
1566 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c);
1569 bool VarDecl::isInExternCXXContext() const {
1570 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx);
1573 VarDecl *VarDecl::getCanonicalDecl() {
1574 return getFirstDeclaration();
1577 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1578 ASTContext &C) const
1580 // C++ [basic.def]p2:
1581 // A declaration is a definition unless [...] it contains the 'extern'
1582 // specifier or a linkage-specification and neither an initializer [...],
1583 // it declares a static data member in a class declaration [...].
1584 // C++ [temp.expl.spec]p15:
1585 // An explicit specialization of a static data member of a template is a
1586 // definition if the declaration includes an initializer; otherwise, it is
1588 if (isStaticDataMember()) {
1589 if (isOutOfLine() && (hasInit() ||
1590 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1593 return DeclarationOnly;
1596 // A definition of an identifier is a declaration for that identifier that
1597 // [...] causes storage to be reserved for that object.
1598 // Note: that applies for all non-file-scope objects.
1600 // If the declaration of an identifier for an object has file scope and an
1601 // initializer, the declaration is an external definition for the identifier
1605 if (hasExternalStorage())
1606 return DeclarationOnly;
1609 // A declaration directly contained in a linkage-specification is treated
1610 // as if it contains the extern specifier for the purpose of determining
1611 // the linkage of the declared name and whether it is a definition.
1612 if (isSingleLineExternC(*this))
1613 return DeclarationOnly;
1616 // A declaration of an object that has file scope without an initializer,
1617 // and without a storage class specifier or the scs 'static', constitutes
1618 // a tentative definition.
1619 // No such thing in C++.
1620 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1621 return TentativeDefinition;
1623 // What's left is (in C, block-scope) declarations without initializers or
1624 // external storage. These are definitions.
1628 VarDecl *VarDecl::getActingDefinition() {
1629 DefinitionKind Kind = isThisDeclarationADefinition();
1630 if (Kind != TentativeDefinition)
1633 VarDecl *LastTentative = 0;
1634 VarDecl *First = getFirstDeclaration();
1635 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1637 Kind = (*I)->isThisDeclarationADefinition();
1638 if (Kind == Definition)
1640 else if (Kind == TentativeDefinition)
1643 return LastTentative;
1646 bool VarDecl::isTentativeDefinitionNow() const {
1647 DefinitionKind Kind = isThisDeclarationADefinition();
1648 if (Kind != TentativeDefinition)
1651 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1652 if ((*I)->isThisDeclarationADefinition() == Definition)
1658 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1659 VarDecl *First = getFirstDeclaration();
1660 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1662 if ((*I)->isThisDeclarationADefinition(C) == Definition)
1668 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1669 DefinitionKind Kind = DeclarationOnly;
1671 const VarDecl *First = getFirstDeclaration();
1672 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1674 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1675 if (Kind == Definition)
1682 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1683 redecl_iterator I = redecls_begin(), E = redecls_end();
1684 while (I != E && !I->getInit())
1689 return I->getInit();
1694 bool VarDecl::isOutOfLine() const {
1695 if (Decl::isOutOfLine())
1698 if (!isStaticDataMember())
1701 // If this static data member was instantiated from a static data member of
1702 // a class template, check whether that static data member was defined
1704 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1705 return VD->isOutOfLine();
1710 VarDecl *VarDecl::getOutOfLineDefinition() {
1711 if (!isStaticDataMember())
1714 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1715 RD != RDEnd; ++RD) {
1716 if (RD->getLexicalDeclContext()->isFileContext())
1723 void VarDecl::setInit(Expr *I) {
1724 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1725 Eval->~EvaluatedStmt();
1726 getASTContext().Deallocate(Eval);
1732 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1733 const LangOptions &Lang = C.getLangOpts();
1735 if (!Lang.CPlusPlus)
1738 // In C++11, any variable of reference type can be used in a constant
1739 // expression if it is initialized by a constant expression.
1740 if (Lang.CPlusPlus11 && getType()->isReferenceType())
1743 // Only const objects can be used in constant expressions in C++. C++98 does
1744 // not require the variable to be non-volatile, but we consider this to be a
1746 if (!getType().isConstQualified() || getType().isVolatileQualified())
1749 // In C++, const, non-volatile variables of integral or enumeration types
1750 // can be used in constant expressions.
1751 if (getType()->isIntegralOrEnumerationType())
1754 // Additionally, in C++11, non-volatile constexpr variables can be used in
1755 // constant expressions.
1756 return Lang.CPlusPlus11 && isConstexpr();
1759 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1760 /// form, which contains extra information on the evaluated value of the
1762 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1763 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1765 Stmt *S = Init.get<Stmt *>();
1766 Eval = new (getASTContext()) EvaluatedStmt;
1773 APValue *VarDecl::evaluateValue() const {
1774 SmallVector<PartialDiagnosticAt, 8> Notes;
1775 return evaluateValue(Notes);
1778 APValue *VarDecl::evaluateValue(
1779 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1780 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1782 // We only produce notes indicating why an initializer is non-constant the
1783 // first time it is evaluated. FIXME: The notes won't always be emitted the
1784 // first time we try evaluation, so might not be produced at all.
1785 if (Eval->WasEvaluated)
1786 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1788 const Expr *Init = cast<Expr>(Eval->Value);
1789 assert(!Init->isValueDependent());
1791 if (Eval->IsEvaluating) {
1792 // FIXME: Produce a diagnostic for self-initialization.
1793 Eval->CheckedICE = true;
1794 Eval->IsICE = false;
1798 Eval->IsEvaluating = true;
1800 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1803 // Ensure the result is an uninitialized APValue if evaluation fails.
1805 Eval->Evaluated = APValue();
1807 Eval->IsEvaluating = false;
1808 Eval->WasEvaluated = true;
1810 // In C++11, we have determined whether the initializer was a constant
1811 // expression as a side-effect.
1812 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1813 Eval->CheckedICE = true;
1814 Eval->IsICE = Result && Notes.empty();
1817 return Result ? &Eval->Evaluated : 0;
1820 bool VarDecl::checkInitIsICE() const {
1821 // Initializers of weak variables are never ICEs.
1825 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1826 if (Eval->CheckedICE)
1827 // We have already checked whether this subexpression is an
1828 // integral constant expression.
1831 const Expr *Init = cast<Expr>(Eval->Value);
1832 assert(!Init->isValueDependent());
1834 // In C++11, evaluate the initializer to check whether it's a constant
1836 if (getASTContext().getLangOpts().CPlusPlus11) {
1837 SmallVector<PartialDiagnosticAt, 8> Notes;
1838 evaluateValue(Notes);
1842 // It's an ICE whether or not the definition we found is
1843 // out-of-line. See DR 721 and the discussion in Clang PR
1844 // 6206 for details.
1846 if (Eval->CheckingICE)
1848 Eval->CheckingICE = true;
1850 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1851 Eval->CheckingICE = false;
1852 Eval->CheckedICE = true;
1856 bool VarDecl::extendsLifetimeOfTemporary() const {
1857 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1859 const Expr *E = getInit();
1863 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1864 E = Cleanups->getSubExpr();
1866 return isa<MaterializeTemporaryExpr>(E);
1869 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1870 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1871 return cast<VarDecl>(MSI->getInstantiatedFrom());
1876 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1877 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1878 return MSI->getTemplateSpecializationKind();
1880 return TSK_Undeclared;
1883 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1884 return getASTContext().getInstantiatedFromStaticDataMember(this);
1887 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1888 SourceLocation PointOfInstantiation) {
1889 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1890 assert(MSI && "Not an instantiated static data member?");
1891 MSI->setTemplateSpecializationKind(TSK);
1892 if (TSK != TSK_ExplicitSpecialization &&
1893 PointOfInstantiation.isValid() &&
1894 MSI->getPointOfInstantiation().isInvalid())
1895 MSI->setPointOfInstantiation(PointOfInstantiation);
1898 //===----------------------------------------------------------------------===//
1899 // ParmVarDecl Implementation
1900 //===----------------------------------------------------------------------===//
1902 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1903 SourceLocation StartLoc,
1904 SourceLocation IdLoc, IdentifierInfo *Id,
1905 QualType T, TypeSourceInfo *TInfo,
1906 StorageClass S, Expr *DefArg) {
1907 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1911 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1912 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1913 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1914 0, QualType(), 0, SC_None, 0);
1917 SourceRange ParmVarDecl::getSourceRange() const {
1918 if (!hasInheritedDefaultArg()) {
1919 SourceRange ArgRange = getDefaultArgRange();
1920 if (ArgRange.isValid())
1921 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1924 // DeclaratorDecl considers the range of postfix types as overlapping with the
1925 // declaration name, but this is not the case with parameters in ObjC methods.
1926 if (isa<ObjCMethodDecl>(getDeclContext()))
1927 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
1929 return DeclaratorDecl::getSourceRange();
1932 Expr *ParmVarDecl::getDefaultArg() {
1933 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1934 assert(!hasUninstantiatedDefaultArg() &&
1935 "Default argument is not yet instantiated!");
1937 Expr *Arg = getInit();
1938 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1939 return E->getSubExpr();
1944 SourceRange ParmVarDecl::getDefaultArgRange() const {
1945 if (const Expr *E = getInit())
1946 return E->getSourceRange();
1948 if (hasUninstantiatedDefaultArg())
1949 return getUninstantiatedDefaultArg()->getSourceRange();
1951 return SourceRange();
1954 bool ParmVarDecl::isParameterPack() const {
1955 return isa<PackExpansionType>(getType());
1958 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1959 getASTContext().setParameterIndex(this, parameterIndex);
1960 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1963 unsigned ParmVarDecl::getParameterIndexLarge() const {
1964 return getASTContext().getParameterIndex(this);
1967 //===----------------------------------------------------------------------===//
1968 // FunctionDecl Implementation
1969 //===----------------------------------------------------------------------===//
1971 void FunctionDecl::getNameForDiagnostic(
1972 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1973 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
1974 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1976 TemplateSpecializationType::PrintTemplateArgumentList(
1977 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
1980 bool FunctionDecl::isVariadic() const {
1981 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1982 return FT->isVariadic();
1986 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1987 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1988 if (I->Body || I->IsLateTemplateParsed) {
1997 bool FunctionDecl::hasTrivialBody() const
1999 Stmt *S = getBody();
2001 // Since we don't have a body for this function, we don't know if it's
2006 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2011 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2012 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2013 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
2014 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2022 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2023 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2026 return I->Body.get(getASTContext().getExternalSource());
2027 } else if (I->IsLateTemplateParsed) {
2036 void FunctionDecl::setBody(Stmt *B) {
2039 EndRangeLoc = B->getLocEnd();
2042 void FunctionDecl::setPure(bool P) {
2045 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2046 Parent->markedVirtualFunctionPure();
2049 bool FunctionDecl::isMain() const {
2050 const TranslationUnitDecl *tunit =
2051 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2053 !tunit->getASTContext().getLangOpts().Freestanding &&
2055 getIdentifier()->isStr("main");
2058 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2059 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2060 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2061 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2062 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2063 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2065 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2066 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2068 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2069 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2071 ASTContext &Context =
2072 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2075 // The result type and first argument type are constant across all
2076 // these operators. The second argument must be exactly void*.
2077 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
2080 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2081 // Users expect to be able to write
2082 // extern "C" void *__builtin_alloca (size_t);
2083 // so consider builtins as having C language linkage.
2085 return CLanguageLinkage;
2087 return getLanguageLinkageTemplate(*this);
2090 bool FunctionDecl::isExternC() const {
2091 return isExternCTemplate(*this);
2094 bool FunctionDecl::isInExternCContext() const {
2095 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c);
2098 bool FunctionDecl::isInExternCXXContext() const {
2099 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx);
2102 bool FunctionDecl::isGlobal() const {
2103 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2104 return Method->isStatic();
2106 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2109 for (const DeclContext *DC = getDeclContext();
2111 DC = DC->getParent()) {
2112 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2113 if (!Namespace->getDeclName())
2122 bool FunctionDecl::isNoReturn() const {
2123 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2124 hasAttr<C11NoReturnAttr>() ||
2125 getType()->getAs<FunctionType>()->getNoReturnAttr();
2129 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2130 redeclarable_base::setPreviousDeclaration(PrevDecl);
2132 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2133 FunctionTemplateDecl *PrevFunTmpl
2134 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2135 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2136 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2139 if (PrevDecl && PrevDecl->IsInline)
2143 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2144 return getFirstDeclaration();
2147 FunctionDecl *FunctionDecl::getCanonicalDecl() {
2148 return getFirstDeclaration();
2151 /// \brief Returns a value indicating whether this function
2152 /// corresponds to a builtin function.
2154 /// The function corresponds to a built-in function if it is
2155 /// declared at translation scope or within an extern "C" block and
2156 /// its name matches with the name of a builtin. The returned value
2157 /// will be 0 for functions that do not correspond to a builtin, a
2158 /// value of type \c Builtin::ID if in the target-independent range
2159 /// \c [1,Builtin::First), or a target-specific builtin value.
2160 unsigned FunctionDecl::getBuiltinID() const {
2161 if (!getIdentifier())
2164 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2168 ASTContext &Context = getASTContext();
2169 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2172 // This function has the name of a known C library
2173 // function. Determine whether it actually refers to the C library
2174 // function or whether it just has the same name.
2176 // If this is a static function, it's not a builtin.
2177 if (getStorageClass() == SC_Static)
2180 // If this function is at translation-unit scope and we're not in
2181 // C++, it refers to the C library function.
2182 if (!Context.getLangOpts().CPlusPlus &&
2183 getDeclContext()->isTranslationUnit())
2186 // If the function is in an extern "C" linkage specification and is
2187 // not marked "overloadable", it's the real function.
2188 if (isa<LinkageSpecDecl>(getDeclContext()) &&
2189 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
2190 == LinkageSpecDecl::lang_c &&
2191 !getAttr<OverloadableAttr>())
2199 /// getNumParams - Return the number of parameters this function must have
2200 /// based on its FunctionType. This is the length of the ParamInfo array
2201 /// after it has been created.
2202 unsigned FunctionDecl::getNumParams() const {
2203 const FunctionType *FT = getType()->castAs<FunctionType>();
2204 if (isa<FunctionNoProtoType>(FT))
2206 return cast<FunctionProtoType>(FT)->getNumArgs();
2210 void FunctionDecl::setParams(ASTContext &C,
2211 ArrayRef<ParmVarDecl *> NewParamInfo) {
2212 assert(ParamInfo == 0 && "Already has param info!");
2213 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2215 // Zero params -> null pointer.
2216 if (!NewParamInfo.empty()) {
2217 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2218 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2222 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2223 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2225 if (!NewDecls.empty()) {
2226 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2227 std::copy(NewDecls.begin(), NewDecls.end(), A);
2228 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2232 /// getMinRequiredArguments - Returns the minimum number of arguments
2233 /// needed to call this function. This may be fewer than the number of
2234 /// function parameters, if some of the parameters have default
2235 /// arguments (in C++) or the last parameter is a parameter pack.
2236 unsigned FunctionDecl::getMinRequiredArguments() const {
2237 if (!getASTContext().getLangOpts().CPlusPlus)
2238 return getNumParams();
2240 unsigned NumRequiredArgs = getNumParams();
2242 // If the last parameter is a parameter pack, we don't need an argument for
2244 if (NumRequiredArgs > 0 &&
2245 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2248 // If this parameter has a default argument, we don't need an argument for
2250 while (NumRequiredArgs > 0 &&
2251 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2254 // We might have parameter packs before the end. These can't be deduced,
2255 // but they can still handle multiple arguments.
2256 unsigned ArgIdx = NumRequiredArgs;
2257 while (ArgIdx > 0) {
2258 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2259 NumRequiredArgs = ArgIdx;
2264 return NumRequiredArgs;
2267 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2268 // Only consider file-scope declarations in this test.
2269 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2272 // Only consider explicit declarations; the presence of a builtin for a
2273 // libcall shouldn't affect whether a definition is externally visible.
2274 if (Redecl->isImplicit())
2277 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2278 return true; // Not an inline definition
2283 /// \brief For a function declaration in C or C++, determine whether this
2284 /// declaration causes the definition to be externally visible.
2286 /// Specifically, this determines if adding the current declaration to the set
2287 /// of redeclarations of the given functions causes
2288 /// isInlineDefinitionExternallyVisible to change from false to true.
2289 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2290 assert(!doesThisDeclarationHaveABody() &&
2291 "Must have a declaration without a body.");
2293 ASTContext &Context = getASTContext();
2295 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2296 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2297 // an externally visible definition.
2299 // FIXME: What happens if gnu_inline gets added on after the first
2301 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2304 const FunctionDecl *Prev = this;
2305 bool FoundBody = false;
2306 while ((Prev = Prev->getPreviousDecl())) {
2307 FoundBody |= Prev->Body;
2310 // If it's not the case that both 'inline' and 'extern' are
2311 // specified on the definition, then it is always externally visible.
2312 if (!Prev->isInlineSpecified() ||
2313 Prev->getStorageClass() != SC_Extern)
2315 } else if (Prev->isInlineSpecified() &&
2316 Prev->getStorageClass() != SC_Extern) {
2323 if (Context.getLangOpts().CPlusPlus)
2327 // [...] If all of the file scope declarations for a function in a
2328 // translation unit include the inline function specifier without extern,
2329 // then the definition in that translation unit is an inline definition.
2330 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2332 const FunctionDecl *Prev = this;
2333 bool FoundBody = false;
2334 while ((Prev = Prev->getPreviousDecl())) {
2335 FoundBody |= Prev->Body;
2336 if (RedeclForcesDefC99(Prev))
2342 /// \brief For an inline function definition in C, or for a gnu_inline function
2343 /// in C++, determine whether the definition will be externally visible.
2345 /// Inline function definitions are always available for inlining optimizations.
2346 /// However, depending on the language dialect, declaration specifiers, and
2347 /// attributes, the definition of an inline function may or may not be
2348 /// "externally" visible to other translation units in the program.
2350 /// In C99, inline definitions are not externally visible by default. However,
2351 /// if even one of the global-scope declarations is marked "extern inline", the
2352 /// inline definition becomes externally visible (C99 6.7.4p6).
2354 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2355 /// definition, we use the GNU semantics for inline, which are nearly the
2356 /// opposite of C99 semantics. In particular, "inline" by itself will create
2357 /// an externally visible symbol, but "extern inline" will not create an
2358 /// externally visible symbol.
2359 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2360 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2361 assert(isInlined() && "Function must be inline");
2362 ASTContext &Context = getASTContext();
2364 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2365 // Note: If you change the logic here, please change
2366 // doesDeclarationForceExternallyVisibleDefinition as well.
2368 // If it's not the case that both 'inline' and 'extern' are
2369 // specified on the definition, then this inline definition is
2370 // externally visible.
2371 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2374 // If any declaration is 'inline' but not 'extern', then this definition
2375 // is externally visible.
2376 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2377 Redecl != RedeclEnd;
2379 if (Redecl->isInlineSpecified() &&
2380 Redecl->getStorageClass() != SC_Extern)
2387 // The rest of this function is C-only.
2388 assert(!Context.getLangOpts().CPlusPlus &&
2389 "should not use C inline rules in C++");
2392 // [...] If all of the file scope declarations for a function in a
2393 // translation unit include the inline function specifier without extern,
2394 // then the definition in that translation unit is an inline definition.
2395 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2396 Redecl != RedeclEnd;
2398 if (RedeclForcesDefC99(*Redecl))
2403 // An inline definition does not provide an external definition for the
2404 // function, and does not forbid an external definition in another
2405 // translation unit.
2409 /// getOverloadedOperator - Which C++ overloaded operator this
2410 /// function represents, if any.
2411 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2412 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2413 return getDeclName().getCXXOverloadedOperator();
2418 /// getLiteralIdentifier - The literal suffix identifier this function
2419 /// represents, if any.
2420 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2421 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2422 return getDeclName().getCXXLiteralIdentifier();
2427 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2428 if (TemplateOrSpecialization.isNull())
2429 return TK_NonTemplate;
2430 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2431 return TK_FunctionTemplate;
2432 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2433 return TK_MemberSpecialization;
2434 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2435 return TK_FunctionTemplateSpecialization;
2436 if (TemplateOrSpecialization.is
2437 <DependentFunctionTemplateSpecializationInfo*>())
2438 return TK_DependentFunctionTemplateSpecialization;
2440 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2443 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2444 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2445 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2451 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2453 TemplateSpecializationKind TSK) {
2454 assert(TemplateOrSpecialization.isNull() &&
2455 "Member function is already a specialization");
2456 MemberSpecializationInfo *Info
2457 = new (C) MemberSpecializationInfo(FD, TSK);
2458 TemplateOrSpecialization = Info;
2461 bool FunctionDecl::isImplicitlyInstantiable() const {
2462 // If the function is invalid, it can't be implicitly instantiated.
2463 if (isInvalidDecl())
2466 switch (getTemplateSpecializationKind()) {
2467 case TSK_Undeclared:
2468 case TSK_ExplicitInstantiationDefinition:
2471 case TSK_ImplicitInstantiation:
2474 // It is possible to instantiate TSK_ExplicitSpecialization kind
2475 // if the FunctionDecl has a class scope specialization pattern.
2476 case TSK_ExplicitSpecialization:
2477 return getClassScopeSpecializationPattern() != 0;
2479 case TSK_ExplicitInstantiationDeclaration:
2484 // Find the actual template from which we will instantiate.
2485 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2486 bool HasPattern = false;
2488 HasPattern = PatternDecl->hasBody(PatternDecl);
2490 // C++0x [temp.explicit]p9:
2491 // Except for inline functions, other explicit instantiation declarations
2492 // have the effect of suppressing the implicit instantiation of the entity
2493 // to which they refer.
2494 if (!HasPattern || !PatternDecl)
2497 return PatternDecl->isInlined();
2500 bool FunctionDecl::isTemplateInstantiation() const {
2501 switch (getTemplateSpecializationKind()) {
2502 case TSK_Undeclared:
2503 case TSK_ExplicitSpecialization:
2505 case TSK_ImplicitInstantiation:
2506 case TSK_ExplicitInstantiationDeclaration:
2507 case TSK_ExplicitInstantiationDefinition:
2510 llvm_unreachable("All TSK values handled.");
2513 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2514 // Handle class scope explicit specialization special case.
2515 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2516 return getClassScopeSpecializationPattern();
2518 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2519 while (Primary->getInstantiatedFromMemberTemplate()) {
2520 // If we have hit a point where the user provided a specialization of
2521 // this template, we're done looking.
2522 if (Primary->isMemberSpecialization())
2525 Primary = Primary->getInstantiatedFromMemberTemplate();
2528 return Primary->getTemplatedDecl();
2531 return getInstantiatedFromMemberFunction();
2534 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2535 if (FunctionTemplateSpecializationInfo *Info
2536 = TemplateOrSpecialization
2537 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2538 return Info->Template.getPointer();
2543 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2544 return getASTContext().getClassScopeSpecializationPattern(this);
2547 const TemplateArgumentList *
2548 FunctionDecl::getTemplateSpecializationArgs() const {
2549 if (FunctionTemplateSpecializationInfo *Info
2550 = TemplateOrSpecialization
2551 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2552 return Info->TemplateArguments;
2557 const ASTTemplateArgumentListInfo *
2558 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2559 if (FunctionTemplateSpecializationInfo *Info
2560 = TemplateOrSpecialization
2561 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2562 return Info->TemplateArgumentsAsWritten;
2568 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2569 FunctionTemplateDecl *Template,
2570 const TemplateArgumentList *TemplateArgs,
2572 TemplateSpecializationKind TSK,
2573 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2574 SourceLocation PointOfInstantiation) {
2575 assert(TSK != TSK_Undeclared &&
2576 "Must specify the type of function template specialization");
2577 FunctionTemplateSpecializationInfo *Info
2578 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2580 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2582 TemplateArgsAsWritten,
2583 PointOfInstantiation);
2584 TemplateOrSpecialization = Info;
2585 Template->addSpecialization(Info, InsertPos);
2589 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2590 const UnresolvedSetImpl &Templates,
2591 const TemplateArgumentListInfo &TemplateArgs) {
2592 assert(TemplateOrSpecialization.isNull());
2593 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2594 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2595 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2596 void *Buffer = Context.Allocate(Size);
2597 DependentFunctionTemplateSpecializationInfo *Info =
2598 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2600 TemplateOrSpecialization = Info;
2603 DependentFunctionTemplateSpecializationInfo::
2604 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2605 const TemplateArgumentListInfo &TArgs)
2606 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2608 d.NumTemplates = Ts.size();
2609 d.NumArgs = TArgs.size();
2611 FunctionTemplateDecl **TsArray =
2612 const_cast<FunctionTemplateDecl**>(getTemplates());
2613 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2614 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2616 TemplateArgumentLoc *ArgsArray =
2617 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2618 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2619 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2622 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2623 // For a function template specialization, query the specialization
2624 // information object.
2625 FunctionTemplateSpecializationInfo *FTSInfo
2626 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2628 return FTSInfo->getTemplateSpecializationKind();
2630 MemberSpecializationInfo *MSInfo
2631 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2633 return MSInfo->getTemplateSpecializationKind();
2635 return TSK_Undeclared;
2639 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2640 SourceLocation PointOfInstantiation) {
2641 if (FunctionTemplateSpecializationInfo *FTSInfo
2642 = TemplateOrSpecialization.dyn_cast<
2643 FunctionTemplateSpecializationInfo*>()) {
2644 FTSInfo->setTemplateSpecializationKind(TSK);
2645 if (TSK != TSK_ExplicitSpecialization &&
2646 PointOfInstantiation.isValid() &&
2647 FTSInfo->getPointOfInstantiation().isInvalid())
2648 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2649 } else if (MemberSpecializationInfo *MSInfo
2650 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2651 MSInfo->setTemplateSpecializationKind(TSK);
2652 if (TSK != TSK_ExplicitSpecialization &&
2653 PointOfInstantiation.isValid() &&
2654 MSInfo->getPointOfInstantiation().isInvalid())
2655 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2657 llvm_unreachable("Function cannot have a template specialization kind");
2660 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2661 if (FunctionTemplateSpecializationInfo *FTSInfo
2662 = TemplateOrSpecialization.dyn_cast<
2663 FunctionTemplateSpecializationInfo*>())
2664 return FTSInfo->getPointOfInstantiation();
2665 else if (MemberSpecializationInfo *MSInfo
2666 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2667 return MSInfo->getPointOfInstantiation();
2669 return SourceLocation();
2672 bool FunctionDecl::isOutOfLine() const {
2673 if (Decl::isOutOfLine())
2676 // If this function was instantiated from a member function of a
2677 // class template, check whether that member function was defined out-of-line.
2678 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2679 const FunctionDecl *Definition;
2680 if (FD->hasBody(Definition))
2681 return Definition->isOutOfLine();
2684 // If this function was instantiated from a function template,
2685 // check whether that function template was defined out-of-line.
2686 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2687 const FunctionDecl *Definition;
2688 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2689 return Definition->isOutOfLine();
2695 SourceRange FunctionDecl::getSourceRange() const {
2696 return SourceRange(getOuterLocStart(), EndRangeLoc);
2699 unsigned FunctionDecl::getMemoryFunctionKind() const {
2700 IdentifierInfo *FnInfo = getIdentifier();
2705 // Builtin handling.
2706 switch (getBuiltinID()) {
2707 case Builtin::BI__builtin_memset:
2708 case Builtin::BI__builtin___memset_chk:
2709 case Builtin::BImemset:
2710 return Builtin::BImemset;
2712 case Builtin::BI__builtin_memcpy:
2713 case Builtin::BI__builtin___memcpy_chk:
2714 case Builtin::BImemcpy:
2715 return Builtin::BImemcpy;
2717 case Builtin::BI__builtin_memmove:
2718 case Builtin::BI__builtin___memmove_chk:
2719 case Builtin::BImemmove:
2720 return Builtin::BImemmove;
2722 case Builtin::BIstrlcpy:
2723 return Builtin::BIstrlcpy;
2724 case Builtin::BIstrlcat:
2725 return Builtin::BIstrlcat;
2727 case Builtin::BI__builtin_memcmp:
2728 case Builtin::BImemcmp:
2729 return Builtin::BImemcmp;
2731 case Builtin::BI__builtin_strncpy:
2732 case Builtin::BI__builtin___strncpy_chk:
2733 case Builtin::BIstrncpy:
2734 return Builtin::BIstrncpy;
2736 case Builtin::BI__builtin_strncmp:
2737 case Builtin::BIstrncmp:
2738 return Builtin::BIstrncmp;
2740 case Builtin::BI__builtin_strncasecmp:
2741 case Builtin::BIstrncasecmp:
2742 return Builtin::BIstrncasecmp;
2744 case Builtin::BI__builtin_strncat:
2745 case Builtin::BI__builtin___strncat_chk:
2746 case Builtin::BIstrncat:
2747 return Builtin::BIstrncat;
2749 case Builtin::BI__builtin_strndup:
2750 case Builtin::BIstrndup:
2751 return Builtin::BIstrndup;
2753 case Builtin::BI__builtin_strlen:
2754 case Builtin::BIstrlen:
2755 return Builtin::BIstrlen;
2759 if (FnInfo->isStr("memset"))
2760 return Builtin::BImemset;
2761 else if (FnInfo->isStr("memcpy"))
2762 return Builtin::BImemcpy;
2763 else if (FnInfo->isStr("memmove"))
2764 return Builtin::BImemmove;
2765 else if (FnInfo->isStr("memcmp"))
2766 return Builtin::BImemcmp;
2767 else if (FnInfo->isStr("strncpy"))
2768 return Builtin::BIstrncpy;
2769 else if (FnInfo->isStr("strncmp"))
2770 return Builtin::BIstrncmp;
2771 else if (FnInfo->isStr("strncasecmp"))
2772 return Builtin::BIstrncasecmp;
2773 else if (FnInfo->isStr("strncat"))
2774 return Builtin::BIstrncat;
2775 else if (FnInfo->isStr("strndup"))
2776 return Builtin::BIstrndup;
2777 else if (FnInfo->isStr("strlen"))
2778 return Builtin::BIstrlen;
2785 //===----------------------------------------------------------------------===//
2786 // FieldDecl Implementation
2787 //===----------------------------------------------------------------------===//
2789 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2790 SourceLocation StartLoc, SourceLocation IdLoc,
2791 IdentifierInfo *Id, QualType T,
2792 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2793 InClassInitStyle InitStyle) {
2794 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2795 BW, Mutable, InitStyle);
2798 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2799 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2800 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2801 0, QualType(), 0, 0, false, ICIS_NoInit);
2804 bool FieldDecl::isAnonymousStructOrUnion() const {
2805 if (!isImplicit() || getDeclName())
2808 if (const RecordType *Record = getType()->getAs<RecordType>())
2809 return Record->getDecl()->isAnonymousStructOrUnion();
2814 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2815 assert(isBitField() && "not a bitfield");
2816 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2817 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2820 unsigned FieldDecl::getFieldIndex() const {
2821 if (CachedFieldIndex) return CachedFieldIndex - 1;
2824 const RecordDecl *RD = getParent();
2825 const FieldDecl *LastFD = 0;
2826 bool IsMsStruct = RD->isMsStruct(getASTContext());
2828 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2829 I != E; ++I, ++Index) {
2830 I->CachedFieldIndex = Index + 1;
2833 // Zero-length bitfields following non-bitfield members are ignored.
2834 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
2842 assert(CachedFieldIndex && "failed to find field in parent");
2843 return CachedFieldIndex - 1;
2846 SourceRange FieldDecl::getSourceRange() const {
2847 if (const Expr *E = InitializerOrBitWidth.getPointer())
2848 return SourceRange(getInnerLocStart(), E->getLocEnd());
2849 return DeclaratorDecl::getSourceRange();
2852 void FieldDecl::setBitWidth(Expr *Width) {
2853 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2854 "bit width or initializer already set");
2855 InitializerOrBitWidth.setPointer(Width);
2858 void FieldDecl::setInClassInitializer(Expr *Init) {
2859 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
2860 "bit width or initializer already set");
2861 InitializerOrBitWidth.setPointer(Init);
2864 //===----------------------------------------------------------------------===//
2865 // TagDecl Implementation
2866 //===----------------------------------------------------------------------===//
2868 SourceLocation TagDecl::getOuterLocStart() const {
2869 return getTemplateOrInnerLocStart(this);
2872 SourceRange TagDecl::getSourceRange() const {
2873 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2874 return SourceRange(getOuterLocStart(), E);
2877 TagDecl* TagDecl::getCanonicalDecl() {
2878 return getFirstDeclaration();
2881 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2882 TypedefNameDeclOrQualifier = TDD;
2884 assert(TypeForDecl->isLinkageValid());
2885 assert(isLinkageValid());
2888 void TagDecl::startDefinition() {
2889 IsBeingDefined = true;
2891 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
2892 struct CXXRecordDecl::DefinitionData *Data =
2893 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2894 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2895 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2899 void TagDecl::completeDefinition() {
2900 assert((!isa<CXXRecordDecl>(this) ||
2901 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2902 "definition completed but not started");
2904 IsCompleteDefinition = true;
2905 IsBeingDefined = false;
2907 if (ASTMutationListener *L = getASTMutationListener())
2908 L->CompletedTagDefinition(this);
2911 TagDecl *TagDecl::getDefinition() const {
2912 if (isCompleteDefinition())
2913 return const_cast<TagDecl *>(this);
2915 // If it's possible for us to have an out-of-date definition, check now.
2916 if (MayHaveOutOfDateDef) {
2917 if (IdentifierInfo *II = getIdentifier()) {
2918 if (II->isOutOfDate()) {
2919 updateOutOfDate(*II);
2924 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2925 return CXXRD->getDefinition();
2927 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2929 if (R->isCompleteDefinition())
2935 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2937 // Make sure the extended qualifier info is allocated.
2939 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2940 // Set qualifier info.
2941 getExtInfo()->QualifierLoc = QualifierLoc;
2943 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2945 if (getExtInfo()->NumTemplParamLists == 0) {
2946 getASTContext().Deallocate(getExtInfo());
2947 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2950 getExtInfo()->QualifierLoc = QualifierLoc;
2955 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2956 unsigned NumTPLists,
2957 TemplateParameterList **TPLists) {
2958 assert(NumTPLists > 0);
2959 // Make sure the extended decl info is allocated.
2961 // Allocate external info struct.
2962 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2963 // Set the template parameter lists info.
2964 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2967 //===----------------------------------------------------------------------===//
2968 // EnumDecl Implementation
2969 //===----------------------------------------------------------------------===//
2971 void EnumDecl::anchor() { }
2973 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2974 SourceLocation StartLoc, SourceLocation IdLoc,
2976 EnumDecl *PrevDecl, bool IsScoped,
2977 bool IsScopedUsingClassTag, bool IsFixed) {
2978 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2979 IsScoped, IsScopedUsingClassTag, IsFixed);
2980 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2981 C.getTypeDeclType(Enum, PrevDecl);
2985 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2986 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2987 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2988 0, 0, false, false, false);
2989 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2993 void EnumDecl::completeDefinition(QualType NewType,
2994 QualType NewPromotionType,
2995 unsigned NumPositiveBits,
2996 unsigned NumNegativeBits) {
2997 assert(!isCompleteDefinition() && "Cannot redefine enums!");
2999 IntegerType = NewType.getTypePtr();
3000 PromotionType = NewPromotionType;
3001 setNumPositiveBits(NumPositiveBits);
3002 setNumNegativeBits(NumNegativeBits);
3003 TagDecl::completeDefinition();
3006 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3007 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3008 return MSI->getTemplateSpecializationKind();
3010 return TSK_Undeclared;
3013 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3014 SourceLocation PointOfInstantiation) {
3015 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3016 assert(MSI && "Not an instantiated member enumeration?");
3017 MSI->setTemplateSpecializationKind(TSK);
3018 if (TSK != TSK_ExplicitSpecialization &&
3019 PointOfInstantiation.isValid() &&
3020 MSI->getPointOfInstantiation().isInvalid())
3021 MSI->setPointOfInstantiation(PointOfInstantiation);
3024 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3025 if (SpecializationInfo)
3026 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3031 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3032 TemplateSpecializationKind TSK) {
3033 assert(!SpecializationInfo && "Member enum is already a specialization");
3034 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3037 //===----------------------------------------------------------------------===//
3038 // RecordDecl Implementation
3039 //===----------------------------------------------------------------------===//
3041 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3042 SourceLocation StartLoc, SourceLocation IdLoc,
3043 IdentifierInfo *Id, RecordDecl *PrevDecl)
3044 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3045 HasFlexibleArrayMember = false;
3046 AnonymousStructOrUnion = false;
3047 HasObjectMember = false;
3048 HasVolatileMember = false;
3049 LoadedFieldsFromExternalStorage = false;
3050 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3053 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3054 SourceLocation StartLoc, SourceLocation IdLoc,
3055 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3056 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3058 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3060 C.getTypeDeclType(R, PrevDecl);
3064 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3065 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
3066 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3067 SourceLocation(), 0, 0);
3068 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3072 bool RecordDecl::isInjectedClassName() const {
3073 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3074 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3077 RecordDecl::field_iterator RecordDecl::field_begin() const {
3078 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3079 LoadFieldsFromExternalStorage();
3081 return field_iterator(decl_iterator(FirstDecl));
3084 /// completeDefinition - Notes that the definition of this type is now
3086 void RecordDecl::completeDefinition() {
3087 assert(!isCompleteDefinition() && "Cannot redefine record!");
3088 TagDecl::completeDefinition();
3091 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3092 /// This which can be turned on with an attribute, pragma, or the
3093 /// -mms-bitfields command-line option.
3094 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3095 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3098 static bool isFieldOrIndirectField(Decl::Kind K) {
3099 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3102 void RecordDecl::LoadFieldsFromExternalStorage() const {
3103 ExternalASTSource *Source = getASTContext().getExternalSource();
3104 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3106 // Notify that we have a RecordDecl doing some initialization.
3107 ExternalASTSource::Deserializing TheFields(Source);
3109 SmallVector<Decl*, 64> Decls;
3110 LoadedFieldsFromExternalStorage = true;
3111 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3116 case ELR_AlreadyLoaded:
3122 // Check that all decls we got were FieldDecls.
3123 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3124 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3130 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3131 /*FieldsAlreadyLoaded=*/false);
3134 //===----------------------------------------------------------------------===//
3135 // BlockDecl Implementation
3136 //===----------------------------------------------------------------------===//
3138 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3139 assert(ParamInfo == 0 && "Already has param info!");
3141 // Zero params -> null pointer.
3142 if (!NewParamInfo.empty()) {
3143 NumParams = NewParamInfo.size();
3144 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3145 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3149 void BlockDecl::setCaptures(ASTContext &Context,
3150 const Capture *begin,
3152 bool capturesCXXThis) {
3153 CapturesCXXThis = capturesCXXThis;
3161 NumCaptures = end - begin;
3163 // Avoid new Capture[] because we don't want to provide a default
3165 size_t allocationSize = NumCaptures * sizeof(Capture);
3166 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3167 memcpy(buffer, begin, allocationSize);
3168 Captures = static_cast<Capture*>(buffer);
3171 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3172 for (capture_const_iterator
3173 i = capture_begin(), e = capture_end(); i != e; ++i)
3174 // Only auto vars can be captured, so no redeclaration worries.
3175 if (i->getVariable() == variable)
3181 SourceRange BlockDecl::getSourceRange() const {
3182 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3185 //===----------------------------------------------------------------------===//
3186 // Other Decl Allocation/Deallocation Method Implementations
3187 //===----------------------------------------------------------------------===//
3189 void TranslationUnitDecl::anchor() { }
3191 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3192 return new (C) TranslationUnitDecl(C);
3195 void LabelDecl::anchor() { }
3197 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3198 SourceLocation IdentL, IdentifierInfo *II) {
3199 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3202 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3203 SourceLocation IdentL, IdentifierInfo *II,
3204 SourceLocation GnuLabelL) {
3205 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3206 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3209 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3210 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3211 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3214 void ValueDecl::anchor() { }
3216 bool ValueDecl::isWeak() const {
3217 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3218 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3221 return isWeakImported();
3224 void ImplicitParamDecl::anchor() { }
3226 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3227 SourceLocation IdLoc,
3230 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
3233 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3235 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3236 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3239 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3240 SourceLocation StartLoc,
3241 const DeclarationNameInfo &NameInfo,
3242 QualType T, TypeSourceInfo *TInfo,
3244 bool isInlineSpecified,
3245 bool hasWrittenPrototype,
3246 bool isConstexprSpecified) {
3247 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3250 isConstexprSpecified);
3251 New->HasWrittenPrototype = hasWrittenPrototype;
3255 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3256 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3257 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3258 DeclarationNameInfo(), QualType(), 0,
3259 SC_None, false, false);
3262 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3263 return new (C) BlockDecl(DC, L);
3266 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3267 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3268 return new (Mem) BlockDecl(0, SourceLocation());
3271 MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3273 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(MSPropertyDecl));
3274 return new (Mem) MSPropertyDecl(0, SourceLocation(), DeclarationName(),
3275 QualType(), 0, SourceLocation(),
3279 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3280 unsigned NumParams) {
3281 unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*);
3282 return new (C.Allocate(Size)) CapturedDecl(DC, NumParams);
3285 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3286 unsigned NumParams) {
3287 unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*);
3288 void *Mem = AllocateDeserializedDecl(C, ID, Size);
3289 return new (Mem) CapturedDecl(0, NumParams);
3292 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3294 IdentifierInfo *Id, QualType T,
3295 Expr *E, const llvm::APSInt &V) {
3296 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3300 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3301 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3302 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3306 void IndirectFieldDecl::anchor() { }
3309 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3310 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3312 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3315 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3317 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3318 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3322 SourceRange EnumConstantDecl::getSourceRange() const {
3323 SourceLocation End = getLocation();
3325 End = Init->getLocEnd();
3326 return SourceRange(getLocation(), End);
3329 void TypeDecl::anchor() { }
3331 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3332 SourceLocation StartLoc, SourceLocation IdLoc,
3333 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3334 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3337 void TypedefNameDecl::anchor() { }
3339 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3340 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3341 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3344 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3345 SourceLocation StartLoc,
3346 SourceLocation IdLoc, IdentifierInfo *Id,
3347 TypeSourceInfo *TInfo) {
3348 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3351 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3352 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3353 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3356 SourceRange TypedefDecl::getSourceRange() const {
3357 SourceLocation RangeEnd = getLocation();
3358 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3359 if (typeIsPostfix(TInfo->getType()))
3360 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3362 return SourceRange(getLocStart(), RangeEnd);
3365 SourceRange TypeAliasDecl::getSourceRange() const {
3366 SourceLocation RangeEnd = getLocStart();
3367 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3368 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3369 return SourceRange(getLocStart(), RangeEnd);
3372 void FileScopeAsmDecl::anchor() { }
3374 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3376 SourceLocation AsmLoc,
3377 SourceLocation RParenLoc) {
3378 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3381 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3383 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3384 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3387 void EmptyDecl::anchor() {}
3389 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3390 return new (C) EmptyDecl(DC, L);
3393 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3394 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3395 return new (Mem) EmptyDecl(0, SourceLocation());
3398 //===----------------------------------------------------------------------===//
3399 // ImportDecl Implementation
3400 //===----------------------------------------------------------------------===//
3402 /// \brief Retrieve the number of module identifiers needed to name the given
3404 static unsigned getNumModuleIdentifiers(Module *Mod) {
3405 unsigned Result = 1;
3406 while (Mod->Parent) {
3413 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3415 ArrayRef<SourceLocation> IdentifierLocs)
3416 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3419 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3420 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3421 memcpy(StoredLocs, IdentifierLocs.data(),
3422 IdentifierLocs.size() * sizeof(SourceLocation));
3425 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3426 Module *Imported, SourceLocation EndLoc)
3427 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3430 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3433 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3434 SourceLocation StartLoc, Module *Imported,
3435 ArrayRef<SourceLocation> IdentifierLocs) {
3436 void *Mem = C.Allocate(sizeof(ImportDecl) +
3437 IdentifierLocs.size() * sizeof(SourceLocation));
3438 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3441 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3442 SourceLocation StartLoc,
3444 SourceLocation EndLoc) {
3445 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
3446 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
3447 Import->setImplicit();
3451 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3452 unsigned NumLocations) {
3453 void *Mem = AllocateDeserializedDecl(C, ID,
3454 (sizeof(ImportDecl) +
3455 NumLocations * sizeof(SourceLocation)));
3456 return new (Mem) ImportDecl(EmptyShell());
3459 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3460 if (!ImportedAndComplete.getInt())
3463 const SourceLocation *StoredLocs
3464 = reinterpret_cast<const SourceLocation *>(this + 1);
3465 return ArrayRef<SourceLocation>(StoredLocs,
3466 getNumModuleIdentifiers(getImportedModule()));
3469 SourceRange ImportDecl::getSourceRange() const {
3470 if (!ImportedAndComplete.getInt())
3471 return SourceRange(getLocation(),
3472 *reinterpret_cast<const SourceLocation *>(this + 1));
3474 return SourceRange(getLocation(), getIdentifierLocs().back());