Don't be so eager to replace UsingDecls in a DeclContext's lookup table;
[clang.git] / lib / AST / Decl.cpp
blobc6c7649bdac1d5f57341b5c20224beba0ba29ff6
1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/ASTMutationListener.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "llvm/Support/ErrorHandling.h"
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
33 // NamedDecl Implementation
34 //===----------------------------------------------------------------------===//
36 static const VisibilityAttr *GetExplicitVisibility(const Decl *D) {
37 // If the decl is redeclarable, make sure we use the explicit
38 // visibility attribute from the most recent declaration.
40 // Note that this isn't necessary for tags, which can't have their
41 // visibility adjusted.
42 if (isa<VarDecl>(D)) {
43 return cast<VarDecl>(D)->getMostRecentDeclaration()
44 ->getAttr<VisibilityAttr>();
45 } else if (isa<FunctionDecl>(D)) {
46 return cast<FunctionDecl>(D)->getMostRecentDeclaration()
47 ->getAttr<VisibilityAttr>();
48 } else {
49 return D->getAttr<VisibilityAttr>();
53 static Visibility GetVisibilityFromAttr(const VisibilityAttr *A) {
54 switch (A->getVisibility()) {
55 case VisibilityAttr::Default:
56 return DefaultVisibility;
57 case VisibilityAttr::Hidden:
58 return HiddenVisibility;
59 case VisibilityAttr::Protected:
60 return ProtectedVisibility;
62 return DefaultVisibility;
65 typedef NamedDecl::LinkageInfo LinkageInfo;
66 typedef std::pair<Linkage,Visibility> LVPair;
68 static LVPair merge(LVPair L, LVPair R) {
69 return LVPair(minLinkage(L.first, R.first),
70 minVisibility(L.second, R.second));
73 static LVPair merge(LVPair L, LinkageInfo R) {
74 return LVPair(minLinkage(L.first, R.linkage()),
75 minVisibility(L.second, R.visibility()));
78 /// Flags controlling the computation of linkage and visibility.
79 struct LVFlags {
80 bool ConsiderGlobalVisibility;
81 bool ConsiderVisibilityAttributes;
83 LVFlags() : ConsiderGlobalVisibility(true),
84 ConsiderVisibilityAttributes(true) {
87 /// Returns a set of flags, otherwise based on these, which ignores
88 /// off all sources of visibility except template arguments.
89 LVFlags onlyTemplateVisibility() const {
90 LVFlags F = *this;
91 F.ConsiderGlobalVisibility = false;
92 F.ConsiderVisibilityAttributes = false;
93 return F;
97 /// \brief Get the most restrictive linkage for the types in the given
98 /// template parameter list.
99 static LVPair
100 getLVForTemplateParameterList(const TemplateParameterList *Params) {
101 LVPair LV(ExternalLinkage, DefaultVisibility);
102 for (TemplateParameterList::const_iterator P = Params->begin(),
103 PEnd = Params->end();
104 P != PEnd; ++P) {
105 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P))
106 if (!NTTP->getType()->isDependentType()) {
107 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
108 continue;
111 if (TemplateTemplateParmDecl *TTP
112 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
113 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
117 return LV;
120 /// \brief Get the most restrictive linkage for the types and
121 /// declarations in the given template argument list.
122 static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
123 unsigned NumArgs) {
124 LVPair LV(ExternalLinkage, DefaultVisibility);
126 for (unsigned I = 0; I != NumArgs; ++I) {
127 switch (Args[I].getKind()) {
128 case TemplateArgument::Null:
129 case TemplateArgument::Integral:
130 case TemplateArgument::Expression:
131 break;
133 case TemplateArgument::Type:
134 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
135 break;
137 case TemplateArgument::Declaration:
138 // The decl can validly be null as the representation of nullptr
139 // arguments, valid only in C++0x.
140 if (Decl *D = Args[I].getAsDecl()) {
141 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
142 LV = merge(LV, ND->getLinkageAndVisibility());
143 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
144 LV = merge(LV, VD->getLinkageAndVisibility());
146 break;
148 case TemplateArgument::Template:
149 if (TemplateDecl *Template = Args[I].getAsTemplate().getAsTemplateDecl())
150 LV = merge(LV, Template->getLinkageAndVisibility());
151 break;
153 case TemplateArgument::Pack:
154 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
155 Args[I].pack_size()));
156 break;
160 return LV;
163 static LVPair
164 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
165 return getLVForTemplateArgumentList(TArgs.getFlatArgumentList(),
166 TArgs.flat_size());
169 /// getLVForDecl - Get the cached linkage and visibility for the given
170 /// declaration.
171 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
173 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
174 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
175 "Not a name having namespace scope");
176 ASTContext &Context = D->getASTContext();
178 // C++ [basic.link]p3:
179 // A name having namespace scope (3.3.6) has internal linkage if it
180 // is the name of
181 // - an object, reference, function or function template that is
182 // explicitly declared static; or,
183 // (This bullet corresponds to C99 6.2.2p3.)
184 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
185 // Explicitly declared static.
186 if (Var->getStorageClass() == SC_Static)
187 return LinkageInfo::internal();
189 // - an object or reference that is explicitly declared const
190 // and neither explicitly declared extern nor previously
191 // declared to have external linkage; or
192 // (there is no equivalent in C99)
193 if (Context.getLangOptions().CPlusPlus &&
194 Var->getType().isConstant(Context) &&
195 Var->getStorageClass() != SC_Extern &&
196 Var->getStorageClass() != SC_PrivateExtern) {
197 bool FoundExtern = false;
198 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
199 PrevVar && !FoundExtern;
200 PrevVar = PrevVar->getPreviousDeclaration())
201 if (isExternalLinkage(PrevVar->getLinkage()))
202 FoundExtern = true;
204 if (!FoundExtern)
205 return LinkageInfo::internal();
207 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
208 // C++ [temp]p4:
209 // A non-member function template can have internal linkage; any
210 // other template name shall have external linkage.
211 const FunctionDecl *Function = 0;
212 if (const FunctionTemplateDecl *FunTmpl
213 = dyn_cast<FunctionTemplateDecl>(D))
214 Function = FunTmpl->getTemplatedDecl();
215 else
216 Function = cast<FunctionDecl>(D);
218 // Explicitly declared static.
219 if (Function->getStorageClass() == SC_Static)
220 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
221 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
222 // - a data member of an anonymous union.
223 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
224 return LinkageInfo::internal();
227 if (D->isInAnonymousNamespace())
228 return LinkageInfo::uniqueExternal();
230 // Set up the defaults.
232 // C99 6.2.2p5:
233 // If the declaration of an identifier for an object has file
234 // scope and no storage-class specifier, its linkage is
235 // external.
236 LinkageInfo LV;
238 if (F.ConsiderVisibilityAttributes) {
239 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) {
240 LV.setVisibility(GetVisibilityFromAttr(VA), true);
241 F.ConsiderGlobalVisibility = false;
245 // C++ [basic.link]p4:
247 // A name having namespace scope has external linkage if it is the
248 // name of
250 // - an object or reference, unless it has internal linkage; or
251 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
252 // GCC applies the following optimization to variables and static
253 // data members, but not to functions:
255 // Modify the variable's LV by the LV of its type unless this is
256 // C or extern "C". This follows from [basic.link]p9:
257 // A type without linkage shall not be used as the type of a
258 // variable or function with external linkage unless
259 // - the entity has C language linkage, or
260 // - the entity is declared within an unnamed namespace, or
261 // - the entity is not used or is defined in the same
262 // translation unit.
263 // and [basic.link]p10:
264 // ...the types specified by all declarations referring to a
265 // given variable or function shall be identical...
266 // C does not have an equivalent rule.
268 // Ignore this if we've got an explicit attribute; the user
269 // probably knows what they're doing.
271 // Note that we don't want to make the variable non-external
272 // because of this, but unique-external linkage suits us.
273 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
274 LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
275 if (TypeLV.first != ExternalLinkage)
276 return LinkageInfo::uniqueExternal();
277 if (!LV.visibilityExplicit())
278 LV.mergeVisibility(TypeLV.second);
281 if (Var->getStorageClass() == SC_PrivateExtern)
282 LV.setVisibility(HiddenVisibility, true);
284 if (!Context.getLangOptions().CPlusPlus &&
285 (Var->getStorageClass() == SC_Extern ||
286 Var->getStorageClass() == SC_PrivateExtern)) {
288 // C99 6.2.2p4:
289 // For an identifier declared with the storage-class specifier
290 // extern in a scope in which a prior declaration of that
291 // identifier is visible, if the prior declaration specifies
292 // internal or external linkage, the linkage of the identifier
293 // at the later declaration is the same as the linkage
294 // specified at the prior declaration. If no prior declaration
295 // is visible, or if the prior declaration specifies no
296 // linkage, then the identifier has external linkage.
297 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
298 LinkageInfo PrevLV = PrevVar->getLinkageAndVisibility();
299 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
300 LV.mergeVisibility(PrevLV);
304 // - a function, unless it has internal linkage; or
305 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
306 // In theory, we can modify the function's LV by the LV of its
307 // type unless it has C linkage (see comment above about variables
308 // for justification). In practice, GCC doesn't do this, so it's
309 // just too painful to make work.
311 if (Function->getStorageClass() == SC_PrivateExtern)
312 LV.setVisibility(HiddenVisibility, true);
314 // C99 6.2.2p5:
315 // If the declaration of an identifier for a function has no
316 // storage-class specifier, its linkage is determined exactly
317 // as if it were declared with the storage-class specifier
318 // extern.
319 if (!Context.getLangOptions().CPlusPlus &&
320 (Function->getStorageClass() == SC_Extern ||
321 Function->getStorageClass() == SC_PrivateExtern ||
322 Function->getStorageClass() == SC_None)) {
323 // C99 6.2.2p4:
324 // For an identifier declared with the storage-class specifier
325 // extern in a scope in which a prior declaration of that
326 // identifier is visible, if the prior declaration specifies
327 // internal or external linkage, the linkage of the identifier
328 // at the later declaration is the same as the linkage
329 // specified at the prior declaration. If no prior declaration
330 // is visible, or if the prior declaration specifies no
331 // linkage, then the identifier has external linkage.
332 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
333 LinkageInfo PrevLV = PrevFunc->getLinkageAndVisibility();
334 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
335 LV.mergeVisibility(PrevLV);
339 if (FunctionTemplateSpecializationInfo *SpecInfo
340 = Function->getTemplateSpecializationInfo()) {
341 LV.merge(getLVForDecl(SpecInfo->getTemplate(),
342 F.onlyTemplateVisibility()));
343 const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments;
344 LV.merge(getLVForTemplateArgumentList(TemplateArgs));
347 // - a named class (Clause 9), or an unnamed class defined in a
348 // typedef declaration in which the class has the typedef name
349 // for linkage purposes (7.1.3); or
350 // - a named enumeration (7.2), or an unnamed enumeration
351 // defined in a typedef declaration in which the enumeration
352 // has the typedef name for linkage purposes (7.1.3); or
353 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
354 // Unnamed tags have no linkage.
355 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl())
356 return LinkageInfo::none();
358 // If this is a class template specialization, consider the
359 // linkage of the template and template arguments.
360 if (const ClassTemplateSpecializationDecl *Spec
361 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
362 // From the template.
363 LV.merge(getLVForDecl(Spec->getSpecializedTemplate(),
364 F.onlyTemplateVisibility()));
366 // The arguments at which the template was instantiated.
367 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
368 LV.merge(getLVForTemplateArgumentList(TemplateArgs));
371 // Consider -fvisibility unless the type has C linkage.
372 if (F.ConsiderGlobalVisibility)
373 F.ConsiderGlobalVisibility =
374 (Context.getLangOptions().CPlusPlus &&
375 !Tag->getDeclContext()->isExternCContext());
377 // - an enumerator belonging to an enumeration with external linkage;
378 } else if (isa<EnumConstantDecl>(D)) {
379 LinkageInfo EnumLV =
380 cast<NamedDecl>(D->getDeclContext())->getLinkageAndVisibility();
381 if (!isExternalLinkage(EnumLV.linkage()))
382 return LinkageInfo::none();
383 LV.merge(EnumLV);
385 // - a template, unless it is a function template that has
386 // internal linkage (Clause 14);
387 } else if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
388 LV.merge(getLVForTemplateParameterList(Template->getTemplateParameters()));
390 // - a namespace (7.3), unless it is declared within an unnamed
391 // namespace.
392 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
393 return LV;
395 // By extension, we assign external linkage to Objective-C
396 // interfaces.
397 } else if (isa<ObjCInterfaceDecl>(D)) {
398 // fallout
400 // Everything not covered here has no linkage.
401 } else {
402 return LinkageInfo::none();
405 // If we ended up with non-external linkage, visibility should
406 // always be default.
407 if (LV.linkage() != ExternalLinkage)
408 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
410 // If we didn't end up with hidden visibility, consider attributes
411 // and -fvisibility.
412 if (F.ConsiderGlobalVisibility)
413 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
415 return LV;
418 static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
419 // Only certain class members have linkage. Note that fields don't
420 // really have linkage, but it's convenient to say they do for the
421 // purposes of calculating linkage of pointer-to-data-member
422 // template arguments.
423 if (!(isa<CXXMethodDecl>(D) ||
424 isa<VarDecl>(D) ||
425 isa<FieldDecl>(D) ||
426 (isa<TagDecl>(D) &&
427 (D->getDeclName() || cast<TagDecl>(D)->getTypedefForAnonDecl()))))
428 return LinkageInfo::none();
430 LinkageInfo LV;
432 // The flags we're going to use to compute the class's visibility.
433 LVFlags ClassF = F;
435 // If we have an explicit visibility attribute, merge that in.
436 if (F.ConsiderVisibilityAttributes) {
437 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) {
438 LV.mergeVisibility(GetVisibilityFromAttr(VA), true);
440 // Ignore global visibility later, but not this attribute.
441 F.ConsiderGlobalVisibility = false;
443 // Ignore both global visibility and attributes when computing our
444 // parent's visibility.
445 ClassF = F.onlyTemplateVisibility();
449 // Class members only have linkage if their class has external
450 // linkage.
451 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
452 if (!isExternalLinkage(LV.linkage()))
453 return LinkageInfo::none();
455 // If the class already has unique-external linkage, we can't improve.
456 if (LV.linkage() == UniqueExternalLinkage)
457 return LinkageInfo::uniqueExternal();
459 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
460 TemplateSpecializationKind TSK = TSK_Undeclared;
462 // If this is a method template specialization, use the linkage for
463 // the template parameters and arguments.
464 if (FunctionTemplateSpecializationInfo *Spec
465 = MD->getTemplateSpecializationInfo()) {
466 LV.merge(getLVForTemplateArgumentList(*Spec->TemplateArguments));
467 LV.merge(getLVForTemplateParameterList(
468 Spec->getTemplate()->getTemplateParameters()));
470 TSK = Spec->getTemplateSpecializationKind();
471 } else if (MemberSpecializationInfo *MSI =
472 MD->getMemberSpecializationInfo()) {
473 TSK = MSI->getTemplateSpecializationKind();
476 // If we're paying attention to global visibility, apply
477 // -finline-visibility-hidden if this is an inline method.
479 // Note that ConsiderGlobalVisibility doesn't yet have information
480 // about whether containing classes have visibility attributes,
481 // and that's intentional.
482 if (TSK != TSK_ExplicitInstantiationDeclaration &&
483 F.ConsiderGlobalVisibility &&
484 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
485 // InlineVisibilityHidden only applies to definitions, and
486 // isInlined() only gives meaningful answers on definitions
487 // anyway.
488 const FunctionDecl *Def = 0;
489 if (MD->hasBody(Def) && Def->isInlined())
490 LV.setVisibility(HiddenVisibility);
493 // Note that in contrast to basically every other situation, we
494 // *do* apply -fvisibility to method declarations.
496 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
497 if (const ClassTemplateSpecializationDecl *Spec
498 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
499 // Merge template argument/parameter information for member
500 // class template specializations.
501 LV.merge(getLVForTemplateArgumentList(Spec->getTemplateArgs()));
502 LV.merge(getLVForTemplateParameterList(
503 Spec->getSpecializedTemplate()->getTemplateParameters()));
506 // Static data members.
507 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
508 // Modify the variable's linkage by its type, but ignore the
509 // type's visibility unless it's a definition.
510 LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
511 if (TypeLV.first != ExternalLinkage)
512 LV.mergeLinkage(UniqueExternalLinkage);
513 if (!LV.visibilityExplicit())
514 LV.mergeVisibility(TypeLV.second);
517 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
519 // Apply -fvisibility if desired.
520 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
521 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
524 return LV;
527 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
528 return getLVForDecl(this, LVFlags());
531 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
532 // Objective-C: treat all Objective-C declarations as having external
533 // linkage.
534 switch (D->getKind()) {
535 default:
536 break;
537 case Decl::TemplateTemplateParm: // count these as external
538 case Decl::NonTypeTemplateParm:
539 case Decl::ObjCAtDefsField:
540 case Decl::ObjCCategory:
541 case Decl::ObjCCategoryImpl:
542 case Decl::ObjCCompatibleAlias:
543 case Decl::ObjCForwardProtocol:
544 case Decl::ObjCImplementation:
545 case Decl::ObjCMethod:
546 case Decl::ObjCProperty:
547 case Decl::ObjCPropertyImpl:
548 case Decl::ObjCProtocol:
549 return LinkageInfo::external();
552 // Handle linkage for namespace-scope names.
553 if (D->getDeclContext()->getRedeclContext()->isFileContext())
554 return getLVForNamespaceScopeDecl(D, Flags);
556 // C++ [basic.link]p5:
557 // In addition, a member function, static data member, a named
558 // class or enumeration of class scope, or an unnamed class or
559 // enumeration defined in a class-scope typedef declaration such
560 // that the class or enumeration has the typedef name for linkage
561 // purposes (7.1.3), has external linkage if the name of the class
562 // has external linkage.
563 if (D->getDeclContext()->isRecord())
564 return getLVForClassMember(D, Flags);
566 // C++ [basic.link]p6:
567 // The name of a function declared in block scope and the name of
568 // an object declared by a block scope extern declaration have
569 // linkage. If there is a visible declaration of an entity with
570 // linkage having the same name and type, ignoring entities
571 // declared outside the innermost enclosing namespace scope, the
572 // block scope declaration declares that same entity and receives
573 // the linkage of the previous declaration. If there is more than
574 // one such matching entity, the program is ill-formed. Otherwise,
575 // if no matching entity is found, the block scope entity receives
576 // external linkage.
577 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
578 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
579 if (Function->isInAnonymousNamespace())
580 return LinkageInfo::uniqueExternal();
582 LinkageInfo LV;
583 if (const VisibilityAttr *VA = GetExplicitVisibility(Function))
584 LV.setVisibility(GetVisibilityFromAttr(VA));
586 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
587 LinkageInfo PrevLV = Prev->getLinkageAndVisibility();
588 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
589 LV.mergeVisibility(PrevLV);
592 return LV;
595 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
596 if (Var->getStorageClass() == SC_Extern ||
597 Var->getStorageClass() == SC_PrivateExtern) {
598 if (Var->isInAnonymousNamespace())
599 return LinkageInfo::uniqueExternal();
601 LinkageInfo LV;
602 if (Var->getStorageClass() == SC_PrivateExtern)
603 LV.setVisibility(HiddenVisibility);
604 else if (const VisibilityAttr *VA = GetExplicitVisibility(Var))
605 LV.setVisibility(GetVisibilityFromAttr(VA));
607 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
608 LinkageInfo PrevLV = Prev->getLinkageAndVisibility();
609 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
610 LV.mergeVisibility(PrevLV);
613 return LV;
617 // C++ [basic.link]p6:
618 // Names not covered by these rules have no linkage.
619 return LinkageInfo::none();
622 std::string NamedDecl::getQualifiedNameAsString() const {
623 return getQualifiedNameAsString(getASTContext().getLangOptions());
626 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
627 const DeclContext *Ctx = getDeclContext();
629 if (Ctx->isFunctionOrMethod())
630 return getNameAsString();
632 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy;
633 ContextsTy Contexts;
635 // Collect contexts.
636 while (Ctx && isa<NamedDecl>(Ctx)) {
637 Contexts.push_back(Ctx);
638 Ctx = Ctx->getParent();
641 std::string QualName;
642 llvm::raw_string_ostream OS(QualName);
644 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
645 I != E; ++I) {
646 if (const ClassTemplateSpecializationDecl *Spec
647 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
648 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
649 std::string TemplateArgsStr
650 = TemplateSpecializationType::PrintTemplateArgumentList(
651 TemplateArgs.getFlatArgumentList(),
652 TemplateArgs.flat_size(),
654 OS << Spec->getName() << TemplateArgsStr;
655 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
656 if (ND->isAnonymousNamespace())
657 OS << "<anonymous namespace>";
658 else
659 OS << ND;
660 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
661 if (!RD->getIdentifier())
662 OS << "<anonymous " << RD->getKindName() << '>';
663 else
664 OS << RD;
665 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
666 const FunctionProtoType *FT = 0;
667 if (FD->hasWrittenPrototype())
668 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
670 OS << FD << '(';
671 if (FT) {
672 unsigned NumParams = FD->getNumParams();
673 for (unsigned i = 0; i < NumParams; ++i) {
674 if (i)
675 OS << ", ";
676 std::string Param;
677 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
678 OS << Param;
681 if (FT->isVariadic()) {
682 if (NumParams > 0)
683 OS << ", ";
684 OS << "...";
687 OS << ')';
688 } else {
689 OS << cast<NamedDecl>(*I);
691 OS << "::";
694 if (getDeclName())
695 OS << this;
696 else
697 OS << "<anonymous>";
699 return OS.str();
702 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
703 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
705 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
706 // We want to keep it, unless it nominates same namespace.
707 if (getKind() == Decl::UsingDirective) {
708 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() ==
709 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace();
712 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
713 // For function declarations, we keep track of redeclarations.
714 return FD->getPreviousDeclaration() == OldD;
716 // For function templates, the underlying function declarations are linked.
717 if (const FunctionTemplateDecl *FunctionTemplate
718 = dyn_cast<FunctionTemplateDecl>(this))
719 if (const FunctionTemplateDecl *OldFunctionTemplate
720 = dyn_cast<FunctionTemplateDecl>(OldD))
721 return FunctionTemplate->getTemplatedDecl()
722 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
724 // For method declarations, we keep track of redeclarations.
725 if (isa<ObjCMethodDecl>(this))
726 return false;
728 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
729 return true;
731 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
732 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
733 cast<UsingShadowDecl>(OldD)->getTargetDecl();
735 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD))
736 return cast<UsingDecl>(this)->getTargetNestedNameDecl() ==
737 cast<UsingDecl>(OldD)->getTargetNestedNameDecl();
739 // For non-function declarations, if the declarations are of the
740 // same kind then this must be a redeclaration, or semantic analysis
741 // would not have given us the new declaration.
742 return this->getKind() == OldD->getKind();
745 bool NamedDecl::hasLinkage() const {
746 return getLinkage() != NoLinkage;
749 NamedDecl *NamedDecl::getUnderlyingDecl() {
750 NamedDecl *ND = this;
751 while (true) {
752 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
753 ND = UD->getTargetDecl();
754 else if (ObjCCompatibleAliasDecl *AD
755 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
756 return AD->getClassInterface();
757 else
758 return ND;
762 bool NamedDecl::isCXXInstanceMember() const {
763 assert(isCXXClassMember() &&
764 "checking whether non-member is instance member");
766 const NamedDecl *D = this;
767 if (isa<UsingShadowDecl>(D))
768 D = cast<UsingShadowDecl>(D)->getTargetDecl();
770 if (isa<FieldDecl>(D))
771 return true;
772 if (isa<CXXMethodDecl>(D))
773 return cast<CXXMethodDecl>(D)->isInstance();
774 if (isa<FunctionTemplateDecl>(D))
775 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
776 ->getTemplatedDecl())->isInstance();
777 return false;
780 //===----------------------------------------------------------------------===//
781 // DeclaratorDecl Implementation
782 //===----------------------------------------------------------------------===//
784 template <typename DeclT>
785 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
786 if (decl->getNumTemplateParameterLists() > 0)
787 return decl->getTemplateParameterList(0)->getTemplateLoc();
788 else
789 return decl->getInnerLocStart();
792 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
793 TypeSourceInfo *TSI = getTypeSourceInfo();
794 if (TSI) return TSI->getTypeLoc().getBeginLoc();
795 return SourceLocation();
798 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
799 SourceRange QualifierRange) {
800 if (Qualifier) {
801 // Make sure the extended decl info is allocated.
802 if (!hasExtInfo()) {
803 // Save (non-extended) type source info pointer.
804 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
805 // Allocate external info struct.
806 DeclInfo = new (getASTContext()) ExtInfo;
807 // Restore savedTInfo into (extended) decl info.
808 getExtInfo()->TInfo = savedTInfo;
810 // Set qualifier info.
811 getExtInfo()->NNS = Qualifier;
812 getExtInfo()->NNSRange = QualifierRange;
814 else {
815 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
816 assert(QualifierRange.isInvalid());
817 if (hasExtInfo()) {
818 // Save type source info pointer.
819 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
820 // Deallocate the extended decl info.
821 getASTContext().Deallocate(getExtInfo());
822 // Restore savedTInfo into (non-extended) decl info.
823 DeclInfo = savedTInfo;
828 SourceLocation DeclaratorDecl::getOuterLocStart() const {
829 return getTemplateOrInnerLocStart(this);
832 void
833 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
834 unsigned NumTPLists,
835 TemplateParameterList **TPLists) {
836 assert((NumTPLists == 0 || TPLists != 0) &&
837 "Empty array of template parameters with positive size!");
838 assert((NumTPLists == 0 || NNS) &&
839 "Nonempty array of template parameters with no qualifier!");
841 // Free previous template parameters (if any).
842 if (NumTemplParamLists > 0) {
843 Context.Deallocate(TemplParamLists);
844 TemplParamLists = 0;
845 NumTemplParamLists = 0;
847 // Set info on matched template parameter lists (if any).
848 if (NumTPLists > 0) {
849 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
850 NumTemplParamLists = NumTPLists;
851 for (unsigned i = NumTPLists; i-- > 0; )
852 TemplParamLists[i] = TPLists[i];
856 //===----------------------------------------------------------------------===//
857 // VarDecl Implementation
858 //===----------------------------------------------------------------------===//
860 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
861 switch (SC) {
862 case SC_None: break;
863 case SC_Auto: return "auto"; break;
864 case SC_Extern: return "extern"; break;
865 case SC_PrivateExtern: return "__private_extern__"; break;
866 case SC_Register: return "register"; break;
867 case SC_Static: return "static"; break;
870 assert(0 && "Invalid storage class");
871 return 0;
874 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
875 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
876 StorageClass S, StorageClass SCAsWritten) {
877 return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten);
880 SourceLocation VarDecl::getInnerLocStart() const {
881 SourceLocation Start = getTypeSpecStartLoc();
882 if (Start.isInvalid())
883 Start = getLocation();
884 return Start;
887 SourceRange VarDecl::getSourceRange() const {
888 if (getInit())
889 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
890 return SourceRange(getOuterLocStart(), getLocation());
893 bool VarDecl::isExternC() const {
894 ASTContext &Context = getASTContext();
895 if (!Context.getLangOptions().CPlusPlus)
896 return (getDeclContext()->isTranslationUnit() &&
897 getStorageClass() != SC_Static) ||
898 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
900 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
901 DC = DC->getParent()) {
902 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
903 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
904 return getStorageClass() != SC_Static;
906 break;
909 if (DC->isFunctionOrMethod())
910 return false;
913 return false;
916 VarDecl *VarDecl::getCanonicalDecl() {
917 return getFirstDeclaration();
920 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
921 // C++ [basic.def]p2:
922 // A declaration is a definition unless [...] it contains the 'extern'
923 // specifier or a linkage-specification and neither an initializer [...],
924 // it declares a static data member in a class declaration [...].
925 // C++ [temp.expl.spec]p15:
926 // An explicit specialization of a static data member of a template is a
927 // definition if the declaration includes an initializer; otherwise, it is
928 // a declaration.
929 if (isStaticDataMember()) {
930 if (isOutOfLine() && (hasInit() ||
931 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
932 return Definition;
933 else
934 return DeclarationOnly;
936 // C99 6.7p5:
937 // A definition of an identifier is a declaration for that identifier that
938 // [...] causes storage to be reserved for that object.
939 // Note: that applies for all non-file-scope objects.
940 // C99 6.9.2p1:
941 // If the declaration of an identifier for an object has file scope and an
942 // initializer, the declaration is an external definition for the identifier
943 if (hasInit())
944 return Definition;
945 // AST for 'extern "C" int foo;' is annotated with 'extern'.
946 if (hasExternalStorage())
947 return DeclarationOnly;
949 if (getStorageClassAsWritten() == SC_Extern ||
950 getStorageClassAsWritten() == SC_PrivateExtern) {
951 for (const VarDecl *PrevVar = getPreviousDeclaration();
952 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
953 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
954 return DeclarationOnly;
957 // C99 6.9.2p2:
958 // A declaration of an object that has file scope without an initializer,
959 // and without a storage class specifier or the scs 'static', constitutes
960 // a tentative definition.
961 // No such thing in C++.
962 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
963 return TentativeDefinition;
965 // What's left is (in C, block-scope) declarations without initializers or
966 // external storage. These are definitions.
967 return Definition;
970 VarDecl *VarDecl::getActingDefinition() {
971 DefinitionKind Kind = isThisDeclarationADefinition();
972 if (Kind != TentativeDefinition)
973 return 0;
975 VarDecl *LastTentative = 0;
976 VarDecl *First = getFirstDeclaration();
977 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
978 I != E; ++I) {
979 Kind = (*I)->isThisDeclarationADefinition();
980 if (Kind == Definition)
981 return 0;
982 else if (Kind == TentativeDefinition)
983 LastTentative = *I;
985 return LastTentative;
988 bool VarDecl::isTentativeDefinitionNow() const {
989 DefinitionKind Kind = isThisDeclarationADefinition();
990 if (Kind != TentativeDefinition)
991 return false;
993 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
994 if ((*I)->isThisDeclarationADefinition() == Definition)
995 return false;
997 return true;
1000 VarDecl *VarDecl::getDefinition() {
1001 VarDecl *First = getFirstDeclaration();
1002 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1003 I != E; ++I) {
1004 if ((*I)->isThisDeclarationADefinition() == Definition)
1005 return *I;
1007 return 0;
1010 VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1011 DefinitionKind Kind = DeclarationOnly;
1013 const VarDecl *First = getFirstDeclaration();
1014 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1015 I != E; ++I)
1016 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1018 return Kind;
1021 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1022 redecl_iterator I = redecls_begin(), E = redecls_end();
1023 while (I != E && !I->getInit())
1024 ++I;
1026 if (I != E) {
1027 D = *I;
1028 return I->getInit();
1030 return 0;
1033 bool VarDecl::isOutOfLine() const {
1034 if (Decl::isOutOfLine())
1035 return true;
1037 if (!isStaticDataMember())
1038 return false;
1040 // If this static data member was instantiated from a static data member of
1041 // a class template, check whether that static data member was defined
1042 // out-of-line.
1043 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1044 return VD->isOutOfLine();
1046 return false;
1049 VarDecl *VarDecl::getOutOfLineDefinition() {
1050 if (!isStaticDataMember())
1051 return 0;
1053 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1054 RD != RDEnd; ++RD) {
1055 if (RD->getLexicalDeclContext()->isFileContext())
1056 return *RD;
1059 return 0;
1062 void VarDecl::setInit(Expr *I) {
1063 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1064 Eval->~EvaluatedStmt();
1065 getASTContext().Deallocate(Eval);
1068 Init = I;
1071 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1072 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1073 return cast<VarDecl>(MSI->getInstantiatedFrom());
1075 return 0;
1078 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1079 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1080 return MSI->getTemplateSpecializationKind();
1082 return TSK_Undeclared;
1085 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1086 return getASTContext().getInstantiatedFromStaticDataMember(this);
1089 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1090 SourceLocation PointOfInstantiation) {
1091 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1092 assert(MSI && "Not an instantiated static data member?");
1093 MSI->setTemplateSpecializationKind(TSK);
1094 if (TSK != TSK_ExplicitSpecialization &&
1095 PointOfInstantiation.isValid() &&
1096 MSI->getPointOfInstantiation().isInvalid())
1097 MSI->setPointOfInstantiation(PointOfInstantiation);
1100 //===----------------------------------------------------------------------===//
1101 // ParmVarDecl Implementation
1102 //===----------------------------------------------------------------------===//
1104 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1105 SourceLocation L, IdentifierInfo *Id,
1106 QualType T, TypeSourceInfo *TInfo,
1107 StorageClass S, StorageClass SCAsWritten,
1108 Expr *DefArg) {
1109 return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo,
1110 S, SCAsWritten, DefArg);
1113 Expr *ParmVarDecl::getDefaultArg() {
1114 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1115 assert(!hasUninstantiatedDefaultArg() &&
1116 "Default argument is not yet instantiated!");
1118 Expr *Arg = getInit();
1119 if (CXXExprWithTemporaries *E = dyn_cast_or_null<CXXExprWithTemporaries>(Arg))
1120 return E->getSubExpr();
1122 return Arg;
1125 unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
1126 if (const CXXExprWithTemporaries *E =
1127 dyn_cast<CXXExprWithTemporaries>(getInit()))
1128 return E->getNumTemporaries();
1130 return 0;
1133 CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
1134 assert(getNumDefaultArgTemporaries() &&
1135 "Default arguments does not have any temporaries!");
1137 CXXExprWithTemporaries *E = cast<CXXExprWithTemporaries>(getInit());
1138 return E->getTemporary(i);
1141 SourceRange ParmVarDecl::getDefaultArgRange() const {
1142 if (const Expr *E = getInit())
1143 return E->getSourceRange();
1145 if (hasUninstantiatedDefaultArg())
1146 return getUninstantiatedDefaultArg()->getSourceRange();
1148 return SourceRange();
1151 //===----------------------------------------------------------------------===//
1152 // FunctionDecl Implementation
1153 //===----------------------------------------------------------------------===//
1155 void FunctionDecl::getNameForDiagnostic(std::string &S,
1156 const PrintingPolicy &Policy,
1157 bool Qualified) const {
1158 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1159 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1160 if (TemplateArgs)
1161 S += TemplateSpecializationType::PrintTemplateArgumentList(
1162 TemplateArgs->getFlatArgumentList(),
1163 TemplateArgs->flat_size(),
1164 Policy);
1168 bool FunctionDecl::isVariadic() const {
1169 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1170 return FT->isVariadic();
1171 return false;
1174 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1175 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1176 if (I->Body) {
1177 Definition = *I;
1178 return true;
1182 return false;
1185 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1186 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1187 if (I->Body) {
1188 Definition = *I;
1189 return I->Body.get(getASTContext().getExternalSource());
1193 return 0;
1196 void FunctionDecl::setBody(Stmt *B) {
1197 Body = B;
1198 if (B)
1199 EndRangeLoc = B->getLocEnd();
1202 void FunctionDecl::setPure(bool P) {
1203 IsPure = P;
1204 if (P)
1205 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1206 Parent->markedVirtualFunctionPure();
1209 bool FunctionDecl::isMain() const {
1210 ASTContext &Context = getASTContext();
1211 return !Context.getLangOptions().Freestanding &&
1212 getDeclContext()->getRedeclContext()->isTranslationUnit() &&
1213 getIdentifier() && getIdentifier()->isStr("main");
1216 bool FunctionDecl::isExternC() const {
1217 ASTContext &Context = getASTContext();
1218 // In C, any non-static, non-overloadable function has external
1219 // linkage.
1220 if (!Context.getLangOptions().CPlusPlus)
1221 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
1223 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
1224 DC = DC->getParent()) {
1225 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1226 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1227 return getStorageClass() != SC_Static &&
1228 !getAttr<OverloadableAttr>();
1230 break;
1233 if (DC->isRecord())
1234 break;
1237 return isMain();
1240 bool FunctionDecl::isGlobal() const {
1241 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1242 return Method->isStatic();
1244 if (getStorageClass() == SC_Static)
1245 return false;
1247 for (const DeclContext *DC = getDeclContext();
1248 DC->isNamespace();
1249 DC = DC->getParent()) {
1250 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1251 if (!Namespace->getDeclName())
1252 return false;
1253 break;
1257 return true;
1260 void
1261 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1262 redeclarable_base::setPreviousDeclaration(PrevDecl);
1264 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1265 FunctionTemplateDecl *PrevFunTmpl
1266 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1267 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1268 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1272 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1273 return getFirstDeclaration();
1276 FunctionDecl *FunctionDecl::getCanonicalDecl() {
1277 return getFirstDeclaration();
1280 /// \brief Returns a value indicating whether this function
1281 /// corresponds to a builtin function.
1283 /// The function corresponds to a built-in function if it is
1284 /// declared at translation scope or within an extern "C" block and
1285 /// its name matches with the name of a builtin. The returned value
1286 /// will be 0 for functions that do not correspond to a builtin, a
1287 /// value of type \c Builtin::ID if in the target-independent range
1288 /// \c [1,Builtin::First), or a target-specific builtin value.
1289 unsigned FunctionDecl::getBuiltinID() const {
1290 ASTContext &Context = getASTContext();
1291 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1292 return 0;
1294 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1295 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1296 return BuiltinID;
1298 // This function has the name of a known C library
1299 // function. Determine whether it actually refers to the C library
1300 // function or whether it just has the same name.
1302 // If this is a static function, it's not a builtin.
1303 if (getStorageClass() == SC_Static)
1304 return 0;
1306 // If this function is at translation-unit scope and we're not in
1307 // C++, it refers to the C library function.
1308 if (!Context.getLangOptions().CPlusPlus &&
1309 getDeclContext()->isTranslationUnit())
1310 return BuiltinID;
1312 // If the function is in an extern "C" linkage specification and is
1313 // not marked "overloadable", it's the real function.
1314 if (isa<LinkageSpecDecl>(getDeclContext()) &&
1315 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1316 == LinkageSpecDecl::lang_c &&
1317 !getAttr<OverloadableAttr>())
1318 return BuiltinID;
1320 // Not a builtin
1321 return 0;
1325 /// getNumParams - Return the number of parameters this function must have
1326 /// based on its FunctionType. This is the length of the PararmInfo array
1327 /// after it has been created.
1328 unsigned FunctionDecl::getNumParams() const {
1329 const FunctionType *FT = getType()->getAs<FunctionType>();
1330 if (isa<FunctionNoProtoType>(FT))
1331 return 0;
1332 return cast<FunctionProtoType>(FT)->getNumArgs();
1336 void FunctionDecl::setParams(ASTContext &C,
1337 ParmVarDecl **NewParamInfo, unsigned NumParams) {
1338 assert(ParamInfo == 0 && "Already has param info!");
1339 assert(NumParams == getNumParams() && "Parameter count mismatch!");
1341 // Zero params -> null pointer.
1342 if (NumParams) {
1343 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams);
1344 ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1345 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1347 // Update source range. The check below allows us to set EndRangeLoc before
1348 // setting the parameters.
1349 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation())
1350 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd();
1354 /// getMinRequiredArguments - Returns the minimum number of arguments
1355 /// needed to call this function. This may be fewer than the number of
1356 /// function parameters, if some of the parameters have default
1357 /// arguments (in C++).
1358 unsigned FunctionDecl::getMinRequiredArguments() const {
1359 unsigned NumRequiredArgs = getNumParams();
1360 while (NumRequiredArgs > 0
1361 && getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1362 --NumRequiredArgs;
1364 return NumRequiredArgs;
1367 bool FunctionDecl::isInlined() const {
1368 // FIXME: This is not enough. Consider:
1370 // inline void f();
1371 // void f() { }
1373 // f is inlined, but does not have inline specified.
1374 // To fix this we should add an 'inline' flag to FunctionDecl.
1375 if (isInlineSpecified())
1376 return true;
1378 if (isa<CXXMethodDecl>(this)) {
1379 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1380 return true;
1383 switch (getTemplateSpecializationKind()) {
1384 case TSK_Undeclared:
1385 case TSK_ExplicitSpecialization:
1386 return false;
1388 case TSK_ImplicitInstantiation:
1389 case TSK_ExplicitInstantiationDeclaration:
1390 case TSK_ExplicitInstantiationDefinition:
1391 // Handle below.
1392 break;
1395 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1396 bool HasPattern = false;
1397 if (PatternDecl)
1398 HasPattern = PatternDecl->hasBody(PatternDecl);
1400 if (HasPattern && PatternDecl)
1401 return PatternDecl->isInlined();
1403 return false;
1406 /// \brief For an inline function definition in C or C++, determine whether the
1407 /// definition will be externally visible.
1409 /// Inline function definitions are always available for inlining optimizations.
1410 /// However, depending on the language dialect, declaration specifiers, and
1411 /// attributes, the definition of an inline function may or may not be
1412 /// "externally" visible to other translation units in the program.
1414 /// In C99, inline definitions are not externally visible by default. However,
1415 /// if even one of the global-scope declarations is marked "extern inline", the
1416 /// inline definition becomes externally visible (C99 6.7.4p6).
1418 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1419 /// definition, we use the GNU semantics for inline, which are nearly the
1420 /// opposite of C99 semantics. In particular, "inline" by itself will create
1421 /// an externally visible symbol, but "extern inline" will not create an
1422 /// externally visible symbol.
1423 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
1424 assert(isThisDeclarationADefinition() && "Must have the function definition");
1425 assert(isInlined() && "Function must be inline");
1426 ASTContext &Context = getASTContext();
1428 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) {
1429 // GNU inline semantics. Based on a number of examples, we came up with the
1430 // following heuristic: if the "inline" keyword is present on a
1431 // declaration of the function but "extern" is not present on that
1432 // declaration, then the symbol is externally visible. Otherwise, the GNU
1433 // "extern inline" semantics applies and the symbol is not externally
1434 // visible.
1435 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1436 Redecl != RedeclEnd;
1437 ++Redecl) {
1438 if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != SC_Extern)
1439 return true;
1442 // GNU "extern inline" semantics; no externally visible symbol.
1443 return false;
1446 // C99 6.7.4p6:
1447 // [...] If all of the file scope declarations for a function in a
1448 // translation unit include the inline function specifier without extern,
1449 // then the definition in that translation unit is an inline definition.
1450 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1451 Redecl != RedeclEnd;
1452 ++Redecl) {
1453 // Only consider file-scope declarations in this test.
1454 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1455 continue;
1457 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1458 return true; // Not an inline definition
1461 // C99 6.7.4p6:
1462 // An inline definition does not provide an external definition for the
1463 // function, and does not forbid an external definition in another
1464 // translation unit.
1465 return false;
1468 /// getOverloadedOperator - Which C++ overloaded operator this
1469 /// function represents, if any.
1470 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
1471 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1472 return getDeclName().getCXXOverloadedOperator();
1473 else
1474 return OO_None;
1477 /// getLiteralIdentifier - The literal suffix identifier this function
1478 /// represents, if any.
1479 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1480 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1481 return getDeclName().getCXXLiteralIdentifier();
1482 else
1483 return 0;
1486 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1487 if (TemplateOrSpecialization.isNull())
1488 return TK_NonTemplate;
1489 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1490 return TK_FunctionTemplate;
1491 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1492 return TK_MemberSpecialization;
1493 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1494 return TK_FunctionTemplateSpecialization;
1495 if (TemplateOrSpecialization.is
1496 <DependentFunctionTemplateSpecializationInfo*>())
1497 return TK_DependentFunctionTemplateSpecialization;
1499 assert(false && "Did we miss a TemplateOrSpecialization type?");
1500 return TK_NonTemplate;
1503 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
1504 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
1505 return cast<FunctionDecl>(Info->getInstantiatedFrom());
1507 return 0;
1510 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1511 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1514 void
1515 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
1516 FunctionDecl *FD,
1517 TemplateSpecializationKind TSK) {
1518 assert(TemplateOrSpecialization.isNull() &&
1519 "Member function is already a specialization");
1520 MemberSpecializationInfo *Info
1521 = new (C) MemberSpecializationInfo(FD, TSK);
1522 TemplateOrSpecialization = Info;
1525 bool FunctionDecl::isImplicitlyInstantiable() const {
1526 // If the function is invalid, it can't be implicitly instantiated.
1527 if (isInvalidDecl())
1528 return false;
1530 switch (getTemplateSpecializationKind()) {
1531 case TSK_Undeclared:
1532 case TSK_ExplicitSpecialization:
1533 case TSK_ExplicitInstantiationDefinition:
1534 return false;
1536 case TSK_ImplicitInstantiation:
1537 return true;
1539 case TSK_ExplicitInstantiationDeclaration:
1540 // Handled below.
1541 break;
1544 // Find the actual template from which we will instantiate.
1545 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1546 bool HasPattern = false;
1547 if (PatternDecl)
1548 HasPattern = PatternDecl->hasBody(PatternDecl);
1550 // C++0x [temp.explicit]p9:
1551 // Except for inline functions, other explicit instantiation declarations
1552 // have the effect of suppressing the implicit instantiation of the entity
1553 // to which they refer.
1554 if (!HasPattern || !PatternDecl)
1555 return true;
1557 return PatternDecl->isInlined();
1560 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
1561 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
1562 while (Primary->getInstantiatedFromMemberTemplate()) {
1563 // If we have hit a point where the user provided a specialization of
1564 // this template, we're done looking.
1565 if (Primary->isMemberSpecialization())
1566 break;
1568 Primary = Primary->getInstantiatedFromMemberTemplate();
1571 return Primary->getTemplatedDecl();
1574 return getInstantiatedFromMemberFunction();
1577 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
1578 if (FunctionTemplateSpecializationInfo *Info
1579 = TemplateOrSpecialization
1580 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1581 return Info->Template.getPointer();
1583 return 0;
1586 const TemplateArgumentList *
1587 FunctionDecl::getTemplateSpecializationArgs() const {
1588 if (FunctionTemplateSpecializationInfo *Info
1589 = TemplateOrSpecialization
1590 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1591 return Info->TemplateArguments;
1593 return 0;
1596 const TemplateArgumentListInfo *
1597 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
1598 if (FunctionTemplateSpecializationInfo *Info
1599 = TemplateOrSpecialization
1600 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1601 return Info->TemplateArgumentsAsWritten;
1603 return 0;
1606 void
1607 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
1608 FunctionTemplateDecl *Template,
1609 const TemplateArgumentList *TemplateArgs,
1610 void *InsertPos,
1611 TemplateSpecializationKind TSK,
1612 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1613 SourceLocation PointOfInstantiation) {
1614 assert(TSK != TSK_Undeclared &&
1615 "Must specify the type of function template specialization");
1616 FunctionTemplateSpecializationInfo *Info
1617 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1618 if (!Info)
1619 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
1620 TemplateArgs,
1621 TemplateArgsAsWritten,
1622 PointOfInstantiation);
1623 TemplateOrSpecialization = Info;
1625 // Insert this function template specialization into the set of known
1626 // function template specializations.
1627 if (InsertPos)
1628 Template->getSpecializations().InsertNode(Info, InsertPos);
1629 else {
1630 // Try to insert the new node. If there is an existing node, leave it, the
1631 // set will contain the canonical decls while
1632 // FunctionTemplateDecl::findSpecialization will return
1633 // the most recent redeclarations.
1634 FunctionTemplateSpecializationInfo *Existing
1635 = Template->getSpecializations().GetOrInsertNode(Info);
1636 (void)Existing;
1637 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
1638 "Set is supposed to only contain canonical decls");
1642 void
1643 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
1644 const UnresolvedSetImpl &Templates,
1645 const TemplateArgumentListInfo &TemplateArgs) {
1646 assert(TemplateOrSpecialization.isNull());
1647 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
1648 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
1649 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
1650 void *Buffer = Context.Allocate(Size);
1651 DependentFunctionTemplateSpecializationInfo *Info =
1652 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
1653 TemplateArgs);
1654 TemplateOrSpecialization = Info;
1657 DependentFunctionTemplateSpecializationInfo::
1658 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
1659 const TemplateArgumentListInfo &TArgs)
1660 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
1662 d.NumTemplates = Ts.size();
1663 d.NumArgs = TArgs.size();
1665 FunctionTemplateDecl **TsArray =
1666 const_cast<FunctionTemplateDecl**>(getTemplates());
1667 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
1668 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
1670 TemplateArgumentLoc *ArgsArray =
1671 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
1672 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
1673 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
1676 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
1677 // For a function template specialization, query the specialization
1678 // information object.
1679 FunctionTemplateSpecializationInfo *FTSInfo
1680 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1681 if (FTSInfo)
1682 return FTSInfo->getTemplateSpecializationKind();
1684 MemberSpecializationInfo *MSInfo
1685 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1686 if (MSInfo)
1687 return MSInfo->getTemplateSpecializationKind();
1689 return TSK_Undeclared;
1692 void
1693 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1694 SourceLocation PointOfInstantiation) {
1695 if (FunctionTemplateSpecializationInfo *FTSInfo
1696 = TemplateOrSpecialization.dyn_cast<
1697 FunctionTemplateSpecializationInfo*>()) {
1698 FTSInfo->setTemplateSpecializationKind(TSK);
1699 if (TSK != TSK_ExplicitSpecialization &&
1700 PointOfInstantiation.isValid() &&
1701 FTSInfo->getPointOfInstantiation().isInvalid())
1702 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
1703 } else if (MemberSpecializationInfo *MSInfo
1704 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
1705 MSInfo->setTemplateSpecializationKind(TSK);
1706 if (TSK != TSK_ExplicitSpecialization &&
1707 PointOfInstantiation.isValid() &&
1708 MSInfo->getPointOfInstantiation().isInvalid())
1709 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1710 } else
1711 assert(false && "Function cannot have a template specialization kind");
1714 SourceLocation FunctionDecl::getPointOfInstantiation() const {
1715 if (FunctionTemplateSpecializationInfo *FTSInfo
1716 = TemplateOrSpecialization.dyn_cast<
1717 FunctionTemplateSpecializationInfo*>())
1718 return FTSInfo->getPointOfInstantiation();
1719 else if (MemberSpecializationInfo *MSInfo
1720 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
1721 return MSInfo->getPointOfInstantiation();
1723 return SourceLocation();
1726 bool FunctionDecl::isOutOfLine() const {
1727 if (Decl::isOutOfLine())
1728 return true;
1730 // If this function was instantiated from a member function of a
1731 // class template, check whether that member function was defined out-of-line.
1732 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
1733 const FunctionDecl *Definition;
1734 if (FD->hasBody(Definition))
1735 return Definition->isOutOfLine();
1738 // If this function was instantiated from a function template,
1739 // check whether that function template was defined out-of-line.
1740 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
1741 const FunctionDecl *Definition;
1742 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
1743 return Definition->isOutOfLine();
1746 return false;
1749 //===----------------------------------------------------------------------===//
1750 // FieldDecl Implementation
1751 //===----------------------------------------------------------------------===//
1753 FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1754 IdentifierInfo *Id, QualType T,
1755 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) {
1756 return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable);
1759 bool FieldDecl::isAnonymousStructOrUnion() const {
1760 if (!isImplicit() || getDeclName())
1761 return false;
1763 if (const RecordType *Record = getType()->getAs<RecordType>())
1764 return Record->getDecl()->isAnonymousStructOrUnion();
1766 return false;
1769 //===----------------------------------------------------------------------===//
1770 // TagDecl Implementation
1771 //===----------------------------------------------------------------------===//
1773 SourceLocation TagDecl::getOuterLocStart() const {
1774 return getTemplateOrInnerLocStart(this);
1777 SourceRange TagDecl::getSourceRange() const {
1778 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
1779 return SourceRange(getOuterLocStart(), E);
1782 TagDecl* TagDecl::getCanonicalDecl() {
1783 return getFirstDeclaration();
1786 void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) {
1787 TypedefDeclOrQualifier = TDD;
1788 if (TypeForDecl)
1789 TypeForDecl->ClearLinkageCache();
1792 void TagDecl::startDefinition() {
1793 IsBeingDefined = true;
1795 if (isa<CXXRecordDecl>(this)) {
1796 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
1797 struct CXXRecordDecl::DefinitionData *Data =
1798 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
1799 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
1800 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
1804 void TagDecl::completeDefinition() {
1805 assert((!isa<CXXRecordDecl>(this) ||
1806 cast<CXXRecordDecl>(this)->hasDefinition()) &&
1807 "definition completed but not started");
1809 IsDefinition = true;
1810 IsBeingDefined = false;
1812 if (ASTMutationListener *L = getASTMutationListener())
1813 L->CompletedTagDefinition(this);
1816 TagDecl* TagDecl::getDefinition() const {
1817 if (isDefinition())
1818 return const_cast<TagDecl *>(this);
1819 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
1820 return CXXRD->getDefinition();
1822 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
1823 R != REnd; ++R)
1824 if (R->isDefinition())
1825 return *R;
1827 return 0;
1830 void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
1831 SourceRange QualifierRange) {
1832 if (Qualifier) {
1833 // Make sure the extended qualifier info is allocated.
1834 if (!hasExtInfo())
1835 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo;
1836 // Set qualifier info.
1837 getExtInfo()->NNS = Qualifier;
1838 getExtInfo()->NNSRange = QualifierRange;
1840 else {
1841 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1842 assert(QualifierRange.isInvalid());
1843 if (hasExtInfo()) {
1844 getASTContext().Deallocate(getExtInfo());
1845 TypedefDeclOrQualifier = (TypedefDecl*) 0;
1850 //===----------------------------------------------------------------------===//
1851 // EnumDecl Implementation
1852 //===----------------------------------------------------------------------===//
1854 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1855 IdentifierInfo *Id, SourceLocation TKL,
1856 EnumDecl *PrevDecl, bool IsScoped, bool IsFixed) {
1857 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL,
1858 IsScoped, IsFixed);
1859 C.getTypeDeclType(Enum, PrevDecl);
1860 return Enum;
1863 EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
1864 return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation(),
1865 false, false);
1868 void EnumDecl::completeDefinition(QualType NewType,
1869 QualType NewPromotionType,
1870 unsigned NumPositiveBits,
1871 unsigned NumNegativeBits) {
1872 assert(!isDefinition() && "Cannot redefine enums!");
1873 if (!IntegerType)
1874 IntegerType = NewType.getTypePtr();
1875 PromotionType = NewPromotionType;
1876 setNumPositiveBits(NumPositiveBits);
1877 setNumNegativeBits(NumNegativeBits);
1878 TagDecl::completeDefinition();
1881 //===----------------------------------------------------------------------===//
1882 // RecordDecl Implementation
1883 //===----------------------------------------------------------------------===//
1885 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
1886 IdentifierInfo *Id, RecordDecl *PrevDecl,
1887 SourceLocation TKL)
1888 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) {
1889 HasFlexibleArrayMember = false;
1890 AnonymousStructOrUnion = false;
1891 HasObjectMember = false;
1892 LoadedFieldsFromExternalStorage = false;
1893 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
1896 RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
1897 SourceLocation L, IdentifierInfo *Id,
1898 SourceLocation TKL, RecordDecl* PrevDecl) {
1900 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL);
1901 C.getTypeDeclType(R, PrevDecl);
1902 return R;
1905 RecordDecl *RecordDecl::Create(ASTContext &C, EmptyShell Empty) {
1906 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0,
1907 SourceLocation());
1910 bool RecordDecl::isInjectedClassName() const {
1911 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
1912 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
1915 RecordDecl::field_iterator RecordDecl::field_begin() const {
1916 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
1917 LoadFieldsFromExternalStorage();
1919 return field_iterator(decl_iterator(FirstDecl));
1922 /// completeDefinition - Notes that the definition of this type is now
1923 /// complete.
1924 void RecordDecl::completeDefinition() {
1925 assert(!isDefinition() && "Cannot redefine record!");
1926 TagDecl::completeDefinition();
1929 ValueDecl *RecordDecl::getAnonymousStructOrUnionObject() {
1930 // Force the decl chain to come into existence properly.
1931 if (!getNextDeclInContext()) getParent()->decls_begin();
1933 assert(isAnonymousStructOrUnion());
1934 ValueDecl *D = cast<ValueDecl>(getNextDeclInContext());
1935 assert(D->getType()->isRecordType());
1936 assert(D->getType()->getAs<RecordType>()->getDecl() == this);
1937 return D;
1940 void RecordDecl::LoadFieldsFromExternalStorage() const {
1941 ExternalASTSource *Source = getASTContext().getExternalSource();
1942 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1944 // Notify that we have a RecordDecl doing some initialization.
1945 ExternalASTSource::Deserializing TheFields(Source);
1947 llvm::SmallVector<Decl*, 64> Decls;
1948 if (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls))
1949 return;
1951 #ifndef NDEBUG
1952 // Check that all decls we got were FieldDecls.
1953 for (unsigned i=0, e=Decls.size(); i != e; ++i)
1954 assert(isa<FieldDecl>(Decls[i]));
1955 #endif
1957 LoadedFieldsFromExternalStorage = true;
1959 if (Decls.empty())
1960 return;
1962 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
1965 //===----------------------------------------------------------------------===//
1966 // BlockDecl Implementation
1967 //===----------------------------------------------------------------------===//
1969 void BlockDecl::setParams(ParmVarDecl **NewParamInfo,
1970 unsigned NParms) {
1971 assert(ParamInfo == 0 && "Already has param info!");
1973 // Zero params -> null pointer.
1974 if (NParms) {
1975 NumParams = NParms;
1976 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams);
1977 ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1978 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1982 unsigned BlockDecl::getNumParams() const {
1983 return NumParams;
1987 //===----------------------------------------------------------------------===//
1988 // Other Decl Allocation/Deallocation Method Implementations
1989 //===----------------------------------------------------------------------===//
1991 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
1992 return new (C) TranslationUnitDecl(C);
1995 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1996 SourceLocation L, IdentifierInfo *Id) {
1997 return new (C) NamespaceDecl(DC, L, Id);
2000 NamespaceDecl *NamespaceDecl::getNextNamespace() {
2001 return dyn_cast_or_null<NamespaceDecl>(
2002 NextNamespace.get(getASTContext().getExternalSource()));
2005 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2006 SourceLocation L, IdentifierInfo *Id, QualType T) {
2007 return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T);
2010 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2011 const DeclarationNameInfo &NameInfo,
2012 QualType T, TypeSourceInfo *TInfo,
2013 StorageClass S, StorageClass SCAsWritten,
2014 bool isInline, bool hasWrittenPrototype) {
2015 FunctionDecl *New = new (C) FunctionDecl(Function, DC, NameInfo, T, TInfo,
2016 S, SCAsWritten, isInline);
2017 New->HasWrittenPrototype = hasWrittenPrototype;
2018 return New;
2021 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2022 return new (C) BlockDecl(DC, L);
2025 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2026 SourceLocation L,
2027 IdentifierInfo *Id, QualType T,
2028 Expr *E, const llvm::APSInt &V) {
2029 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2032 SourceRange EnumConstantDecl::getSourceRange() const {
2033 SourceLocation End = getLocation();
2034 if (Init)
2035 End = Init->getLocEnd();
2036 return SourceRange(getLocation(), End);
2039 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2040 SourceLocation L, IdentifierInfo *Id,
2041 TypeSourceInfo *TInfo) {
2042 return new (C) TypedefDecl(DC, L, Id, TInfo);
2045 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2046 SourceLocation L,
2047 StringLiteral *Str) {
2048 return new (C) FileScopeAsmDecl(DC, L, Str);