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
68 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
69 void overrideType(QualType T) { Ty = T; }
72 /// TranslationUnitDecl - The top declaration context.
73 class TranslationUnitDecl : public Decl, public DeclContext {
74 virtual void anchor();
77 /// The (most recently entered) anonymous namespace for this
78 /// translation unit, if one has been created.
79 NamespaceDecl *AnonymousNamespace;
81 explicit TranslationUnitDecl(ASTContext &ctx)
82 : Decl(TranslationUnit, 0, SourceLocation()),
83 DeclContext(TranslationUnit),
84 Ctx(ctx), AnonymousNamespace(0) {}
86 ASTContext &getASTContext() const { return Ctx; }
88 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
89 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
91 static TranslationUnitDecl *Create(ASTContext &C);
92 // Implement isa/cast/dyncast/etc.
93 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
94 static bool classof(const TranslationUnitDecl *D) { return true; }
95 static bool classofKind(Kind K) { return K == TranslationUnit; }
96 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
97 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
99 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
100 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
104 /// NamedDecl - This represents a decl with a name. Many decls have names such
105 /// as ObjCMethodDecl, but not @class, etc.
106 class NamedDecl : public Decl {
107 virtual void anchor();
108 /// Name - The name of this declaration, which is typically a normal
109 /// identifier but may also be a special kind of name (C++
110 /// constructor, Objective-C selector, etc.)
111 DeclarationName Name;
114 NamedDecl *getUnderlyingDeclImpl();
117 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
118 : Decl(DK, DC, L), Name(N) { }
121 /// getIdentifier - Get the identifier that names this declaration,
122 /// if there is one. This will return NULL if this declaration has
123 /// no name (e.g., for an unnamed class) or if the name is a special
124 /// name (C++ constructor, Objective-C selector, etc.).
125 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
127 /// getName - Get the name of identifier for this declaration as a StringRef.
128 /// This requires that the declaration have a name and that it be a simple
130 StringRef getName() const {
131 assert(Name.isIdentifier() && "Name is not a simple identifier");
132 return getIdentifier() ? getIdentifier()->getName() : "";
135 /// getNameAsString - Get a human-readable name for the declaration, even if
136 /// it is one of the special kinds of names (C++ constructor, Objective-C
137 /// selector, etc). Creating this name requires expensive string
138 /// manipulation, so it should be called only when performance doesn't matter.
139 /// For simple declarations, getNameAsCString() should suffice.
141 // FIXME: This function should be renamed to indicate that it is not just an
142 // alternate form of getName(), and clients should move as appropriate.
144 // FIXME: Deprecated, move clients to getName().
145 std::string getNameAsString() const { return Name.getAsString(); }
147 void printName(raw_ostream &os) const { return Name.printName(os); }
149 /// getDeclName - Get the actual, stored name of the declaration,
150 /// which may be a special name.
151 DeclarationName getDeclName() const { return Name; }
153 /// \brief Set the name of this declaration.
154 void setDeclName(DeclarationName N) { Name = N; }
156 /// getQualifiedNameAsString - Returns human-readable qualified name for
157 /// declaration, like A::B::i, for i being member of namespace A::B.
158 /// If declaration is not member of context which can be named (record,
159 /// namespace), it will return same result as getNameAsString().
160 /// Creating this name is expensive, so it should be called only when
161 /// performance doesn't matter.
162 std::string getQualifiedNameAsString() const;
163 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
165 /// getNameForDiagnostic - Appends a human-readable name for this
166 /// declaration into the given string.
168 /// This is the method invoked by Sema when displaying a NamedDecl
169 /// in a diagnostic. It does not necessarily produce the same
170 /// result as getNameAsString(); for example, class template
171 /// specializations are printed with their template arguments.
173 /// TODO: use an API that doesn't require so many temporary strings
174 virtual void getNameForDiagnostic(std::string &S,
175 const PrintingPolicy &Policy,
176 bool Qualified) const {
178 S += getQualifiedNameAsString(Policy);
180 S += getNameAsString();
183 /// declarationReplaces - Determine whether this declaration, if
184 /// known to be well-formed within its context, will replace the
185 /// declaration OldD if introduced into scope. A declaration will
186 /// replace another declaration if, for example, it is a
187 /// redeclaration of the same variable or function, but not if it is
188 /// a declaration of a different kind (function vs. class) or an
189 /// overloaded function.
190 bool declarationReplaces(NamedDecl *OldD) const;
192 /// \brief Determine whether this declaration has linkage.
193 bool hasLinkage() const;
195 using Decl::isModulePrivate;
196 using Decl::setModulePrivate;
198 /// \brief Determine whether this declaration is hidden from name lookup.
199 bool isHidden() const { return Hidden; }
201 /// \brief Determine whether this declaration is a C++ class member.
202 bool isCXXClassMember() const {
203 const DeclContext *DC = getDeclContext();
205 // C++0x [class.mem]p1:
206 // The enumerators of an unscoped enumeration defined in
207 // the class are members of the class.
208 // FIXME: support C++0x scoped enumerations.
209 if (isa<EnumDecl>(DC))
210 DC = DC->getParent();
212 return DC->isRecord();
215 /// \brief Determine whether the given declaration is an instance member of
217 bool isCXXInstanceMember() const;
221 Visibility visibility_;
225 LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
227 LinkageInfo(Linkage L, Visibility V, bool E)
228 : linkage_(L), visibility_(V), explicit_(E) {}
230 static LinkageInfo external() {
231 return LinkageInfo();
233 static LinkageInfo internal() {
234 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
236 static LinkageInfo uniqueExternal() {
237 return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
239 static LinkageInfo none() {
240 return LinkageInfo(NoLinkage, DefaultVisibility, false);
243 Linkage linkage() const { return linkage_; }
244 Visibility visibility() const { return visibility_; }
245 bool visibilityExplicit() const { return explicit_; }
247 void setLinkage(Linkage L) { linkage_ = L; }
248 void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
250 void mergeLinkage(Linkage L) {
251 setLinkage(minLinkage(linkage(), L));
253 void mergeLinkage(LinkageInfo Other) {
254 mergeLinkage(Other.linkage());
257 // Merge the visibility V giving preference to explicit ones.
258 // This is used, for example, when merging the visibility of a class
259 // down to one of its members. If the member has no explicit visibility,
260 // the class visibility wins.
261 void mergeVisibility(Visibility V, bool E = false) {
262 // If one has explicit visibility and the other doesn't, keep the
264 if (visibilityExplicit() && !E)
266 if (!visibilityExplicit() && E)
269 // If both are explicit or both are implicit, keep the minimum.
270 setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
272 // Merge the visibility V, keeping the most restrictive one.
273 // This is used for cases like merging the visibility of a template
274 // argument to an instantiation. If we already have a hidden class,
275 // no argument should give it default visibility.
276 void mergeVisibilityWithMin(Visibility V, bool E = false) {
277 // Never increase the visibility
278 if (visibility() < V)
281 // If this visibility is explicit, keep it.
282 if (visibilityExplicit() && !E)
286 void mergeVisibility(LinkageInfo Other) {
287 mergeVisibility(Other.visibility(), Other.visibilityExplicit());
289 void mergeVisibilityWithMin(LinkageInfo Other) {
290 mergeVisibilityWithMin(Other.visibility(), Other.visibilityExplicit());
293 void merge(LinkageInfo Other) {
295 mergeVisibility(Other);
297 void mergeWithMin(LinkageInfo Other) {
299 mergeVisibilityWithMin(Other);
302 friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
308 /// \brief Determine what kind of linkage this entity has.
309 Linkage getLinkage() const;
311 /// \brief Determines the visibility of this entity.
312 Visibility getVisibility() const {
313 return getLinkageAndVisibility().visibility();
316 /// \brief Determines the linkage and visibility of this entity.
317 LinkageInfo getLinkageAndVisibility() const;
319 /// \brief If visibility was explicitly specified for this
320 /// declaration, return that visibility.
321 llvm::Optional<Visibility> getExplicitVisibility() const;
323 /// \brief Clear the linkage cache in response to a change
324 /// to the declaration.
325 void ClearLinkageCache();
327 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
328 /// the underlying named decl.
329 NamedDecl *getUnderlyingDecl() {
330 // Fast-path the common case.
331 if (this->getKind() != UsingShadow &&
332 this->getKind() != ObjCCompatibleAlias)
335 return getUnderlyingDeclImpl();
337 const NamedDecl *getUnderlyingDecl() const {
338 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
341 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
342 static bool classof(const NamedDecl *D) { return true; }
343 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
346 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
351 /// LabelDecl - Represents the declaration of a label. Labels also have a
352 /// corresponding LabelStmt, which indicates the position that the label was
353 /// defined at. For normal labels, the location of the decl is the same as the
354 /// location of the statement. For GNU local labels (__label__), the decl
355 /// location is where the __label__ is.
356 class LabelDecl : public NamedDecl {
357 virtual void anchor();
359 /// LocStart - For normal labels, this is the same as the main declaration
360 /// label, i.e., the location of the identifier; for GNU local labels,
361 /// this is the location of the __label__ keyword.
362 SourceLocation LocStart;
364 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
365 LabelStmt *S, SourceLocation StartL)
366 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
369 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
370 SourceLocation IdentL, IdentifierInfo *II);
371 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
372 SourceLocation IdentL, IdentifierInfo *II,
373 SourceLocation GnuLabelL);
374 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
376 LabelStmt *getStmt() const { return TheStmt; }
377 void setStmt(LabelStmt *T) { TheStmt = T; }
379 bool isGnuLocal() const { return LocStart != getLocation(); }
380 void setLocStart(SourceLocation L) { LocStart = L; }
382 SourceRange getSourceRange() const LLVM_READONLY {
383 return SourceRange(LocStart, getLocation());
386 // Implement isa/cast/dyncast/etc.
387 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
388 static bool classof(const LabelDecl *D) { return true; }
389 static bool classofKind(Kind K) { return K == Label; }
392 /// NamespaceDecl - Represent a C++ namespace.
393 class NamespaceDecl : public NamedDecl, public DeclContext,
394 public Redeclarable<NamespaceDecl>
396 virtual void anchor();
398 /// LocStart - The starting location of the source range, pointing
399 /// to either the namespace or the inline keyword.
400 SourceLocation LocStart;
401 /// RBraceLoc - The ending location of the source range.
402 SourceLocation RBraceLoc;
404 /// \brief A pointer to either the anonymous namespace that lives just inside
405 /// this namespace or to the first namespace in the chain (the latter case
406 /// only when this is not the first in the chain), along with a
407 /// boolean value indicating whether this is an inline namespace.
408 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
410 NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
411 SourceLocation IdLoc, IdentifierInfo *Id,
412 NamespaceDecl *PrevDecl);
414 typedef Redeclarable<NamespaceDecl> redeclarable_base;
415 virtual NamespaceDecl *getNextRedeclaration() {
416 return RedeclLink.getNext();
418 virtual NamespaceDecl *getPreviousDeclImpl() {
419 return getPreviousDecl();
421 virtual NamespaceDecl *getMostRecentDeclImpl() {
422 return getMostRecentDecl();
426 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
427 bool Inline, SourceLocation StartLoc,
428 SourceLocation IdLoc, IdentifierInfo *Id,
429 NamespaceDecl *PrevDecl);
431 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
433 typedef redeclarable_base::redecl_iterator redecl_iterator;
434 using redeclarable_base::redecls_begin;
435 using redeclarable_base::redecls_end;
436 using redeclarable_base::getPreviousDecl;
437 using redeclarable_base::getMostRecentDecl;
439 /// \brief Returns true if this is an anonymous namespace declaration.
447 /// q.v. C++ [namespace.unnamed]
448 bool isAnonymousNamespace() const {
449 return !getIdentifier();
452 /// \brief Returns true if this is an inline namespace declaration.
453 bool isInline() const {
454 return AnonOrFirstNamespaceAndInline.getInt();
457 /// \brief Set whether this is an inline namespace declaration.
458 void setInline(bool Inline) {
459 AnonOrFirstNamespaceAndInline.setInt(Inline);
462 /// \brief Get the original (first) namespace declaration.
463 NamespaceDecl *getOriginalNamespace() {
464 if (isFirstDeclaration())
467 return AnonOrFirstNamespaceAndInline.getPointer();
470 /// \brief Get the original (first) namespace declaration.
471 const NamespaceDecl *getOriginalNamespace() const {
472 if (isFirstDeclaration())
475 return AnonOrFirstNamespaceAndInline.getPointer();
478 /// \brief Return true if this declaration is an original (first) declaration
479 /// of the namespace. This is false for non-original (subsequent) namespace
480 /// declarations and anonymous namespaces.
481 bool isOriginalNamespace() const {
482 return isFirstDeclaration();
485 /// \brief Retrieve the anonymous namespace nested inside this namespace,
487 NamespaceDecl *getAnonymousNamespace() const {
488 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
491 void setAnonymousNamespace(NamespaceDecl *D) {
492 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
495 /// Retrieves the canonical declaration of this namespace.
496 NamespaceDecl *getCanonicalDecl() {
497 return getOriginalNamespace();
499 const NamespaceDecl *getCanonicalDecl() const {
500 return getOriginalNamespace();
503 virtual SourceRange getSourceRange() const LLVM_READONLY {
504 return SourceRange(LocStart, RBraceLoc);
507 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
508 SourceLocation getRBraceLoc() const { return RBraceLoc; }
509 void setLocStart(SourceLocation L) { LocStart = L; }
510 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
512 // Implement isa/cast/dyncast/etc.
513 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
514 static bool classof(const NamespaceDecl *D) { return true; }
515 static bool classofKind(Kind K) { return K == Namespace; }
516 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
517 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
519 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
520 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
523 friend class ASTDeclReader;
524 friend class ASTDeclWriter;
527 /// ValueDecl - Represent the declaration of a variable (in which case it is
528 /// an lvalue) a function (in which case it is a function designator) or
529 /// an enum constant.
530 class ValueDecl : public NamedDecl {
531 virtual void anchor();
535 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
536 DeclarationName N, QualType T)
537 : NamedDecl(DK, DC, L, N), DeclType(T) {}
539 QualType getType() const { return DeclType; }
540 void setType(QualType newType) { DeclType = newType; }
542 /// \brief Determine whether this symbol is weakly-imported,
543 /// or declared with the weak or weak-ref attr.
544 bool isWeak() const {
545 return hasAttr<WeakAttr>() || hasAttr<WeakRefAttr>() || isWeakImported();
548 // Implement isa/cast/dyncast/etc.
549 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
550 static bool classof(const ValueDecl *D) { return true; }
551 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
554 /// QualifierInfo - A struct with extended info about a syntactic
555 /// name qualifier, to be used for the case of out-of-line declarations.
556 struct QualifierInfo {
557 NestedNameSpecifierLoc QualifierLoc;
559 /// NumTemplParamLists - The number of "outer" template parameter lists.
560 /// The count includes all of the template parameter lists that were matched
561 /// against the template-ids occurring into the NNS and possibly (in the
562 /// case of an explicit specialization) a final "template <>".
563 unsigned NumTemplParamLists;
565 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
566 /// containing pointers to the "outer" template parameter lists.
567 /// It includes all of the template parameter lists that were matched
568 /// against the template-ids occurring into the NNS and possibly (in the
569 /// case of an explicit specialization) a final "template <>".
570 TemplateParameterList** TemplParamLists;
572 /// Default constructor.
573 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
575 /// setTemplateParameterListsInfo - Sets info about "outer" template
577 void setTemplateParameterListsInfo(ASTContext &Context,
579 TemplateParameterList **TPLists);
582 // Copy constructor and copy assignment are disabled.
583 QualifierInfo(const QualifierInfo&);
584 QualifierInfo& operator=(const QualifierInfo&);
587 /// \brief Represents a ValueDecl that came out of a declarator.
588 /// Contains type source information through TypeSourceInfo.
589 class DeclaratorDecl : public ValueDecl {
590 // A struct representing both a TInfo and a syntactic qualifier,
591 // to be used for the (uncommon) case of out-of-line declarations.
592 struct ExtInfo : public QualifierInfo {
593 TypeSourceInfo *TInfo;
596 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
598 /// InnerLocStart - The start of the source range for this declaration,
599 /// ignoring outer template declarations.
600 SourceLocation InnerLocStart;
602 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
603 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
604 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
607 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
608 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
609 SourceLocation StartL)
610 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
614 TypeSourceInfo *getTypeSourceInfo() const {
616 ? getExtInfo()->TInfo
617 : DeclInfo.get<TypeSourceInfo*>();
619 void setTypeSourceInfo(TypeSourceInfo *TI) {
621 getExtInfo()->TInfo = TI;
626 /// getInnerLocStart - Return SourceLocation representing start of source
627 /// range ignoring outer template declarations.
628 SourceLocation getInnerLocStart() const { return InnerLocStart; }
629 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
631 /// getOuterLocStart - Return SourceLocation representing start of source
632 /// range taking into account any outer template declarations.
633 SourceLocation getOuterLocStart() const;
635 virtual SourceRange getSourceRange() const LLVM_READONLY;
636 SourceLocation getLocStart() const LLVM_READONLY {
637 return getOuterLocStart();
640 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
641 /// declaration, if it was present in the source.
642 NestedNameSpecifier *getQualifier() const {
643 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
647 /// \brief Retrieve the nested-name-specifier (with source-location
648 /// information) that qualifies the name of this declaration, if it was
649 /// present in the source.
650 NestedNameSpecifierLoc getQualifierLoc() const {
651 return hasExtInfo() ? getExtInfo()->QualifierLoc
652 : NestedNameSpecifierLoc();
655 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
657 unsigned getNumTemplateParameterLists() const {
658 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
660 TemplateParameterList *getTemplateParameterList(unsigned index) const {
661 assert(index < getNumTemplateParameterLists());
662 return getExtInfo()->TemplParamLists[index];
664 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
665 TemplateParameterList **TPLists);
667 SourceLocation getTypeSpecStartLoc() const;
669 // Implement isa/cast/dyncast/etc.
670 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
671 static bool classof(const DeclaratorDecl *D) { return true; }
672 static bool classofKind(Kind K) {
673 return K >= firstDeclarator && K <= lastDeclarator;
676 friend class ASTDeclReader;
677 friend class ASTDeclWriter;
680 /// \brief Structure used to store a statement, the constant value to
681 /// which it was evaluated (if any), and whether or not the statement
682 /// is an integral constant expression (if known).
683 struct EvaluatedStmt {
684 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
685 CheckingICE(false), IsICE(false) { }
687 /// \brief Whether this statement was already evaluated.
688 bool WasEvaluated : 1;
690 /// \brief Whether this statement is being evaluated.
691 bool IsEvaluating : 1;
693 /// \brief Whether we already checked whether this statement was an
694 /// integral constant expression.
697 /// \brief Whether we are checking whether this statement is an
698 /// integral constant expression.
699 bool CheckingICE : 1;
701 /// \brief Whether this statement is an integral constant expression,
702 /// or in C++11, whether the statement is a constant expression. Only
703 /// valid if CheckedICE is true.
710 /// VarDecl - An instance of this class is created to represent a variable
711 /// declaration or definition.
712 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
714 typedef clang::StorageClass StorageClass;
716 /// getStorageClassSpecifierString - Return the string used to
717 /// specify the storage class \arg SC.
719 /// It is illegal to call this function with SC == None.
720 static const char *getStorageClassSpecifierString(StorageClass SC);
722 /// \brief Initialization styles.
723 enum InitializationStyle {
724 CInit, ///< C-style initialization with assignment
725 CallInit, ///< Call-style initialization (C++98)
726 ListInit ///< Direct list-initialization (C++11)
730 /// \brief Placeholder type used in Init to denote an unparsed C++ default
732 struct UnparsedDefaultArgument;
734 /// \brief Placeholder type used in Init to denote an uninstantiated C++
735 /// default argument.
736 struct UninstantiatedDefaultArgument;
738 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
739 UnparsedDefaultArgument *,
740 UninstantiatedDefaultArgument *> InitType;
742 /// \brief The initializer for this variable or, for a ParmVarDecl, the
743 /// C++ default argument.
744 mutable InitType Init;
747 class VarDeclBitfields {
748 friend class VarDecl;
749 friend class ASTDeclReader;
752 unsigned SClassAsWritten : 3;
753 unsigned ThreadSpecified : 1;
754 unsigned InitStyle : 2;
756 /// \brief Whether this variable is the exception variable in a C++ catch
757 /// or an Objective-C @catch statement.
758 unsigned ExceptionVar : 1;
760 /// \brief Whether this local variable could be allocated in the return
761 /// slot of its function, enabling the named return value optimization
763 unsigned NRVOVariable : 1;
765 /// \brief Whether this variable is the for-range-declaration in a C++0x
766 /// for-range statement.
767 unsigned CXXForRangeDecl : 1;
769 /// \brief Whether this variable is an ARC pseudo-__strong
770 /// variable; see isARCPseudoStrong() for details.
771 unsigned ARCPseudoStrong : 1;
773 /// \brief Whether this variable is (C++0x) constexpr.
774 unsigned IsConstexpr : 1;
776 enum { NumVarDeclBits = 14 };
778 friend class ASTDeclReader;
779 friend class StmtIteratorBase;
782 enum { NumParameterIndexBits = 8 };
784 class ParmVarDeclBitfields {
785 friend class ParmVarDecl;
786 friend class ASTDeclReader;
788 unsigned : NumVarDeclBits;
790 /// Whether this parameter inherits a default argument from a
791 /// prior declaration.
792 unsigned HasInheritedDefaultArg : 1;
794 /// Whether this parameter undergoes K&R argument promotion.
795 unsigned IsKNRPromoted : 1;
797 /// Whether this parameter is an ObjC method parameter or not.
798 unsigned IsObjCMethodParam : 1;
800 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
801 /// Otherwise, the number of function parameter scopes enclosing
802 /// the function parameter scope in which this parameter was
804 unsigned ScopeDepthOrObjCQuals : 7;
806 /// The number of parameters preceding this parameter in the
807 /// function parameter scope in which it was declared.
808 unsigned ParameterIndex : NumParameterIndexBits;
813 VarDeclBitfields VarDeclBits;
814 ParmVarDeclBitfields ParmVarDeclBits;
817 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
818 SourceLocation IdLoc, IdentifierInfo *Id,
819 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
820 StorageClass SCAsWritten)
821 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
822 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
823 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
825 VarDeclBits.SClass = SC;
826 VarDeclBits.SClassAsWritten = SCAsWritten;
827 // Everything else is implicitly initialized to false.
830 typedef Redeclarable<VarDecl> redeclarable_base;
831 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
832 virtual VarDecl *getPreviousDeclImpl() {
833 return getPreviousDecl();
835 virtual VarDecl *getMostRecentDeclImpl() {
836 return getMostRecentDecl();
840 typedef redeclarable_base::redecl_iterator redecl_iterator;
841 using redeclarable_base::redecls_begin;
842 using redeclarable_base::redecls_end;
843 using redeclarable_base::getPreviousDecl;
844 using redeclarable_base::getMostRecentDecl;
846 static VarDecl *Create(ASTContext &C, DeclContext *DC,
847 SourceLocation StartLoc, SourceLocation IdLoc,
848 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
849 StorageClass S, StorageClass SCAsWritten);
851 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
853 virtual SourceRange getSourceRange() const LLVM_READONLY;
855 StorageClass getStorageClass() const {
856 return (StorageClass) VarDeclBits.SClass;
858 StorageClass getStorageClassAsWritten() const {
859 return (StorageClass) VarDeclBits.SClassAsWritten;
861 void setStorageClass(StorageClass SC);
862 void setStorageClassAsWritten(StorageClass SC) {
863 assert(isLegalForVariable(SC));
864 VarDeclBits.SClassAsWritten = SC;
867 void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
868 bool isThreadSpecified() const {
869 return VarDeclBits.ThreadSpecified;
872 /// hasLocalStorage - Returns true if a variable with function scope
873 /// is a non-static local variable.
874 bool hasLocalStorage() const {
875 if (getStorageClass() == SC_None)
876 return !isFileVarDecl();
878 // Return true for: Auto, Register.
879 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
881 return getStorageClass() >= SC_Auto;
884 /// isStaticLocal - Returns true if a variable with function scope is a
885 /// static local variable.
886 bool isStaticLocal() const {
887 return getStorageClass() == SC_Static && !isFileVarDecl();
890 /// hasExternStorage - Returns true if a variable has extern or
891 /// __private_extern__ storage.
892 bool hasExternalStorage() const {
893 return getStorageClass() == SC_Extern ||
894 getStorageClass() == SC_PrivateExtern;
897 /// hasGlobalStorage - Returns true for all variables that do not
898 /// have local storage. This includs all global variables as well
899 /// as static variables declared within a function.
900 bool hasGlobalStorage() const { return !hasLocalStorage(); }
902 /// \brief Determines whether this variable is a variable with
903 /// external, C linkage.
904 bool isExternC() const;
906 /// isLocalVarDecl - Returns true for local variable declarations
907 /// other than parameters. Note that this includes static variables
908 /// inside of functions. It also includes variables inside blocks.
910 /// void foo() { int x; static int y; extern int z; }
912 bool isLocalVarDecl() const {
913 if (getKind() != Decl::Var)
915 if (const DeclContext *DC = getDeclContext())
916 return DC->getRedeclContext()->isFunctionOrMethod();
920 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
921 /// excludes variables declared in blocks.
922 bool isFunctionOrMethodVarDecl() const {
923 if (getKind() != Decl::Var)
925 const DeclContext *DC = getDeclContext()->getRedeclContext();
926 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
929 /// \brief Determines whether this is a static data member.
931 /// This will only be true in C++, and applies to, e.g., the
938 bool isStaticDataMember() const {
939 // If it wasn't static, it would be a FieldDecl.
940 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
943 virtual VarDecl *getCanonicalDecl();
944 const VarDecl *getCanonicalDecl() const {
945 return const_cast<VarDecl*>(this)->getCanonicalDecl();
948 enum DefinitionKind {
949 DeclarationOnly, ///< This declaration is only a declaration.
950 TentativeDefinition, ///< This declaration is a tentative definition.
951 Definition ///< This declaration is definitely a definition.
954 /// \brief Check whether this declaration is a definition. If this could be
955 /// a tentative definition (in C), don't check whether there's an overriding
957 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
958 DefinitionKind isThisDeclarationADefinition() const {
959 return isThisDeclarationADefinition(getASTContext());
962 /// \brief Check whether this variable is defined in this
963 /// translation unit.
964 DefinitionKind hasDefinition(ASTContext &) const;
965 DefinitionKind hasDefinition() const {
966 return hasDefinition(getASTContext());
969 /// \brief Get the tentative definition that acts as the real definition in
970 /// a TU. Returns null if there is a proper definition available.
971 VarDecl *getActingDefinition();
972 const VarDecl *getActingDefinition() const {
973 return const_cast<VarDecl*>(this)->getActingDefinition();
976 /// \brief Determine whether this is a tentative definition of a
978 bool isTentativeDefinitionNow() const;
980 /// \brief Get the real (not just tentative) definition for this declaration.
981 VarDecl *getDefinition(ASTContext &);
982 const VarDecl *getDefinition(ASTContext &C) const {
983 return const_cast<VarDecl*>(this)->getDefinition(C);
985 VarDecl *getDefinition() {
986 return getDefinition(getASTContext());
988 const VarDecl *getDefinition() const {
989 return const_cast<VarDecl*>(this)->getDefinition();
992 /// \brief Determine whether this is or was instantiated from an out-of-line
993 /// definition of a static data member.
994 virtual bool isOutOfLine() const;
996 /// \brief If this is a static data member, find its out-of-line definition.
997 VarDecl *getOutOfLineDefinition();
999 /// isFileVarDecl - Returns true for file scoped variable declaration.
1000 bool isFileVarDecl() const {
1001 if (getKind() != Decl::Var)
1004 if (getDeclContext()->getRedeclContext()->isFileContext())
1007 if (isStaticDataMember())
1013 /// getAnyInitializer - Get the initializer for this variable, no matter which
1014 /// declaration it is attached to.
1015 const Expr *getAnyInitializer() const {
1017 return getAnyInitializer(D);
1020 /// getAnyInitializer - Get the initializer for this variable, no matter which
1021 /// declaration it is attached to. Also get that declaration.
1022 const Expr *getAnyInitializer(const VarDecl *&D) const;
1024 bool hasInit() const {
1025 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
1027 const Expr *getInit() const {
1031 const Stmt *S = Init.dyn_cast<Stmt *>();
1033 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1036 return (const Expr*) S;
1042 Stmt *S = Init.dyn_cast<Stmt *>();
1044 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1051 /// \brief Retrieve the address of the initializer expression.
1052 Stmt **getInitAddress() {
1053 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1056 // This union hack tip-toes around strict-aliasing rules.
1066 void setInit(Expr *I);
1068 /// \brief Determine whether this variable is a reference that
1069 /// extends the lifetime of its temporary initializer.
1071 /// A reference extends the lifetime of its temporary initializer if
1072 /// it's initializer is an rvalue that would normally go out of scope
1073 /// at the end of the initializer (a full expression). In such cases,
1074 /// the reference itself takes ownership of the temporary, which will
1075 /// be destroyed when the reference goes out of scope. For example:
1078 /// const int &r = 1.0; // creates a temporary of type 'int'
1080 bool extendsLifetimeOfTemporary() const;
1082 /// \brief Determine whether this variable's value can be used in a
1083 /// constant expression, according to the relevant language standard.
1084 /// This only checks properties of the declaration, and does not check
1085 /// whether the initializer is in fact a constant expression.
1086 bool isUsableInConstantExpressions(ASTContext &C) const;
1088 EvaluatedStmt *ensureEvaluatedStmt() const;
1090 /// \brief Attempt to evaluate the value of the initializer attached to this
1091 /// declaration, and produce notes explaining why it cannot be evaluated or is
1092 /// not a constant expression. Returns a pointer to the value if evaluation
1093 /// succeeded, 0 otherwise.
1094 APValue *evaluateValue() const;
1095 APValue *evaluateValue(
1096 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1098 /// \brief Return the already-evaluated value of this variable's
1099 /// initializer, or NULL if the value is not yet known. Returns pointer
1100 /// to untyped APValue if the value could not be evaluated.
1101 APValue *getEvaluatedValue() const {
1102 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1103 if (Eval->WasEvaluated)
1104 return &Eval->Evaluated;
1109 /// \brief Determines whether it is already known whether the
1110 /// initializer is an integral constant expression or not.
1111 bool isInitKnownICE() const {
1112 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1113 return Eval->CheckedICE;
1118 /// \brief Determines whether the initializer is an integral constant
1119 /// expression, or in C++11, whether the initializer is a constant
1122 /// \pre isInitKnownICE()
1123 bool isInitICE() const {
1124 assert(isInitKnownICE() &&
1125 "Check whether we already know that the initializer is an ICE");
1126 return Init.get<EvaluatedStmt *>()->IsICE;
1129 /// \brief Determine whether the value of the initializer attached to this
1130 /// declaration is an integral constant expression.
1131 bool checkInitIsICE() const;
1133 void setInitStyle(InitializationStyle Style) {
1134 VarDeclBits.InitStyle = Style;
1137 /// \brief The style of initialization for this declaration.
1139 /// C-style initialization is "int x = 1;". Call-style initialization is
1140 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1141 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1142 /// expression for class types. List-style initialization is C++11 syntax,
1143 /// e.g. "int x{1};". Clients can distinguish between different forms of
1144 /// initialization by checking this value. In particular, "int x = {1};" is
1145 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1146 /// Init expression in all three cases is an InitListExpr.
1147 InitializationStyle getInitStyle() const {
1148 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1151 /// \brief Whether the initializer is a direct-initializer (list or call).
1152 bool isDirectInit() const {
1153 return getInitStyle() != CInit;
1156 /// \brief Determine whether this variable is the exception variable in a
1157 /// C++ catch statememt or an Objective-C @catch statement.
1158 bool isExceptionVariable() const {
1159 return VarDeclBits.ExceptionVar;
1161 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1163 /// \brief Determine whether this local variable can be used with the named
1164 /// return value optimization (NRVO).
1166 /// The named return value optimization (NRVO) works by marking certain
1167 /// non-volatile local variables of class type as NRVO objects. These
1168 /// locals can be allocated within the return slot of their containing
1169 /// function, in which case there is no need to copy the object to the
1170 /// return slot when returning from the function. Within the function body,
1171 /// each return that returns the NRVO object will have this variable as its
1173 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1174 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1176 /// \brief Determine whether this variable is the for-range-declaration in
1177 /// a C++0x for-range statement.
1178 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1179 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1181 /// \brief Determine whether this variable is an ARC pseudo-__strong
1182 /// variable. A pseudo-__strong variable has a __strong-qualified
1183 /// type but does not actually retain the object written into it.
1184 /// Generally such variables are also 'const' for safety.
1185 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1186 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1188 /// Whether this variable is (C++0x) constexpr.
1189 bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1190 void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1192 /// \brief If this variable is an instantiated static data member of a
1193 /// class template specialization, returns the templated static data member
1194 /// from which it was instantiated.
1195 VarDecl *getInstantiatedFromStaticDataMember() const;
1197 /// \brief If this variable is a static data member, determine what kind of
1198 /// template specialization or instantiation this is.
1199 TemplateSpecializationKind getTemplateSpecializationKind() const;
1201 /// \brief If this variable is an instantiation of a static data member of a
1202 /// class template specialization, retrieves the member specialization
1204 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1206 /// \brief For a static data member that was instantiated from a static
1207 /// data member of a class template, set the template specialiation kind.
1208 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1209 SourceLocation PointOfInstantiation = SourceLocation());
1211 // Implement isa/cast/dyncast/etc.
1212 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1213 static bool classof(const VarDecl *D) { return true; }
1214 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1217 class ImplicitParamDecl : public VarDecl {
1218 virtual void anchor();
1220 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1221 SourceLocation IdLoc, IdentifierInfo *Id,
1224 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1226 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1227 IdentifierInfo *Id, QualType Type)
1228 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1229 /*tinfo*/ 0, SC_None, SC_None) {
1233 // Implement isa/cast/dyncast/etc.
1234 static bool classof(const ImplicitParamDecl *D) { return true; }
1235 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1236 static bool classofKind(Kind K) { return K == ImplicitParam; }
1239 /// ParmVarDecl - Represents a parameter to a function.
1240 class ParmVarDecl : public VarDecl {
1242 enum { MaxFunctionScopeDepth = 255 };
1243 enum { MaxFunctionScopeIndex = 255 };
1246 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1247 SourceLocation IdLoc, IdentifierInfo *Id,
1248 QualType T, TypeSourceInfo *TInfo,
1249 StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1250 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1251 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1252 assert(ParmVarDeclBits.IsKNRPromoted == false);
1253 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1254 setDefaultArg(DefArg);
1258 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1259 SourceLocation StartLoc,
1260 SourceLocation IdLoc, IdentifierInfo *Id,
1261 QualType T, TypeSourceInfo *TInfo,
1262 StorageClass S, StorageClass SCAsWritten,
1265 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1267 virtual SourceRange getSourceRange() const LLVM_READONLY;
1269 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1270 ParmVarDeclBits.IsObjCMethodParam = true;
1271 setParameterIndex(parameterIndex);
1274 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1275 assert(!ParmVarDeclBits.IsObjCMethodParam);
1277 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1278 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1281 setParameterIndex(parameterIndex);
1284 bool isObjCMethodParameter() const {
1285 return ParmVarDeclBits.IsObjCMethodParam;
1288 unsigned getFunctionScopeDepth() const {
1289 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1290 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1293 /// Returns the index of this parameter in its prototype or method scope.
1294 unsigned getFunctionScopeIndex() const {
1295 return getParameterIndex();
1298 ObjCDeclQualifier getObjCDeclQualifier() const {
1299 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1300 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1302 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1303 assert(ParmVarDeclBits.IsObjCMethodParam);
1304 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1307 /// True if the value passed to this parameter must undergo
1308 /// K&R-style default argument promotion:
1311 /// If the expression that denotes the called function has a type
1312 /// that does not include a prototype, the integer promotions are
1313 /// performed on each argument, and arguments that have type float
1314 /// are promoted to double.
1315 bool isKNRPromoted() const {
1316 return ParmVarDeclBits.IsKNRPromoted;
1318 void setKNRPromoted(bool promoted) {
1319 ParmVarDeclBits.IsKNRPromoted = promoted;
1322 Expr *getDefaultArg();
1323 const Expr *getDefaultArg() const {
1324 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1327 void setDefaultArg(Expr *defarg) {
1328 Init = reinterpret_cast<Stmt *>(defarg);
1331 /// \brief Retrieve the source range that covers the entire default
1333 SourceRange getDefaultArgRange() const;
1334 void setUninstantiatedDefaultArg(Expr *arg) {
1335 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1337 Expr *getUninstantiatedDefaultArg() {
1338 return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1340 const Expr *getUninstantiatedDefaultArg() const {
1341 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1344 /// hasDefaultArg - Determines whether this parameter has a default argument,
1345 /// either parsed or not.
1346 bool hasDefaultArg() const {
1347 return getInit() || hasUnparsedDefaultArg() ||
1348 hasUninstantiatedDefaultArg();
1351 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1352 /// default argument that has not yet been parsed. This will occur
1353 /// during the processing of a C++ class whose member functions have
1354 /// default arguments, e.g.,
1358 /// void f(int x = 17); // x has an unparsed default argument now
1359 /// }; // x has a regular default argument now
1361 bool hasUnparsedDefaultArg() const {
1362 return Init.is<UnparsedDefaultArgument*>();
1365 bool hasUninstantiatedDefaultArg() const {
1366 return Init.is<UninstantiatedDefaultArgument*>();
1369 /// setUnparsedDefaultArg - Specify that this parameter has an
1370 /// unparsed default argument. The argument will be replaced with a
1371 /// real default argument via setDefaultArg when the class
1372 /// definition enclosing the function declaration that owns this
1373 /// default argument is completed.
1374 void setUnparsedDefaultArg() {
1375 Init = (UnparsedDefaultArgument *)0;
1378 bool hasInheritedDefaultArg() const {
1379 return ParmVarDeclBits.HasInheritedDefaultArg;
1382 void setHasInheritedDefaultArg(bool I = true) {
1383 ParmVarDeclBits.HasInheritedDefaultArg = I;
1386 QualType getOriginalType() const {
1387 if (getTypeSourceInfo())
1388 return getTypeSourceInfo()->getType();
1392 /// \brief Determine whether this parameter is actually a function
1394 bool isParameterPack() const;
1396 /// setOwningFunction - Sets the function declaration that owns this
1397 /// ParmVarDecl. Since ParmVarDecls are often created before the
1398 /// FunctionDecls that own them, this routine is required to update
1399 /// the DeclContext appropriately.
1400 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1402 // Implement isa/cast/dyncast/etc.
1403 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1404 static bool classof(const ParmVarDecl *D) { return true; }
1405 static bool classofKind(Kind K) { return K == ParmVar; }
1408 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1410 void setParameterIndex(unsigned parameterIndex) {
1411 if (parameterIndex >= ParameterIndexSentinel) {
1412 setParameterIndexLarge(parameterIndex);
1416 ParmVarDeclBits.ParameterIndex = parameterIndex;
1417 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1419 unsigned getParameterIndex() const {
1420 unsigned d = ParmVarDeclBits.ParameterIndex;
1421 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1424 void setParameterIndexLarge(unsigned parameterIndex);
1425 unsigned getParameterIndexLarge() const;
1428 /// FunctionDecl - An instance of this class is created to represent a
1429 /// function declaration or definition.
1431 /// Since a given function can be declared several times in a program,
1432 /// there may be several FunctionDecls that correspond to that
1433 /// function. Only one of those FunctionDecls will be found when
1434 /// traversing the list of declarations in the context of the
1435 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1436 /// contains all of the information known about the function. Other,
1437 /// previous declarations of the function are available via the
1438 /// getPreviousDecl() chain.
1439 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1440 public Redeclarable<FunctionDecl> {
1442 typedef clang::StorageClass StorageClass;
1444 /// \brief The kind of templated function a FunctionDecl can be.
1445 enum TemplatedKind {
1447 TK_FunctionTemplate,
1448 TK_MemberSpecialization,
1449 TK_FunctionTemplateSpecialization,
1450 TK_DependentFunctionTemplateSpecialization
1454 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1455 /// parameters of this function. This is null if a prototype or if there are
1457 ParmVarDecl **ParamInfo;
1459 /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1460 /// decls defined in the function prototype that are not parameters. E.g.
1461 /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1462 llvm::ArrayRef<NamedDecl*> DeclsInPrototypeScope;
1464 LazyDeclStmtPtr Body;
1466 // FIXME: This can be packed into the bitfields in Decl.
1467 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1468 unsigned SClass : 2;
1469 unsigned SClassAsWritten : 2;
1471 bool IsInlineSpecified : 1;
1472 bool IsVirtualAsWritten : 1;
1474 bool HasInheritedPrototype : 1;
1475 bool HasWrittenPrototype : 1;
1477 bool IsTrivial : 1; // sunk from CXXMethodDecl
1478 bool IsDefaulted : 1; // sunk from CXXMethoDecl
1479 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1480 bool HasImplicitReturnZero : 1;
1481 bool IsLateTemplateParsed : 1;
1482 bool IsConstexpr : 1;
1484 /// \brief End part of this FunctionDecl's source range.
1486 /// We could compute the full range in getSourceRange(). However, when we're
1487 /// dealing with a function definition deserialized from a PCH/AST file,
1488 /// we can only compute the full range once the function body has been
1489 /// de-serialized, so it's far better to have the (sometimes-redundant)
1491 SourceLocation EndRangeLoc;
1493 /// \brief The template or declaration that this declaration
1494 /// describes or was instantiated from, respectively.
1496 /// For non-templates, this value will be NULL. For function
1497 /// declarations that describe a function template, this will be a
1498 /// pointer to a FunctionTemplateDecl. For member functions
1499 /// of class template specializations, this will be a MemberSpecializationInfo
1500 /// pointer containing information about the specialization.
1501 /// For function template specializations, this will be a
1502 /// FunctionTemplateSpecializationInfo, which contains information about
1503 /// the template being specialized and the template arguments involved in
1504 /// that specialization.
1505 llvm::PointerUnion4<FunctionTemplateDecl *,
1506 MemberSpecializationInfo *,
1507 FunctionTemplateSpecializationInfo *,
1508 DependentFunctionTemplateSpecializationInfo *>
1509 TemplateOrSpecialization;
1511 /// DNLoc - Provides source/type location info for the
1512 /// declaration name embedded in the DeclaratorDecl base class.
1513 DeclarationNameLoc DNLoc;
1515 /// \brief Specify that this function declaration is actually a function
1516 /// template specialization.
1518 /// \param C the ASTContext.
1520 /// \param Template the function template that this function template
1521 /// specialization specializes.
1523 /// \param TemplateArgs the template arguments that produced this
1524 /// function template specialization from the template.
1526 /// \param InsertPos If non-NULL, the position in the function template
1527 /// specialization set where the function template specialization data will
1530 /// \param TSK the kind of template specialization this is.
1532 /// \param TemplateArgsAsWritten location info of template arguments.
1534 /// \param PointOfInstantiation point at which the function template
1535 /// specialization was first instantiated.
1536 void setFunctionTemplateSpecialization(ASTContext &C,
1537 FunctionTemplateDecl *Template,
1538 const TemplateArgumentList *TemplateArgs,
1540 TemplateSpecializationKind TSK,
1541 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1542 SourceLocation PointOfInstantiation);
1544 /// \brief Specify that this record is an instantiation of the
1545 /// member function FD.
1546 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1547 TemplateSpecializationKind TSK);
1549 void setParams(ASTContext &C, llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
1552 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1553 const DeclarationNameInfo &NameInfo,
1554 QualType T, TypeSourceInfo *TInfo,
1555 StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
1556 bool isConstexprSpecified)
1557 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1560 ParamInfo(0), Body(),
1561 SClass(S), SClassAsWritten(SCAsWritten),
1562 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1563 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1564 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1565 IsDefaulted(false), IsExplicitlyDefaulted(false),
1566 HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1567 IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()),
1568 TemplateOrSpecialization(),
1569 DNLoc(NameInfo.getInfo()) {}
1571 typedef Redeclarable<FunctionDecl> redeclarable_base;
1572 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1573 virtual FunctionDecl *getPreviousDeclImpl() {
1574 return getPreviousDecl();
1576 virtual FunctionDecl *getMostRecentDeclImpl() {
1577 return getMostRecentDecl();
1581 typedef redeclarable_base::redecl_iterator redecl_iterator;
1582 using redeclarable_base::redecls_begin;
1583 using redeclarable_base::redecls_end;
1584 using redeclarable_base::getPreviousDecl;
1585 using redeclarable_base::getMostRecentDecl;
1587 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1588 SourceLocation StartLoc, SourceLocation NLoc,
1589 DeclarationName N, QualType T,
1590 TypeSourceInfo *TInfo,
1591 StorageClass SC = SC_None,
1592 StorageClass SCAsWritten = SC_None,
1593 bool isInlineSpecified = false,
1594 bool hasWrittenPrototype = true,
1595 bool isConstexprSpecified = false) {
1596 DeclarationNameInfo NameInfo(N, NLoc);
1597 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1599 isInlineSpecified, hasWrittenPrototype,
1600 isConstexprSpecified);
1603 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1604 SourceLocation StartLoc,
1605 const DeclarationNameInfo &NameInfo,
1606 QualType T, TypeSourceInfo *TInfo,
1607 StorageClass SC = SC_None,
1608 StorageClass SCAsWritten = SC_None,
1609 bool isInlineSpecified = false,
1610 bool hasWrittenPrototype = true,
1611 bool isConstexprSpecified = false);
1613 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1615 DeclarationNameInfo getNameInfo() const {
1616 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1619 virtual void getNameForDiagnostic(std::string &S,
1620 const PrintingPolicy &Policy,
1621 bool Qualified) const;
1623 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1625 virtual SourceRange getSourceRange() const LLVM_READONLY;
1627 /// \brief Returns true if the function has a body (definition). The
1628 /// function body might be in any of the (re-)declarations of this
1629 /// function. The variant that accepts a FunctionDecl pointer will
1630 /// set that function declaration to the actual declaration
1631 /// containing the body (if there is one).
1632 bool hasBody(const FunctionDecl *&Definition) const;
1634 virtual bool hasBody() const {
1635 const FunctionDecl* Definition;
1636 return hasBody(Definition);
1639 /// hasTrivialBody - Returns whether the function has a trivial body that does
1640 /// not require any specific codegen.
1641 bool hasTrivialBody() const;
1643 /// isDefined - Returns true if the function is defined at all, including
1644 /// a deleted definition. Except for the behavior when the function is
1645 /// deleted, behaves like hasBody.
1646 bool isDefined(const FunctionDecl *&Definition) const;
1648 virtual bool isDefined() const {
1649 const FunctionDecl* Definition;
1650 return isDefined(Definition);
1653 /// getBody - Retrieve the body (definition) of the function. The
1654 /// function body might be in any of the (re-)declarations of this
1655 /// function. The variant that accepts a FunctionDecl pointer will
1656 /// set that function declaration to the actual declaration
1657 /// containing the body (if there is one).
1658 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1659 /// unnecessary AST de-serialization of the body.
1660 Stmt *getBody(const FunctionDecl *&Definition) const;
1662 virtual Stmt *getBody() const {
1663 const FunctionDecl* Definition;
1664 return getBody(Definition);
1667 /// isThisDeclarationADefinition - Returns whether this specific
1668 /// declaration of the function is also a definition. This does not
1669 /// determine whether the function has been defined (e.g., in a
1670 /// previous definition); for that information, use isDefined. Note
1671 /// that this returns false for a defaulted function unless that function
1672 /// has been implicitly defined (possibly as deleted).
1673 bool isThisDeclarationADefinition() const {
1674 return IsDeleted || Body || IsLateTemplateParsed;
1677 /// doesThisDeclarationHaveABody - Returns whether this specific
1678 /// declaration of the function has a body - that is, if it is a non-
1679 /// deleted definition.
1680 bool doesThisDeclarationHaveABody() const {
1681 return Body || IsLateTemplateParsed;
1684 void setBody(Stmt *B);
1685 void setLazyBody(uint64_t Offset) { Body = Offset; }
1687 /// Whether this function is variadic.
1688 bool isVariadic() const;
1690 /// Whether this function is marked as virtual explicitly.
1691 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1692 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1694 /// Whether this virtual function is pure, i.e. makes the containing class
1696 bool isPure() const { return IsPure; }
1697 void setPure(bool P = true);
1699 /// Whether this templated function will be late parsed.
1700 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1701 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1703 /// Whether this function is "trivial" in some specialized C++ senses.
1704 /// Can only be true for default constructors, copy constructors,
1705 /// copy assignment operators, and destructors. Not meaningful until
1706 /// the class has been fully built by Sema.
1707 bool isTrivial() const { return IsTrivial; }
1708 void setTrivial(bool IT) { IsTrivial = IT; }
1710 /// Whether this function is defaulted per C++0x. Only valid for
1711 /// special member functions.
1712 bool isDefaulted() const { return IsDefaulted; }
1713 void setDefaulted(bool D = true) { IsDefaulted = D; }
1715 /// Whether this function is explicitly defaulted per C++0x. Only valid
1716 /// for special member functions.
1717 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1718 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1720 /// Whether falling off this function implicitly returns null/zero.
1721 /// If a more specific implicit return value is required, front-ends
1722 /// should synthesize the appropriate return statements.
1723 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1724 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1726 /// \brief Whether this function has a prototype, either because one
1727 /// was explicitly written or because it was "inherited" by merging
1728 /// a declaration without a prototype with a declaration that has a
1730 bool hasPrototype() const {
1731 return HasWrittenPrototype || HasInheritedPrototype;
1734 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1736 /// \brief Whether this function inherited its prototype from a
1737 /// previous declaration.
1738 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1739 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1741 /// Whether this is a (C++0x) constexpr function or constexpr constructor.
1742 bool isConstexpr() const { return IsConstexpr; }
1743 void setConstexpr(bool IC) { IsConstexpr = IC; }
1745 /// \brief Whether this function has been deleted.
1747 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1748 /// acts like a normal function, except that it cannot actually be
1749 /// called or have its address taken. Deleted functions are
1750 /// typically used in C++ overload resolution to attract arguments
1751 /// whose type or lvalue/rvalue-ness would permit the use of a
1752 /// different overload that would behave incorrectly. For example,
1753 /// one might use deleted functions to ban implicit conversion from
1754 /// a floating-point number to an Integer type:
1757 /// struct Integer {
1758 /// Integer(long); // construct from a long
1759 /// Integer(double) = delete; // no construction from float or double
1760 /// Integer(long double) = delete; // no construction from long double
1763 // If a function is deleted, its first declaration must be.
1764 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1765 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1766 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1768 /// \brief Determines whether this function is "main", which is the
1769 /// entry point into an executable program.
1770 bool isMain() const;
1772 /// \brief Determines whether this operator new or delete is one
1773 /// of the reserved global placement operators:
1774 /// void *operator new(size_t, void *);
1775 /// void *operator new[](size_t, void *);
1776 /// void operator delete(void *, void *);
1777 /// void operator delete[](void *, void *);
1778 /// These functions have special behavior under [new.delete.placement]:
1779 /// These functions are reserved, a C++ program may not define
1780 /// functions that displace the versions in the Standard C++ library.
1781 /// The provisions of [basic.stc.dynamic] do not apply to these
1782 /// reserved placement forms of operator new and operator delete.
1784 /// This function must be an allocation or deallocation function.
1785 bool isReservedGlobalPlacementOperator() const;
1787 /// \brief Determines whether this function is a function with
1788 /// external, C linkage.
1789 bool isExternC() const;
1791 /// \brief Determines whether this is a global function.
1792 bool isGlobal() const;
1794 void setPreviousDeclaration(FunctionDecl * PrevDecl);
1796 virtual const FunctionDecl *getCanonicalDecl() const;
1797 virtual FunctionDecl *getCanonicalDecl();
1799 unsigned getBuiltinID() const;
1801 // Iterator access to formal parameters.
1802 unsigned param_size() const { return getNumParams(); }
1803 typedef ParmVarDecl **param_iterator;
1804 typedef ParmVarDecl * const *param_const_iterator;
1806 param_iterator param_begin() { return ParamInfo; }
1807 param_iterator param_end() { return ParamInfo+param_size(); }
1809 param_const_iterator param_begin() const { return ParamInfo; }
1810 param_const_iterator param_end() const { return ParamInfo+param_size(); }
1812 /// getNumParams - Return the number of parameters this function must have
1813 /// based on its FunctionType. This is the length of the ParamInfo array
1814 /// after it has been created.
1815 unsigned getNumParams() const;
1817 const ParmVarDecl *getParamDecl(unsigned i) const {
1818 assert(i < getNumParams() && "Illegal param #");
1819 return ParamInfo[i];
1821 ParmVarDecl *getParamDecl(unsigned i) {
1822 assert(i < getNumParams() && "Illegal param #");
1823 return ParamInfo[i];
1825 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1826 setParams(getASTContext(), NewParamInfo);
1829 const llvm::ArrayRef<NamedDecl*> &getDeclsInPrototypeScope() const {
1830 return DeclsInPrototypeScope;
1832 void setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls);
1834 /// getMinRequiredArguments - Returns the minimum number of arguments
1835 /// needed to call this function. This may be fewer than the number of
1836 /// function parameters, if some of the parameters have default
1837 /// arguments (in C++).
1838 unsigned getMinRequiredArguments() const;
1840 QualType getResultType() const {
1841 return getType()->getAs<FunctionType>()->getResultType();
1844 /// \brief Determine the type of an expression that calls this function.
1845 QualType getCallResultType() const {
1846 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1849 StorageClass getStorageClass() const { return StorageClass(SClass); }
1850 void setStorageClass(StorageClass SC);
1852 StorageClass getStorageClassAsWritten() const {
1853 return StorageClass(SClassAsWritten);
1856 /// \brief Determine whether the "inline" keyword was specified for this
1858 bool isInlineSpecified() const { return IsInlineSpecified; }
1860 /// Set whether the "inline" keyword was specified for this function.
1861 void setInlineSpecified(bool I) {
1862 IsInlineSpecified = I;
1866 /// Flag that this function is implicitly inline.
1867 void setImplicitlyInline() {
1871 /// \brief Determine whether this function should be inlined, because it is
1872 /// either marked "inline" or "constexpr" or is a member function of a class
1873 /// that was defined in the class body.
1874 bool isInlined() const;
1876 bool isInlineDefinitionExternallyVisible() const;
1878 bool doesDeclarationForceExternallyVisibleDefinition() const;
1880 /// isOverloadedOperator - Whether this function declaration
1881 /// represents an C++ overloaded operator, e.g., "operator+".
1882 bool isOverloadedOperator() const {
1883 return getOverloadedOperator() != OO_None;
1886 OverloadedOperatorKind getOverloadedOperator() const;
1888 const IdentifierInfo *getLiteralIdentifier() const;
1890 /// \brief If this function is an instantiation of a member function
1891 /// of a class template specialization, retrieves the function from
1892 /// which it was instantiated.
1894 /// This routine will return non-NULL for (non-templated) member
1895 /// functions of class templates and for instantiations of function
1896 /// templates. For example, given:
1899 /// template<typename T>
1905 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1906 /// whose parent is the class template specialization X<int>. For
1907 /// this declaration, getInstantiatedFromFunction() will return
1908 /// the FunctionDecl X<T>::A. When a complete definition of
1909 /// X<int>::A is required, it will be instantiated from the
1910 /// declaration returned by getInstantiatedFromMemberFunction().
1911 FunctionDecl *getInstantiatedFromMemberFunction() const;
1913 /// \brief What kind of templated function this is.
1914 TemplatedKind getTemplatedKind() const;
1916 /// \brief If this function is an instantiation of a member function of a
1917 /// class template specialization, retrieves the member specialization
1919 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1921 /// \brief Specify that this record is an instantiation of the
1922 /// member function FD.
1923 void setInstantiationOfMemberFunction(FunctionDecl *FD,
1924 TemplateSpecializationKind TSK) {
1925 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1928 /// \brief Retrieves the function template that is described by this
1929 /// function declaration.
1931 /// Every function template is represented as a FunctionTemplateDecl
1932 /// and a FunctionDecl (or something derived from FunctionDecl). The
1933 /// former contains template properties (such as the template
1934 /// parameter lists) while the latter contains the actual
1935 /// description of the template's
1936 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1937 /// FunctionDecl that describes the function template,
1938 /// getDescribedFunctionTemplate() retrieves the
1939 /// FunctionTemplateDecl from a FunctionDecl.
1940 FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1941 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1944 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1945 TemplateOrSpecialization = Template;
1948 /// \brief Determine whether this function is a function template
1950 bool isFunctionTemplateSpecialization() const {
1951 return getPrimaryTemplate() != 0;
1954 /// \brief Retrieve the class scope template pattern that this function
1955 /// template specialization is instantiated from.
1956 FunctionDecl *getClassScopeSpecializationPattern() const;
1958 /// \brief If this function is actually a function template specialization,
1959 /// retrieve information about this function template specialization.
1960 /// Otherwise, returns NULL.
1961 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1962 return TemplateOrSpecialization.
1963 dyn_cast<FunctionTemplateSpecializationInfo*>();
1966 /// \brief Determines whether this function is a function template
1967 /// specialization or a member of a class template specialization that can
1968 /// be implicitly instantiated.
1969 bool isImplicitlyInstantiable() const;
1971 /// \brief Determines if the given function was instantiated from a
1972 /// function template.
1973 bool isTemplateInstantiation() const;
1975 /// \brief Retrieve the function declaration from which this function could
1976 /// be instantiated, if it is an instantiation (rather than a non-template
1977 /// or a specialization, for example).
1978 FunctionDecl *getTemplateInstantiationPattern() const;
1980 /// \brief Retrieve the primary template that this function template
1981 /// specialization either specializes or was instantiated from.
1983 /// If this function declaration is not a function template specialization,
1985 FunctionTemplateDecl *getPrimaryTemplate() const;
1987 /// \brief Retrieve the template arguments used to produce this function
1988 /// template specialization from the primary template.
1990 /// If this function declaration is not a function template specialization,
1992 const TemplateArgumentList *getTemplateSpecializationArgs() const;
1994 /// \brief Retrieve the template argument list as written in the sources,
1997 /// If this function declaration is not a function template specialization
1998 /// or if it had no explicit template argument list, returns NULL.
1999 /// Note that it an explicit template argument list may be written empty,
2000 /// e.g., template<> void foo<>(char* s);
2001 const ASTTemplateArgumentListInfo*
2002 getTemplateSpecializationArgsAsWritten() const;
2004 /// \brief Specify that this function declaration is actually a function
2005 /// template specialization.
2007 /// \param Template the function template that this function template
2008 /// specialization specializes.
2010 /// \param TemplateArgs the template arguments that produced this
2011 /// function template specialization from the template.
2013 /// \param InsertPos If non-NULL, the position in the function template
2014 /// specialization set where the function template specialization data will
2017 /// \param TSK the kind of template specialization this is.
2019 /// \param TemplateArgsAsWritten location info of template arguments.
2021 /// \param PointOfInstantiation point at which the function template
2022 /// specialization was first instantiated.
2023 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2024 const TemplateArgumentList *TemplateArgs,
2026 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2027 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
2028 SourceLocation PointOfInstantiation = SourceLocation()) {
2029 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2030 InsertPos, TSK, TemplateArgsAsWritten,
2031 PointOfInstantiation);
2034 /// \brief Specifies that this function declaration is actually a
2035 /// dependent function template specialization.
2036 void setDependentTemplateSpecialization(ASTContext &Context,
2037 const UnresolvedSetImpl &Templates,
2038 const TemplateArgumentListInfo &TemplateArgs);
2040 DependentFunctionTemplateSpecializationInfo *
2041 getDependentSpecializationInfo() const {
2042 return TemplateOrSpecialization.
2043 dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
2046 /// \brief Determine what kind of template instantiation this function
2048 TemplateSpecializationKind getTemplateSpecializationKind() const;
2050 /// \brief Determine what kind of template instantiation this function
2052 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2053 SourceLocation PointOfInstantiation = SourceLocation());
2055 /// \brief Retrieve the (first) point of instantiation of a function template
2056 /// specialization or a member of a class template specialization.
2058 /// \returns the first point of instantiation, if this function was
2059 /// instantiated from a template; otherwise, returns an invalid source
2061 SourceLocation getPointOfInstantiation() const;
2063 /// \brief Determine whether this is or was instantiated from an out-of-line
2064 /// definition of a member function.
2065 virtual bool isOutOfLine() const;
2067 /// \brief Identify a memory copying or setting function.
2068 /// If the given function is a memory copy or setting function, returns
2069 /// the corresponding Builtin ID. If the function is not a memory function,
2071 unsigned getMemoryFunctionKind() const;
2073 // Implement isa/cast/dyncast/etc.
2074 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2075 static bool classof(const FunctionDecl *D) { return true; }
2076 static bool classofKind(Kind K) {
2077 return K >= firstFunction && K <= lastFunction;
2079 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2080 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2082 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2083 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2086 friend class ASTDeclReader;
2087 friend class ASTDeclWriter;
2091 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2092 /// represent a member of a struct/union/class.
2093 class FieldDecl : public DeclaratorDecl {
2094 // FIXME: This can be packed into the bitfields in Decl.
2096 mutable unsigned CachedFieldIndex : 31;
2098 /// \brief A pointer to either the in-class initializer for this field (if
2099 /// the boolean value is false), or the bit width expression for this bit
2100 /// field (if the boolean value is true).
2102 /// We can safely combine these two because in-class initializers are not
2103 /// permitted for bit-fields.
2105 /// If the boolean is false and the initializer is null, then this field has
2106 /// an in-class initializer which has not yet been parsed and attached.
2107 llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
2109 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2110 SourceLocation IdLoc, IdentifierInfo *Id,
2111 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2113 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2114 Mutable(Mutable), CachedFieldIndex(0),
2115 InitializerOrBitWidth(BW, !HasInit) {
2116 assert(!(BW && HasInit) && "got initializer for bitfield");
2120 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2121 SourceLocation StartLoc, SourceLocation IdLoc,
2122 IdentifierInfo *Id, QualType T,
2123 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2126 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2128 /// getFieldIndex - Returns the index of this field within its record,
2129 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2130 unsigned getFieldIndex() const;
2132 /// isMutable - Determines whether this field is mutable (C++ only).
2133 bool isMutable() const { return Mutable; }
2135 /// \brief Set whether this field is mutable (C++ only).
2136 void setMutable(bool M) { Mutable = M; }
2138 /// isBitfield - Determines whether this field is a bitfield.
2139 bool isBitField() const {
2140 return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
2143 /// @brief Determines whether this is an unnamed bitfield.
2144 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2146 /// isAnonymousStructOrUnion - Determines whether this field is a
2147 /// representative for an anonymous struct or union. Such fields are
2148 /// unnamed and are implicitly generated by the implementation to
2149 /// store the data for the anonymous union or struct.
2150 bool isAnonymousStructOrUnion() const;
2152 Expr *getBitWidth() const {
2153 return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2155 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2156 void setBitWidth(Expr *BW) {
2157 assert(!InitializerOrBitWidth.getPointer() &&
2158 "bit width or initializer already set");
2159 InitializerOrBitWidth.setPointer(BW);
2160 InitializerOrBitWidth.setInt(1);
2162 /// removeBitWidth - Remove the bitfield width from this member.
2163 void removeBitWidth() {
2164 assert(isBitField() && "no bit width to remove");
2165 InitializerOrBitWidth.setPointer(0);
2168 /// hasInClassInitializer - Determine whether this member has a C++0x in-class
2170 bool hasInClassInitializer() const {
2171 return !InitializerOrBitWidth.getInt();
2173 /// getInClassInitializer - Get the C++0x in-class initializer for this
2174 /// member, or null if one has not been set. If a valid declaration has an
2175 /// in-class initializer, but this returns null, then we have not parsed and
2176 /// attached it yet.
2177 Expr *getInClassInitializer() const {
2178 return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2180 /// setInClassInitializer - Set the C++0x in-class initializer for this
2182 void setInClassInitializer(Expr *Init);
2183 /// removeInClassInitializer - Remove the C++0x in-class initializer from this
2185 void removeInClassInitializer() {
2186 assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
2187 InitializerOrBitWidth.setPointer(0);
2188 InitializerOrBitWidth.setInt(1);
2191 /// getParent - Returns the parent of this field declaration, which
2192 /// is the struct in which this method is defined.
2193 const RecordDecl *getParent() const {
2194 return cast<RecordDecl>(getDeclContext());
2197 RecordDecl *getParent() {
2198 return cast<RecordDecl>(getDeclContext());
2201 SourceRange getSourceRange() const LLVM_READONLY;
2203 // Implement isa/cast/dyncast/etc.
2204 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2205 static bool classof(const FieldDecl *D) { return true; }
2206 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2209 /// EnumConstantDecl - An instance of this object exists for each enum constant
2210 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2211 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2212 /// TagType for the X EnumDecl.
2213 class EnumConstantDecl : public ValueDecl {
2214 Stmt *Init; // an integer constant expression
2215 llvm::APSInt Val; // The value.
2217 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2218 IdentifierInfo *Id, QualType T, Expr *E,
2219 const llvm::APSInt &V)
2220 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2224 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2225 SourceLocation L, IdentifierInfo *Id,
2226 QualType T, Expr *E,
2227 const llvm::APSInt &V);
2228 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2230 const Expr *getInitExpr() const { return (const Expr*) Init; }
2231 Expr *getInitExpr() { return (Expr*) Init; }
2232 const llvm::APSInt &getInitVal() const { return Val; }
2234 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2235 void setInitVal(const llvm::APSInt &V) { Val = V; }
2237 SourceRange getSourceRange() const LLVM_READONLY;
2239 // Implement isa/cast/dyncast/etc.
2240 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2241 static bool classof(const EnumConstantDecl *D) { return true; }
2242 static bool classofKind(Kind K) { return K == EnumConstant; }
2244 friend class StmtIteratorBase;
2247 /// IndirectFieldDecl - An instance of this class is created to represent a
2248 /// field injected from an anonymous union/struct into the parent scope.
2249 /// IndirectFieldDecl are always implicit.
2250 class IndirectFieldDecl : public ValueDecl {
2251 virtual void anchor();
2252 NamedDecl **Chaining;
2253 unsigned ChainingSize;
2255 IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2256 DeclarationName N, QualType T,
2257 NamedDecl **CH, unsigned CHS)
2258 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2261 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2262 SourceLocation L, IdentifierInfo *Id,
2263 QualType T, NamedDecl **CH, unsigned CHS);
2265 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2267 typedef NamedDecl * const *chain_iterator;
2268 chain_iterator chain_begin() const { return Chaining; }
2269 chain_iterator chain_end() const { return Chaining+ChainingSize; }
2271 unsigned getChainingSize() const { return ChainingSize; }
2273 FieldDecl *getAnonField() const {
2274 assert(ChainingSize >= 2);
2275 return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2278 VarDecl *getVarDecl() const {
2279 assert(ChainingSize >= 2);
2280 return dyn_cast<VarDecl>(*chain_begin());
2283 // Implement isa/cast/dyncast/etc.
2284 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2285 static bool classof(const IndirectFieldDecl *D) { return true; }
2286 static bool classofKind(Kind K) { return K == IndirectField; }
2287 friend class ASTDeclReader;
2290 /// TypeDecl - Represents a declaration of a type.
2292 class TypeDecl : public NamedDecl {
2293 virtual void anchor();
2294 /// TypeForDecl - This indicates the Type object that represents
2295 /// this TypeDecl. It is a cache maintained by
2296 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2297 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2298 mutable const Type *TypeForDecl;
2299 /// LocStart - The start of the source range for this declaration.
2300 SourceLocation LocStart;
2301 friend class ASTContext;
2302 friend class DeclContext;
2303 friend class TagDecl;
2304 friend class TemplateTypeParmDecl;
2305 friend class TagType;
2306 friend class ASTReader;
2309 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2310 SourceLocation StartL = SourceLocation())
2311 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2314 // Low-level accessor
2315 const Type *getTypeForDecl() const { return TypeForDecl; }
2316 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2318 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2319 void setLocStart(SourceLocation L) { LocStart = L; }
2320 virtual SourceRange getSourceRange() const LLVM_READONLY {
2321 if (LocStart.isValid())
2322 return SourceRange(LocStart, getLocation());
2324 return SourceRange(getLocation());
2327 // Implement isa/cast/dyncast/etc.
2328 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2329 static bool classof(const TypeDecl *D) { return true; }
2330 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2334 /// Base class for declarations which introduce a typedef-name.
2335 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2336 virtual void anchor();
2337 /// UnderlyingType - This is the type the typedef is set to.
2338 TypeSourceInfo *TInfo;
2341 TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2342 SourceLocation IdLoc, IdentifierInfo *Id,
2343 TypeSourceInfo *TInfo)
2344 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2346 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2347 virtual TypedefNameDecl *getNextRedeclaration() {
2348 return RedeclLink.getNext();
2350 virtual TypedefNameDecl *getPreviousDeclImpl() {
2351 return getPreviousDecl();
2353 virtual TypedefNameDecl *getMostRecentDeclImpl() {
2354 return getMostRecentDecl();
2358 typedef redeclarable_base::redecl_iterator redecl_iterator;
2359 using redeclarable_base::redecls_begin;
2360 using redeclarable_base::redecls_end;
2361 using redeclarable_base::getPreviousDecl;
2362 using redeclarable_base::getMostRecentDecl;
2364 TypeSourceInfo *getTypeSourceInfo() const {
2368 /// Retrieves the canonical declaration of this typedef-name.
2369 TypedefNameDecl *getCanonicalDecl() {
2370 return getFirstDeclaration();
2372 const TypedefNameDecl *getCanonicalDecl() const {
2373 return getFirstDeclaration();
2376 QualType getUnderlyingType() const {
2377 return TInfo->getType();
2379 void setTypeSourceInfo(TypeSourceInfo *newType) {
2383 // Implement isa/cast/dyncast/etc.
2384 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2385 static bool classof(const TypedefNameDecl *D) { return true; }
2386 static bool classofKind(Kind K) {
2387 return K >= firstTypedefName && K <= lastTypedefName;
2391 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2393 class TypedefDecl : public TypedefNameDecl {
2394 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2395 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2396 : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2399 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2400 SourceLocation StartLoc, SourceLocation IdLoc,
2401 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2402 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2404 SourceRange getSourceRange() const LLVM_READONLY;
2406 // Implement isa/cast/dyncast/etc.
2407 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2408 static bool classof(const TypedefDecl *D) { return true; }
2409 static bool classofKind(Kind K) { return K == Typedef; }
2412 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2413 /// alias-declaration.
2414 class TypeAliasDecl : public TypedefNameDecl {
2415 TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2416 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2417 : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2420 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2421 SourceLocation StartLoc, SourceLocation IdLoc,
2422 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2423 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2425 SourceRange getSourceRange() const LLVM_READONLY;
2427 // Implement isa/cast/dyncast/etc.
2428 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2429 static bool classof(const TypeAliasDecl *D) { return true; }
2430 static bool classofKind(Kind K) { return K == TypeAlias; }
2433 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2435 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2437 // This is really ugly.
2438 typedef TagTypeKind TagKind;
2441 // FIXME: This can be packed into the bitfields in Decl.
2442 /// TagDeclKind - The TagKind enum.
2443 unsigned TagDeclKind : 2;
2445 /// IsCompleteDefinition - True if this is a definition ("struct foo
2446 /// {};"), false if it is a declaration ("struct foo;"). It is not
2447 /// a definition until the definition has been fully processed.
2448 bool IsCompleteDefinition : 1;
2451 /// IsBeingDefined - True if this is currently being defined.
2452 bool IsBeingDefined : 1;
2455 /// IsEmbeddedInDeclarator - True if this tag declaration is
2456 /// "embedded" (i.e., defined or declared for the very first time)
2457 /// in the syntax of a declarator.
2458 bool IsEmbeddedInDeclarator : 1;
2460 /// \brief True if this tag is free standing, e.g. "struct foo;".
2461 bool IsFreeStanding : 1;
2464 // These are used by (and only defined for) EnumDecl.
2465 unsigned NumPositiveBits : 8;
2466 unsigned NumNegativeBits : 8;
2468 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2469 /// possible in C++11 mode.
2471 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2472 /// then this is true if the scoped enum was declared using the class
2473 /// tag, false if it was declared with the struct tag. No meaning is
2474 /// associated if this tag declaration is not a scoped enum.
2475 bool IsScopedUsingClassTag : 1;
2477 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2478 /// possible in C++11 or Microsoft extensions mode.
2482 SourceLocation RBraceLoc;
2484 // A struct representing syntactic qualifier info,
2485 // to be used for the (uncommon) case of out-of-line declarations.
2486 typedef QualifierInfo ExtInfo;
2488 /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2489 /// is qualified, it points to the qualifier info (nns and range);
2490 /// otherwise, if the tag declaration is anonymous and it is part of
2491 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2492 /// otherwise, it is a null (TypedefNameDecl) pointer.
2493 llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2495 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2496 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2497 const ExtInfo *getExtInfo() const {
2498 return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2502 TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2503 SourceLocation L, IdentifierInfo *Id,
2504 TagDecl *PrevDecl, SourceLocation StartL)
2505 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2506 TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2507 assert((DK != Enum || TK == TTK_Enum) &&
2508 "EnumDecl not matched with TTK_Enum");
2510 IsCompleteDefinition = false;
2511 IsBeingDefined = false;
2512 IsEmbeddedInDeclarator = false;
2513 IsFreeStanding = false;
2514 setPreviousDeclaration(PrevDecl);
2517 typedef Redeclarable<TagDecl> redeclarable_base;
2518 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2519 virtual TagDecl *getPreviousDeclImpl() {
2520 return getPreviousDecl();
2522 virtual TagDecl *getMostRecentDeclImpl() {
2523 return getMostRecentDecl();
2526 /// @brief Completes the definition of this tag declaration.
2528 /// This is a helper function for derived classes.
2529 void completeDefinition();
2532 typedef redeclarable_base::redecl_iterator redecl_iterator;
2533 using redeclarable_base::redecls_begin;
2534 using redeclarable_base::redecls_end;
2535 using redeclarable_base::getPreviousDecl;
2536 using redeclarable_base::getMostRecentDecl;
2538 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2539 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2541 /// getInnerLocStart - Return SourceLocation representing start of source
2542 /// range ignoring outer template declarations.
2543 SourceLocation getInnerLocStart() const { return getLocStart(); }
2545 /// getOuterLocStart - Return SourceLocation representing start of source
2546 /// range taking into account any outer template declarations.
2547 SourceLocation getOuterLocStart() const;
2548 virtual SourceRange getSourceRange() const LLVM_READONLY;
2550 virtual TagDecl* getCanonicalDecl();
2551 const TagDecl* getCanonicalDecl() const {
2552 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2555 /// isThisDeclarationADefinition() - Return true if this declaration
2556 /// is a completion definintion of the type. Provided for consistency.
2557 bool isThisDeclarationADefinition() const {
2558 return isCompleteDefinition();
2561 /// isCompleteDefinition - Return true if this decl has its body
2562 /// fully specified.
2563 bool isCompleteDefinition() const {
2564 return IsCompleteDefinition;
2567 /// isBeingDefined - Return true if this decl is currently being defined.
2568 bool isBeingDefined() const {
2569 return IsBeingDefined;
2572 bool isEmbeddedInDeclarator() const {
2573 return IsEmbeddedInDeclarator;
2575 void setEmbeddedInDeclarator(bool isInDeclarator) {
2576 IsEmbeddedInDeclarator = isInDeclarator;
2579 bool isFreeStanding() const { return IsFreeStanding; }
2580 void setFreeStanding(bool isFreeStanding = true) {
2581 IsFreeStanding = isFreeStanding;
2584 /// \brief Whether this declaration declares a type that is
2585 /// dependent, i.e., a type that somehow depends on template
2587 bool isDependentType() const { return isDependentContext(); }
2589 /// @brief Starts the definition of this tag declaration.
2591 /// This method should be invoked at the beginning of the definition
2592 /// of this tag declaration. It will set the tag type into a state
2593 /// where it is in the process of being defined.
2594 void startDefinition();
2596 /// getDefinition - Returns the TagDecl that actually defines this
2597 /// struct/union/class/enum. When determining whether or not a
2598 /// struct/union/class/enum has a definition, one should use this
2599 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2600 /// whether or not a specific TagDecl is defining declaration, not
2601 /// whether or not the struct/union/class/enum type is defined.
2602 /// This method returns NULL if there is no TagDecl that defines
2603 /// the struct/union/class/enum.
2604 TagDecl *getDefinition() const;
2606 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2608 const char *getKindName() const {
2609 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2612 TagKind getTagKind() const {
2613 return TagKind(TagDeclKind);
2616 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2618 bool isStruct() const { return getTagKind() == TTK_Struct; }
2619 bool isClass() const { return getTagKind() == TTK_Class; }
2620 bool isUnion() const { return getTagKind() == TTK_Union; }
2621 bool isEnum() const { return getTagKind() == TTK_Enum; }
2623 TypedefNameDecl *getTypedefNameForAnonDecl() const {
2624 return hasExtInfo() ? 0 :
2625 TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2628 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2630 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2631 /// declaration, if it was present in the source.
2632 NestedNameSpecifier *getQualifier() const {
2633 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2637 /// \brief Retrieve the nested-name-specifier (with source-location
2638 /// information) that qualifies the name of this declaration, if it was
2639 /// present in the source.
2640 NestedNameSpecifierLoc getQualifierLoc() const {
2641 return hasExtInfo() ? getExtInfo()->QualifierLoc
2642 : NestedNameSpecifierLoc();
2645 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2647 unsigned getNumTemplateParameterLists() const {
2648 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2650 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2651 assert(i < getNumTemplateParameterLists());
2652 return getExtInfo()->TemplParamLists[i];
2654 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2655 TemplateParameterList **TPLists);
2657 // Implement isa/cast/dyncast/etc.
2658 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2659 static bool classof(const TagDecl *D) { return true; }
2660 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2662 static DeclContext *castToDeclContext(const TagDecl *D) {
2663 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2665 static TagDecl *castFromDeclContext(const DeclContext *DC) {
2666 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2669 friend class ASTDeclReader;
2670 friend class ASTDeclWriter;
2673 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
2674 /// with a fixed underlying type, and in C we allow them to be forward-declared
2675 /// with no underlying type as an extension.
2676 class EnumDecl : public TagDecl {
2677 virtual void anchor();
2678 /// IntegerType - This represent the integer type that the enum corresponds
2679 /// to for code generation purposes. Note that the enumerator constants may
2680 /// have a different type than this does.
2682 /// If the underlying integer type was explicitly stated in the source
2683 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2684 /// was automatically deduced somehow, and this is a Type*.
2686 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2687 /// some cases it won't.
2689 /// The underlying type of an enumeration never has any qualifiers, so
2690 /// we can get away with just storing a raw Type*, and thus save an
2691 /// extra pointer when TypeSourceInfo is needed.
2693 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2695 /// PromotionType - The integer type that values of this type should
2696 /// promote to. In C, enumerators are generally of an integer type
2697 /// directly, but gcc-style large enumerators (and all enumerators
2698 /// in C++) are of the enum type instead.
2699 QualType PromotionType;
2701 /// \brief If this enumeration is an instantiation of a member enumeration
2702 /// of a class template specialization, this is the member specialization
2704 MemberSpecializationInfo *SpecializationInfo;
2706 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2707 IdentifierInfo *Id, EnumDecl *PrevDecl,
2708 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2709 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2710 SpecializationInfo(0) {
2711 assert(Scoped || !ScopedUsingClassTag);
2712 IntegerType = (const Type*)0;
2713 NumNegativeBits = 0;
2714 NumPositiveBits = 0;
2716 IsScopedUsingClassTag = ScopedUsingClassTag;
2720 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2721 TemplateSpecializationKind TSK);
2723 EnumDecl *getCanonicalDecl() {
2724 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2726 const EnumDecl *getCanonicalDecl() const {
2727 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2730 const EnumDecl *getPreviousDecl() const {
2731 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2733 EnumDecl *getPreviousDecl() {
2734 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2737 const EnumDecl *getMostRecentDecl() const {
2738 return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2740 EnumDecl *getMostRecentDecl() {
2741 return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2744 EnumDecl *getDefinition() const {
2745 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2748 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2749 SourceLocation StartLoc, SourceLocation IdLoc,
2750 IdentifierInfo *Id, EnumDecl *PrevDecl,
2751 bool IsScoped, bool IsScopedUsingClassTag,
2753 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2755 /// completeDefinition - When created, the EnumDecl corresponds to a
2756 /// forward-declared enum. This method is used to mark the
2757 /// declaration as being defined; it's enumerators have already been
2758 /// added (via DeclContext::addDecl). NewType is the new underlying
2759 /// type of the enumeration type.
2760 void completeDefinition(QualType NewType,
2761 QualType PromotionType,
2762 unsigned NumPositiveBits,
2763 unsigned NumNegativeBits);
2765 // enumerator_iterator - Iterates through the enumerators of this
2767 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2769 enumerator_iterator enumerator_begin() const {
2770 const EnumDecl *E = getDefinition();
2773 return enumerator_iterator(E->decls_begin());
2776 enumerator_iterator enumerator_end() const {
2777 const EnumDecl *E = getDefinition();
2780 return enumerator_iterator(E->decls_end());
2783 /// getPromotionType - Return the integer type that enumerators
2784 /// should promote to.
2785 QualType getPromotionType() const { return PromotionType; }
2787 /// \brief Set the promotion type.
2788 void setPromotionType(QualType T) { PromotionType = T; }
2790 /// getIntegerType - Return the integer type this enum decl corresponds to.
2791 /// This returns a null qualtype for an enum forward definition.
2792 QualType getIntegerType() const {
2795 if (const Type* T = IntegerType.dyn_cast<const Type*>())
2796 return QualType(T, 0);
2797 return IntegerType.get<TypeSourceInfo*>()->getType();
2800 /// \brief Set the underlying integer type.
2801 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2803 /// \brief Set the underlying integer type source info.
2804 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2806 /// \brief Return the type source info for the underlying integer type,
2807 /// if no type source info exists, return 0.
2808 TypeSourceInfo* getIntegerTypeSourceInfo() const {
2809 return IntegerType.dyn_cast<TypeSourceInfo*>();
2812 /// \brief Returns the width in bits required to store all the
2813 /// non-negative enumerators of this enum.
2814 unsigned getNumPositiveBits() const {
2815 return NumPositiveBits;
2817 void setNumPositiveBits(unsigned Num) {
2818 NumPositiveBits = Num;
2819 assert(NumPositiveBits == Num && "can't store this bitcount");
2822 /// \brief Returns the width in bits required to store all the
2823 /// negative enumerators of this enum. These widths include
2824 /// the rightmost leading 1; that is:
2826 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
2827 /// ------------------------ ------- -----------------
2831 unsigned getNumNegativeBits() const {
2832 return NumNegativeBits;
2834 void setNumNegativeBits(unsigned Num) {
2835 NumNegativeBits = Num;
2838 /// \brief Returns true if this is a C++0x scoped enumeration.
2839 bool isScoped() const {
2843 /// \brief Returns true if this is a C++0x scoped enumeration.
2844 bool isScopedUsingClassTag() const {
2845 return IsScopedUsingClassTag;
2848 /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2850 bool isFixed() const {
2854 /// \brief Returns true if this can be considered a complete type.
2855 bool isComplete() const {
2856 return isCompleteDefinition() || isFixed();
2859 /// \brief Returns the enumeration (declared within the template)
2860 /// from which this enumeration type was instantiated, or NULL if
2861 /// this enumeration was not instantiated from any template.
2862 EnumDecl *getInstantiatedFromMemberEnum() const;
2864 /// \brief If this enumeration is a member of a specialization of a
2865 /// templated class, determine what kind of template specialization
2866 /// or instantiation this is.
2867 TemplateSpecializationKind getTemplateSpecializationKind() const;
2869 /// \brief For an enumeration member that was instantiated from a member
2870 /// enumeration of a templated class, set the template specialiation kind.
2871 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2872 SourceLocation PointOfInstantiation = SourceLocation());
2874 /// \brief If this enumeration is an instantiation of a member enumeration of
2875 /// a class template specialization, retrieves the member specialization
2877 MemberSpecializationInfo *getMemberSpecializationInfo() const {
2878 return SpecializationInfo;
2881 /// \brief Specify that this enumeration is an instantiation of the
2882 /// member enumeration ED.
2883 void setInstantiationOfMemberEnum(EnumDecl *ED,
2884 TemplateSpecializationKind TSK) {
2885 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classof(const EnumDecl *D) { return true; }
2890 static bool classofKind(Kind K) { return K == Enum; }
2892 friend class ASTDeclReader;
2896 /// RecordDecl - Represents a struct/union/class. For example:
2897 /// struct X; // Forward declaration, no "body".
2898 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
2899 /// This decl will be marked invalid if *any* members are invalid.
2901 class RecordDecl : public TagDecl {
2902 // FIXME: This can be packed into the bitfields in Decl.
2903 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2904 /// array member (e.g. int X[]) or if this union contains a struct that does.
2905 /// If so, this cannot be contained in arrays or other structs as a member.
2906 bool HasFlexibleArrayMember : 1;
2908 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2910 bool AnonymousStructOrUnion : 1;
2912 /// HasObjectMember - This is true if this struct has at least one member
2913 /// containing an Objective-C object pointer type.
2914 bool HasObjectMember : 1;
2916 /// \brief Whether the field declarations of this record have been loaded
2917 /// from external storage. To avoid unnecessary deserialization of
2918 /// methods/nested types we allow deserialization of just the fields
2920 mutable bool LoadedFieldsFromExternalStorage : 1;
2921 friend class DeclContext;
2924 RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2925 SourceLocation StartLoc, SourceLocation IdLoc,
2926 IdentifierInfo *Id, RecordDecl *PrevDecl);
2929 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2930 SourceLocation StartLoc, SourceLocation IdLoc,
2931 IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2932 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
2934 const RecordDecl *getPreviousDecl() const {
2935 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2937 RecordDecl *getPreviousDecl() {
2938 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2941 const RecordDecl *getMostRecentDecl() const {
2942 return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2944 RecordDecl *getMostRecentDecl() {
2945 return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2948 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2949 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2951 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2952 /// or union. To be an anonymous struct or union, it must have been
2953 /// declared without a name and there must be no objects of this
2954 /// type declared, e.g.,
2956 /// union { int i; float f; };
2958 /// is an anonymous union but neither of the following are:
2960 /// union X { int i; float f; };
2961 /// union { int i; float f; } obj;
2963 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2964 void setAnonymousStructOrUnion(bool Anon) {
2965 AnonymousStructOrUnion = Anon;
2968 bool hasObjectMember() const { return HasObjectMember; }
2969 void setHasObjectMember (bool val) { HasObjectMember = val; }
2971 /// \brief Determines whether this declaration represents the
2972 /// injected class name.
2974 /// The injected class name in C++ is the name of the class that
2975 /// appears inside the class itself. For example:
2979 /// // C is implicitly declared here as a synonym for the class name.
2982 /// C::C c; // same as "C c;"
2984 bool isInjectedClassName() const;
2986 /// getDefinition - Returns the RecordDecl that actually defines
2987 /// this struct/union/class. When determining whether or not a
2988 /// struct/union/class is completely defined, one should use this
2989 /// method as opposed to 'isCompleteDefinition'.
2990 /// 'isCompleteDefinition' indicates whether or not a specific
2991 /// RecordDecl is a completed definition, not whether or not the
2992 /// record type is defined. This method returns NULL if there is
2993 /// no RecordDecl that defines the struct/union/tag.
2994 RecordDecl *getDefinition() const {
2995 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2998 // Iterator access to field members. The field iterator only visits
2999 // the non-static data members of this class, ignoring any static
3000 // data members, functions, constructors, destructors, etc.
3001 typedef specific_decl_iterator<FieldDecl> field_iterator;
3003 field_iterator field_begin() const;
3005 field_iterator field_end() const {
3006 return field_iterator(decl_iterator());
3009 // field_empty - Whether there are any fields (non-static data
3010 // members) in this record.
3011 bool field_empty() const {
3012 return field_begin() == field_end();
3015 /// completeDefinition - Notes that the definition of this type is
3017 virtual void completeDefinition();
3019 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3020 static bool classof(const RecordDecl *D) { return true; }
3021 static bool classofKind(Kind K) {
3022 return K >= firstRecord && K <= lastRecord;
3026 /// \brief Deserialize just the fields.
3027 void LoadFieldsFromExternalStorage() const;
3030 class FileScopeAsmDecl : public Decl {
3031 virtual void anchor();
3032 StringLiteral *AsmString;
3033 SourceLocation RParenLoc;
3034 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3035 SourceLocation StartL, SourceLocation EndL)
3036 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3038 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3039 StringLiteral *Str, SourceLocation AsmLoc,
3040 SourceLocation RParenLoc);
3042 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3044 SourceLocation getAsmLoc() const { return getLocation(); }
3045 SourceLocation getRParenLoc() const { return RParenLoc; }
3046 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3047 SourceRange getSourceRange() const LLVM_READONLY {
3048 return SourceRange(getAsmLoc(), getRParenLoc());
3051 const StringLiteral *getAsmString() const { return AsmString; }
3052 StringLiteral *getAsmString() { return AsmString; }
3053 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3055 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3056 static bool classof(const FileScopeAsmDecl *D) { return true; }
3057 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3060 /// BlockDecl - This represents a block literal declaration, which is like an
3061 /// unnamed FunctionDecl. For example:
3062 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3064 class BlockDecl : public Decl, public DeclContext {
3066 /// A class which contains all the information about a particular
3074 /// The variable being captured.
3075 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3077 /// The copy expression, expressed in terms of a DeclRef (or
3078 /// BlockDeclRef) to the captured variable. Only required if the
3079 /// variable has a C++ class type.
3083 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3084 : VariableAndFlags(variable,
3085 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3088 /// The variable being captured.
3089 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3091 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3093 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3095 /// Whether this is a nested capture, i.e. the variable captured
3096 /// is not from outside the immediately enclosing function/block.
3097 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3099 bool hasCopyExpr() const { return CopyExpr != 0; }
3100 Expr *getCopyExpr() const { return CopyExpr; }
3101 void setCopyExpr(Expr *e) { CopyExpr = e; }
3105 // FIXME: This can be packed into the bitfields in Decl.
3106 bool IsVariadic : 1;
3107 bool CapturesCXXThis : 1;
3108 bool BlockMissingReturnType : 1;
3109 bool IsConversionFromLambda : 1;
3110 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3111 /// parameters of this function. This is null if a prototype or if there are
3113 ParmVarDecl **ParamInfo;
3117 TypeSourceInfo *SignatureAsWritten;
3120 unsigned NumCaptures;
3123 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3124 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3125 IsVariadic(false), CapturesCXXThis(false),
3126 BlockMissingReturnType(true), IsConversionFromLambda(false),
3127 ParamInfo(0), NumParams(0), Body(0),
3128 SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
3131 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3132 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3134 SourceLocation getCaretLocation() const { return getLocation(); }
3136 bool isVariadic() const { return IsVariadic; }
3137 void setIsVariadic(bool value) { IsVariadic = value; }
3139 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3140 Stmt *getBody() const { return (Stmt*) Body; }
3141 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3143 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3144 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3146 // Iterator access to formal parameters.
3147 unsigned param_size() const { return getNumParams(); }
3148 typedef ParmVarDecl **param_iterator;
3149 typedef ParmVarDecl * const *param_const_iterator;
3151 bool param_empty() const { return NumParams == 0; }
3152 param_iterator param_begin() { return ParamInfo; }
3153 param_iterator param_end() { return ParamInfo+param_size(); }
3155 param_const_iterator param_begin() const { return ParamInfo; }
3156 param_const_iterator param_end() const { return ParamInfo+param_size(); }
3158 unsigned getNumParams() const { return NumParams; }
3159 const ParmVarDecl *getParamDecl(unsigned i) const {
3160 assert(i < getNumParams() && "Illegal param #");
3161 return ParamInfo[i];
3163 ParmVarDecl *getParamDecl(unsigned i) {
3164 assert(i < getNumParams() && "Illegal param #");
3165 return ParamInfo[i];
3167 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
3169 /// hasCaptures - True if this block (or its nested blocks) captures
3170 /// anything of local storage from its enclosing scopes.
3171 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3173 /// getNumCaptures - Returns the number of captured variables.
3174 /// Does not include an entry for 'this'.
3175 unsigned getNumCaptures() const { return NumCaptures; }
3177 typedef const Capture *capture_iterator;
3178 typedef const Capture *capture_const_iterator;
3179 capture_iterator capture_begin() { return Captures; }
3180 capture_iterator capture_end() { return Captures + NumCaptures; }
3181 capture_const_iterator capture_begin() const { return Captures; }
3182 capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3184 bool capturesCXXThis() const { return CapturesCXXThis; }
3185 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3186 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3188 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3189 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3191 bool capturesVariable(const VarDecl *var) const;
3193 void setCaptures(ASTContext &Context,
3194 const Capture *begin,
3196 bool capturesCXXThis);
3198 virtual SourceRange getSourceRange() const LLVM_READONLY;
3200 // Implement isa/cast/dyncast/etc.
3201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3202 static bool classof(const BlockDecl *D) { return true; }
3203 static bool classofKind(Kind K) { return K == Block; }
3204 static DeclContext *castToDeclContext(const BlockDecl *D) {
3205 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3207 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3208 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3212 /// \brief Describes a module import declaration, which makes the contents
3213 /// of the named module visible in the current translation unit.
3215 /// An import declaration imports the named module (or submodule). For example:
3217 /// @__experimental_modules_import std.vector;
3220 /// Import declarations can also be implicitly generated from #include/#import
3222 class ImportDecl : public Decl {
3223 /// \brief The imported module, along with a bit that indicates whether
3224 /// we have source-location information for each identifier in the module
3227 /// When the bit is false, we only have a single source location for the
3228 /// end of the import declaration.
3229 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3231 /// \brief The next import in the list of imports local to the translation
3232 /// unit being parsed (not loaded from an AST file).
3233 ImportDecl *NextLocalImport;
3235 friend class ASTReader;
3236 friend class ASTDeclReader;
3237 friend class ASTContext;
3239 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3240 ArrayRef<SourceLocation> IdentifierLocs);
3242 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3243 SourceLocation EndLoc);
3245 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3248 /// \brief Create a new module import declaration.
3249 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3250 SourceLocation StartLoc, Module *Imported,
3251 ArrayRef<SourceLocation> IdentifierLocs);
3253 /// \brief Create a new module import declaration for an implicitly-generated
3255 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3256 SourceLocation StartLoc, Module *Imported,
3257 SourceLocation EndLoc);
3259 /// \brief Create a new, deserialized module import declaration.
3260 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3261 unsigned NumLocations);
3263 /// \brief Retrieve the module that was imported by the import declaration.
3264 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3266 /// \brief Retrieves the locations of each of the identifiers that make up
3267 /// the complete module name in the import declaration.
3269 /// This will return an empty array if the locations of the individual
3270 /// identifiers aren't available.
3271 ArrayRef<SourceLocation> getIdentifierLocs() const;
3273 virtual SourceRange getSourceRange() const LLVM_READONLY;
3275 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3276 static bool classof(const ImportDecl *D) { return true; }
3277 static bool classofKind(Kind K) { return K == Import; }
3281 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3282 /// into a diagnostic with <<.
3283 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3284 const NamedDecl* ND) {
3285 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3286 DiagnosticsEngine::ak_nameddecl);
3289 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3290 const NamedDecl* ND) {
3291 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3292 DiagnosticsEngine::ak_nameddecl);
3296 template<typename decl_type>
3297 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3298 // Note: This routine is implemented here because we need both NamedDecl
3299 // and Redeclarable to be defined.
3304 // Point to previous. Make sure that this is actually the most recent
3305 // redeclaration, or we can build invalid chains. If the most recent
3306 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3307 RedeclLink = PreviousDeclLink(
3308 llvm::cast<decl_type>(PrevDecl->getMostRecentDecl()));
3309 First = PrevDecl->getFirstDeclaration();
3310 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3313 First = static_cast<decl_type*>(this);
3316 // First one will point to this one as latest.
3317 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3318 if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
3319 ND->ClearLinkageCache();
3322 // Inline function definitions.
3324 /// \brief Check if the given decl is complete.
3326 /// We use this function to break a cycle between the inline definitions in
3327 /// Type.h and Decl.h.
3328 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3329 return ED->isComplete();
3332 /// \brief Check if the given decl is scoped.
3334 /// We use this function to break a cycle between the inline definitions in
3335 /// Type.h and Decl.h.
3336 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3337 return ED->isScoped();
3340 } // end namespace clang