1 //===--- Decl.h - Classes for representing declarations ---------*- C++ -*-===//
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 defines the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECL_H
15 #define LLVM_CLANG_AST_DECL_H
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/Redeclarable.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/ExternalASTSource.h"
22 #include "clang/Basic/Linkage.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/Support/Compiler.h"
30 class FunctionTemplateDecl;
34 class NestedNameSpecifier;
35 class TemplateParameterList;
36 class TemplateArgumentList;
37 struct ASTTemplateArgumentListInfo;
38 class MemberSpecializationInfo;
39 class FunctionTemplateSpecializationInfo;
40 class DependentFunctionTemplateSpecializationInfo;
42 class UnresolvedSetImpl;
46 /// \brief A container of type source information.
48 /// A client can read the relevant info using TypeLoc wrappers, e.g:
50 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
51 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
52 /// PL->getStarLoc().print(OS, SrcMgr);
55 class TypeSourceInfo {
57 // Contains a memory block after the class, used for type source information,
58 // allocated by ASTContext.
59 friend class ASTContext;
60 TypeSourceInfo(QualType ty) : Ty(ty) { }
62 /// \brief Return the type wrapped by this type source info.
63 QualType getType() const { return Ty; }
65 /// \brief Return the TypeLoc wrapper for the type source info.
66 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
69 /// TranslationUnitDecl - The top declaration context.
70 class TranslationUnitDecl : public Decl, public DeclContext {
71 virtual void anchor();
74 /// The (most recently entered) anonymous namespace for this
75 /// translation unit, if one has been created.
76 NamespaceDecl *AnonymousNamespace;
78 explicit TranslationUnitDecl(ASTContext &ctx)
79 : Decl(TranslationUnit, 0, SourceLocation()),
80 DeclContext(TranslationUnit),
81 Ctx(ctx), AnonymousNamespace(0) {}
83 ASTContext &getASTContext() const { return Ctx; }
85 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
86 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
88 static TranslationUnitDecl *Create(ASTContext &C);
89 // Implement isa/cast/dyncast/etc.
90 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
91 static bool classof(const TranslationUnitDecl *D) { return true; }
92 static bool classofKind(Kind K) { return K == TranslationUnit; }
93 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
94 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
96 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
97 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
101 /// NamedDecl - This represents a decl with a name. Many decls have names such
102 /// as ObjCMethodDecl, but not @class, etc.
103 class NamedDecl : public Decl {
104 virtual void anchor();
105 /// Name - The name of this declaration, which is typically a normal
106 /// identifier but may also be a special kind of name (C++
107 /// constructor, Objective-C selector, etc.)
108 DeclarationName Name;
111 NamedDecl *getUnderlyingDeclImpl();
114 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
115 : Decl(DK, DC, L), Name(N) { }
118 /// getIdentifier - Get the identifier that names this declaration,
119 /// if there is one. This will return NULL if this declaration has
120 /// no name (e.g., for an unnamed class) or if the name is a special
121 /// name (C++ constructor, Objective-C selector, etc.).
122 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
124 /// getName - Get the name of identifier for this declaration as a StringRef.
125 /// This requires that the declaration have a name and that it be a simple
127 StringRef getName() const {
128 assert(Name.isIdentifier() && "Name is not a simple identifier");
129 return getIdentifier() ? getIdentifier()->getName() : "";
132 /// getNameAsString - Get a human-readable name for the declaration, even if
133 /// it is one of the special kinds of names (C++ constructor, Objective-C
134 /// selector, etc). Creating this name requires expensive string
135 /// manipulation, so it should be called only when performance doesn't matter.
136 /// For simple declarations, getNameAsCString() should suffice.
138 // FIXME: This function should be renamed to indicate that it is not just an
139 // alternate form of getName(), and clients should move as appropriate.
141 // FIXME: Deprecated, move clients to getName().
142 std::string getNameAsString() const { return Name.getAsString(); }
144 void printName(raw_ostream &os) const { return Name.printName(os); }
146 /// getDeclName - Get the actual, stored name of the declaration,
147 /// which may be a special name.
148 DeclarationName getDeclName() const { return Name; }
150 /// \brief Set the name of this declaration.
151 void setDeclName(DeclarationName N) { Name = N; }
153 /// getQualifiedNameAsString - Returns human-readable qualified name for
154 /// declaration, like A::B::i, for i being member of namespace A::B.
155 /// If declaration is not member of context which can be named (record,
156 /// namespace), it will return same result as getNameAsString().
157 /// Creating this name is expensive, so it should be called only when
158 /// performance doesn't matter.
159 std::string getQualifiedNameAsString() const;
160 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
162 /// getNameForDiagnostic - Appends a human-readable name for this
163 /// declaration into the given string.
165 /// This is the method invoked by Sema when displaying a NamedDecl
166 /// in a diagnostic. It does not necessarily produce the same
167 /// result as getNameAsString(); for example, class template
168 /// specializations are printed with their template arguments.
170 /// TODO: use an API that doesn't require so many temporary strings
171 virtual void getNameForDiagnostic(std::string &S,
172 const PrintingPolicy &Policy,
173 bool Qualified) const {
175 S += getQualifiedNameAsString(Policy);
177 S += getNameAsString();
180 /// declarationReplaces - Determine whether this declaration, if
181 /// known to be well-formed within its context, will replace the
182 /// declaration OldD if introduced into scope. A declaration will
183 /// replace another declaration if, for example, it is a
184 /// redeclaration of the same variable or function, but not if it is
185 /// a declaration of a different kind (function vs. class) or an
186 /// overloaded function.
187 bool declarationReplaces(NamedDecl *OldD) const;
189 /// \brief Determine whether this declaration has linkage.
190 bool hasLinkage() const;
192 using Decl::isModulePrivate;
193 using Decl::setModulePrivate;
195 /// \brief Determine whether this declaration is hidden from name lookup.
196 bool isHidden() const { return Hidden; }
198 /// \brief Determine whether this declaration is a C++ class member.
199 bool isCXXClassMember() const {
200 const DeclContext *DC = getDeclContext();
202 // C++0x [class.mem]p1:
203 // The enumerators of an unscoped enumeration defined in
204 // the class are members of the class.
205 // FIXME: support C++0x scoped enumerations.
206 if (isa<EnumDecl>(DC))
207 DC = DC->getParent();
209 return DC->isRecord();
212 /// \brief Determine whether the given declaration is an instance member of
214 bool isCXXInstanceMember() const;
218 Visibility visibility_;
222 LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
224 LinkageInfo(Linkage L, Visibility V, bool E)
225 : linkage_(L), visibility_(V), explicit_(E) {}
227 static LinkageInfo external() {
228 return LinkageInfo();
230 static LinkageInfo internal() {
231 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
233 static LinkageInfo uniqueExternal() {
234 return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
236 static LinkageInfo none() {
237 return LinkageInfo(NoLinkage, DefaultVisibility, false);
240 Linkage linkage() const { return linkage_; }
241 Visibility visibility() const { return visibility_; }
242 bool visibilityExplicit() const { return explicit_; }
244 void setLinkage(Linkage L) { linkage_ = L; }
245 void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
247 void mergeLinkage(Linkage L) {
248 setLinkage(minLinkage(linkage(), L));
250 void mergeLinkage(LinkageInfo Other) {
251 mergeLinkage(Other.linkage());
254 // Merge the visibility V giving preference to explicit ones.
255 // This is used, for example, when merging the visibility of a class
256 // down to one of its members. If the member has no explicit visibility,
257 // the class visibility wins.
258 void mergeVisibility(Visibility V, bool E = false) {
259 // If one has explicit visibility and the other doesn't, keep the
261 if (visibilityExplicit() && !E)
263 if (!visibilityExplicit() && E)
266 // If both are explicit or both are implicit, keep the minimum.
267 setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
269 // Merge the visibility V, keeping the most restrictive one.
270 // This is used for cases like merging the visibility of a template
271 // argument to an instantiation. If we already have a hidden class,
272 // no argument should give it default visibility.
273 void mergeVisibilityWithMin(Visibility V, bool E = false) {
274 // Never increase the visibility
275 if (visibility() < V)
278 // If this visibility is explicit, keep it.
279 if (visibilityExplicit() && !E)
283 void mergeVisibility(LinkageInfo Other) {
284 mergeVisibility(Other.visibility(), Other.visibilityExplicit());
286 void mergeVisibilityWithMin(LinkageInfo Other) {
287 mergeVisibilityWithMin(Other.visibility(), Other.visibilityExplicit());
290 void merge(LinkageInfo Other) {
292 mergeVisibility(Other);
294 void mergeWithMin(LinkageInfo Other) {
296 mergeVisibilityWithMin(Other);
299 friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
305 /// \brief Determine what kind of linkage this entity has.
306 Linkage getLinkage() const;
308 /// \brief Determines the visibility of this entity.
309 Visibility getVisibility() const {
310 return getLinkageAndVisibility().visibility();
313 /// \brief Determines the linkage and visibility of this entity.
314 LinkageInfo getLinkageAndVisibility() const;
316 /// \brief If visibility was explicitly specified for this
317 /// declaration, return that visibility.
318 llvm::Optional<Visibility> getExplicitVisibility() const;
320 /// \brief Clear the linkage cache in response to a change
321 /// to the declaration.
322 void ClearLinkageCache();
324 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
325 /// the underlying named decl.
326 NamedDecl *getUnderlyingDecl() {
327 // Fast-path the common case.
328 if (this->getKind() != UsingShadow &&
329 this->getKind() != ObjCCompatibleAlias)
332 return getUnderlyingDeclImpl();
334 const NamedDecl *getUnderlyingDecl() const {
335 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
338 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
339 static bool classof(const NamedDecl *D) { return true; }
340 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
343 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
348 /// LabelDecl - Represents the declaration of a label. Labels also have a
349 /// corresponding LabelStmt, which indicates the position that the label was
350 /// defined at. For normal labels, the location of the decl is the same as the
351 /// location of the statement. For GNU local labels (__label__), the decl
352 /// location is where the __label__ is.
353 class LabelDecl : public NamedDecl {
354 virtual void anchor();
356 /// LocStart - For normal labels, this is the same as the main declaration
357 /// label, i.e., the location of the identifier; for GNU local labels,
358 /// this is the location of the __label__ keyword.
359 SourceLocation LocStart;
361 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
362 LabelStmt *S, SourceLocation StartL)
363 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
366 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
367 SourceLocation IdentL, IdentifierInfo *II);
368 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
369 SourceLocation IdentL, IdentifierInfo *II,
370 SourceLocation GnuLabelL);
371 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
373 LabelStmt *getStmt() const { return TheStmt; }
374 void setStmt(LabelStmt *T) { TheStmt = T; }
376 bool isGnuLocal() const { return LocStart != getLocation(); }
377 void setLocStart(SourceLocation L) { LocStart = L; }
379 SourceRange getSourceRange() const LLVM_READONLY {
380 return SourceRange(LocStart, getLocation());
383 // Implement isa/cast/dyncast/etc.
384 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
385 static bool classof(const LabelDecl *D) { return true; }
386 static bool classofKind(Kind K) { return K == Label; }
389 /// NamespaceDecl - Represent a C++ namespace.
390 class NamespaceDecl : public NamedDecl, public DeclContext,
391 public Redeclarable<NamespaceDecl>
393 virtual void anchor();
395 /// LocStart - The starting location of the source range, pointing
396 /// to either the namespace or the inline keyword.
397 SourceLocation LocStart;
398 /// RBraceLoc - The ending location of the source range.
399 SourceLocation RBraceLoc;
401 /// \brief A pointer to either the anonymous namespace that lives just inside
402 /// this namespace or to the first namespace in the chain (the latter case
403 /// only when this is not the first in the chain), along with a
404 /// boolean value indicating whether this is an inline namespace.
405 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
407 NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
408 SourceLocation IdLoc, IdentifierInfo *Id,
409 NamespaceDecl *PrevDecl);
411 typedef Redeclarable<NamespaceDecl> redeclarable_base;
412 virtual NamespaceDecl *getNextRedeclaration() {
413 return RedeclLink.getNext();
415 virtual NamespaceDecl *getPreviousDeclImpl() {
416 return getPreviousDecl();
418 virtual NamespaceDecl *getMostRecentDeclImpl() {
419 return getMostRecentDecl();
423 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
424 bool Inline, SourceLocation StartLoc,
425 SourceLocation IdLoc, IdentifierInfo *Id,
426 NamespaceDecl *PrevDecl);
428 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
430 typedef redeclarable_base::redecl_iterator redecl_iterator;
431 using redeclarable_base::redecls_begin;
432 using redeclarable_base::redecls_end;
433 using redeclarable_base::getPreviousDecl;
434 using redeclarable_base::getMostRecentDecl;
436 /// \brief Returns true if this is an anonymous namespace declaration.
444 /// q.v. C++ [namespace.unnamed]
445 bool isAnonymousNamespace() const {
446 return !getIdentifier();
449 /// \brief Returns true if this is an inline namespace declaration.
450 bool isInline() const {
451 return AnonOrFirstNamespaceAndInline.getInt();
454 /// \brief Set whether this is an inline namespace declaration.
455 void setInline(bool Inline) {
456 AnonOrFirstNamespaceAndInline.setInt(Inline);
459 /// \brief Get the original (first) namespace declaration.
460 NamespaceDecl *getOriginalNamespace() {
461 if (isFirstDeclaration())
464 return AnonOrFirstNamespaceAndInline.getPointer();
467 /// \brief Get the original (first) namespace declaration.
468 const NamespaceDecl *getOriginalNamespace() const {
469 if (isFirstDeclaration())
472 return AnonOrFirstNamespaceAndInline.getPointer();
475 /// \brief Return true if this declaration is an original (first) declaration
476 /// of the namespace. This is false for non-original (subsequent) namespace
477 /// declarations and anonymous namespaces.
478 bool isOriginalNamespace() const {
479 return isFirstDeclaration();
482 /// \brief Retrieve the anonymous namespace nested inside this namespace,
484 NamespaceDecl *getAnonymousNamespace() const {
485 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
488 void setAnonymousNamespace(NamespaceDecl *D) {
489 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
492 /// Retrieves the canonical declaration of this namespace.
493 NamespaceDecl *getCanonicalDecl() {
494 return getOriginalNamespace();
496 const NamespaceDecl *getCanonicalDecl() const {
497 return getOriginalNamespace();
500 virtual SourceRange getSourceRange() const LLVM_READONLY {
501 return SourceRange(LocStart, RBraceLoc);
504 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
505 SourceLocation getRBraceLoc() const { return RBraceLoc; }
506 void setLocStart(SourceLocation L) { LocStart = L; }
507 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
509 // Implement isa/cast/dyncast/etc.
510 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
511 static bool classof(const NamespaceDecl *D) { return true; }
512 static bool classofKind(Kind K) { return K == Namespace; }
513 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
514 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
516 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
517 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
520 friend class ASTDeclReader;
521 friend class ASTDeclWriter;
524 /// ValueDecl - Represent the declaration of a variable (in which case it is
525 /// an lvalue) a function (in which case it is a function designator) or
526 /// an enum constant.
527 class ValueDecl : public NamedDecl {
528 virtual void anchor();
532 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
533 DeclarationName N, QualType T)
534 : NamedDecl(DK, DC, L, N), DeclType(T) {}
536 QualType getType() const { return DeclType; }
537 void setType(QualType newType) { DeclType = newType; }
539 /// \brief Determine whether this symbol is weakly-imported,
540 /// or declared with the weak or weak-ref attr.
541 bool isWeak() const {
542 return hasAttr<WeakAttr>() || hasAttr<WeakRefAttr>() || isWeakImported();
545 // Implement isa/cast/dyncast/etc.
546 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
547 static bool classof(const ValueDecl *D) { return true; }
548 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
551 /// QualifierInfo - A struct with extended info about a syntactic
552 /// name qualifier, to be used for the case of out-of-line declarations.
553 struct QualifierInfo {
554 NestedNameSpecifierLoc QualifierLoc;
556 /// NumTemplParamLists - The number of "outer" template parameter lists.
557 /// The count includes all of the template parameter lists that were matched
558 /// against the template-ids occurring into the NNS and possibly (in the
559 /// case of an explicit specialization) a final "template <>".
560 unsigned NumTemplParamLists;
562 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
563 /// containing pointers to the "outer" template parameter lists.
564 /// It includes all of the template parameter lists that were matched
565 /// against the template-ids occurring into the NNS and possibly (in the
566 /// case of an explicit specialization) a final "template <>".
567 TemplateParameterList** TemplParamLists;
569 /// Default constructor.
570 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
572 /// setTemplateParameterListsInfo - Sets info about "outer" template
574 void setTemplateParameterListsInfo(ASTContext &Context,
576 TemplateParameterList **TPLists);
579 // Copy constructor and copy assignment are disabled.
580 QualifierInfo(const QualifierInfo&);
581 QualifierInfo& operator=(const QualifierInfo&);
584 /// \brief Represents a ValueDecl that came out of a declarator.
585 /// Contains type source information through TypeSourceInfo.
586 class DeclaratorDecl : public ValueDecl {
587 // A struct representing both a TInfo and a syntactic qualifier,
588 // to be used for the (uncommon) case of out-of-line declarations.
589 struct ExtInfo : public QualifierInfo {
590 TypeSourceInfo *TInfo;
593 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
595 /// InnerLocStart - The start of the source range for this declaration,
596 /// ignoring outer template declarations.
597 SourceLocation InnerLocStart;
599 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
600 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
601 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
604 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
605 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
606 SourceLocation StartL)
607 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
611 TypeSourceInfo *getTypeSourceInfo() const {
613 ? getExtInfo()->TInfo
614 : DeclInfo.get<TypeSourceInfo*>();
616 void setTypeSourceInfo(TypeSourceInfo *TI) {
618 getExtInfo()->TInfo = TI;
623 /// getInnerLocStart - Return SourceLocation representing start of source
624 /// range ignoring outer template declarations.
625 SourceLocation getInnerLocStart() const { return InnerLocStart; }
626 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
628 /// getOuterLocStart - Return SourceLocation representing start of source
629 /// range taking into account any outer template declarations.
630 SourceLocation getOuterLocStart() const;
632 virtual SourceRange getSourceRange() const LLVM_READONLY;
633 SourceLocation getLocStart() const LLVM_READONLY {
634 return getOuterLocStart();
637 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
638 /// declaration, if it was present in the source.
639 NestedNameSpecifier *getQualifier() const {
640 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
644 /// \brief Retrieve the nested-name-specifier (with source-location
645 /// information) that qualifies the name of this declaration, if it was
646 /// present in the source.
647 NestedNameSpecifierLoc getQualifierLoc() const {
648 return hasExtInfo() ? getExtInfo()->QualifierLoc
649 : NestedNameSpecifierLoc();
652 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
654 unsigned getNumTemplateParameterLists() const {
655 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
657 TemplateParameterList *getTemplateParameterList(unsigned index) const {
658 assert(index < getNumTemplateParameterLists());
659 return getExtInfo()->TemplParamLists[index];
661 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
662 TemplateParameterList **TPLists);
664 SourceLocation getTypeSpecStartLoc() const;
666 // Implement isa/cast/dyncast/etc.
667 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
668 static bool classof(const DeclaratorDecl *D) { return true; }
669 static bool classofKind(Kind K) {
670 return K >= firstDeclarator && K <= lastDeclarator;
673 friend class ASTDeclReader;
674 friend class ASTDeclWriter;
677 /// \brief Structure used to store a statement, the constant value to
678 /// which it was evaluated (if any), and whether or not the statement
679 /// is an integral constant expression (if known).
680 struct EvaluatedStmt {
681 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
682 CheckingICE(false), IsICE(false) { }
684 /// \brief Whether this statement was already evaluated.
685 bool WasEvaluated : 1;
687 /// \brief Whether this statement is being evaluated.
688 bool IsEvaluating : 1;
690 /// \brief Whether we already checked whether this statement was an
691 /// integral constant expression.
694 /// \brief Whether we are checking whether this statement is an
695 /// integral constant expression.
696 bool CheckingICE : 1;
698 /// \brief Whether this statement is an integral constant expression,
699 /// or in C++11, whether the statement is a constant expression. Only
700 /// valid if CheckedICE is true.
707 /// VarDecl - An instance of this class is created to represent a variable
708 /// declaration or definition.
709 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
711 typedef clang::StorageClass StorageClass;
713 /// getStorageClassSpecifierString - Return the string used to
714 /// specify the storage class \arg SC.
716 /// It is illegal to call this function with SC == None.
717 static const char *getStorageClassSpecifierString(StorageClass SC);
719 /// \brief Initialization styles.
720 enum InitializationStyle {
721 CInit, ///< C-style initialization with assignment
722 CallInit, ///< Call-style initialization (C++98)
723 ListInit ///< Direct list-initialization (C++11)
727 /// \brief Placeholder type used in Init to denote an unparsed C++ default
729 struct UnparsedDefaultArgument;
731 /// \brief Placeholder type used in Init to denote an uninstantiated C++
732 /// default argument.
733 struct UninstantiatedDefaultArgument;
735 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
736 UnparsedDefaultArgument *,
737 UninstantiatedDefaultArgument *> InitType;
739 /// \brief The initializer for this variable or, for a ParmVarDecl, the
740 /// C++ default argument.
741 mutable InitType Init;
744 class VarDeclBitfields {
745 friend class VarDecl;
746 friend class ASTDeclReader;
749 unsigned SClassAsWritten : 3;
750 unsigned ThreadSpecified : 1;
751 unsigned InitStyle : 2;
753 /// \brief Whether this variable is the exception variable in a C++ catch
754 /// or an Objective-C @catch statement.
755 unsigned ExceptionVar : 1;
757 /// \brief Whether this local variable could be allocated in the return
758 /// slot of its function, enabling the named return value optimization
760 unsigned NRVOVariable : 1;
762 /// \brief Whether this variable is the for-range-declaration in a C++0x
763 /// for-range statement.
764 unsigned CXXForRangeDecl : 1;
766 /// \brief Whether this variable is an ARC pseudo-__strong
767 /// variable; see isARCPseudoStrong() for details.
768 unsigned ARCPseudoStrong : 1;
770 /// \brief Whether this variable is (C++0x) constexpr.
771 unsigned IsConstexpr : 1;
773 enum { NumVarDeclBits = 14 };
775 friend class ASTDeclReader;
776 friend class StmtIteratorBase;
779 enum { NumParameterIndexBits = 8 };
781 class ParmVarDeclBitfields {
782 friend class ParmVarDecl;
783 friend class ASTDeclReader;
785 unsigned : NumVarDeclBits;
787 /// Whether this parameter inherits a default argument from a
788 /// prior declaration.
789 unsigned HasInheritedDefaultArg : 1;
791 /// Whether this parameter undergoes K&R argument promotion.
792 unsigned IsKNRPromoted : 1;
794 /// Whether this parameter is an ObjC method parameter or not.
795 unsigned IsObjCMethodParam : 1;
797 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
798 /// Otherwise, the number of function parameter scopes enclosing
799 /// the function parameter scope in which this parameter was
801 unsigned ScopeDepthOrObjCQuals : 7;
803 /// The number of parameters preceding this parameter in the
804 /// function parameter scope in which it was declared.
805 unsigned ParameterIndex : NumParameterIndexBits;
810 VarDeclBitfields VarDeclBits;
811 ParmVarDeclBitfields ParmVarDeclBits;
814 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
815 SourceLocation IdLoc, IdentifierInfo *Id,
816 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
817 StorageClass SCAsWritten)
818 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
819 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
820 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
822 VarDeclBits.SClass = SC;
823 VarDeclBits.SClassAsWritten = SCAsWritten;
824 // Everything else is implicitly initialized to false.
827 typedef Redeclarable<VarDecl> redeclarable_base;
828 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
829 virtual VarDecl *getPreviousDeclImpl() {
830 return getPreviousDecl();
832 virtual VarDecl *getMostRecentDeclImpl() {
833 return getMostRecentDecl();
837 typedef redeclarable_base::redecl_iterator redecl_iterator;
838 using redeclarable_base::redecls_begin;
839 using redeclarable_base::redecls_end;
840 using redeclarable_base::getPreviousDecl;
841 using redeclarable_base::getMostRecentDecl;
843 static VarDecl *Create(ASTContext &C, DeclContext *DC,
844 SourceLocation StartLoc, SourceLocation IdLoc,
845 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
846 StorageClass S, StorageClass SCAsWritten);
848 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
850 virtual SourceRange getSourceRange() const LLVM_READONLY;
852 StorageClass getStorageClass() const {
853 return (StorageClass) VarDeclBits.SClass;
855 StorageClass getStorageClassAsWritten() const {
856 return (StorageClass) VarDeclBits.SClassAsWritten;
858 void setStorageClass(StorageClass SC);
859 void setStorageClassAsWritten(StorageClass SC) {
860 assert(isLegalForVariable(SC));
861 VarDeclBits.SClassAsWritten = SC;
864 void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
865 bool isThreadSpecified() const {
866 return VarDeclBits.ThreadSpecified;
869 /// hasLocalStorage - Returns true if a variable with function scope
870 /// is a non-static local variable.
871 bool hasLocalStorage() const {
872 if (getStorageClass() == SC_None)
873 return !isFileVarDecl();
875 // Return true for: Auto, Register.
876 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
878 return getStorageClass() >= SC_Auto;
881 /// isStaticLocal - Returns true if a variable with function scope is a
882 /// static local variable.
883 bool isStaticLocal() const {
884 return getStorageClass() == SC_Static && !isFileVarDecl();
887 /// hasExternStorage - Returns true if a variable has extern or
888 /// __private_extern__ storage.
889 bool hasExternalStorage() const {
890 return getStorageClass() == SC_Extern ||
891 getStorageClass() == SC_PrivateExtern;
894 /// hasGlobalStorage - Returns true for all variables that do not
895 /// have local storage. This includs all global variables as well
896 /// as static variables declared within a function.
897 bool hasGlobalStorage() const { return !hasLocalStorage(); }
899 /// \brief Determines whether this variable is a variable with
900 /// external, C linkage.
901 bool isExternC() const;
903 /// isLocalVarDecl - Returns true for local variable declarations
904 /// other than parameters. Note that this includes static variables
905 /// inside of functions. It also includes variables inside blocks.
907 /// void foo() { int x; static int y; extern int z; }
909 bool isLocalVarDecl() const {
910 if (getKind() != Decl::Var)
912 if (const DeclContext *DC = getDeclContext())
913 return DC->getRedeclContext()->isFunctionOrMethod();
917 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
918 /// excludes variables declared in blocks.
919 bool isFunctionOrMethodVarDecl() const {
920 if (getKind() != Decl::Var)
922 const DeclContext *DC = getDeclContext()->getRedeclContext();
923 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
926 /// \brief Determines whether this is a static data member.
928 /// This will only be true in C++, and applies to, e.g., the
935 bool isStaticDataMember() const {
936 // If it wasn't static, it would be a FieldDecl.
937 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
940 virtual VarDecl *getCanonicalDecl();
941 const VarDecl *getCanonicalDecl() const {
942 return const_cast<VarDecl*>(this)->getCanonicalDecl();
945 enum DefinitionKind {
946 DeclarationOnly, ///< This declaration is only a declaration.
947 TentativeDefinition, ///< This declaration is a tentative definition.
948 Definition ///< This declaration is definitely a definition.
951 /// \brief Check whether this declaration is a definition. If this could be
952 /// a tentative definition (in C), don't check whether there's an overriding
954 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
955 DefinitionKind isThisDeclarationADefinition() const {
956 return isThisDeclarationADefinition(getASTContext());
959 /// \brief Check whether this variable is defined in this
960 /// translation unit.
961 DefinitionKind hasDefinition(ASTContext &) const;
962 DefinitionKind hasDefinition() const {
963 return hasDefinition(getASTContext());
966 /// \brief Get the tentative definition that acts as the real definition in
967 /// a TU. Returns null if there is a proper definition available.
968 VarDecl *getActingDefinition();
969 const VarDecl *getActingDefinition() const {
970 return const_cast<VarDecl*>(this)->getActingDefinition();
973 /// \brief Determine whether this is a tentative definition of a
975 bool isTentativeDefinitionNow() const;
977 /// \brief Get the real (not just tentative) definition for this declaration.
978 VarDecl *getDefinition(ASTContext &);
979 const VarDecl *getDefinition(ASTContext &C) const {
980 return const_cast<VarDecl*>(this)->getDefinition(C);
982 VarDecl *getDefinition() {
983 return getDefinition(getASTContext());
985 const VarDecl *getDefinition() const {
986 return const_cast<VarDecl*>(this)->getDefinition();
989 /// \brief Determine whether this is or was instantiated from an out-of-line
990 /// definition of a static data member.
991 virtual bool isOutOfLine() const;
993 /// \brief If this is a static data member, find its out-of-line definition.
994 VarDecl *getOutOfLineDefinition();
996 /// isFileVarDecl - Returns true for file scoped variable declaration.
997 bool isFileVarDecl() const {
998 if (getKind() != Decl::Var)
1001 if (getDeclContext()->getRedeclContext()->isFileContext())
1004 if (isStaticDataMember())
1010 /// getAnyInitializer - Get the initializer for this variable, no matter which
1011 /// declaration it is attached to.
1012 const Expr *getAnyInitializer() const {
1014 return getAnyInitializer(D);
1017 /// getAnyInitializer - Get the initializer for this variable, no matter which
1018 /// declaration it is attached to. Also get that declaration.
1019 const Expr *getAnyInitializer(const VarDecl *&D) const;
1021 bool hasInit() const {
1022 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
1024 const Expr *getInit() const {
1028 const Stmt *S = Init.dyn_cast<Stmt *>();
1030 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1033 return (const Expr*) S;
1039 Stmt *S = Init.dyn_cast<Stmt *>();
1041 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1048 /// \brief Retrieve the address of the initializer expression.
1049 Stmt **getInitAddress() {
1050 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1053 // This union hack tip-toes around strict-aliasing rules.
1063 void setInit(Expr *I);
1065 /// \brief Determine whether this variable is a reference that
1066 /// extends the lifetime of its temporary initializer.
1068 /// A reference extends the lifetime of its temporary initializer if
1069 /// it's initializer is an rvalue that would normally go out of scope
1070 /// at the end of the initializer (a full expression). In such cases,
1071 /// the reference itself takes ownership of the temporary, which will
1072 /// be destroyed when the reference goes out of scope. For example:
1075 /// const int &r = 1.0; // creates a temporary of type 'int'
1077 bool extendsLifetimeOfTemporary() const;
1079 /// \brief Determine whether this variable's value can be used in a
1080 /// constant expression, according to the relevant language standard.
1081 /// This only checks properties of the declaration, and does not check
1082 /// whether the initializer is in fact a constant expression.
1083 bool isUsableInConstantExpressions(ASTContext &C) const;
1085 EvaluatedStmt *ensureEvaluatedStmt() const;
1087 /// \brief Attempt to evaluate the value of the initializer attached to this
1088 /// declaration, and produce notes explaining why it cannot be evaluated or is
1089 /// not a constant expression. Returns a pointer to the value if evaluation
1090 /// succeeded, 0 otherwise.
1091 APValue *evaluateValue() const;
1092 APValue *evaluateValue(
1093 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1095 /// \brief Return the already-evaluated value of this variable's
1096 /// initializer, or NULL if the value is not yet known. Returns pointer
1097 /// to untyped APValue if the value could not be evaluated.
1098 APValue *getEvaluatedValue() const {
1099 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1100 if (Eval->WasEvaluated)
1101 return &Eval->Evaluated;
1106 /// \brief Determines whether it is already known whether the
1107 /// initializer is an integral constant expression or not.
1108 bool isInitKnownICE() const {
1109 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1110 return Eval->CheckedICE;
1115 /// \brief Determines whether the initializer is an integral constant
1116 /// expression, or in C++11, whether the initializer is a constant
1119 /// \pre isInitKnownICE()
1120 bool isInitICE() const {
1121 assert(isInitKnownICE() &&
1122 "Check whether we already know that the initializer is an ICE");
1123 return Init.get<EvaluatedStmt *>()->IsICE;
1126 /// \brief Determine whether the value of the initializer attached to this
1127 /// declaration is an integral constant expression.
1128 bool checkInitIsICE() const;
1130 void setInitStyle(InitializationStyle Style) {
1131 VarDeclBits.InitStyle = Style;
1134 /// \brief The style of initialization for this declaration.
1136 /// C-style initialization is "int x = 1;". Call-style initialization is
1137 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1138 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1139 /// expression for class types. List-style initialization is C++11 syntax,
1140 /// e.g. "int x{1};". Clients can distinguish between different forms of
1141 /// initialization by checking this value. In particular, "int x = {1};" is
1142 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1143 /// Init expression in all three cases is an InitListExpr.
1144 InitializationStyle getInitStyle() const {
1145 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1148 /// \brief Whether the initializer is a direct-initializer (list or call).
1149 bool isDirectInit() const {
1150 return getInitStyle() != CInit;
1153 /// \brief Determine whether this variable is the exception variable in a
1154 /// C++ catch statememt or an Objective-C @catch statement.
1155 bool isExceptionVariable() const {
1156 return VarDeclBits.ExceptionVar;
1158 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1160 /// \brief Determine whether this local variable can be used with the named
1161 /// return value optimization (NRVO).
1163 /// The named return value optimization (NRVO) works by marking certain
1164 /// non-volatile local variables of class type as NRVO objects. These
1165 /// locals can be allocated within the return slot of their containing
1166 /// function, in which case there is no need to copy the object to the
1167 /// return slot when returning from the function. Within the function body,
1168 /// each return that returns the NRVO object will have this variable as its
1170 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1171 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1173 /// \brief Determine whether this variable is the for-range-declaration in
1174 /// a C++0x for-range statement.
1175 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1176 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1178 /// \brief Determine whether this variable is an ARC pseudo-__strong
1179 /// variable. A pseudo-__strong variable has a __strong-qualified
1180 /// type but does not actually retain the object written into it.
1181 /// Generally such variables are also 'const' for safety.
1182 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1183 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1185 /// Whether this variable is (C++0x) constexpr.
1186 bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1187 void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1189 /// \brief If this variable is an instantiated static data member of a
1190 /// class template specialization, returns the templated static data member
1191 /// from which it was instantiated.
1192 VarDecl *getInstantiatedFromStaticDataMember() const;
1194 /// \brief If this variable is a static data member, determine what kind of
1195 /// template specialization or instantiation this is.
1196 TemplateSpecializationKind getTemplateSpecializationKind() const;
1198 /// \brief If this variable is an instantiation of a static data member of a
1199 /// class template specialization, retrieves the member specialization
1201 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1203 /// \brief For a static data member that was instantiated from a static
1204 /// data member of a class template, set the template specialiation kind.
1205 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1206 SourceLocation PointOfInstantiation = SourceLocation());
1208 // Implement isa/cast/dyncast/etc.
1209 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1210 static bool classof(const VarDecl *D) { return true; }
1211 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1214 class ImplicitParamDecl : public VarDecl {
1215 virtual void anchor();
1217 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1218 SourceLocation IdLoc, IdentifierInfo *Id,
1221 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1223 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1224 IdentifierInfo *Id, QualType Type)
1225 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1226 /*tinfo*/ 0, SC_None, SC_None) {
1230 // Implement isa/cast/dyncast/etc.
1231 static bool classof(const ImplicitParamDecl *D) { return true; }
1232 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1233 static bool classofKind(Kind K) { return K == ImplicitParam; }
1236 /// ParmVarDecl - Represents a parameter to a function.
1237 class ParmVarDecl : public VarDecl {
1239 enum { MaxFunctionScopeDepth = 255 };
1240 enum { MaxFunctionScopeIndex = 255 };
1243 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1244 SourceLocation IdLoc, IdentifierInfo *Id,
1245 QualType T, TypeSourceInfo *TInfo,
1246 StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1247 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1248 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1249 assert(ParmVarDeclBits.IsKNRPromoted == false);
1250 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1251 setDefaultArg(DefArg);
1255 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1256 SourceLocation StartLoc,
1257 SourceLocation IdLoc, IdentifierInfo *Id,
1258 QualType T, TypeSourceInfo *TInfo,
1259 StorageClass S, StorageClass SCAsWritten,
1262 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1264 virtual SourceRange getSourceRange() const LLVM_READONLY;
1266 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1267 ParmVarDeclBits.IsObjCMethodParam = true;
1268 setParameterIndex(parameterIndex);
1271 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1272 assert(!ParmVarDeclBits.IsObjCMethodParam);
1274 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1275 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1278 setParameterIndex(parameterIndex);
1281 bool isObjCMethodParameter() const {
1282 return ParmVarDeclBits.IsObjCMethodParam;
1285 unsigned getFunctionScopeDepth() const {
1286 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1287 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1290 /// Returns the index of this parameter in its prototype or method scope.
1291 unsigned getFunctionScopeIndex() const {
1292 return getParameterIndex();
1295 ObjCDeclQualifier getObjCDeclQualifier() const {
1296 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1297 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1299 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1300 assert(ParmVarDeclBits.IsObjCMethodParam);
1301 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1304 /// True if the value passed to this parameter must undergo
1305 /// K&R-style default argument promotion:
1308 /// If the expression that denotes the called function has a type
1309 /// that does not include a prototype, the integer promotions are
1310 /// performed on each argument, and arguments that have type float
1311 /// are promoted to double.
1312 bool isKNRPromoted() const {
1313 return ParmVarDeclBits.IsKNRPromoted;
1315 void setKNRPromoted(bool promoted) {
1316 ParmVarDeclBits.IsKNRPromoted = promoted;
1319 Expr *getDefaultArg();
1320 const Expr *getDefaultArg() const {
1321 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1324 void setDefaultArg(Expr *defarg) {
1325 Init = reinterpret_cast<Stmt *>(defarg);
1328 /// \brief Retrieve the source range that covers the entire default
1330 SourceRange getDefaultArgRange() const;
1331 void setUninstantiatedDefaultArg(Expr *arg) {
1332 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1334 Expr *getUninstantiatedDefaultArg() {
1335 return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1337 const Expr *getUninstantiatedDefaultArg() const {
1338 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1341 /// hasDefaultArg - Determines whether this parameter has a default argument,
1342 /// either parsed or not.
1343 bool hasDefaultArg() const {
1344 return getInit() || hasUnparsedDefaultArg() ||
1345 hasUninstantiatedDefaultArg();
1348 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1349 /// default argument that has not yet been parsed. This will occur
1350 /// during the processing of a C++ class whose member functions have
1351 /// default arguments, e.g.,
1355 /// void f(int x = 17); // x has an unparsed default argument now
1356 /// }; // x has a regular default argument now
1358 bool hasUnparsedDefaultArg() const {
1359 return Init.is<UnparsedDefaultArgument*>();
1362 bool hasUninstantiatedDefaultArg() const {
1363 return Init.is<UninstantiatedDefaultArgument*>();
1366 /// setUnparsedDefaultArg - Specify that this parameter has an
1367 /// unparsed default argument. The argument will be replaced with a
1368 /// real default argument via setDefaultArg when the class
1369 /// definition enclosing the function declaration that owns this
1370 /// default argument is completed.
1371 void setUnparsedDefaultArg() {
1372 Init = (UnparsedDefaultArgument *)0;
1375 bool hasInheritedDefaultArg() const {
1376 return ParmVarDeclBits.HasInheritedDefaultArg;
1379 void setHasInheritedDefaultArg(bool I = true) {
1380 ParmVarDeclBits.HasInheritedDefaultArg = I;
1383 QualType getOriginalType() const {
1384 if (getTypeSourceInfo())
1385 return getTypeSourceInfo()->getType();
1389 /// \brief Determine whether this parameter is actually a function
1391 bool isParameterPack() const;
1393 /// setOwningFunction - Sets the function declaration that owns this
1394 /// ParmVarDecl. Since ParmVarDecls are often created before the
1395 /// FunctionDecls that own them, this routine is required to update
1396 /// the DeclContext appropriately.
1397 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1399 // Implement isa/cast/dyncast/etc.
1400 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1401 static bool classof(const ParmVarDecl *D) { return true; }
1402 static bool classofKind(Kind K) { return K == ParmVar; }
1405 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1407 void setParameterIndex(unsigned parameterIndex) {
1408 if (parameterIndex >= ParameterIndexSentinel) {
1409 setParameterIndexLarge(parameterIndex);
1413 ParmVarDeclBits.ParameterIndex = parameterIndex;
1414 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1416 unsigned getParameterIndex() const {
1417 unsigned d = ParmVarDeclBits.ParameterIndex;
1418 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1421 void setParameterIndexLarge(unsigned parameterIndex);
1422 unsigned getParameterIndexLarge() const;
1425 /// FunctionDecl - An instance of this class is created to represent a
1426 /// function declaration or definition.
1428 /// Since a given function can be declared several times in a program,
1429 /// there may be several FunctionDecls that correspond to that
1430 /// function. Only one of those FunctionDecls will be found when
1431 /// traversing the list of declarations in the context of the
1432 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1433 /// contains all of the information known about the function. Other,
1434 /// previous declarations of the function are available via the
1435 /// getPreviousDecl() chain.
1436 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1437 public Redeclarable<FunctionDecl> {
1439 typedef clang::StorageClass StorageClass;
1441 /// \brief The kind of templated function a FunctionDecl can be.
1442 enum TemplatedKind {
1444 TK_FunctionTemplate,
1445 TK_MemberSpecialization,
1446 TK_FunctionTemplateSpecialization,
1447 TK_DependentFunctionTemplateSpecialization
1451 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1452 /// parameters of this function. This is null if a prototype or if there are
1454 ParmVarDecl **ParamInfo;
1456 /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1457 /// decls defined in the function prototype that are not parameters. E.g.
1458 /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1459 llvm::ArrayRef<NamedDecl*> DeclsInPrototypeScope;
1461 LazyDeclStmtPtr Body;
1463 // FIXME: This can be packed into the bitfields in Decl.
1464 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1465 unsigned SClass : 2;
1466 unsigned SClassAsWritten : 2;
1468 bool IsInlineSpecified : 1;
1469 bool IsVirtualAsWritten : 1;
1471 bool HasInheritedPrototype : 1;
1472 bool HasWrittenPrototype : 1;
1474 bool IsTrivial : 1; // sunk from CXXMethodDecl
1475 bool IsDefaulted : 1; // sunk from CXXMethoDecl
1476 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1477 bool HasImplicitReturnZero : 1;
1478 bool IsLateTemplateParsed : 1;
1479 bool IsConstexpr : 1;
1481 /// \brief End part of this FunctionDecl's source range.
1483 /// We could compute the full range in getSourceRange(). However, when we're
1484 /// dealing with a function definition deserialized from a PCH/AST file,
1485 /// we can only compute the full range once the function body has been
1486 /// de-serialized, so it's far better to have the (sometimes-redundant)
1488 SourceLocation EndRangeLoc;
1490 /// \brief The template or declaration that this declaration
1491 /// describes or was instantiated from, respectively.
1493 /// For non-templates, this value will be NULL. For function
1494 /// declarations that describe a function template, this will be a
1495 /// pointer to a FunctionTemplateDecl. For member functions
1496 /// of class template specializations, this will be a MemberSpecializationInfo
1497 /// pointer containing information about the specialization.
1498 /// For function template specializations, this will be a
1499 /// FunctionTemplateSpecializationInfo, which contains information about
1500 /// the template being specialized and the template arguments involved in
1501 /// that specialization.
1502 llvm::PointerUnion4<FunctionTemplateDecl *,
1503 MemberSpecializationInfo *,
1504 FunctionTemplateSpecializationInfo *,
1505 DependentFunctionTemplateSpecializationInfo *>
1506 TemplateOrSpecialization;
1508 /// DNLoc - Provides source/type location info for the
1509 /// declaration name embedded in the DeclaratorDecl base class.
1510 DeclarationNameLoc DNLoc;
1512 /// \brief Specify that this function declaration is actually a function
1513 /// template specialization.
1515 /// \param C the ASTContext.
1517 /// \param Template the function template that this function template
1518 /// specialization specializes.
1520 /// \param TemplateArgs the template arguments that produced this
1521 /// function template specialization from the template.
1523 /// \param InsertPos If non-NULL, the position in the function template
1524 /// specialization set where the function template specialization data will
1527 /// \param TSK the kind of template specialization this is.
1529 /// \param TemplateArgsAsWritten location info of template arguments.
1531 /// \param PointOfInstantiation point at which the function template
1532 /// specialization was first instantiated.
1533 void setFunctionTemplateSpecialization(ASTContext &C,
1534 FunctionTemplateDecl *Template,
1535 const TemplateArgumentList *TemplateArgs,
1537 TemplateSpecializationKind TSK,
1538 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1539 SourceLocation PointOfInstantiation);
1541 /// \brief Specify that this record is an instantiation of the
1542 /// member function FD.
1543 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1544 TemplateSpecializationKind TSK);
1546 void setParams(ASTContext &C, llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
1549 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1550 const DeclarationNameInfo &NameInfo,
1551 QualType T, TypeSourceInfo *TInfo,
1552 StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
1553 bool isConstexprSpecified)
1554 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1557 ParamInfo(0), Body(),
1558 SClass(S), SClassAsWritten(SCAsWritten),
1559 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1560 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1561 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1562 IsDefaulted(false), IsExplicitlyDefaulted(false),
1563 HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1564 IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()),
1565 TemplateOrSpecialization(),
1566 DNLoc(NameInfo.getInfo()) {}
1568 typedef Redeclarable<FunctionDecl> redeclarable_base;
1569 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1570 virtual FunctionDecl *getPreviousDeclImpl() {
1571 return getPreviousDecl();
1573 virtual FunctionDecl *getMostRecentDeclImpl() {
1574 return getMostRecentDecl();
1578 typedef redeclarable_base::redecl_iterator redecl_iterator;
1579 using redeclarable_base::redecls_begin;
1580 using redeclarable_base::redecls_end;
1581 using redeclarable_base::getPreviousDecl;
1582 using redeclarable_base::getMostRecentDecl;
1584 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1585 SourceLocation StartLoc, SourceLocation NLoc,
1586 DeclarationName N, QualType T,
1587 TypeSourceInfo *TInfo,
1588 StorageClass SC = SC_None,
1589 StorageClass SCAsWritten = SC_None,
1590 bool isInlineSpecified = false,
1591 bool hasWrittenPrototype = true,
1592 bool isConstexprSpecified = false) {
1593 DeclarationNameInfo NameInfo(N, NLoc);
1594 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1596 isInlineSpecified, hasWrittenPrototype,
1597 isConstexprSpecified);
1600 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1601 SourceLocation StartLoc,
1602 const DeclarationNameInfo &NameInfo,
1603 QualType T, TypeSourceInfo *TInfo,
1604 StorageClass SC = SC_None,
1605 StorageClass SCAsWritten = SC_None,
1606 bool isInlineSpecified = false,
1607 bool hasWrittenPrototype = true,
1608 bool isConstexprSpecified = false);
1610 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1612 DeclarationNameInfo getNameInfo() const {
1613 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1616 virtual void getNameForDiagnostic(std::string &S,
1617 const PrintingPolicy &Policy,
1618 bool Qualified) const;
1620 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1622 virtual SourceRange getSourceRange() const LLVM_READONLY;
1624 /// \brief Returns true if the function has a body (definition). The
1625 /// function body might be in any of the (re-)declarations of this
1626 /// function. The variant that accepts a FunctionDecl pointer will
1627 /// set that function declaration to the actual declaration
1628 /// containing the body (if there is one).
1629 bool hasBody(const FunctionDecl *&Definition) const;
1631 virtual bool hasBody() const {
1632 const FunctionDecl* Definition;
1633 return hasBody(Definition);
1636 /// hasTrivialBody - Returns whether the function has a trivial body that does
1637 /// not require any specific codegen.
1638 bool hasTrivialBody() const;
1640 /// isDefined - Returns true if the function is defined at all, including
1641 /// a deleted definition. Except for the behavior when the function is
1642 /// deleted, behaves like hasBody.
1643 bool isDefined(const FunctionDecl *&Definition) const;
1645 virtual bool isDefined() const {
1646 const FunctionDecl* Definition;
1647 return isDefined(Definition);
1650 /// getBody - Retrieve the body (definition) of the function. The
1651 /// function body might be in any of the (re-)declarations of this
1652 /// function. The variant that accepts a FunctionDecl pointer will
1653 /// set that function declaration to the actual declaration
1654 /// containing the body (if there is one).
1655 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1656 /// unnecessary AST de-serialization of the body.
1657 Stmt *getBody(const FunctionDecl *&Definition) const;
1659 virtual Stmt *getBody() const {
1660 const FunctionDecl* Definition;
1661 return getBody(Definition);
1664 /// isThisDeclarationADefinition - Returns whether this specific
1665 /// declaration of the function is also a definition. This does not
1666 /// determine whether the function has been defined (e.g., in a
1667 /// previous definition); for that information, use isDefined. Note
1668 /// that this returns false for a defaulted function unless that function
1669 /// has been implicitly defined (possibly as deleted).
1670 bool isThisDeclarationADefinition() const {
1671 return IsDeleted || Body || IsLateTemplateParsed;
1674 /// doesThisDeclarationHaveABody - Returns whether this specific
1675 /// declaration of the function has a body - that is, if it is a non-
1676 /// deleted definition.
1677 bool doesThisDeclarationHaveABody() const {
1678 return Body || IsLateTemplateParsed;
1681 void setBody(Stmt *B);
1682 void setLazyBody(uint64_t Offset) { Body = Offset; }
1684 /// Whether this function is variadic.
1685 bool isVariadic() const;
1687 /// Whether this function is marked as virtual explicitly.
1688 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1689 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1691 /// Whether this virtual function is pure, i.e. makes the containing class
1693 bool isPure() const { return IsPure; }
1694 void setPure(bool P = true);
1696 /// Whether this templated function will be late parsed.
1697 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1698 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1700 /// Whether this function is "trivial" in some specialized C++ senses.
1701 /// Can only be true for default constructors, copy constructors,
1702 /// copy assignment operators, and destructors. Not meaningful until
1703 /// the class has been fully built by Sema.
1704 bool isTrivial() const { return IsTrivial; }
1705 void setTrivial(bool IT) { IsTrivial = IT; }
1707 /// Whether this function is defaulted per C++0x. Only valid for
1708 /// special member functions.
1709 bool isDefaulted() const { return IsDefaulted; }
1710 void setDefaulted(bool D = true) { IsDefaulted = D; }
1712 /// Whether this function is explicitly defaulted per C++0x. Only valid
1713 /// for special member functions.
1714 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1715 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1717 /// Whether falling off this function implicitly returns null/zero.
1718 /// If a more specific implicit return value is required, front-ends
1719 /// should synthesize the appropriate return statements.
1720 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1721 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1723 /// \brief Whether this function has a prototype, either because one
1724 /// was explicitly written or because it was "inherited" by merging
1725 /// a declaration without a prototype with a declaration that has a
1727 bool hasPrototype() const {
1728 return HasWrittenPrototype || HasInheritedPrototype;
1731 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1733 /// \brief Whether this function inherited its prototype from a
1734 /// previous declaration.
1735 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1736 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1738 /// Whether this is a (C++0x) constexpr function or constexpr constructor.
1739 bool isConstexpr() const { return IsConstexpr; }
1740 void setConstexpr(bool IC) { IsConstexpr = IC; }
1742 /// \brief Whether this function has been deleted.
1744 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1745 /// acts like a normal function, except that it cannot actually be
1746 /// called or have its address taken. Deleted functions are
1747 /// typically used in C++ overload resolution to attract arguments
1748 /// whose type or lvalue/rvalue-ness would permit the use of a
1749 /// different overload that would behave incorrectly. For example,
1750 /// one might use deleted functions to ban implicit conversion from
1751 /// a floating-point number to an Integer type:
1754 /// struct Integer {
1755 /// Integer(long); // construct from a long
1756 /// Integer(double) = delete; // no construction from float or double
1757 /// Integer(long double) = delete; // no construction from long double
1760 // If a function is deleted, its first declaration must be.
1761 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1762 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1763 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1765 /// \brief Determines whether this function is "main", which is the
1766 /// entry point into an executable program.
1767 bool isMain() const;
1769 /// \brief Determines whether this operator new or delete is one
1770 /// of the reserved global placement operators:
1771 /// void *operator new(size_t, void *);
1772 /// void *operator new[](size_t, void *);
1773 /// void operator delete(void *, void *);
1774 /// void operator delete[](void *, void *);
1775 /// These functions have special behavior under [new.delete.placement]:
1776 /// These functions are reserved, a C++ program may not define
1777 /// functions that displace the versions in the Standard C++ library.
1778 /// The provisions of [basic.stc.dynamic] do not apply to these
1779 /// reserved placement forms of operator new and operator delete.
1781 /// This function must be an allocation or deallocation function.
1782 bool isReservedGlobalPlacementOperator() const;
1784 /// \brief Determines whether this function is a function with
1785 /// external, C linkage.
1786 bool isExternC() const;
1788 /// \brief Determines whether this is a global function.
1789 bool isGlobal() const;
1791 void setPreviousDeclaration(FunctionDecl * PrevDecl);
1793 virtual const FunctionDecl *getCanonicalDecl() const;
1794 virtual FunctionDecl *getCanonicalDecl();
1796 unsigned getBuiltinID() const;
1798 // Iterator access to formal parameters.
1799 unsigned param_size() const { return getNumParams(); }
1800 typedef ParmVarDecl **param_iterator;
1801 typedef ParmVarDecl * const *param_const_iterator;
1803 param_iterator param_begin() { return ParamInfo; }
1804 param_iterator param_end() { return ParamInfo+param_size(); }
1806 param_const_iterator param_begin() const { return ParamInfo; }
1807 param_const_iterator param_end() const { return ParamInfo+param_size(); }
1809 /// getNumParams - Return the number of parameters this function must have
1810 /// based on its FunctionType. This is the length of the ParamInfo array
1811 /// after it has been created.
1812 unsigned getNumParams() const;
1814 const ParmVarDecl *getParamDecl(unsigned i) const {
1815 assert(i < getNumParams() && "Illegal param #");
1816 return ParamInfo[i];
1818 ParmVarDecl *getParamDecl(unsigned i) {
1819 assert(i < getNumParams() && "Illegal param #");
1820 return ParamInfo[i];
1822 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1823 setParams(getASTContext(), NewParamInfo);
1826 const llvm::ArrayRef<NamedDecl*> &getDeclsInPrototypeScope() const {
1827 return DeclsInPrototypeScope;
1829 void setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls);
1831 /// getMinRequiredArguments - Returns the minimum number of arguments
1832 /// needed to call this function. This may be fewer than the number of
1833 /// function parameters, if some of the parameters have default
1834 /// arguments (in C++).
1835 unsigned getMinRequiredArguments() const;
1837 QualType getResultType() const {
1838 return getType()->getAs<FunctionType>()->getResultType();
1841 /// \brief Determine the type of an expression that calls this function.
1842 QualType getCallResultType() const {
1843 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1846 StorageClass getStorageClass() const { return StorageClass(SClass); }
1847 void setStorageClass(StorageClass SC);
1849 StorageClass getStorageClassAsWritten() const {
1850 return StorageClass(SClassAsWritten);
1853 /// \brief Determine whether the "inline" keyword was specified for this
1855 bool isInlineSpecified() const { return IsInlineSpecified; }
1857 /// Set whether the "inline" keyword was specified for this function.
1858 void setInlineSpecified(bool I) {
1859 IsInlineSpecified = I;
1863 /// Flag that this function is implicitly inline.
1864 void setImplicitlyInline() {
1868 /// \brief Determine whether this function should be inlined, because it is
1869 /// either marked "inline" or "constexpr" or is a member function of a class
1870 /// that was defined in the class body.
1871 bool isInlined() const;
1873 bool isInlineDefinitionExternallyVisible() const;
1875 bool doesDeclarationForceExternallyVisibleDefinition() const;
1877 /// isOverloadedOperator - Whether this function declaration
1878 /// represents an C++ overloaded operator, e.g., "operator+".
1879 bool isOverloadedOperator() const {
1880 return getOverloadedOperator() != OO_None;
1883 OverloadedOperatorKind getOverloadedOperator() const;
1885 const IdentifierInfo *getLiteralIdentifier() const;
1887 /// \brief If this function is an instantiation of a member function
1888 /// of a class template specialization, retrieves the function from
1889 /// which it was instantiated.
1891 /// This routine will return non-NULL for (non-templated) member
1892 /// functions of class templates and for instantiations of function
1893 /// templates. For example, given:
1896 /// template<typename T>
1902 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1903 /// whose parent is the class template specialization X<int>. For
1904 /// this declaration, getInstantiatedFromFunction() will return
1905 /// the FunctionDecl X<T>::A. When a complete definition of
1906 /// X<int>::A is required, it will be instantiated from the
1907 /// declaration returned by getInstantiatedFromMemberFunction().
1908 FunctionDecl *getInstantiatedFromMemberFunction() const;
1910 /// \brief What kind of templated function this is.
1911 TemplatedKind getTemplatedKind() const;
1913 /// \brief If this function is an instantiation of a member function of a
1914 /// class template specialization, retrieves the member specialization
1916 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1918 /// \brief Specify that this record is an instantiation of the
1919 /// member function FD.
1920 void setInstantiationOfMemberFunction(FunctionDecl *FD,
1921 TemplateSpecializationKind TSK) {
1922 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1925 /// \brief Retrieves the function template that is described by this
1926 /// function declaration.
1928 /// Every function template is represented as a FunctionTemplateDecl
1929 /// and a FunctionDecl (or something derived from FunctionDecl). The
1930 /// former contains template properties (such as the template
1931 /// parameter lists) while the latter contains the actual
1932 /// description of the template's
1933 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1934 /// FunctionDecl that describes the function template,
1935 /// getDescribedFunctionTemplate() retrieves the
1936 /// FunctionTemplateDecl from a FunctionDecl.
1937 FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1938 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1941 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1942 TemplateOrSpecialization = Template;
1945 /// \brief Determine whether this function is a function template
1947 bool isFunctionTemplateSpecialization() const {
1948 return getPrimaryTemplate() != 0;
1951 /// \brief Retrieve the class scope template pattern that this function
1952 /// template specialization is instantiated from.
1953 FunctionDecl *getClassScopeSpecializationPattern() const;
1955 /// \brief If this function is actually a function template specialization,
1956 /// retrieve information about this function template specialization.
1957 /// Otherwise, returns NULL.
1958 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1959 return TemplateOrSpecialization.
1960 dyn_cast<FunctionTemplateSpecializationInfo*>();
1963 /// \brief Determines whether this function is a function template
1964 /// specialization or a member of a class template specialization that can
1965 /// be implicitly instantiated.
1966 bool isImplicitlyInstantiable() const;
1968 /// \brief Determines if the given function was instantiated from a
1969 /// function template.
1970 bool isTemplateInstantiation() const;
1972 /// \brief Retrieve the function declaration from which this function could
1973 /// be instantiated, if it is an instantiation (rather than a non-template
1974 /// or a specialization, for example).
1975 FunctionDecl *getTemplateInstantiationPattern() const;
1977 /// \brief Retrieve the primary template that this function template
1978 /// specialization either specializes or was instantiated from.
1980 /// If this function declaration is not a function template specialization,
1982 FunctionTemplateDecl *getPrimaryTemplate() const;
1984 /// \brief Retrieve the template arguments used to produce this function
1985 /// template specialization from the primary template.
1987 /// If this function declaration is not a function template specialization,
1989 const TemplateArgumentList *getTemplateSpecializationArgs() const;
1991 /// \brief Retrieve the template argument list as written in the sources,
1994 /// If this function declaration is not a function template specialization
1995 /// or if it had no explicit template argument list, returns NULL.
1996 /// Note that it an explicit template argument list may be written empty,
1997 /// e.g., template<> void foo<>(char* s);
1998 const ASTTemplateArgumentListInfo*
1999 getTemplateSpecializationArgsAsWritten() const;
2001 /// \brief Specify that this function declaration is actually a function
2002 /// template specialization.
2004 /// \param Template the function template that this function template
2005 /// specialization specializes.
2007 /// \param TemplateArgs the template arguments that produced this
2008 /// function template specialization from the template.
2010 /// \param InsertPos If non-NULL, the position in the function template
2011 /// specialization set where the function template specialization data will
2014 /// \param TSK the kind of template specialization this is.
2016 /// \param TemplateArgsAsWritten location info of template arguments.
2018 /// \param PointOfInstantiation point at which the function template
2019 /// specialization was first instantiated.
2020 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2021 const TemplateArgumentList *TemplateArgs,
2023 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2024 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
2025 SourceLocation PointOfInstantiation = SourceLocation()) {
2026 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2027 InsertPos, TSK, TemplateArgsAsWritten,
2028 PointOfInstantiation);
2031 /// \brief Specifies that this function declaration is actually a
2032 /// dependent function template specialization.
2033 void setDependentTemplateSpecialization(ASTContext &Context,
2034 const UnresolvedSetImpl &Templates,
2035 const TemplateArgumentListInfo &TemplateArgs);
2037 DependentFunctionTemplateSpecializationInfo *
2038 getDependentSpecializationInfo() const {
2039 return TemplateOrSpecialization.
2040 dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
2043 /// \brief Determine what kind of template instantiation this function
2045 TemplateSpecializationKind getTemplateSpecializationKind() const;
2047 /// \brief Determine what kind of template instantiation this function
2049 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2050 SourceLocation PointOfInstantiation = SourceLocation());
2052 /// \brief Retrieve the (first) point of instantiation of a function template
2053 /// specialization or a member of a class template specialization.
2055 /// \returns the first point of instantiation, if this function was
2056 /// instantiated from a template; otherwise, returns an invalid source
2058 SourceLocation getPointOfInstantiation() const;
2060 /// \brief Determine whether this is or was instantiated from an out-of-line
2061 /// definition of a member function.
2062 virtual bool isOutOfLine() const;
2064 /// \brief Identify a memory copying or setting function.
2065 /// If the given function is a memory copy or setting function, returns
2066 /// the corresponding Builtin ID. If the function is not a memory function,
2068 unsigned getMemoryFunctionKind() const;
2070 // Implement isa/cast/dyncast/etc.
2071 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2072 static bool classof(const FunctionDecl *D) { return true; }
2073 static bool classofKind(Kind K) {
2074 return K >= firstFunction && K <= lastFunction;
2076 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2077 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2079 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2080 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2083 friend class ASTDeclReader;
2084 friend class ASTDeclWriter;
2088 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2089 /// represent a member of a struct/union/class.
2090 class FieldDecl : public DeclaratorDecl {
2091 // FIXME: This can be packed into the bitfields in Decl.
2093 mutable unsigned CachedFieldIndex : 31;
2095 /// \brief A pointer to either the in-class initializer for this field (if
2096 /// the boolean value is false), or the bit width expression for this bit
2097 /// field (if the boolean value is true).
2099 /// We can safely combine these two because in-class initializers are not
2100 /// permitted for bit-fields.
2102 /// If the boolean is false and the initializer is null, then this field has
2103 /// an in-class initializer which has not yet been parsed and attached.
2104 llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
2106 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2107 SourceLocation IdLoc, IdentifierInfo *Id,
2108 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2110 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2111 Mutable(Mutable), CachedFieldIndex(0),
2112 InitializerOrBitWidth(BW, !HasInit) {
2113 assert(!(BW && HasInit) && "got initializer for bitfield");
2117 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2118 SourceLocation StartLoc, SourceLocation IdLoc,
2119 IdentifierInfo *Id, QualType T,
2120 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2123 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2125 /// getFieldIndex - Returns the index of this field within its record,
2126 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2127 unsigned getFieldIndex() const;
2129 /// isMutable - Determines whether this field is mutable (C++ only).
2130 bool isMutable() const { return Mutable; }
2132 /// \brief Set whether this field is mutable (C++ only).
2133 void setMutable(bool M) { Mutable = M; }
2135 /// isBitfield - Determines whether this field is a bitfield.
2136 bool isBitField() const {
2137 return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
2140 /// @brief Determines whether this is an unnamed bitfield.
2141 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2143 /// isAnonymousStructOrUnion - Determines whether this field is a
2144 /// representative for an anonymous struct or union. Such fields are
2145 /// unnamed and are implicitly generated by the implementation to
2146 /// store the data for the anonymous union or struct.
2147 bool isAnonymousStructOrUnion() const;
2149 Expr *getBitWidth() const {
2150 return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2152 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2153 void setBitWidth(Expr *BW) {
2154 assert(!InitializerOrBitWidth.getPointer() &&
2155 "bit width or initializer already set");
2156 InitializerOrBitWidth.setPointer(BW);
2157 InitializerOrBitWidth.setInt(1);
2159 /// removeBitWidth - Remove the bitfield width from this member.
2160 void removeBitWidth() {
2161 assert(isBitField() && "no bit width to remove");
2162 InitializerOrBitWidth.setPointer(0);
2165 /// hasInClassInitializer - Determine whether this member has a C++0x in-class
2167 bool hasInClassInitializer() const {
2168 return !InitializerOrBitWidth.getInt();
2170 /// getInClassInitializer - Get the C++0x in-class initializer for this
2171 /// member, or null if one has not been set. If a valid declaration has an
2172 /// in-class initializer, but this returns null, then we have not parsed and
2173 /// attached it yet.
2174 Expr *getInClassInitializer() const {
2175 return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2177 /// setInClassInitializer - Set the C++0x in-class initializer for this
2179 void setInClassInitializer(Expr *Init);
2180 /// removeInClassInitializer - Remove the C++0x in-class initializer from this
2182 void removeInClassInitializer() {
2183 assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
2184 InitializerOrBitWidth.setPointer(0);
2185 InitializerOrBitWidth.setInt(1);
2188 /// getParent - Returns the parent of this field declaration, which
2189 /// is the struct in which this method is defined.
2190 const RecordDecl *getParent() const {
2191 return cast<RecordDecl>(getDeclContext());
2194 RecordDecl *getParent() {
2195 return cast<RecordDecl>(getDeclContext());
2198 SourceRange getSourceRange() const LLVM_READONLY;
2200 // Implement isa/cast/dyncast/etc.
2201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2202 static bool classof(const FieldDecl *D) { return true; }
2203 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2206 /// EnumConstantDecl - An instance of this object exists for each enum constant
2207 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2208 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2209 /// TagType for the X EnumDecl.
2210 class EnumConstantDecl : public ValueDecl {
2211 Stmt *Init; // an integer constant expression
2212 llvm::APSInt Val; // The value.
2214 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2215 IdentifierInfo *Id, QualType T, Expr *E,
2216 const llvm::APSInt &V)
2217 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2221 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2222 SourceLocation L, IdentifierInfo *Id,
2223 QualType T, Expr *E,
2224 const llvm::APSInt &V);
2225 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2227 const Expr *getInitExpr() const { return (const Expr*) Init; }
2228 Expr *getInitExpr() { return (Expr*) Init; }
2229 const llvm::APSInt &getInitVal() const { return Val; }
2231 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2232 void setInitVal(const llvm::APSInt &V) { Val = V; }
2234 SourceRange getSourceRange() const LLVM_READONLY;
2236 // Implement isa/cast/dyncast/etc.
2237 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2238 static bool classof(const EnumConstantDecl *D) { return true; }
2239 static bool classofKind(Kind K) { return K == EnumConstant; }
2241 friend class StmtIteratorBase;
2244 /// IndirectFieldDecl - An instance of this class is created to represent a
2245 /// field injected from an anonymous union/struct into the parent scope.
2246 /// IndirectFieldDecl are always implicit.
2247 class IndirectFieldDecl : public ValueDecl {
2248 virtual void anchor();
2249 NamedDecl **Chaining;
2250 unsigned ChainingSize;
2252 IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2253 DeclarationName N, QualType T,
2254 NamedDecl **CH, unsigned CHS)
2255 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2258 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2259 SourceLocation L, IdentifierInfo *Id,
2260 QualType T, NamedDecl **CH, unsigned CHS);
2262 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2264 typedef NamedDecl * const *chain_iterator;
2265 chain_iterator chain_begin() const { return Chaining; }
2266 chain_iterator chain_end() const { return Chaining+ChainingSize; }
2268 unsigned getChainingSize() const { return ChainingSize; }
2270 FieldDecl *getAnonField() const {
2271 assert(ChainingSize >= 2);
2272 return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2275 VarDecl *getVarDecl() const {
2276 assert(ChainingSize >= 2);
2277 return dyn_cast<VarDecl>(*chain_begin());
2280 // Implement isa/cast/dyncast/etc.
2281 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2282 static bool classof(const IndirectFieldDecl *D) { return true; }
2283 static bool classofKind(Kind K) { return K == IndirectField; }
2284 friend class ASTDeclReader;
2287 /// TypeDecl - Represents a declaration of a type.
2289 class TypeDecl : public NamedDecl {
2290 virtual void anchor();
2291 /// TypeForDecl - This indicates the Type object that represents
2292 /// this TypeDecl. It is a cache maintained by
2293 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2294 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2295 mutable const Type *TypeForDecl;
2296 /// LocStart - The start of the source range for this declaration.
2297 SourceLocation LocStart;
2298 friend class ASTContext;
2299 friend class DeclContext;
2300 friend class TagDecl;
2301 friend class TemplateTypeParmDecl;
2302 friend class TagType;
2303 friend class ASTReader;
2306 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2307 SourceLocation StartL = SourceLocation())
2308 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2311 // Low-level accessor
2312 const Type *getTypeForDecl() const { return TypeForDecl; }
2313 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2315 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2316 void setLocStart(SourceLocation L) { LocStart = L; }
2317 virtual SourceRange getSourceRange() const LLVM_READONLY {
2318 if (LocStart.isValid())
2319 return SourceRange(LocStart, getLocation());
2321 return SourceRange(getLocation());
2324 // Implement isa/cast/dyncast/etc.
2325 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2326 static bool classof(const TypeDecl *D) { return true; }
2327 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2331 /// Base class for declarations which introduce a typedef-name.
2332 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2333 virtual void anchor();
2334 /// UnderlyingType - This is the type the typedef is set to.
2335 TypeSourceInfo *TInfo;
2338 TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2339 SourceLocation IdLoc, IdentifierInfo *Id,
2340 TypeSourceInfo *TInfo)
2341 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2343 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2344 virtual TypedefNameDecl *getNextRedeclaration() {
2345 return RedeclLink.getNext();
2347 virtual TypedefNameDecl *getPreviousDeclImpl() {
2348 return getPreviousDecl();
2350 virtual TypedefNameDecl *getMostRecentDeclImpl() {
2351 return getMostRecentDecl();
2355 typedef redeclarable_base::redecl_iterator redecl_iterator;
2356 using redeclarable_base::redecls_begin;
2357 using redeclarable_base::redecls_end;
2358 using redeclarable_base::getPreviousDecl;
2359 using redeclarable_base::getMostRecentDecl;
2361 TypeSourceInfo *getTypeSourceInfo() const {
2365 /// Retrieves the canonical declaration of this typedef-name.
2366 TypedefNameDecl *getCanonicalDecl() {
2367 return getFirstDeclaration();
2369 const TypedefNameDecl *getCanonicalDecl() const {
2370 return getFirstDeclaration();
2373 QualType getUnderlyingType() const {
2374 return TInfo->getType();
2376 void setTypeSourceInfo(TypeSourceInfo *newType) {
2380 // Implement isa/cast/dyncast/etc.
2381 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2382 static bool classof(const TypedefNameDecl *D) { return true; }
2383 static bool classofKind(Kind K) {
2384 return K >= firstTypedefName && K <= lastTypedefName;
2388 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2390 class TypedefDecl : public TypedefNameDecl {
2391 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2392 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2393 : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2396 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2397 SourceLocation StartLoc, SourceLocation IdLoc,
2398 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2399 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2401 SourceRange getSourceRange() const LLVM_READONLY;
2403 // Implement isa/cast/dyncast/etc.
2404 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2405 static bool classof(const TypedefDecl *D) { return true; }
2406 static bool classofKind(Kind K) { return K == Typedef; }
2409 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2410 /// alias-declaration.
2411 class TypeAliasDecl : public TypedefNameDecl {
2412 TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2413 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2414 : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2417 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2418 SourceLocation StartLoc, SourceLocation IdLoc,
2419 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2420 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2422 SourceRange getSourceRange() const LLVM_READONLY;
2424 // Implement isa/cast/dyncast/etc.
2425 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2426 static bool classof(const TypeAliasDecl *D) { return true; }
2427 static bool classofKind(Kind K) { return K == TypeAlias; }
2430 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2432 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2434 // This is really ugly.
2435 typedef TagTypeKind TagKind;
2438 // FIXME: This can be packed into the bitfields in Decl.
2439 /// TagDeclKind - The TagKind enum.
2440 unsigned TagDeclKind : 2;
2442 /// IsCompleteDefinition - True if this is a definition ("struct foo
2443 /// {};"), false if it is a declaration ("struct foo;"). It is not
2444 /// a definition until the definition has been fully processed.
2445 bool IsCompleteDefinition : 1;
2448 /// IsBeingDefined - True if this is currently being defined.
2449 bool IsBeingDefined : 1;
2452 /// IsEmbeddedInDeclarator - True if this tag declaration is
2453 /// "embedded" (i.e., defined or declared for the very first time)
2454 /// in the syntax of a declarator.
2455 bool IsEmbeddedInDeclarator : 1;
2457 /// \brief True if this tag is free standing, e.g. "struct foo;".
2458 bool IsFreeStanding : 1;
2461 // These are used by (and only defined for) EnumDecl.
2462 unsigned NumPositiveBits : 8;
2463 unsigned NumNegativeBits : 8;
2465 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2466 /// possible in C++11 mode.
2468 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2469 /// then this is true if the scoped enum was declared using the class
2470 /// tag, false if it was declared with the struct tag. No meaning is
2471 /// associated if this tag declaration is not a scoped enum.
2472 bool IsScopedUsingClassTag : 1;
2474 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2475 /// possible in C++11 or Microsoft extensions mode.
2479 SourceLocation RBraceLoc;
2481 // A struct representing syntactic qualifier info,
2482 // to be used for the (uncommon) case of out-of-line declarations.
2483 typedef QualifierInfo ExtInfo;
2485 /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2486 /// is qualified, it points to the qualifier info (nns and range);
2487 /// otherwise, if the tag declaration is anonymous and it is part of
2488 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2489 /// otherwise, it is a null (TypedefNameDecl) pointer.
2490 llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2492 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2493 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2494 const ExtInfo *getExtInfo() const {
2495 return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2499 TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2500 SourceLocation L, IdentifierInfo *Id,
2501 TagDecl *PrevDecl, SourceLocation StartL)
2502 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2503 TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2504 assert((DK != Enum || TK == TTK_Enum) &&
2505 "EnumDecl not matched with TTK_Enum");
2507 IsCompleteDefinition = false;
2508 IsBeingDefined = false;
2509 IsEmbeddedInDeclarator = false;
2510 IsFreeStanding = false;
2511 setPreviousDeclaration(PrevDecl);
2514 typedef Redeclarable<TagDecl> redeclarable_base;
2515 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2516 virtual TagDecl *getPreviousDeclImpl() {
2517 return getPreviousDecl();
2519 virtual TagDecl *getMostRecentDeclImpl() {
2520 return getMostRecentDecl();
2523 /// @brief Completes the definition of this tag declaration.
2525 /// This is a helper function for derived classes.
2526 void completeDefinition();
2529 typedef redeclarable_base::redecl_iterator redecl_iterator;
2530 using redeclarable_base::redecls_begin;
2531 using redeclarable_base::redecls_end;
2532 using redeclarable_base::getPreviousDecl;
2533 using redeclarable_base::getMostRecentDecl;
2535 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2536 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2538 /// getInnerLocStart - Return SourceLocation representing start of source
2539 /// range ignoring outer template declarations.
2540 SourceLocation getInnerLocStart() const { return getLocStart(); }
2542 /// getOuterLocStart - Return SourceLocation representing start of source
2543 /// range taking into account any outer template declarations.
2544 SourceLocation getOuterLocStart() const;
2545 virtual SourceRange getSourceRange() const LLVM_READONLY;
2547 virtual TagDecl* getCanonicalDecl();
2548 const TagDecl* getCanonicalDecl() const {
2549 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2552 /// isThisDeclarationADefinition() - Return true if this declaration
2553 /// is a completion definintion of the type. Provided for consistency.
2554 bool isThisDeclarationADefinition() const {
2555 return isCompleteDefinition();
2558 /// isCompleteDefinition - Return true if this decl has its body
2559 /// fully specified.
2560 bool isCompleteDefinition() const {
2561 return IsCompleteDefinition;
2564 /// isBeingDefined - Return true if this decl is currently being defined.
2565 bool isBeingDefined() const {
2566 return IsBeingDefined;
2569 bool isEmbeddedInDeclarator() const {
2570 return IsEmbeddedInDeclarator;
2572 void setEmbeddedInDeclarator(bool isInDeclarator) {
2573 IsEmbeddedInDeclarator = isInDeclarator;
2576 bool isFreeStanding() const { return IsFreeStanding; }
2577 void setFreeStanding(bool isFreeStanding = true) {
2578 IsFreeStanding = isFreeStanding;
2581 /// \brief Whether this declaration declares a type that is
2582 /// dependent, i.e., a type that somehow depends on template
2584 bool isDependentType() const { return isDependentContext(); }
2586 /// @brief Starts the definition of this tag declaration.
2588 /// This method should be invoked at the beginning of the definition
2589 /// of this tag declaration. It will set the tag type into a state
2590 /// where it is in the process of being defined.
2591 void startDefinition();
2593 /// getDefinition - Returns the TagDecl that actually defines this
2594 /// struct/union/class/enum. When determining whether or not a
2595 /// struct/union/class/enum has a definition, one should use this
2596 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2597 /// whether or not a specific TagDecl is defining declaration, not
2598 /// whether or not the struct/union/class/enum type is defined.
2599 /// This method returns NULL if there is no TagDecl that defines
2600 /// the struct/union/class/enum.
2601 TagDecl *getDefinition() const;
2603 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2605 const char *getKindName() const {
2606 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2609 TagKind getTagKind() const {
2610 return TagKind(TagDeclKind);
2613 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2615 bool isStruct() const { return getTagKind() == TTK_Struct; }
2616 bool isClass() const { return getTagKind() == TTK_Class; }
2617 bool isUnion() const { return getTagKind() == TTK_Union; }
2618 bool isEnum() const { return getTagKind() == TTK_Enum; }
2620 TypedefNameDecl *getTypedefNameForAnonDecl() const {
2621 return hasExtInfo() ? 0 :
2622 TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2625 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2627 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2628 /// declaration, if it was present in the source.
2629 NestedNameSpecifier *getQualifier() const {
2630 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2634 /// \brief Retrieve the nested-name-specifier (with source-location
2635 /// information) that qualifies the name of this declaration, if it was
2636 /// present in the source.
2637 NestedNameSpecifierLoc getQualifierLoc() const {
2638 return hasExtInfo() ? getExtInfo()->QualifierLoc
2639 : NestedNameSpecifierLoc();
2642 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2644 unsigned getNumTemplateParameterLists() const {
2645 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2647 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2648 assert(i < getNumTemplateParameterLists());
2649 return getExtInfo()->TemplParamLists[i];
2651 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2652 TemplateParameterList **TPLists);
2654 // Implement isa/cast/dyncast/etc.
2655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2656 static bool classof(const TagDecl *D) { return true; }
2657 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2659 static DeclContext *castToDeclContext(const TagDecl *D) {
2660 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2662 static TagDecl *castFromDeclContext(const DeclContext *DC) {
2663 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2666 friend class ASTDeclReader;
2667 friend class ASTDeclWriter;
2670 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
2671 /// with a fixed underlying type, and in C we allow them to be forward-declared
2672 /// with no underlying type as an extension.
2673 class EnumDecl : public TagDecl {
2674 virtual void anchor();
2675 /// IntegerType - This represent the integer type that the enum corresponds
2676 /// to for code generation purposes. Note that the enumerator constants may
2677 /// have a different type than this does.
2679 /// If the underlying integer type was explicitly stated in the source
2680 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2681 /// was automatically deduced somehow, and this is a Type*.
2683 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2684 /// some cases it won't.
2686 /// The underlying type of an enumeration never has any qualifiers, so
2687 /// we can get away with just storing a raw Type*, and thus save an
2688 /// extra pointer when TypeSourceInfo is needed.
2690 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2692 /// PromotionType - The integer type that values of this type should
2693 /// promote to. In C, enumerators are generally of an integer type
2694 /// directly, but gcc-style large enumerators (and all enumerators
2695 /// in C++) are of the enum type instead.
2696 QualType PromotionType;
2698 /// \brief If this enumeration is an instantiation of a member enumeration
2699 /// of a class template specialization, this is the member specialization
2701 MemberSpecializationInfo *SpecializationInfo;
2703 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2704 IdentifierInfo *Id, EnumDecl *PrevDecl,
2705 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2706 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2707 SpecializationInfo(0) {
2708 assert(Scoped || !ScopedUsingClassTag);
2709 IntegerType = (const Type*)0;
2710 NumNegativeBits = 0;
2711 NumPositiveBits = 0;
2713 IsScopedUsingClassTag = ScopedUsingClassTag;
2717 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2718 TemplateSpecializationKind TSK);
2720 EnumDecl *getCanonicalDecl() {
2721 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2723 const EnumDecl *getCanonicalDecl() const {
2724 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2727 const EnumDecl *getPreviousDecl() const {
2728 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2730 EnumDecl *getPreviousDecl() {
2731 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2734 const EnumDecl *getMostRecentDecl() const {
2735 return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2737 EnumDecl *getMostRecentDecl() {
2738 return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2741 EnumDecl *getDefinition() const {
2742 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2745 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2746 SourceLocation StartLoc, SourceLocation IdLoc,
2747 IdentifierInfo *Id, EnumDecl *PrevDecl,
2748 bool IsScoped, bool IsScopedUsingClassTag,
2750 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2752 /// completeDefinition - When created, the EnumDecl corresponds to a
2753 /// forward-declared enum. This method is used to mark the
2754 /// declaration as being defined; it's enumerators have already been
2755 /// added (via DeclContext::addDecl). NewType is the new underlying
2756 /// type of the enumeration type.
2757 void completeDefinition(QualType NewType,
2758 QualType PromotionType,
2759 unsigned NumPositiveBits,
2760 unsigned NumNegativeBits);
2762 // enumerator_iterator - Iterates through the enumerators of this
2764 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2766 enumerator_iterator enumerator_begin() const {
2767 const EnumDecl *E = getDefinition();
2770 return enumerator_iterator(E->decls_begin());
2773 enumerator_iterator enumerator_end() const {
2774 const EnumDecl *E = getDefinition();
2777 return enumerator_iterator(E->decls_end());
2780 /// getPromotionType - Return the integer type that enumerators
2781 /// should promote to.
2782 QualType getPromotionType() const { return PromotionType; }
2784 /// \brief Set the promotion type.
2785 void setPromotionType(QualType T) { PromotionType = T; }
2787 /// getIntegerType - Return the integer type this enum decl corresponds to.
2788 /// This returns a null qualtype for an enum forward definition.
2789 QualType getIntegerType() const {
2792 if (const Type* T = IntegerType.dyn_cast<const Type*>())
2793 return QualType(T, 0);
2794 return IntegerType.get<TypeSourceInfo*>()->getType();
2797 /// \brief Set the underlying integer type.
2798 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2800 /// \brief Set the underlying integer type source info.
2801 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2803 /// \brief Return the type source info for the underlying integer type,
2804 /// if no type source info exists, return 0.
2805 TypeSourceInfo* getIntegerTypeSourceInfo() const {
2806 return IntegerType.dyn_cast<TypeSourceInfo*>();
2809 /// \brief Returns the width in bits required to store all the
2810 /// non-negative enumerators of this enum.
2811 unsigned getNumPositiveBits() const {
2812 return NumPositiveBits;
2814 void setNumPositiveBits(unsigned Num) {
2815 NumPositiveBits = Num;
2816 assert(NumPositiveBits == Num && "can't store this bitcount");
2819 /// \brief Returns the width in bits required to store all the
2820 /// negative enumerators of this enum. These widths include
2821 /// the rightmost leading 1; that is:
2823 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
2824 /// ------------------------ ------- -----------------
2828 unsigned getNumNegativeBits() const {
2829 return NumNegativeBits;
2831 void setNumNegativeBits(unsigned Num) {
2832 NumNegativeBits = Num;
2835 /// \brief Returns true if this is a C++0x scoped enumeration.
2836 bool isScoped() const {
2840 /// \brief Returns true if this is a C++0x scoped enumeration.
2841 bool isScopedUsingClassTag() const {
2842 return IsScopedUsingClassTag;
2845 /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2847 bool isFixed() const {
2851 /// \brief Returns true if this can be considered a complete type.
2852 bool isComplete() const {
2853 return isCompleteDefinition() || isFixed();
2856 /// \brief Returns the enumeration (declared within the template)
2857 /// from which this enumeration type was instantiated, or NULL if
2858 /// this enumeration was not instantiated from any template.
2859 EnumDecl *getInstantiatedFromMemberEnum() const;
2861 /// \brief If this enumeration is a member of a specialization of a
2862 /// templated class, determine what kind of template specialization
2863 /// or instantiation this is.
2864 TemplateSpecializationKind getTemplateSpecializationKind() const;
2866 /// \brief For an enumeration member that was instantiated from a member
2867 /// enumeration of a templated class, set the template specialiation kind.
2868 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2869 SourceLocation PointOfInstantiation = SourceLocation());
2871 /// \brief If this enumeration is an instantiation of a member enumeration of
2872 /// a class template specialization, retrieves the member specialization
2874 MemberSpecializationInfo *getMemberSpecializationInfo() const {
2875 return SpecializationInfo;
2878 /// \brief Specify that this enumeration is an instantiation of the
2879 /// member enumeration ED.
2880 void setInstantiationOfMemberEnum(EnumDecl *ED,
2881 TemplateSpecializationKind TSK) {
2882 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2885 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2886 static bool classof(const EnumDecl *D) { return true; }
2887 static bool classofKind(Kind K) { return K == Enum; }
2889 friend class ASTDeclReader;
2893 /// RecordDecl - Represents a struct/union/class. For example:
2894 /// struct X; // Forward declaration, no "body".
2895 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
2896 /// This decl will be marked invalid if *any* members are invalid.
2898 class RecordDecl : public TagDecl {
2899 // FIXME: This can be packed into the bitfields in Decl.
2900 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2901 /// array member (e.g. int X[]) or if this union contains a struct that does.
2902 /// If so, this cannot be contained in arrays or other structs as a member.
2903 bool HasFlexibleArrayMember : 1;
2905 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2907 bool AnonymousStructOrUnion : 1;
2909 /// HasObjectMember - This is true if this struct has at least one member
2910 /// containing an Objective-C object pointer type.
2911 bool HasObjectMember : 1;
2913 /// \brief Whether the field declarations of this record have been loaded
2914 /// from external storage. To avoid unnecessary deserialization of
2915 /// methods/nested types we allow deserialization of just the fields
2917 mutable bool LoadedFieldsFromExternalStorage : 1;
2918 friend class DeclContext;
2921 RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2922 SourceLocation StartLoc, SourceLocation IdLoc,
2923 IdentifierInfo *Id, RecordDecl *PrevDecl);
2926 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2927 SourceLocation StartLoc, SourceLocation IdLoc,
2928 IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2929 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
2931 const RecordDecl *getPreviousDecl() const {
2932 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2934 RecordDecl *getPreviousDecl() {
2935 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2938 const RecordDecl *getMostRecentDecl() const {
2939 return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2941 RecordDecl *getMostRecentDecl() {
2942 return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2945 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2946 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2948 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2949 /// or union. To be an anonymous struct or union, it must have been
2950 /// declared without a name and there must be no objects of this
2951 /// type declared, e.g.,
2953 /// union { int i; float f; };
2955 /// is an anonymous union but neither of the following are:
2957 /// union X { int i; float f; };
2958 /// union { int i; float f; } obj;
2960 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2961 void setAnonymousStructOrUnion(bool Anon) {
2962 AnonymousStructOrUnion = Anon;
2965 bool hasObjectMember() const { return HasObjectMember; }
2966 void setHasObjectMember (bool val) { HasObjectMember = val; }
2968 /// \brief Determines whether this declaration represents the
2969 /// injected class name.
2971 /// The injected class name in C++ is the name of the class that
2972 /// appears inside the class itself. For example:
2976 /// // C is implicitly declared here as a synonym for the class name.
2979 /// C::C c; // same as "C c;"
2981 bool isInjectedClassName() const;
2983 /// getDefinition - Returns the RecordDecl that actually defines
2984 /// this struct/union/class. When determining whether or not a
2985 /// struct/union/class is completely defined, one should use this
2986 /// method as opposed to 'isCompleteDefinition'.
2987 /// 'isCompleteDefinition' indicates whether or not a specific
2988 /// RecordDecl is a completed definition, not whether or not the
2989 /// record type is defined. This method returns NULL if there is
2990 /// no RecordDecl that defines the struct/union/tag.
2991 RecordDecl *getDefinition() const {
2992 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2995 // Iterator access to field members. The field iterator only visits
2996 // the non-static data members of this class, ignoring any static
2997 // data members, functions, constructors, destructors, etc.
2998 typedef specific_decl_iterator<FieldDecl> field_iterator;
3000 field_iterator field_begin() const;
3002 field_iterator field_end() const {
3003 return field_iterator(decl_iterator());
3006 // field_empty - Whether there are any fields (non-static data
3007 // members) in this record.
3008 bool field_empty() const {
3009 return field_begin() == field_end();
3012 /// completeDefinition - Notes that the definition of this type is
3014 virtual void completeDefinition();
3016 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3017 static bool classof(const RecordDecl *D) { return true; }
3018 static bool classofKind(Kind K) {
3019 return K >= firstRecord && K <= lastRecord;
3023 /// \brief Deserialize just the fields.
3024 void LoadFieldsFromExternalStorage() const;
3027 class FileScopeAsmDecl : public Decl {
3028 virtual void anchor();
3029 StringLiteral *AsmString;
3030 SourceLocation RParenLoc;
3031 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3032 SourceLocation StartL, SourceLocation EndL)
3033 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3035 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3036 StringLiteral *Str, SourceLocation AsmLoc,
3037 SourceLocation RParenLoc);
3039 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3041 SourceLocation getAsmLoc() const { return getLocation(); }
3042 SourceLocation getRParenLoc() const { return RParenLoc; }
3043 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3044 SourceRange getSourceRange() const LLVM_READONLY {
3045 return SourceRange(getAsmLoc(), getRParenLoc());
3048 const StringLiteral *getAsmString() const { return AsmString; }
3049 StringLiteral *getAsmString() { return AsmString; }
3050 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3052 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3053 static bool classof(const FileScopeAsmDecl *D) { return true; }
3054 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3057 /// BlockDecl - This represents a block literal declaration, which is like an
3058 /// unnamed FunctionDecl. For example:
3059 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3061 class BlockDecl : public Decl, public DeclContext {
3063 /// A class which contains all the information about a particular
3071 /// The variable being captured.
3072 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3074 /// The copy expression, expressed in terms of a DeclRef (or
3075 /// BlockDeclRef) to the captured variable. Only required if the
3076 /// variable has a C++ class type.
3080 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3081 : VariableAndFlags(variable,
3082 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3085 /// The variable being captured.
3086 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3088 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3090 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3092 /// Whether this is a nested capture, i.e. the variable captured
3093 /// is not from outside the immediately enclosing function/block.
3094 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3096 bool hasCopyExpr() const { return CopyExpr != 0; }
3097 Expr *getCopyExpr() const { return CopyExpr; }
3098 void setCopyExpr(Expr *e) { CopyExpr = e; }
3102 // FIXME: This can be packed into the bitfields in Decl.
3103 bool IsVariadic : 1;
3104 bool CapturesCXXThis : 1;
3105 bool BlockMissingReturnType : 1;
3106 bool IsConversionFromLambda : 1;
3107 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3108 /// parameters of this function. This is null if a prototype or if there are
3110 ParmVarDecl **ParamInfo;
3114 TypeSourceInfo *SignatureAsWritten;
3117 unsigned NumCaptures;
3120 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3121 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3122 IsVariadic(false), CapturesCXXThis(false),
3123 BlockMissingReturnType(true), IsConversionFromLambda(false),
3124 ParamInfo(0), NumParams(0), Body(0),
3125 SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
3128 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3129 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3131 SourceLocation getCaretLocation() const { return getLocation(); }
3133 bool isVariadic() const { return IsVariadic; }
3134 void setIsVariadic(bool value) { IsVariadic = value; }
3136 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3137 Stmt *getBody() const { return (Stmt*) Body; }
3138 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3140 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3141 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3143 // Iterator access to formal parameters.
3144 unsigned param_size() const { return getNumParams(); }
3145 typedef ParmVarDecl **param_iterator;
3146 typedef ParmVarDecl * const *param_const_iterator;
3148 bool param_empty() const { return NumParams == 0; }
3149 param_iterator param_begin() { return ParamInfo; }
3150 param_iterator param_end() { return ParamInfo+param_size(); }
3152 param_const_iterator param_begin() const { return ParamInfo; }
3153 param_const_iterator param_end() const { return ParamInfo+param_size(); }
3155 unsigned getNumParams() const { return NumParams; }
3156 const ParmVarDecl *getParamDecl(unsigned i) const {
3157 assert(i < getNumParams() && "Illegal param #");
3158 return ParamInfo[i];
3160 ParmVarDecl *getParamDecl(unsigned i) {
3161 assert(i < getNumParams() && "Illegal param #");
3162 return ParamInfo[i];
3164 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
3166 /// hasCaptures - True if this block (or its nested blocks) captures
3167 /// anything of local storage from its enclosing scopes.
3168 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3170 /// getNumCaptures - Returns the number of captured variables.
3171 /// Does not include an entry for 'this'.
3172 unsigned getNumCaptures() const { return NumCaptures; }
3174 typedef const Capture *capture_iterator;
3175 typedef const Capture *capture_const_iterator;
3176 capture_iterator capture_begin() { return Captures; }
3177 capture_iterator capture_end() { return Captures + NumCaptures; }
3178 capture_const_iterator capture_begin() const { return Captures; }
3179 capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3181 bool capturesCXXThis() const { return CapturesCXXThis; }
3182 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3183 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3185 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3186 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3188 bool capturesVariable(const VarDecl *var) const;
3190 void setCaptures(ASTContext &Context,
3191 const Capture *begin,
3193 bool capturesCXXThis);
3195 virtual SourceRange getSourceRange() const LLVM_READONLY;
3197 // Implement isa/cast/dyncast/etc.
3198 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3199 static bool classof(const BlockDecl *D) { return true; }
3200 static bool classofKind(Kind K) { return K == Block; }
3201 static DeclContext *castToDeclContext(const BlockDecl *D) {
3202 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3204 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3205 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3209 /// \brief Describes a module import declaration, which makes the contents
3210 /// of the named module visible in the current translation unit.
3212 /// An import declaration imports the named module (or submodule). For example:
3214 /// @__experimental_modules_import std.vector;
3217 /// Import declarations can also be implicitly generated from #include/#import
3219 class ImportDecl : public Decl {
3220 /// \brief The imported module, along with a bit that indicates whether
3221 /// we have source-location information for each identifier in the module
3224 /// When the bit is false, we only have a single source location for the
3225 /// end of the import declaration.
3226 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3228 /// \brief The next import in the list of imports local to the translation
3229 /// unit being parsed (not loaded from an AST file).
3230 ImportDecl *NextLocalImport;
3232 friend class ASTReader;
3233 friend class ASTDeclReader;
3234 friend class ASTContext;
3236 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3237 ArrayRef<SourceLocation> IdentifierLocs);
3239 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3240 SourceLocation EndLoc);
3242 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3245 /// \brief Create a new module import declaration.
3246 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3247 SourceLocation StartLoc, Module *Imported,
3248 ArrayRef<SourceLocation> IdentifierLocs);
3250 /// \brief Create a new module import declaration for an implicitly-generated
3252 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3253 SourceLocation StartLoc, Module *Imported,
3254 SourceLocation EndLoc);
3256 /// \brief Create a new, deserialized module import declaration.
3257 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3258 unsigned NumLocations);
3260 /// \brief Retrieve the module that was imported by the import declaration.
3261 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3263 /// \brief Retrieves the locations of each of the identifiers that make up
3264 /// the complete module name in the import declaration.
3266 /// This will return an empty array if the locations of the individual
3267 /// identifiers aren't available.
3268 ArrayRef<SourceLocation> getIdentifierLocs() const;
3270 virtual SourceRange getSourceRange() const LLVM_READONLY;
3272 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3273 static bool classof(const ImportDecl *D) { return true; }
3274 static bool classofKind(Kind K) { return K == Import; }
3278 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3279 /// into a diagnostic with <<.
3280 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3281 const NamedDecl* ND) {
3282 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3283 DiagnosticsEngine::ak_nameddecl);
3286 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3287 const NamedDecl* ND) {
3288 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3289 DiagnosticsEngine::ak_nameddecl);
3293 template<typename decl_type>
3294 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3295 // Note: This routine is implemented here because we need both NamedDecl
3296 // and Redeclarable to be defined.
3301 // Point to previous. Make sure that this is actually the most recent
3302 // redeclaration, or we can build invalid chains. If the most recent
3303 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3304 RedeclLink = PreviousDeclLink(
3305 llvm::cast<decl_type>(PrevDecl->getMostRecentDecl()));
3306 First = PrevDecl->getFirstDeclaration();
3307 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3310 First = static_cast<decl_type*>(this);
3313 // First one will point to this one as latest.
3314 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3315 if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
3316 ND->ClearLinkageCache();
3319 // Inline function definitions.
3321 /// \brief Check if the given decl is complete.
3323 /// We use this function to break a cycle between the inline definitions in
3324 /// Type.h and Decl.h.
3325 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3326 return ED->isComplete();
3329 /// \brief Check if the given decl is scoped.
3331 /// We use this function to break a cycle between the inline definitions in
3332 /// Type.h and Decl.h.
3333 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3334 return ED->isScoped();
3337 } // end namespace clang