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/DeclarationName.h"
20 #include "clang/AST/ExternalASTSource.h"
21 #include "clang/AST/Redeclarable.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/Linkage.h"
24 #include "clang/Basic/OperatorKinds.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/raw_ostream.h"
31 struct ASTTemplateArgumentListInfo;
34 class DependentFunctionTemplateSpecializationInfo;
36 class FunctionTemplateDecl;
37 class FunctionTemplateSpecializationInfo;
39 class MemberSpecializationInfo;
41 class NestedNameSpecifier;
44 class TemplateArgumentList;
45 class TemplateParameterList;
46 class TypeAliasTemplateDecl;
48 class UnresolvedSetImpl;
49 class VarTemplateDecl;
51 /// \brief A container of type source information.
53 /// A client can read the relevant info using TypeLoc wrappers, e.g:
55 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
56 /// TL.getStartLoc().print(OS, SrcMgr);
59 class TypeSourceInfo {
61 // Contains a memory block after the class, used for type source information,
62 // allocated by ASTContext.
63 friend class ASTContext;
64 TypeSourceInfo(QualType ty) : Ty(ty) { }
66 /// \brief Return the type wrapped by this type source info.
67 QualType getType() const { return Ty; }
69 /// \brief Return the TypeLoc wrapper for the type source info.
70 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
72 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
73 void overrideType(QualType T) { Ty = T; }
76 /// TranslationUnitDecl - The top declaration context.
77 class TranslationUnitDecl : public Decl, public DeclContext {
78 virtual void anchor();
81 /// The (most recently entered) anonymous namespace for this
82 /// translation unit, if one has been created.
83 NamespaceDecl *AnonymousNamespace;
85 explicit TranslationUnitDecl(ASTContext &ctx)
86 : Decl(TranslationUnit, nullptr, SourceLocation()),
87 DeclContext(TranslationUnit),
88 Ctx(ctx), AnonymousNamespace(nullptr) {}
90 ASTContext &getASTContext() const { return Ctx; }
92 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
93 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
95 static TranslationUnitDecl *Create(ASTContext &C);
96 // Implement isa/cast/dyncast/etc.
97 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
98 static bool classofKind(Kind K) { return K == TranslationUnit; }
99 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
100 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
102 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
103 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
107 /// NamedDecl - This represents a decl with a name. Many decls have names such
108 /// as ObjCMethodDecl, but not \@class, etc.
109 class NamedDecl : public Decl {
110 virtual void anchor();
111 /// Name - The name of this declaration, which is typically a normal
112 /// identifier but may also be a special kind of name (C++
113 /// constructor, Objective-C selector, etc.)
114 DeclarationName Name;
117 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
120 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
121 : Decl(DK, DC, L), Name(N) { }
124 /// getIdentifier - Get the identifier that names this declaration,
125 /// if there is one. This will return NULL if this declaration has
126 /// no name (e.g., for an unnamed class) or if the name is a special
127 /// name (C++ constructor, Objective-C selector, etc.).
128 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
130 /// getName - Get the name of identifier for this declaration as a StringRef.
131 /// This requires that the declaration have a name and that it be a simple
133 StringRef getName() const {
134 assert(Name.isIdentifier() && "Name is not a simple identifier");
135 return getIdentifier() ? getIdentifier()->getName() : "";
138 /// getNameAsString - Get a human-readable name for the declaration, even if
139 /// it is one of the special kinds of names (C++ constructor, Objective-C
140 /// selector, etc). Creating this name requires expensive string
141 /// manipulation, so it should be called only when performance doesn't matter.
142 /// For simple declarations, getNameAsCString() should suffice.
144 // FIXME: This function should be renamed to indicate that it is not just an
145 // alternate form of getName(), and clients should move as appropriate.
147 // FIXME: Deprecated, move clients to getName().
148 std::string getNameAsString() const { return Name.getAsString(); }
150 void printName(raw_ostream &os) const { os << Name; }
152 /// getDeclName - Get the actual, stored name of the declaration,
153 /// which may be a special name.
154 DeclarationName getDeclName() const { return Name; }
156 /// \brief Set the name of this declaration.
157 void setDeclName(DeclarationName N) { Name = N; }
159 /// printQualifiedName - Returns human-readable qualified name for
160 /// declaration, like A::B::i, for i being member of namespace A::B.
161 /// If declaration is not member of context which can be named (record,
162 /// namespace), it will return same result as printName().
163 /// Creating this name is expensive, so it should be called only when
164 /// performance doesn't matter.
165 void printQualifiedName(raw_ostream &OS) const;
166 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
168 // FIXME: Remove string version.
169 std::string getQualifiedNameAsString() const;
171 /// getNameForDiagnostic - Appends a human-readable name for this
172 /// declaration into the given stream.
174 /// This is the method invoked by Sema when displaying a NamedDecl
175 /// in a diagnostic. It does not necessarily produce the same
176 /// result as printName(); for example, class template
177 /// specializations are printed with their template arguments.
178 virtual void getNameForDiagnostic(raw_ostream &OS,
179 const PrintingPolicy &Policy,
180 bool Qualified) const;
182 /// declarationReplaces - Determine whether this declaration, if
183 /// known to be well-formed within its context, will replace the
184 /// declaration OldD if introduced into scope. A declaration will
185 /// replace another declaration if, for example, it is a
186 /// redeclaration of the same variable or function, but not if it is
187 /// a declaration of a different kind (function vs. class) or an
188 /// overloaded function.
189 bool declarationReplaces(NamedDecl *OldD) const;
191 /// \brief Determine whether this declaration has linkage.
192 bool hasLinkage() const;
194 using Decl::isModulePrivate;
195 using Decl::setModulePrivate;
197 /// \brief Determine whether this declaration is hidden from name lookup.
198 bool isHidden() const { return Hidden; }
200 /// \brief Set whether this declaration is hidden from name lookup.
201 void setHidden(bool Hide) { Hidden = Hide; }
203 /// \brief Determine whether this declaration is a C++ class member.
204 bool isCXXClassMember() const {
205 const DeclContext *DC = getDeclContext();
207 // C++0x [class.mem]p1:
208 // The enumerators of an unscoped enumeration defined in
209 // the class are members of the class.
210 if (isa<EnumDecl>(DC))
211 DC = DC->getRedeclContext();
213 return DC->isRecord();
216 /// \brief Determine whether the given declaration is an instance member of
218 bool isCXXInstanceMember() const;
220 /// \brief Determine what kind of linkage this entity has.
221 /// This is not the linkage as defined by the standard or the codegen notion
222 /// of linkage. It is just an implementation detail that is used to compute
224 Linkage getLinkageInternal() const;
226 /// \brief Get the linkage from a semantic point of view. Entities in
227 /// anonymous namespaces are external (in c++98).
228 Linkage getFormalLinkage() const {
229 return clang::getFormalLinkage(getLinkageInternal());
232 /// \brief True if this decl has external linkage.
233 bool hasExternalFormalLinkage() const {
234 return isExternalFormalLinkage(getLinkageInternal());
237 bool isExternallyVisible() const {
238 return clang::isExternallyVisible(getLinkageInternal());
241 /// \brief Determines the visibility of this entity.
242 Visibility getVisibility() const {
243 return getLinkageAndVisibility().getVisibility();
246 /// \brief Determines the linkage and visibility of this entity.
247 LinkageInfo getLinkageAndVisibility() const;
249 /// Kinds of explicit visibility.
250 enum ExplicitVisibilityKind {
255 /// \brief If visibility was explicitly specified for this
256 /// declaration, return that visibility.
258 getExplicitVisibility(ExplicitVisibilityKind kind) const;
260 /// \brief True if the computed linkage is valid. Used for consistency
261 /// checking. Should always return true.
262 bool isLinkageValid() const;
264 /// \brief True if something has required us to compute the linkage
265 /// of this declaration.
267 /// Language features which can retroactively change linkage (like a
268 /// typedef name for linkage purposes) may need to consider this,
269 /// but hopefully only in transitory ways during parsing.
270 bool hasLinkageBeenComputed() const {
271 return hasCachedLinkage();
274 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
275 /// the underlying named decl.
276 NamedDecl *getUnderlyingDecl() {
277 // Fast-path the common case.
278 if (this->getKind() != UsingShadow &&
279 this->getKind() != ObjCCompatibleAlias)
282 return getUnderlyingDeclImpl();
284 const NamedDecl *getUnderlyingDecl() const {
285 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
288 NamedDecl *getMostRecentDecl() {
289 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
291 const NamedDecl *getMostRecentDecl() const {
292 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
295 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
297 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
298 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
301 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
306 /// LabelDecl - Represents the declaration of a label. Labels also have a
307 /// corresponding LabelStmt, which indicates the position that the label was
308 /// defined at. For normal labels, the location of the decl is the same as the
309 /// location of the statement. For GNU local labels (__label__), the decl
310 /// location is where the __label__ is.
311 class LabelDecl : public NamedDecl {
312 void anchor() override;
315 bool MSAsmNameResolved;
316 /// LocStart - For normal labels, this is the same as the main declaration
317 /// label, i.e., the location of the identifier; for GNU local labels,
318 /// this is the location of the __label__ keyword.
319 SourceLocation LocStart;
321 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
322 LabelStmt *S, SourceLocation StartL)
323 : NamedDecl(Label, DC, IdentL, II),
325 MSAsmNameResolved(false),
329 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
330 SourceLocation IdentL, IdentifierInfo *II);
331 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
332 SourceLocation IdentL, IdentifierInfo *II,
333 SourceLocation GnuLabelL);
334 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
336 LabelStmt *getStmt() const { return TheStmt; }
337 void setStmt(LabelStmt *T) { TheStmt = T; }
339 bool isGnuLocal() const { return LocStart != getLocation(); }
340 void setLocStart(SourceLocation L) { LocStart = L; }
342 SourceRange getSourceRange() const override LLVM_READONLY {
343 return SourceRange(LocStart, getLocation());
346 bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
347 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
348 void setMSAsmLabel(StringRef Name);
349 StringRef getMSAsmLabel() const { return MSAsmName; }
350 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
352 // Implement isa/cast/dyncast/etc.
353 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
354 static bool classofKind(Kind K) { return K == Label; }
357 /// NamespaceDecl - Represent a C++ namespace.
358 class NamespaceDecl : public NamedDecl, public DeclContext,
359 public Redeclarable<NamespaceDecl>
361 /// LocStart - The starting location of the source range, pointing
362 /// to either the namespace or the inline keyword.
363 SourceLocation LocStart;
364 /// RBraceLoc - The ending location of the source range.
365 SourceLocation RBraceLoc;
367 /// \brief A pointer to either the anonymous namespace that lives just inside
368 /// this namespace or to the first namespace in the chain (the latter case
369 /// only when this is not the first in the chain), along with a
370 /// boolean value indicating whether this is an inline namespace.
371 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
373 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
374 SourceLocation StartLoc, SourceLocation IdLoc,
375 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
377 typedef Redeclarable<NamespaceDecl> redeclarable_base;
378 NamespaceDecl *getNextRedeclarationImpl() override;
379 NamespaceDecl *getPreviousDeclImpl() override;
380 NamespaceDecl *getMostRecentDeclImpl() override;
383 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
384 bool Inline, SourceLocation StartLoc,
385 SourceLocation IdLoc, IdentifierInfo *Id,
386 NamespaceDecl *PrevDecl);
388 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
390 typedef redeclarable_base::redecl_range redecl_range;
391 typedef redeclarable_base::redecl_iterator redecl_iterator;
392 using redeclarable_base::redecls_begin;
393 using redeclarable_base::redecls_end;
394 using redeclarable_base::redecls;
395 using redeclarable_base::getPreviousDecl;
396 using redeclarable_base::getMostRecentDecl;
397 using redeclarable_base::isFirstDecl;
399 /// \brief Returns true if this is an anonymous namespace declaration.
407 /// q.v. C++ [namespace.unnamed]
408 bool isAnonymousNamespace() const {
409 return !getIdentifier();
412 /// \brief Returns true if this is an inline namespace declaration.
413 bool isInline() const {
414 return AnonOrFirstNamespaceAndInline.getInt();
417 /// \brief Set whether this is an inline namespace declaration.
418 void setInline(bool Inline) {
419 AnonOrFirstNamespaceAndInline.setInt(Inline);
422 /// \brief Get the original (first) namespace declaration.
423 NamespaceDecl *getOriginalNamespace() {
427 return AnonOrFirstNamespaceAndInline.getPointer();
430 /// \brief Get the original (first) namespace declaration.
431 const NamespaceDecl *getOriginalNamespace() const {
435 return AnonOrFirstNamespaceAndInline.getPointer();
438 /// \brief Return true if this declaration is an original (first) declaration
439 /// of the namespace. This is false for non-original (subsequent) namespace
440 /// declarations and anonymous namespaces.
441 bool isOriginalNamespace() const { return isFirstDecl(); }
443 /// \brief Retrieve the anonymous namespace nested inside this namespace,
445 NamespaceDecl *getAnonymousNamespace() const {
446 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
449 void setAnonymousNamespace(NamespaceDecl *D) {
450 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
453 /// Retrieves the canonical declaration of this namespace.
454 NamespaceDecl *getCanonicalDecl() override {
455 return getOriginalNamespace();
457 const NamespaceDecl *getCanonicalDecl() const {
458 return getOriginalNamespace();
461 SourceRange getSourceRange() const override LLVM_READONLY {
462 return SourceRange(LocStart, RBraceLoc);
465 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
466 SourceLocation getRBraceLoc() const { return RBraceLoc; }
467 void setLocStart(SourceLocation L) { LocStart = L; }
468 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
470 // Implement isa/cast/dyncast/etc.
471 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
472 static bool classofKind(Kind K) { return K == Namespace; }
473 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
474 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
476 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
477 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
480 friend class ASTDeclReader;
481 friend class ASTDeclWriter;
484 /// ValueDecl - Represent the declaration of a variable (in which case it is
485 /// an lvalue) a function (in which case it is a function designator) or
486 /// an enum constant.
487 class ValueDecl : public NamedDecl {
488 void anchor() override;
492 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
493 DeclarationName N, QualType T)
494 : NamedDecl(DK, DC, L, N), DeclType(T) {}
496 QualType getType() const { return DeclType; }
497 void setType(QualType newType) { DeclType = newType; }
499 /// \brief Determine whether this symbol is weakly-imported,
500 /// or declared with the weak or weak-ref attr.
503 // Implement isa/cast/dyncast/etc.
504 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
505 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
508 /// QualifierInfo - A struct with extended info about a syntactic
509 /// name qualifier, to be used for the case of out-of-line declarations.
510 struct QualifierInfo {
511 NestedNameSpecifierLoc QualifierLoc;
513 /// NumTemplParamLists - The number of "outer" template parameter lists.
514 /// The count includes all of the template parameter lists that were matched
515 /// against the template-ids occurring into the NNS and possibly (in the
516 /// case of an explicit specialization) a final "template <>".
517 unsigned NumTemplParamLists;
519 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
520 /// containing pointers to the "outer" template parameter lists.
521 /// It includes all of the template parameter lists that were matched
522 /// against the template-ids occurring into the NNS and possibly (in the
523 /// case of an explicit specialization) a final "template <>".
524 TemplateParameterList** TemplParamLists;
526 /// Default constructor.
528 : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(nullptr) {}
530 /// setTemplateParameterListsInfo - Sets info about "outer" template
532 void setTemplateParameterListsInfo(ASTContext &Context,
534 TemplateParameterList **TPLists);
537 // Copy constructor and copy assignment are disabled.
538 QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION;
539 QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION;
542 /// \brief Represents a ValueDecl that came out of a declarator.
543 /// Contains type source information through TypeSourceInfo.
544 class DeclaratorDecl : public ValueDecl {
545 // A struct representing both a TInfo and a syntactic qualifier,
546 // to be used for the (uncommon) case of out-of-line declarations.
547 struct ExtInfo : public QualifierInfo {
548 TypeSourceInfo *TInfo;
551 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
553 /// InnerLocStart - The start of the source range for this declaration,
554 /// ignoring outer template declarations.
555 SourceLocation InnerLocStart;
557 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
558 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
559 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
562 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
563 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
564 SourceLocation StartL)
565 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
569 TypeSourceInfo *getTypeSourceInfo() const {
571 ? getExtInfo()->TInfo
572 : DeclInfo.get<TypeSourceInfo*>();
574 void setTypeSourceInfo(TypeSourceInfo *TI) {
576 getExtInfo()->TInfo = TI;
581 /// getInnerLocStart - Return SourceLocation representing start of source
582 /// range ignoring outer template declarations.
583 SourceLocation getInnerLocStart() const { return InnerLocStart; }
584 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
586 /// getOuterLocStart - Return SourceLocation representing start of source
587 /// range taking into account any outer template declarations.
588 SourceLocation getOuterLocStart() const;
590 SourceRange getSourceRange() const override LLVM_READONLY;
591 SourceLocation getLocStart() const LLVM_READONLY {
592 return getOuterLocStart();
595 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
596 /// declaration, if it was present in the source.
597 NestedNameSpecifier *getQualifier() const {
598 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
602 /// \brief Retrieve the nested-name-specifier (with source-location
603 /// information) that qualifies the name of this declaration, if it was
604 /// present in the source.
605 NestedNameSpecifierLoc getQualifierLoc() const {
606 return hasExtInfo() ? getExtInfo()->QualifierLoc
607 : NestedNameSpecifierLoc();
610 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
612 unsigned getNumTemplateParameterLists() const {
613 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
615 TemplateParameterList *getTemplateParameterList(unsigned index) const {
616 assert(index < getNumTemplateParameterLists());
617 return getExtInfo()->TemplParamLists[index];
619 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
620 TemplateParameterList **TPLists);
622 SourceLocation getTypeSpecStartLoc() const;
624 // Implement isa/cast/dyncast/etc.
625 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
626 static bool classofKind(Kind K) {
627 return K >= firstDeclarator && K <= lastDeclarator;
630 friend class ASTDeclReader;
631 friend class ASTDeclWriter;
634 /// \brief Structure used to store a statement, the constant value to
635 /// which it was evaluated (if any), and whether or not the statement
636 /// is an integral constant expression (if known).
637 struct EvaluatedStmt {
638 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
639 CheckingICE(false), IsICE(false) { }
641 /// \brief Whether this statement was already evaluated.
642 bool WasEvaluated : 1;
644 /// \brief Whether this statement is being evaluated.
645 bool IsEvaluating : 1;
647 /// \brief Whether we already checked whether this statement was an
648 /// integral constant expression.
651 /// \brief Whether we are checking whether this statement is an
652 /// integral constant expression.
653 bool CheckingICE : 1;
655 /// \brief Whether this statement is an integral constant expression,
656 /// or in C++11, whether the statement is a constant expression. Only
657 /// valid if CheckedICE is true.
664 /// VarDecl - An instance of this class is created to represent a variable
665 /// declaration or definition.
666 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
668 /// getStorageClassSpecifierString - Return the string used to
669 /// specify the storage class \p SC.
671 /// It is illegal to call this function with SC == None.
672 static const char *getStorageClassSpecifierString(StorageClass SC);
674 /// \brief Initialization styles.
675 enum InitializationStyle {
676 CInit, ///< C-style initialization with assignment
677 CallInit, ///< Call-style initialization (C++98)
678 ListInit ///< Direct list-initialization (C++11)
681 /// \brief Kinds of thread-local storage.
683 TLS_None, ///< Not a TLS variable.
684 TLS_Static, ///< TLS with a known-constant initializer.
685 TLS_Dynamic ///< TLS with a dynamic initializer.
689 /// \brief Placeholder type used in Init to denote an unparsed C++ default
691 struct UnparsedDefaultArgument;
693 /// \brief Placeholder type used in Init to denote an uninstantiated C++
694 /// default argument.
695 struct UninstantiatedDefaultArgument;
697 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
698 UnparsedDefaultArgument *,
699 UninstantiatedDefaultArgument *> InitType;
701 /// \brief The initializer for this variable or, for a ParmVarDecl, the
702 /// C++ default argument.
703 mutable InitType Init;
706 class VarDeclBitfields {
707 friend class VarDecl;
708 friend class ASTDeclReader;
711 unsigned TSCSpec : 2;
712 unsigned InitStyle : 2;
714 /// \brief Whether this variable is the exception variable in a C++ catch
715 /// or an Objective-C @catch statement.
716 unsigned ExceptionVar : 1;
718 /// \brief Whether this local variable could be allocated in the return
719 /// slot of its function, enabling the named return value optimization
721 unsigned NRVOVariable : 1;
723 /// \brief Whether this variable is the for-range-declaration in a C++0x
724 /// for-range statement.
725 unsigned CXXForRangeDecl : 1;
727 /// \brief Whether this variable is an ARC pseudo-__strong
728 /// variable; see isARCPseudoStrong() for details.
729 unsigned ARCPseudoStrong : 1;
731 /// \brief Whether this variable is (C++0x) constexpr.
732 unsigned IsConstexpr : 1;
734 /// \brief Whether this variable is the implicit variable for a lambda
736 unsigned IsInitCapture : 1;
738 /// \brief Whether this local extern variable's previous declaration was
739 /// declared in the same block scope. This controls whether we should merge
740 /// the type of this declaration with its previous declaration.
741 unsigned PreviousDeclInSameBlockScope : 1;
743 enum { NumVarDeclBits = 14 };
745 friend class ASTDeclReader;
746 friend class StmtIteratorBase;
747 friend class ASTNodeImporter;
750 enum { NumParameterIndexBits = 8 };
752 class ParmVarDeclBitfields {
753 friend class ParmVarDecl;
754 friend class ASTDeclReader;
756 unsigned : NumVarDeclBits;
758 /// Whether this parameter inherits a default argument from a
759 /// prior declaration.
760 unsigned HasInheritedDefaultArg : 1;
762 /// Whether this parameter undergoes K&R argument promotion.
763 unsigned IsKNRPromoted : 1;
765 /// Whether this parameter is an ObjC method parameter or not.
766 unsigned IsObjCMethodParam : 1;
768 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
769 /// Otherwise, the number of function parameter scopes enclosing
770 /// the function parameter scope in which this parameter was
772 unsigned ScopeDepthOrObjCQuals : 7;
774 /// The number of parameters preceding this parameter in the
775 /// function parameter scope in which it was declared.
776 unsigned ParameterIndex : NumParameterIndexBits;
781 VarDeclBitfields VarDeclBits;
782 ParmVarDeclBitfields ParmVarDeclBits;
785 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
786 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
787 TypeSourceInfo *TInfo, StorageClass SC);
789 typedef Redeclarable<VarDecl> redeclarable_base;
790 VarDecl *getNextRedeclarationImpl() override {
791 return getNextRedeclaration();
793 VarDecl *getPreviousDeclImpl() override {
794 return getPreviousDecl();
796 VarDecl *getMostRecentDeclImpl() override {
797 return getMostRecentDecl();
801 typedef redeclarable_base::redecl_range redecl_range;
802 typedef redeclarable_base::redecl_iterator redecl_iterator;
803 using redeclarable_base::redecls_begin;
804 using redeclarable_base::redecls_end;
805 using redeclarable_base::redecls;
806 using redeclarable_base::getPreviousDecl;
807 using redeclarable_base::getMostRecentDecl;
808 using redeclarable_base::isFirstDecl;
810 static VarDecl *Create(ASTContext &C, DeclContext *DC,
811 SourceLocation StartLoc, SourceLocation IdLoc,
812 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
815 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
817 SourceRange getSourceRange() const override LLVM_READONLY;
819 /// \brief Returns the storage class as written in the source. For the
820 /// computed linkage of symbol, see getLinkage.
821 StorageClass getStorageClass() const {
822 return (StorageClass) VarDeclBits.SClass;
824 void setStorageClass(StorageClass SC);
826 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
827 VarDeclBits.TSCSpec = TSC;
828 assert(VarDeclBits.TSCSpec == TSC && "truncation");
830 ThreadStorageClassSpecifier getTSCSpec() const {
831 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
833 TLSKind getTLSKind() const;
835 /// hasLocalStorage - Returns true if a variable with function scope
836 /// is a non-static local variable.
837 bool hasLocalStorage() const {
838 if (getStorageClass() == SC_None)
839 // Second check is for C++11 [dcl.stc]p4.
840 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
842 // Global Named Register (GNU extension)
843 if (getStorageClass() == SC_Register && !isLocalVarDecl())
846 // Return true for: Auto, Register.
847 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
849 return getStorageClass() >= SC_Auto;
852 /// isStaticLocal - Returns true if a variable with function scope is a
853 /// static local variable.
854 bool isStaticLocal() const {
855 return (getStorageClass() == SC_Static ||
857 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
861 /// \brief Returns true if a variable has extern or __private_extern__
863 bool hasExternalStorage() const {
864 return getStorageClass() == SC_Extern ||
865 getStorageClass() == SC_PrivateExtern;
868 /// \brief Returns true for all variables that do not have local storage.
870 /// This includes all global variables as well as static variables declared
871 /// within a function.
872 bool hasGlobalStorage() const { return !hasLocalStorage(); }
874 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
875 StorageDuration getStorageDuration() const {
876 return hasLocalStorage() ? SD_Automatic :
877 getTSCSpec() ? SD_Thread : SD_Static;
880 /// \brief Compute the language linkage.
881 LanguageLinkage getLanguageLinkage() const;
883 /// \brief Determines whether this variable is a variable with
884 /// external, C linkage.
885 bool isExternC() const;
887 /// \brief Determines whether this variable's context is, or is nested within,
888 /// a C++ extern "C" linkage spec.
889 bool isInExternCContext() const;
891 /// \brief Determines whether this variable's context is, or is nested within,
892 /// a C++ extern "C++" linkage spec.
893 bool isInExternCXXContext() const;
895 /// isLocalVarDecl - Returns true for local variable declarations
896 /// other than parameters. Note that this includes static variables
897 /// inside of functions. It also includes variables inside blocks.
899 /// void foo() { int x; static int y; extern int z; }
901 bool isLocalVarDecl() const {
902 if (getKind() != Decl::Var)
904 if (const DeclContext *DC = getLexicalDeclContext())
905 return DC->getRedeclContext()->isFunctionOrMethod();
909 /// \brief Similar to isLocalVarDecl but also includes parameters.
910 bool isLocalVarDeclOrParm() const {
911 return isLocalVarDecl() || getKind() == Decl::ParmVar;
914 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
915 /// excludes variables declared in blocks.
916 bool isFunctionOrMethodVarDecl() const {
917 if (getKind() != Decl::Var)
919 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
920 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
923 /// \brief Determines whether this is a static data member.
925 /// This will only be true in C++, and applies to, e.g., the
932 bool isStaticDataMember() const {
933 // If it wasn't static, it would be a FieldDecl.
934 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
937 VarDecl *getCanonicalDecl() override;
938 const VarDecl *getCanonicalDecl() const {
939 return const_cast<VarDecl*>(this)->getCanonicalDecl();
942 enum DefinitionKind {
943 DeclarationOnly, ///< This declaration is only a declaration.
944 TentativeDefinition, ///< This declaration is a tentative definition.
945 Definition ///< This declaration is definitely a definition.
948 /// \brief Check whether this declaration is a definition. If this could be
949 /// a tentative definition (in C), don't check whether there's an overriding
951 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
952 DefinitionKind isThisDeclarationADefinition() const {
953 return isThisDeclarationADefinition(getASTContext());
956 /// \brief Check whether this variable is defined in this
957 /// translation unit.
958 DefinitionKind hasDefinition(ASTContext &) const;
959 DefinitionKind hasDefinition() const {
960 return hasDefinition(getASTContext());
963 /// \brief Get the tentative definition that acts as the real definition in
964 /// a TU. Returns null if there is a proper definition available.
965 VarDecl *getActingDefinition();
966 const VarDecl *getActingDefinition() const {
967 return const_cast<VarDecl*>(this)->getActingDefinition();
970 /// \brief Get the real (not just tentative) definition for this declaration.
971 VarDecl *getDefinition(ASTContext &);
972 const VarDecl *getDefinition(ASTContext &C) const {
973 return const_cast<VarDecl*>(this)->getDefinition(C);
975 VarDecl *getDefinition() {
976 return getDefinition(getASTContext());
978 const VarDecl *getDefinition() const {
979 return const_cast<VarDecl*>(this)->getDefinition();
982 /// \brief Determine whether this is or was instantiated from an out-of-line
983 /// definition of a static data member.
984 bool isOutOfLine() const override;
986 /// \brief If this is a static data member, find its out-of-line definition.
987 VarDecl *getOutOfLineDefinition();
989 /// isFileVarDecl - Returns true for file scoped variable declaration.
990 bool isFileVarDecl() const {
992 if (K == ParmVar || K == ImplicitParam)
995 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
998 if (isStaticDataMember())
1004 /// getAnyInitializer - Get the initializer for this variable, no matter which
1005 /// declaration it is attached to.
1006 const Expr *getAnyInitializer() const {
1008 return getAnyInitializer(D);
1011 /// getAnyInitializer - Get the initializer for this variable, no matter which
1012 /// declaration it is attached to. Also get that declaration.
1013 const Expr *getAnyInitializer(const VarDecl *&D) const;
1015 bool hasInit() const {
1016 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
1018 const Expr *getInit() const {
1022 const Stmt *S = Init.dyn_cast<Stmt *>();
1024 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1027 return (const Expr*) S;
1033 Stmt *S = Init.dyn_cast<Stmt *>();
1035 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1042 /// \brief Retrieve the address of the initializer expression.
1043 Stmt **getInitAddress() {
1044 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1047 // This union hack tip-toes around strict-aliasing rules.
1057 void setInit(Expr *I);
1059 /// \brief Determine whether this variable's value can be used in a
1060 /// constant expression, according to the relevant language standard.
1061 /// This only checks properties of the declaration, and does not check
1062 /// whether the initializer is in fact a constant expression.
1063 bool isUsableInConstantExpressions(ASTContext &C) const;
1065 EvaluatedStmt *ensureEvaluatedStmt() const;
1067 /// \brief Attempt to evaluate the value of the initializer attached to this
1068 /// declaration, and produce notes explaining why it cannot be evaluated or is
1069 /// not a constant expression. Returns a pointer to the value if evaluation
1070 /// succeeded, 0 otherwise.
1071 APValue *evaluateValue() const;
1072 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1074 /// \brief Return the already-evaluated value of this variable's
1075 /// initializer, or NULL if the value is not yet known. Returns pointer
1076 /// to untyped APValue if the value could not be evaluated.
1077 APValue *getEvaluatedValue() const {
1078 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1079 if (Eval->WasEvaluated)
1080 return &Eval->Evaluated;
1085 /// \brief Determines whether it is already known whether the
1086 /// initializer is an integral constant expression or not.
1087 bool isInitKnownICE() const {
1088 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1089 return Eval->CheckedICE;
1094 /// \brief Determines whether the initializer is an integral constant
1095 /// expression, or in C++11, whether the initializer is a constant
1098 /// \pre isInitKnownICE()
1099 bool isInitICE() const {
1100 assert(isInitKnownICE() &&
1101 "Check whether we already know that the initializer is an ICE");
1102 return Init.get<EvaluatedStmt *>()->IsICE;
1105 /// \brief Determine whether the value of the initializer attached to this
1106 /// declaration is an integral constant expression.
1107 bool checkInitIsICE() const;
1109 void setInitStyle(InitializationStyle Style) {
1110 VarDeclBits.InitStyle = Style;
1113 /// \brief The style of initialization for this declaration.
1115 /// C-style initialization is "int x = 1;". Call-style initialization is
1116 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1117 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1118 /// expression for class types. List-style initialization is C++11 syntax,
1119 /// e.g. "int x{1};". Clients can distinguish between different forms of
1120 /// initialization by checking this value. In particular, "int x = {1};" is
1121 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1122 /// Init expression in all three cases is an InitListExpr.
1123 InitializationStyle getInitStyle() const {
1124 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1127 /// \brief Whether the initializer is a direct-initializer (list or call).
1128 bool isDirectInit() const {
1129 return getInitStyle() != CInit;
1132 /// \brief Determine whether this variable is the exception variable in a
1133 /// C++ catch statememt or an Objective-C \@catch statement.
1134 bool isExceptionVariable() const {
1135 return VarDeclBits.ExceptionVar;
1137 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1139 /// \brief Determine whether this local variable can be used with the named
1140 /// return value optimization (NRVO).
1142 /// The named return value optimization (NRVO) works by marking certain
1143 /// non-volatile local variables of class type as NRVO objects. These
1144 /// locals can be allocated within the return slot of their containing
1145 /// function, in which case there is no need to copy the object to the
1146 /// return slot when returning from the function. Within the function body,
1147 /// each return that returns the NRVO object will have this variable as its
1149 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1150 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1152 /// \brief Determine whether this variable is the for-range-declaration in
1153 /// a C++0x for-range statement.
1154 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1155 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1157 /// \brief Determine whether this variable is an ARC pseudo-__strong
1158 /// variable. A pseudo-__strong variable has a __strong-qualified
1159 /// type but does not actually retain the object written into it.
1160 /// Generally such variables are also 'const' for safety.
1161 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1162 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1164 /// Whether this variable is (C++11) constexpr.
1165 bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1166 void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1168 /// Whether this variable is the implicit variable for a lambda init-capture.
1169 bool isInitCapture() const { return VarDeclBits.IsInitCapture; }
1170 void setInitCapture(bool IC) { VarDeclBits.IsInitCapture = IC; }
1172 /// Whether this local extern variable declaration's previous declaration
1173 /// was declared in the same block scope. Only correct in C++.
1174 bool isPreviousDeclInSameBlockScope() const {
1175 return VarDeclBits.PreviousDeclInSameBlockScope;
1177 void setPreviousDeclInSameBlockScope(bool Same) {
1178 VarDeclBits.PreviousDeclInSameBlockScope = Same;
1181 /// \brief If this variable is an instantiated static data member of a
1182 /// class template specialization, returns the templated static data member
1183 /// from which it was instantiated.
1184 VarDecl *getInstantiatedFromStaticDataMember() const;
1186 /// \brief If this variable is an instantiation of a variable template or a
1187 /// static data member of a class template, determine what kind of
1188 /// template specialization or instantiation this is.
1189 TemplateSpecializationKind getTemplateSpecializationKind() const;
1191 /// \brief If this variable is an instantiation of a variable template or a
1192 /// static data member of a class template, determine its point of
1194 SourceLocation getPointOfInstantiation() const;
1196 /// \brief If this variable is an instantiation of a static data member of a
1197 /// class template specialization, retrieves the member specialization
1199 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1201 /// \brief For a static data member that was instantiated from a static
1202 /// data member of a class template, set the template specialiation kind.
1203 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1204 SourceLocation PointOfInstantiation = SourceLocation());
1206 /// \brief Specify that this variable is an instantiation of the
1207 /// static data member VD.
1208 void setInstantiationOfStaticDataMember(VarDecl *VD,
1209 TemplateSpecializationKind TSK);
1211 /// \brief Retrieves the variable template that is described by this
1212 /// variable declaration.
1214 /// Every variable template is represented as a VarTemplateDecl and a
1215 /// VarDecl. The former contains template properties (such as
1216 /// the template parameter lists) while the latter contains the
1217 /// actual description of the template's
1218 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1219 /// VarDecl that from a VarTemplateDecl, while
1220 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1222 VarTemplateDecl *getDescribedVarTemplate() const;
1224 void setDescribedVarTemplate(VarTemplateDecl *Template);
1226 // Implement isa/cast/dyncast/etc.
1227 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1228 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1231 class ImplicitParamDecl : public VarDecl {
1232 void anchor() override;
1234 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1235 SourceLocation IdLoc, IdentifierInfo *Id,
1238 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1240 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1241 IdentifierInfo *Id, QualType Type)
1242 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1243 /*tinfo*/ nullptr, SC_None) {
1247 // Implement isa/cast/dyncast/etc.
1248 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1249 static bool classofKind(Kind K) { return K == ImplicitParam; }
1252 /// ParmVarDecl - Represents a parameter to a function.
1253 class ParmVarDecl : public VarDecl {
1255 enum { MaxFunctionScopeDepth = 255 };
1256 enum { MaxFunctionScopeIndex = 255 };
1259 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1260 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1261 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1262 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1263 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1264 assert(ParmVarDeclBits.IsKNRPromoted == false);
1265 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1266 setDefaultArg(DefArg);
1270 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1271 SourceLocation StartLoc,
1272 SourceLocation IdLoc, IdentifierInfo *Id,
1273 QualType T, TypeSourceInfo *TInfo,
1274 StorageClass S, Expr *DefArg);
1276 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1278 SourceRange getSourceRange() const override LLVM_READONLY;
1280 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1281 ParmVarDeclBits.IsObjCMethodParam = true;
1282 setParameterIndex(parameterIndex);
1285 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1286 assert(!ParmVarDeclBits.IsObjCMethodParam);
1288 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1289 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1292 setParameterIndex(parameterIndex);
1295 bool isObjCMethodParameter() const {
1296 return ParmVarDeclBits.IsObjCMethodParam;
1299 unsigned getFunctionScopeDepth() const {
1300 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1301 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1304 /// Returns the index of this parameter in its prototype or method scope.
1305 unsigned getFunctionScopeIndex() const {
1306 return getParameterIndex();
1309 ObjCDeclQualifier getObjCDeclQualifier() const {
1310 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1311 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1313 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1314 assert(ParmVarDeclBits.IsObjCMethodParam);
1315 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1318 /// True if the value passed to this parameter must undergo
1319 /// K&R-style default argument promotion:
1322 /// If the expression that denotes the called function has a type
1323 /// that does not include a prototype, the integer promotions are
1324 /// performed on each argument, and arguments that have type float
1325 /// are promoted to double.
1326 bool isKNRPromoted() const {
1327 return ParmVarDeclBits.IsKNRPromoted;
1329 void setKNRPromoted(bool promoted) {
1330 ParmVarDeclBits.IsKNRPromoted = promoted;
1333 Expr *getDefaultArg();
1334 const Expr *getDefaultArg() const {
1335 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1338 void setDefaultArg(Expr *defarg) {
1339 Init = reinterpret_cast<Stmt *>(defarg);
1342 /// \brief Retrieve the source range that covers the entire default
1344 SourceRange getDefaultArgRange() const;
1345 void setUninstantiatedDefaultArg(Expr *arg) {
1346 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1348 Expr *getUninstantiatedDefaultArg() {
1349 return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1351 const Expr *getUninstantiatedDefaultArg() const {
1352 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1355 /// hasDefaultArg - Determines whether this parameter has a default argument,
1356 /// either parsed or not.
1357 bool hasDefaultArg() const {
1358 return getInit() || hasUnparsedDefaultArg() ||
1359 hasUninstantiatedDefaultArg();
1362 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1363 /// default argument that has not yet been parsed. This will occur
1364 /// during the processing of a C++ class whose member functions have
1365 /// default arguments, e.g.,
1369 /// void f(int x = 17); // x has an unparsed default argument now
1370 /// }; // x has a regular default argument now
1372 bool hasUnparsedDefaultArg() const {
1373 return Init.is<UnparsedDefaultArgument*>();
1376 bool hasUninstantiatedDefaultArg() const {
1377 return Init.is<UninstantiatedDefaultArgument*>();
1380 /// setUnparsedDefaultArg - Specify that this parameter has an
1381 /// unparsed default argument. The argument will be replaced with a
1382 /// real default argument via setDefaultArg when the class
1383 /// definition enclosing the function declaration that owns this
1384 /// default argument is completed.
1385 void setUnparsedDefaultArg() { Init = (UnparsedDefaultArgument *)nullptr; }
1387 bool hasInheritedDefaultArg() const {
1388 return ParmVarDeclBits.HasInheritedDefaultArg;
1391 void setHasInheritedDefaultArg(bool I = true) {
1392 ParmVarDeclBits.HasInheritedDefaultArg = I;
1395 QualType getOriginalType() const;
1397 /// \brief Determine whether this parameter is actually a function
1399 bool isParameterPack() const;
1401 /// setOwningFunction - Sets the function declaration that owns this
1402 /// ParmVarDecl. Since ParmVarDecls are often created before the
1403 /// FunctionDecls that own them, this routine is required to update
1404 /// the DeclContext appropriately.
1405 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1407 // Implement isa/cast/dyncast/etc.
1408 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1409 static bool classofKind(Kind K) { return K == ParmVar; }
1412 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1414 void setParameterIndex(unsigned parameterIndex) {
1415 if (parameterIndex >= ParameterIndexSentinel) {
1416 setParameterIndexLarge(parameterIndex);
1420 ParmVarDeclBits.ParameterIndex = parameterIndex;
1421 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1423 unsigned getParameterIndex() const {
1424 unsigned d = ParmVarDeclBits.ParameterIndex;
1425 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1428 void setParameterIndexLarge(unsigned parameterIndex);
1429 unsigned getParameterIndexLarge() const;
1432 /// FunctionDecl - An instance of this class is created to represent a
1433 /// function declaration or definition.
1435 /// Since a given function can be declared several times in a program,
1436 /// there may be several FunctionDecls that correspond to that
1437 /// function. Only one of those FunctionDecls will be found when
1438 /// traversing the list of declarations in the context of the
1439 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1440 /// contains all of the information known about the function. Other,
1441 /// previous declarations of the function are available via the
1442 /// getPreviousDecl() chain.
1443 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1444 public Redeclarable<FunctionDecl> {
1446 /// \brief The kind of templated function a FunctionDecl can be.
1447 enum TemplatedKind {
1449 TK_FunctionTemplate,
1450 TK_MemberSpecialization,
1451 TK_FunctionTemplateSpecialization,
1452 TK_DependentFunctionTemplateSpecialization
1456 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1457 /// parameters of this function. This is null if a prototype or if there are
1459 ParmVarDecl **ParamInfo;
1461 /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1462 /// decls defined in the function prototype that are not parameters. E.g.
1463 /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1464 ArrayRef<NamedDecl *> DeclsInPrototypeScope;
1466 LazyDeclStmtPtr Body;
1468 // FIXME: This can be packed into the bitfields in Decl.
1469 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1470 unsigned SClass : 2;
1472 bool IsInlineSpecified : 1;
1473 bool IsVirtualAsWritten : 1;
1475 bool HasInheritedPrototype : 1;
1476 bool HasWrittenPrototype : 1;
1478 bool IsTrivial : 1; // sunk from CXXMethodDecl
1479 bool IsDefaulted : 1; // sunk from CXXMethoDecl
1480 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1481 bool HasImplicitReturnZero : 1;
1482 bool IsLateTemplateParsed : 1;
1483 bool IsConstexpr : 1;
1485 /// \brief Indicates if the function was a definition but its body was
1487 unsigned HasSkippedBody : 1;
1489 /// \brief End part of this FunctionDecl's source range.
1491 /// We could compute the full range in getSourceRange(). However, when we're
1492 /// dealing with a function definition deserialized from a PCH/AST file,
1493 /// we can only compute the full range once the function body has been
1494 /// de-serialized, so it's far better to have the (sometimes-redundant)
1496 SourceLocation EndRangeLoc;
1498 /// \brief The template or declaration that this declaration
1499 /// describes or was instantiated from, respectively.
1501 /// For non-templates, this value will be NULL. For function
1502 /// declarations that describe a function template, this will be a
1503 /// pointer to a FunctionTemplateDecl. For member functions
1504 /// of class template specializations, this will be a MemberSpecializationInfo
1505 /// pointer containing information about the specialization.
1506 /// For function template specializations, this will be a
1507 /// FunctionTemplateSpecializationInfo, which contains information about
1508 /// the template being specialized and the template arguments involved in
1509 /// that specialization.
1510 llvm::PointerUnion4<FunctionTemplateDecl *,
1511 MemberSpecializationInfo *,
1512 FunctionTemplateSpecializationInfo *,
1513 DependentFunctionTemplateSpecializationInfo *>
1514 TemplateOrSpecialization;
1516 /// DNLoc - Provides source/type location info for the
1517 /// declaration name embedded in the DeclaratorDecl base class.
1518 DeclarationNameLoc DNLoc;
1520 /// \brief Specify that this function declaration is actually a function
1521 /// template specialization.
1523 /// \param C the ASTContext.
1525 /// \param Template the function template that this function template
1526 /// specialization specializes.
1528 /// \param TemplateArgs the template arguments that produced this
1529 /// function template specialization from the template.
1531 /// \param InsertPos If non-NULL, the position in the function template
1532 /// specialization set where the function template specialization data will
1535 /// \param TSK the kind of template specialization this is.
1537 /// \param TemplateArgsAsWritten location info of template arguments.
1539 /// \param PointOfInstantiation point at which the function template
1540 /// specialization was first instantiated.
1541 void setFunctionTemplateSpecialization(ASTContext &C,
1542 FunctionTemplateDecl *Template,
1543 const TemplateArgumentList *TemplateArgs,
1545 TemplateSpecializationKind TSK,
1546 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1547 SourceLocation PointOfInstantiation);
1549 /// \brief Specify that this record is an instantiation of the
1550 /// member function FD.
1551 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1552 TemplateSpecializationKind TSK);
1554 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1557 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1558 const DeclarationNameInfo &NameInfo,
1559 QualType T, TypeSourceInfo *TInfo,
1560 StorageClass S, bool isInlineSpecified,
1561 bool isConstexprSpecified)
1562 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1565 redeclarable_base(C),
1566 ParamInfo(nullptr), Body(),
1568 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1569 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1570 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1571 IsDefaulted(false), IsExplicitlyDefaulted(false),
1572 HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1573 IsConstexpr(isConstexprSpecified), HasSkippedBody(false),
1574 EndRangeLoc(NameInfo.getEndLoc()),
1575 TemplateOrSpecialization(),
1576 DNLoc(NameInfo.getInfo()) {}
1578 typedef Redeclarable<FunctionDecl> redeclarable_base;
1579 FunctionDecl *getNextRedeclarationImpl() override {
1580 return getNextRedeclaration();
1582 FunctionDecl *getPreviousDeclImpl() override {
1583 return getPreviousDecl();
1585 FunctionDecl *getMostRecentDeclImpl() override {
1586 return getMostRecentDecl();
1590 typedef redeclarable_base::redecl_range redecl_range;
1591 typedef redeclarable_base::redecl_iterator redecl_iterator;
1592 using redeclarable_base::redecls_begin;
1593 using redeclarable_base::redecls_end;
1594 using redeclarable_base::redecls;
1595 using redeclarable_base::getPreviousDecl;
1596 using redeclarable_base::getMostRecentDecl;
1597 using redeclarable_base::isFirstDecl;
1599 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1600 SourceLocation StartLoc, SourceLocation NLoc,
1601 DeclarationName N, QualType T,
1602 TypeSourceInfo *TInfo,
1604 bool isInlineSpecified = false,
1605 bool hasWrittenPrototype = true,
1606 bool isConstexprSpecified = false) {
1607 DeclarationNameInfo NameInfo(N, NLoc);
1608 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1610 isInlineSpecified, hasWrittenPrototype,
1611 isConstexprSpecified);
1614 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1615 SourceLocation StartLoc,
1616 const DeclarationNameInfo &NameInfo,
1617 QualType T, TypeSourceInfo *TInfo,
1619 bool isInlineSpecified,
1620 bool hasWrittenPrototype,
1621 bool isConstexprSpecified = false);
1623 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1625 DeclarationNameInfo getNameInfo() const {
1626 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1629 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1630 bool Qualified) const override;
1632 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1634 SourceRange getSourceRange() const override LLVM_READONLY;
1636 /// \brief Returns true if the function has a body (definition). The
1637 /// function body might be in any of the (re-)declarations of this
1638 /// function. The variant that accepts a FunctionDecl pointer will
1639 /// set that function declaration to the actual declaration
1640 /// containing the body (if there is one).
1641 bool hasBody(const FunctionDecl *&Definition) const;
1643 bool hasBody() const override {
1644 const FunctionDecl* Definition;
1645 return hasBody(Definition);
1648 /// hasTrivialBody - Returns whether the function has a trivial body that does
1649 /// not require any specific codegen.
1650 bool hasTrivialBody() const;
1652 /// isDefined - Returns true if the function is defined at all, including
1653 /// a deleted definition. Except for the behavior when the function is
1654 /// deleted, behaves like hasBody.
1655 bool isDefined(const FunctionDecl *&Definition) const;
1657 virtual bool isDefined() const {
1658 const FunctionDecl* Definition;
1659 return isDefined(Definition);
1662 /// getBody - Retrieve the body (definition) of the function. The
1663 /// function body might be in any of the (re-)declarations of this
1664 /// function. The variant that accepts a FunctionDecl pointer will
1665 /// set that function declaration to the actual declaration
1666 /// containing the body (if there is one).
1667 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1668 /// unnecessary AST de-serialization of the body.
1669 Stmt *getBody(const FunctionDecl *&Definition) const;
1671 Stmt *getBody() const override {
1672 const FunctionDecl* Definition;
1673 return getBody(Definition);
1676 /// isThisDeclarationADefinition - Returns whether this specific
1677 /// declaration of the function is also a definition. This does not
1678 /// determine whether the function has been defined (e.g., in a
1679 /// previous definition); for that information, use isDefined. Note
1680 /// that this returns false for a defaulted function unless that function
1681 /// has been implicitly defined (possibly as deleted).
1682 bool isThisDeclarationADefinition() const {
1683 return IsDeleted || Body || IsLateTemplateParsed;
1686 /// doesThisDeclarationHaveABody - Returns whether this specific
1687 /// declaration of the function has a body - that is, if it is a non-
1688 /// deleted definition.
1689 bool doesThisDeclarationHaveABody() const {
1690 return Body || IsLateTemplateParsed;
1693 void setBody(Stmt *B);
1694 void setLazyBody(uint64_t Offset) { Body = Offset; }
1696 /// Whether this function is variadic.
1697 bool isVariadic() const;
1699 /// Whether this function is marked as virtual explicitly.
1700 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1701 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1703 /// Whether this virtual function is pure, i.e. makes the containing class
1705 bool isPure() const { return IsPure; }
1706 void setPure(bool P = true);
1708 /// Whether this templated function will be late parsed.
1709 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1710 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1712 /// Whether this function is "trivial" in some specialized C++ senses.
1713 /// Can only be true for default constructors, copy constructors,
1714 /// copy assignment operators, and destructors. Not meaningful until
1715 /// the class has been fully built by Sema.
1716 bool isTrivial() const { return IsTrivial; }
1717 void setTrivial(bool IT) { IsTrivial = IT; }
1719 /// Whether this function is defaulted per C++0x. Only valid for
1720 /// special member functions.
1721 bool isDefaulted() const { return IsDefaulted; }
1722 void setDefaulted(bool D = true) { IsDefaulted = D; }
1724 /// Whether this function is explicitly defaulted per C++0x. Only valid
1725 /// for special member functions.
1726 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1727 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1729 /// Whether falling off this function implicitly returns null/zero.
1730 /// If a more specific implicit return value is required, front-ends
1731 /// should synthesize the appropriate return statements.
1732 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1733 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1735 /// \brief Whether this function has a prototype, either because one
1736 /// was explicitly written or because it was "inherited" by merging
1737 /// a declaration without a prototype with a declaration that has a
1739 bool hasPrototype() const {
1740 return HasWrittenPrototype || HasInheritedPrototype;
1743 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1745 /// \brief Whether this function inherited its prototype from a
1746 /// previous declaration.
1747 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1748 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1750 /// Whether this is a (C++11) constexpr function or constexpr constructor.
1751 bool isConstexpr() const { return IsConstexpr; }
1752 void setConstexpr(bool IC) { IsConstexpr = IC; }
1754 /// \brief Whether this function has been deleted.
1756 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1757 /// acts like a normal function, except that it cannot actually be
1758 /// called or have its address taken. Deleted functions are
1759 /// typically used in C++ overload resolution to attract arguments
1760 /// whose type or lvalue/rvalue-ness would permit the use of a
1761 /// different overload that would behave incorrectly. For example,
1762 /// one might use deleted functions to ban implicit conversion from
1763 /// a floating-point number to an Integer type:
1766 /// struct Integer {
1767 /// Integer(long); // construct from a long
1768 /// Integer(double) = delete; // no construction from float or double
1769 /// Integer(long double) = delete; // no construction from long double
1772 // If a function is deleted, its first declaration must be.
1773 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1774 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1775 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1777 /// \brief Determines whether this function is "main", which is the
1778 /// entry point into an executable program.
1779 bool isMain() const;
1781 /// \brief Determines whether this function is a MSVCRT user defined entry
1783 bool isMSVCRTEntryPoint() const;
1785 /// \brief Determines whether this operator new or delete is one
1786 /// of the reserved global placement operators:
1787 /// void *operator new(size_t, void *);
1788 /// void *operator new[](size_t, void *);
1789 /// void operator delete(void *, void *);
1790 /// void operator delete[](void *, void *);
1791 /// These functions have special behavior under [new.delete.placement]:
1792 /// These functions are reserved, a C++ program may not define
1793 /// functions that displace the versions in the Standard C++ library.
1794 /// The provisions of [basic.stc.dynamic] do not apply to these
1795 /// reserved placement forms of operator new and operator delete.
1797 /// This function must be an allocation or deallocation function.
1798 bool isReservedGlobalPlacementOperator() const;
1800 /// \brief Determines whether this function is one of the replaceable
1801 /// global allocation functions:
1802 /// void *operator new(size_t);
1803 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
1804 /// void *operator new[](size_t);
1805 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
1806 /// void operator delete(void *) noexcept;
1807 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
1808 /// void operator delete(void *, const std::nothrow_t &) noexcept;
1809 /// void operator delete[](void *) noexcept;
1810 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
1811 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
1812 /// These functions have special behavior under C++1y [expr.new]:
1813 /// An implementation is allowed to omit a call to a replaceable global
1814 /// allocation function. [...]
1815 bool isReplaceableGlobalAllocationFunction() const;
1817 /// \brief Determine whether this function is a sized global deallocation
1818 /// function in C++1y. If so, find and return the corresponding unsized
1819 /// deallocation function.
1820 FunctionDecl *getCorrespondingUnsizedGlobalDeallocationFunction() const;
1822 /// Compute the language linkage.
1823 LanguageLinkage getLanguageLinkage() const;
1825 /// \brief Determines whether this function is a function with
1826 /// external, C linkage.
1827 bool isExternC() const;
1829 /// \brief Determines whether this function's context is, or is nested within,
1830 /// a C++ extern "C" linkage spec.
1831 bool isInExternCContext() const;
1833 /// \brief Determines whether this function's context is, or is nested within,
1834 /// a C++ extern "C++" linkage spec.
1835 bool isInExternCXXContext() const;
1837 /// \brief Determines whether this is a global function.
1838 bool isGlobal() const;
1840 /// \brief Determines whether this function is known to be 'noreturn', through
1841 /// an attribute on its declaration or its type.
1842 bool isNoReturn() const;
1844 /// \brief True if the function was a definition but its body was skipped.
1845 bool hasSkippedBody() const { return HasSkippedBody; }
1846 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
1848 void setPreviousDeclaration(FunctionDecl * PrevDecl);
1850 virtual const FunctionDecl *getCanonicalDecl() const;
1851 FunctionDecl *getCanonicalDecl() override;
1853 unsigned getBuiltinID() const;
1855 // Iterator access to formal parameters.
1856 unsigned param_size() const { return getNumParams(); }
1857 typedef ParmVarDecl **param_iterator;
1858 typedef ParmVarDecl * const *param_const_iterator;
1859 typedef llvm::iterator_range<param_iterator> param_range;
1860 typedef llvm::iterator_range<param_const_iterator> param_const_range;
1862 param_iterator param_begin() { return param_iterator(ParamInfo); }
1863 param_iterator param_end() {
1864 return param_iterator(ParamInfo + param_size());
1866 param_range params() { return param_range(param_begin(), param_end()); }
1868 param_const_iterator param_begin() const {
1869 return param_const_iterator(ParamInfo);
1871 param_const_iterator param_end() const {
1872 return param_const_iterator(ParamInfo + param_size());
1874 param_const_range params() const {
1875 return param_const_range(param_begin(), param_end());
1878 /// getNumParams - Return the number of parameters this function must have
1879 /// based on its FunctionType. This is the length of the ParamInfo array
1880 /// after it has been created.
1881 unsigned getNumParams() const;
1883 const ParmVarDecl *getParamDecl(unsigned i) const {
1884 assert(i < getNumParams() && "Illegal param #");
1885 return ParamInfo[i];
1887 ParmVarDecl *getParamDecl(unsigned i) {
1888 assert(i < getNumParams() && "Illegal param #");
1889 return ParamInfo[i];
1891 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
1892 setParams(getASTContext(), NewParamInfo);
1895 // ArrayRef iterface to parameters.
1896 // FIXME: Should one day replace iterator interface.
1897 ArrayRef<ParmVarDecl*> parameters() const {
1898 return llvm::makeArrayRef(ParamInfo, getNumParams());
1901 ArrayRef<NamedDecl *> getDeclsInPrototypeScope() const {
1902 return DeclsInPrototypeScope;
1904 void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
1906 /// getMinRequiredArguments - Returns the minimum number of arguments
1907 /// needed to call this function. This may be fewer than the number of
1908 /// function parameters, if some of the parameters have default
1909 /// arguments (in C++).
1910 unsigned getMinRequiredArguments() const;
1912 QualType getReturnType() const {
1913 return getType()->getAs<FunctionType>()->getReturnType();
1916 /// \brief Attempt to compute an informative source range covering the
1917 /// function return type. This may omit qualifiers and other information with
1918 /// limited representation in the AST.
1919 SourceRange getReturnTypeSourceRange() const;
1921 /// \brief Determine the type of an expression that calls this function.
1922 QualType getCallResultType() const {
1923 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1926 /// \brief Returns the storage class as written in the source. For the
1927 /// computed linkage of symbol, see getLinkage.
1928 StorageClass getStorageClass() const { return StorageClass(SClass); }
1930 /// \brief Determine whether the "inline" keyword was specified for this
1932 bool isInlineSpecified() const { return IsInlineSpecified; }
1934 /// Set whether the "inline" keyword was specified for this function.
1935 void setInlineSpecified(bool I) {
1936 IsInlineSpecified = I;
1940 /// Flag that this function is implicitly inline.
1941 void setImplicitlyInline() {
1945 /// \brief Determine whether this function should be inlined, because it is
1946 /// either marked "inline" or "constexpr" or is a member function of a class
1947 /// that was defined in the class body.
1948 bool isInlined() const { return IsInline; }
1950 bool isInlineDefinitionExternallyVisible() const;
1952 bool isMSExternInline() const;
1954 bool doesDeclarationForceExternallyVisibleDefinition() const;
1956 /// isOverloadedOperator - Whether this function declaration
1957 /// represents an C++ overloaded operator, e.g., "operator+".
1958 bool isOverloadedOperator() const {
1959 return getOverloadedOperator() != OO_None;
1962 OverloadedOperatorKind getOverloadedOperator() const;
1964 const IdentifierInfo *getLiteralIdentifier() const;
1966 /// \brief If this function is an instantiation of a member function
1967 /// of a class template specialization, retrieves the function from
1968 /// which it was instantiated.
1970 /// This routine will return non-NULL for (non-templated) member
1971 /// functions of class templates and for instantiations of function
1972 /// templates. For example, given:
1975 /// template<typename T>
1981 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1982 /// whose parent is the class template specialization X<int>. For
1983 /// this declaration, getInstantiatedFromFunction() will return
1984 /// the FunctionDecl X<T>::A. When a complete definition of
1985 /// X<int>::A is required, it will be instantiated from the
1986 /// declaration returned by getInstantiatedFromMemberFunction().
1987 FunctionDecl *getInstantiatedFromMemberFunction() const;
1989 /// \brief What kind of templated function this is.
1990 TemplatedKind getTemplatedKind() const;
1992 /// \brief If this function is an instantiation of a member function of a
1993 /// class template specialization, retrieves the member specialization
1995 MemberSpecializationInfo *getMemberSpecializationInfo() const {
1996 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1999 /// \brief Specify that this record is an instantiation of the
2000 /// member function FD.
2001 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2002 TemplateSpecializationKind TSK) {
2003 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2006 /// \brief Retrieves the function template that is described by this
2007 /// function declaration.
2009 /// Every function template is represented as a FunctionTemplateDecl
2010 /// and a FunctionDecl (or something derived from FunctionDecl). The
2011 /// former contains template properties (such as the template
2012 /// parameter lists) while the latter contains the actual
2013 /// description of the template's
2014 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2015 /// FunctionDecl that describes the function template,
2016 /// getDescribedFunctionTemplate() retrieves the
2017 /// FunctionTemplateDecl from a FunctionDecl.
2018 FunctionTemplateDecl *getDescribedFunctionTemplate() const {
2019 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
2022 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
2023 TemplateOrSpecialization = Template;
2026 /// \brief Determine whether this function is a function template
2028 bool isFunctionTemplateSpecialization() const {
2029 return getPrimaryTemplate() != nullptr;
2032 /// \brief Retrieve the class scope template pattern that this function
2033 /// template specialization is instantiated from.
2034 FunctionDecl *getClassScopeSpecializationPattern() const;
2036 /// \brief If this function is actually a function template specialization,
2037 /// retrieve information about this function template specialization.
2038 /// Otherwise, returns NULL.
2039 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
2040 return TemplateOrSpecialization.
2041 dyn_cast<FunctionTemplateSpecializationInfo*>();
2044 /// \brief Determines whether this function is a function template
2045 /// specialization or a member of a class template specialization that can
2046 /// be implicitly instantiated.
2047 bool isImplicitlyInstantiable() const;
2049 /// \brief Determines if the given function was instantiated from a
2050 /// function template.
2051 bool isTemplateInstantiation() const;
2053 /// \brief Retrieve the function declaration from which this function could
2054 /// be instantiated, if it is an instantiation (rather than a non-template
2055 /// or a specialization, for example).
2056 FunctionDecl *getTemplateInstantiationPattern() const;
2058 /// \brief Retrieve the primary template that this function template
2059 /// specialization either specializes or was instantiated from.
2061 /// If this function declaration is not a function template specialization,
2063 FunctionTemplateDecl *getPrimaryTemplate() const;
2065 /// \brief Retrieve the template arguments used to produce this function
2066 /// template specialization from the primary template.
2068 /// If this function declaration is not a function template specialization,
2070 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2072 /// \brief Retrieve the template argument list as written in the sources,
2075 /// If this function declaration is not a function template specialization
2076 /// or if it had no explicit template argument list, returns NULL.
2077 /// Note that it an explicit template argument list may be written empty,
2078 /// e.g., template<> void foo<>(char* s);
2079 const ASTTemplateArgumentListInfo*
2080 getTemplateSpecializationArgsAsWritten() const;
2082 /// \brief Specify that this function declaration is actually a function
2083 /// template specialization.
2085 /// \param Template the function template that this function template
2086 /// specialization specializes.
2088 /// \param TemplateArgs the template arguments that produced this
2089 /// function template specialization from the template.
2091 /// \param InsertPos If non-NULL, the position in the function template
2092 /// specialization set where the function template specialization data will
2095 /// \param TSK the kind of template specialization this is.
2097 /// \param TemplateArgsAsWritten location info of template arguments.
2099 /// \param PointOfInstantiation point at which the function template
2100 /// specialization was first instantiated.
2101 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2102 const TemplateArgumentList *TemplateArgs,
2104 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2105 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2106 SourceLocation PointOfInstantiation = SourceLocation()) {
2107 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2108 InsertPos, TSK, TemplateArgsAsWritten,
2109 PointOfInstantiation);
2112 /// \brief Specifies that this function declaration is actually a
2113 /// dependent function template specialization.
2114 void setDependentTemplateSpecialization(ASTContext &Context,
2115 const UnresolvedSetImpl &Templates,
2116 const TemplateArgumentListInfo &TemplateArgs);
2118 DependentFunctionTemplateSpecializationInfo *
2119 getDependentSpecializationInfo() const {
2120 return TemplateOrSpecialization.
2121 dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
2124 /// \brief Determine what kind of template instantiation this function
2126 TemplateSpecializationKind getTemplateSpecializationKind() const;
2128 /// \brief Determine what kind of template instantiation this function
2130 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2131 SourceLocation PointOfInstantiation = SourceLocation());
2133 /// \brief Retrieve the (first) point of instantiation of a function template
2134 /// specialization or a member of a class template specialization.
2136 /// \returns the first point of instantiation, if this function was
2137 /// instantiated from a template; otherwise, returns an invalid source
2139 SourceLocation getPointOfInstantiation() const;
2141 /// \brief Determine whether this is or was instantiated from an out-of-line
2142 /// definition of a member function.
2143 bool isOutOfLine() const override;
2145 /// \brief Identify a memory copying or setting function.
2146 /// If the given function is a memory copy or setting function, returns
2147 /// the corresponding Builtin ID. If the function is not a memory function,
2149 unsigned getMemoryFunctionKind() const;
2151 // Implement isa/cast/dyncast/etc.
2152 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2153 static bool classofKind(Kind K) {
2154 return K >= firstFunction && K <= lastFunction;
2156 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2157 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2159 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2160 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2163 friend class ASTDeclReader;
2164 friend class ASTDeclWriter;
2168 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2169 /// represent a member of a struct/union/class.
2170 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2171 // FIXME: This can be packed into the bitfields in Decl.
2173 mutable unsigned CachedFieldIndex : 31;
2175 /// The kinds of value we can store in InitializerOrBitWidth.
2177 /// Note that this is compatible with InClassInitStyle except for
2178 /// ISK_CapturedVLAType.
2179 enum InitStorageKind {
2180 /// If the pointer is null, there's nothing special. Otherwise,
2181 /// this is a bitfield and the pointer is the Expr* storing the
2183 ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2185 /// The pointer is an (optional due to delayed parsing) Expr*
2186 /// holding the copy-initializer.
2187 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2189 /// The pointer is an (optional due to delayed parsing) Expr*
2190 /// holding the list-initializer.
2191 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2193 /// The pointer is a VariableArrayType* that's been captured;
2194 /// the enclosing context is a lambda or captured statement.
2195 ISK_CapturedVLAType,
2198 /// \brief Storage for either the bit-width, the in-class
2199 /// initializer, or the captured variable length array bound.
2201 /// We can safely combine these because in-class initializers are
2202 /// not permitted for bit-fields, and both are exclusive with VLA
2205 /// If the storage kind is ISK_InClassCopyInit or
2206 /// ISK_InClassListInit, but the initializer is null, then this
2207 /// field has an in-class initializer which has not yet been parsed
2209 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2211 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2212 SourceLocation IdLoc, IdentifierInfo *Id,
2213 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2214 InClassInitStyle InitStyle)
2215 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2216 Mutable(Mutable), CachedFieldIndex(0),
2217 InitStorage(BW, (InitStorageKind) InitStyle) {
2218 assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2222 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2223 SourceLocation StartLoc, SourceLocation IdLoc,
2224 IdentifierInfo *Id, QualType T,
2225 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2226 InClassInitStyle InitStyle);
2228 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2230 /// getFieldIndex - Returns the index of this field within its record,
2231 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2232 unsigned getFieldIndex() const;
2234 /// isMutable - Determines whether this field is mutable (C++ only).
2235 bool isMutable() const { return Mutable; }
2237 /// \brief Determines whether this field is a bitfield.
2238 bool isBitField() const {
2239 return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2240 InitStorage.getPointer() != nullptr;
2243 /// @brief Determines whether this is an unnamed bitfield.
2244 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2246 /// isAnonymousStructOrUnion - Determines whether this field is a
2247 /// representative for an anonymous struct or union. Such fields are
2248 /// unnamed and are implicitly generated by the implementation to
2249 /// store the data for the anonymous union or struct.
2250 bool isAnonymousStructOrUnion() const;
2252 Expr *getBitWidth() const {
2254 ? static_cast<Expr *>(InitStorage.getPointer())
2257 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2259 /// setBitWidth - Set the bit-field width for this member.
2260 // Note: used by some clients (i.e., do not remove it).
2261 void setBitWidth(Expr *Width) {
2262 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2263 InitStorage.getPointer() == nullptr &&
2264 "bit width, initializer or captured type already set");
2265 InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2268 /// removeBitWidth - Remove the bit-field width from this member.
2269 // Note: used by some clients (i.e., do not remove it).
2270 void removeBitWidth() {
2271 assert(isBitField() && "no bitfield width to remove");
2272 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2275 /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2277 InClassInitStyle getInClassInitStyle() const {
2278 InitStorageKind storageKind = InitStorage.getInt();
2279 return (storageKind == ISK_CapturedVLAType
2280 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2283 /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2285 bool hasInClassInitializer() const {
2286 return getInClassInitStyle() != ICIS_NoInit;
2289 /// getInClassInitializer - Get the C++11 in-class initializer for this
2290 /// member, or null if one has not been set. If a valid declaration has an
2291 /// in-class initializer, but this returns null, then we have not parsed and
2292 /// attached it yet.
2293 Expr *getInClassInitializer() const {
2294 return hasInClassInitializer()
2295 ? static_cast<Expr *>(InitStorage.getPointer())
2299 /// setInClassInitializer - Set the C++11 in-class initializer for this
2301 void setInClassInitializer(Expr *Init) {
2302 assert(hasInClassInitializer() &&
2303 InitStorage.getPointer() == nullptr &&
2304 "bit width, initializer or captured type already set");
2305 InitStorage.setPointer(Init);
2308 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2310 void removeInClassInitializer() {
2311 assert(hasInClassInitializer() && "no initializer to remove");
2312 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2315 /// \brief Determine whether this member captures the variable length array
2317 bool hasCapturedVLAType() const {
2318 return InitStorage.getInt() == ISK_CapturedVLAType;
2321 /// \brief Get the captured variable length array type.
2322 const VariableArrayType *getCapturedVLAType() const {
2323 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2324 InitStorage.getPointer())
2327 /// \brief Set the captured variable length array type for this field.
2328 void setCapturedVLAType(const VariableArrayType *VLAType);
2330 /// getParent - Returns the parent of this field declaration, which
2331 /// is the struct in which this method is defined.
2332 const RecordDecl *getParent() const {
2333 return cast<RecordDecl>(getDeclContext());
2336 RecordDecl *getParent() {
2337 return cast<RecordDecl>(getDeclContext());
2340 SourceRange getSourceRange() const override LLVM_READONLY;
2342 /// Retrieves the canonical declaration of this field.
2343 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2344 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2346 // Implement isa/cast/dyncast/etc.
2347 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2348 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2350 friend class ASTDeclReader;
2351 friend class ASTDeclWriter;
2354 /// EnumConstantDecl - An instance of this object exists for each enum constant
2355 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2356 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2357 /// TagType for the X EnumDecl.
2358 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2359 Stmt *Init; // an integer constant expression
2360 llvm::APSInt Val; // The value.
2362 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2363 IdentifierInfo *Id, QualType T, Expr *E,
2364 const llvm::APSInt &V)
2365 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2369 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2370 SourceLocation L, IdentifierInfo *Id,
2371 QualType T, Expr *E,
2372 const llvm::APSInt &V);
2373 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2375 const Expr *getInitExpr() const { return (const Expr*) Init; }
2376 Expr *getInitExpr() { return (Expr*) Init; }
2377 const llvm::APSInt &getInitVal() const { return Val; }
2379 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2380 void setInitVal(const llvm::APSInt &V) { Val = V; }
2382 SourceRange getSourceRange() const override LLVM_READONLY;
2384 /// Retrieves the canonical declaration of this enumerator.
2385 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2386 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2388 // Implement isa/cast/dyncast/etc.
2389 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2390 static bool classofKind(Kind K) { return K == EnumConstant; }
2392 friend class StmtIteratorBase;
2395 /// IndirectFieldDecl - An instance of this class is created to represent a
2396 /// field injected from an anonymous union/struct into the parent scope.
2397 /// IndirectFieldDecl are always implicit.
2398 class IndirectFieldDecl : public ValueDecl {
2399 void anchor() override;
2400 NamedDecl **Chaining;
2401 unsigned ChainingSize;
2403 IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2404 DeclarationName N, QualType T,
2405 NamedDecl **CH, unsigned CHS)
2406 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2409 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2410 SourceLocation L, IdentifierInfo *Id,
2411 QualType T, NamedDecl **CH, unsigned CHS);
2413 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2415 typedef NamedDecl * const *chain_iterator;
2416 typedef llvm::iterator_range<chain_iterator> chain_range;
2418 chain_range chain() const { return chain_range(chain_begin(), chain_end()); }
2419 chain_iterator chain_begin() const { return chain_iterator(Chaining); }
2420 chain_iterator chain_end() const {
2421 return chain_iterator(Chaining + ChainingSize);
2424 unsigned getChainingSize() const { return ChainingSize; }
2426 FieldDecl *getAnonField() const {
2427 assert(ChainingSize >= 2);
2428 return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2431 VarDecl *getVarDecl() const {
2432 assert(ChainingSize >= 2);
2433 return dyn_cast<VarDecl>(*chain_begin());
2436 // Implement isa/cast/dyncast/etc.
2437 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2438 static bool classofKind(Kind K) { return K == IndirectField; }
2439 friend class ASTDeclReader;
2442 /// TypeDecl - Represents a declaration of a type.
2444 class TypeDecl : public NamedDecl {
2445 void anchor() override;
2446 /// TypeForDecl - This indicates the Type object that represents
2447 /// this TypeDecl. It is a cache maintained by
2448 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2449 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2450 mutable const Type *TypeForDecl;
2451 /// LocStart - The start of the source range for this declaration.
2452 SourceLocation LocStart;
2453 friend class ASTContext;
2456 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2457 SourceLocation StartL = SourceLocation())
2458 : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2461 // Low-level accessor. If you just want the type defined by this node,
2462 // check out ASTContext::getTypeDeclType or one of
2463 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2464 // already know the specific kind of node this is.
2465 const Type *getTypeForDecl() const { return TypeForDecl; }
2466 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2468 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2469 void setLocStart(SourceLocation L) { LocStart = L; }
2470 SourceRange getSourceRange() const override LLVM_READONLY {
2471 if (LocStart.isValid())
2472 return SourceRange(LocStart, getLocation());
2474 return SourceRange(getLocation());
2477 // Implement isa/cast/dyncast/etc.
2478 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2479 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2483 /// Base class for declarations which introduce a typedef-name.
2484 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2485 void anchor() override;
2486 typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2487 llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2490 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2491 SourceLocation StartLoc, SourceLocation IdLoc,
2492 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2493 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2494 MaybeModedTInfo(TInfo) {}
2496 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2497 TypedefNameDecl *getNextRedeclarationImpl() override {
2498 return getNextRedeclaration();
2500 TypedefNameDecl *getPreviousDeclImpl() override {
2501 return getPreviousDecl();
2503 TypedefNameDecl *getMostRecentDeclImpl() override {
2504 return getMostRecentDecl();
2508 typedef redeclarable_base::redecl_range redecl_range;
2509 typedef redeclarable_base::redecl_iterator redecl_iterator;
2510 using redeclarable_base::redecls_begin;
2511 using redeclarable_base::redecls_end;
2512 using redeclarable_base::redecls;
2513 using redeclarable_base::getPreviousDecl;
2514 using redeclarable_base::getMostRecentDecl;
2515 using redeclarable_base::isFirstDecl;
2517 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2519 TypeSourceInfo *getTypeSourceInfo() const {
2521 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2522 : MaybeModedTInfo.get<TypeSourceInfo*>();
2524 QualType getUnderlyingType() const {
2526 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2527 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2529 void setTypeSourceInfo(TypeSourceInfo *newType) {
2530 MaybeModedTInfo = newType;
2532 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2533 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2536 /// Retrieves the canonical declaration of this typedef-name.
2537 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2538 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2540 // Implement isa/cast/dyncast/etc.
2541 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2542 static bool classofKind(Kind K) {
2543 return K >= firstTypedefName && K <= lastTypedefName;
2547 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2549 class TypedefDecl : public TypedefNameDecl {
2550 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2552 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2555 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2556 SourceLocation StartLoc, SourceLocation IdLoc,
2557 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2558 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2560 SourceRange getSourceRange() const override LLVM_READONLY;
2562 // Implement isa/cast/dyncast/etc.
2563 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2564 static bool classofKind(Kind K) { return K == Typedef; }
2567 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2568 /// alias-declaration.
2569 class TypeAliasDecl : public TypedefNameDecl {
2570 /// The template for which this is the pattern, if any.
2571 TypeAliasTemplateDecl *Template;
2573 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2574 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2575 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2576 Template(nullptr) {}
2579 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2580 SourceLocation StartLoc, SourceLocation IdLoc,
2581 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2582 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2584 SourceRange getSourceRange() const override LLVM_READONLY;
2586 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2587 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2589 // Implement isa/cast/dyncast/etc.
2590 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2591 static bool classofKind(Kind K) { return K == TypeAlias; }
2594 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2596 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2598 // This is really ugly.
2599 typedef TagTypeKind TagKind;
2602 // FIXME: This can be packed into the bitfields in Decl.
2603 /// TagDeclKind - The TagKind enum.
2604 unsigned TagDeclKind : 3;
2606 /// IsCompleteDefinition - True if this is a definition ("struct foo
2607 /// {};"), false if it is a declaration ("struct foo;"). It is not
2608 /// a definition until the definition has been fully processed.
2609 bool IsCompleteDefinition : 1;
2612 /// IsBeingDefined - True if this is currently being defined.
2613 bool IsBeingDefined : 1;
2616 /// IsEmbeddedInDeclarator - True if this tag declaration is
2617 /// "embedded" (i.e., defined or declared for the very first time)
2618 /// in the syntax of a declarator.
2619 bool IsEmbeddedInDeclarator : 1;
2621 /// \brief True if this tag is free standing, e.g. "struct foo;".
2622 bool IsFreeStanding : 1;
2625 // These are used by (and only defined for) EnumDecl.
2626 unsigned NumPositiveBits : 8;
2627 unsigned NumNegativeBits : 8;
2629 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2630 /// possible in C++11 mode.
2632 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2633 /// then this is true if the scoped enum was declared using the class
2634 /// tag, false if it was declared with the struct tag. No meaning is
2635 /// associated if this tag declaration is not a scoped enum.
2636 bool IsScopedUsingClassTag : 1;
2638 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2639 /// possible in C++11, Microsoft extensions, or Objective C mode.
2642 /// \brief Indicates whether it is possible for declarations of this kind
2643 /// to have an out-of-date definition.
2645 /// This option is only enabled when modules are enabled.
2646 bool MayHaveOutOfDateDef : 1;
2648 /// Has the full definition of this type been required by a use somewhere in
2650 bool IsCompleteDefinitionRequired : 1;
2652 SourceLocation RBraceLoc;
2654 // A struct representing syntactic qualifier info,
2655 // to be used for the (uncommon) case of out-of-line declarations.
2656 typedef QualifierInfo ExtInfo;
2658 /// \brief If the (out-of-line) tag declaration name
2659 /// is qualified, it points to the qualifier info (nns and range);
2660 /// otherwise, if the tag declaration is anonymous and it is part of
2661 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2662 /// otherwise, if the tag declaration is anonymous and it is used as a
2663 /// declaration specifier for variables, it points to the first VarDecl (used
2665 /// otherwise, it is a null (TypedefNameDecl) pointer.
2666 llvm::PointerUnion<NamedDecl *, ExtInfo *> NamedDeclOrQualifier;
2668 bool hasExtInfo() const { return NamedDeclOrQualifier.is<ExtInfo *>(); }
2669 ExtInfo *getExtInfo() { return NamedDeclOrQualifier.get<ExtInfo *>(); }
2670 const ExtInfo *getExtInfo() const {
2671 return NamedDeclOrQualifier.get<ExtInfo *>();
2675 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2676 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2677 SourceLocation StartL)
2678 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2679 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2680 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2681 IsCompleteDefinitionRequired(false),
2682 NamedDeclOrQualifier((NamedDecl *)nullptr) {
2683 assert((DK != Enum || TK == TTK_Enum) &&
2684 "EnumDecl not matched with TTK_Enum");
2685 setPreviousDecl(PrevDecl);
2688 typedef Redeclarable<TagDecl> redeclarable_base;
2689 TagDecl *getNextRedeclarationImpl() override {
2690 return getNextRedeclaration();
2692 TagDecl *getPreviousDeclImpl() override {
2693 return getPreviousDecl();
2695 TagDecl *getMostRecentDeclImpl() override {
2696 return getMostRecentDecl();
2699 /// @brief Completes the definition of this tag declaration.
2701 /// This is a helper function for derived classes.
2702 void completeDefinition();
2705 typedef redeclarable_base::redecl_range redecl_range;
2706 typedef redeclarable_base::redecl_iterator redecl_iterator;
2707 using redeclarable_base::redecls_begin;
2708 using redeclarable_base::redecls_end;
2709 using redeclarable_base::redecls;
2710 using redeclarable_base::getPreviousDecl;
2711 using redeclarable_base::getMostRecentDecl;
2712 using redeclarable_base::isFirstDecl;
2714 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2715 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2717 /// getInnerLocStart - Return SourceLocation representing start of source
2718 /// range ignoring outer template declarations.
2719 SourceLocation getInnerLocStart() const { return getLocStart(); }
2721 /// getOuterLocStart - Return SourceLocation representing start of source
2722 /// range taking into account any outer template declarations.
2723 SourceLocation getOuterLocStart() const;
2724 SourceRange getSourceRange() const override LLVM_READONLY;
2726 TagDecl *getCanonicalDecl() override;
2727 const TagDecl *getCanonicalDecl() const {
2728 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2731 /// isThisDeclarationADefinition() - Return true if this declaration
2732 /// is a completion definition of the type. Provided for consistency.
2733 bool isThisDeclarationADefinition() const {
2734 return isCompleteDefinition();
2737 /// isCompleteDefinition - Return true if this decl has its body
2738 /// fully specified.
2739 bool isCompleteDefinition() const {
2740 return IsCompleteDefinition;
2743 /// \brief Return true if this complete decl is
2744 /// required to be complete for some existing use.
2745 bool isCompleteDefinitionRequired() const {
2746 return IsCompleteDefinitionRequired;
2749 /// isBeingDefined - Return true if this decl is currently being defined.
2750 bool isBeingDefined() const {
2751 return IsBeingDefined;
2754 bool isEmbeddedInDeclarator() const {
2755 return IsEmbeddedInDeclarator;
2757 void setEmbeddedInDeclarator(bool isInDeclarator) {
2758 IsEmbeddedInDeclarator = isInDeclarator;
2761 bool isFreeStanding() const { return IsFreeStanding; }
2762 void setFreeStanding(bool isFreeStanding = true) {
2763 IsFreeStanding = isFreeStanding;
2766 /// \brief Whether this declaration declares a type that is
2767 /// dependent, i.e., a type that somehow depends on template
2769 bool isDependentType() const { return isDependentContext(); }
2771 /// @brief Starts the definition of this tag declaration.
2773 /// This method should be invoked at the beginning of the definition
2774 /// of this tag declaration. It will set the tag type into a state
2775 /// where it is in the process of being defined.
2776 void startDefinition();
2778 /// getDefinition - Returns the TagDecl that actually defines this
2779 /// struct/union/class/enum. When determining whether or not a
2780 /// struct/union/class/enum has a definition, one should use this
2781 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2782 /// whether or not a specific TagDecl is defining declaration, not
2783 /// whether or not the struct/union/class/enum type is defined.
2784 /// This method returns NULL if there is no TagDecl that defines
2785 /// the struct/union/class/enum.
2786 TagDecl *getDefinition() const;
2788 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2790 void setCompleteDefinitionRequired(bool V = true) {
2791 IsCompleteDefinitionRequired = V;
2794 StringRef getKindName() const {
2795 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2798 TagKind getTagKind() const {
2799 return TagKind(TagDeclKind);
2802 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2804 bool isStruct() const { return getTagKind() == TTK_Struct; }
2805 bool isInterface() const { return getTagKind() == TTK_Interface; }
2806 bool isClass() const { return getTagKind() == TTK_Class; }
2807 bool isUnion() const { return getTagKind() == TTK_Union; }
2808 bool isEnum() const { return getTagKind() == TTK_Enum; }
2810 /// Is this tag type named, either directly or via being defined in
2811 /// a typedef of this type?
2813 /// C++11 [basic.link]p8:
2814 /// A type is said to have linkage if and only if:
2815 /// - it is a class or enumeration type that is named (or has a
2816 /// name for linkage purposes) and the name has linkage; ...
2817 /// C++11 [dcl.typedef]p9:
2818 /// If the typedef declaration defines an unnamed class (or enum),
2819 /// the first typedef-name declared by the declaration to be that
2820 /// class type (or enum type) is used to denote the class type (or
2821 /// enum type) for linkage purposes only.
2823 /// C does not have an analogous rule, but the same concept is
2824 /// nonetheless useful in some places.
2825 bool hasNameForLinkage() const {
2826 return (getDeclName() || getTypedefNameForAnonDecl());
2829 bool hasDeclaratorForAnonDecl() const {
2830 return dyn_cast_or_null<DeclaratorDecl>(
2831 NamedDeclOrQualifier.get<NamedDecl *>());
2833 DeclaratorDecl *getDeclaratorForAnonDecl() const {
2834 return hasExtInfo() ? nullptr : dyn_cast_or_null<DeclaratorDecl>(
2835 NamedDeclOrQualifier.get<NamedDecl *>());
2838 TypedefNameDecl *getTypedefNameForAnonDecl() const {
2839 return hasExtInfo() ? nullptr : dyn_cast_or_null<TypedefNameDecl>(
2840 NamedDeclOrQualifier.get<NamedDecl *>());
2843 void setDeclaratorForAnonDecl(DeclaratorDecl *DD) { NamedDeclOrQualifier = DD; }
2845 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2847 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2848 /// declaration, if it was present in the source.
2849 NestedNameSpecifier *getQualifier() const {
2850 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2854 /// \brief Retrieve the nested-name-specifier (with source-location
2855 /// information) that qualifies the name of this declaration, if it was
2856 /// present in the source.
2857 NestedNameSpecifierLoc getQualifierLoc() const {
2858 return hasExtInfo() ? getExtInfo()->QualifierLoc
2859 : NestedNameSpecifierLoc();
2862 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2864 unsigned getNumTemplateParameterLists() const {
2865 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2867 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2868 assert(i < getNumTemplateParameterLists());
2869 return getExtInfo()->TemplParamLists[i];
2871 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2872 TemplateParameterList **TPLists);
2874 // Implement isa/cast/dyncast/etc.
2875 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2876 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2878 static DeclContext *castToDeclContext(const TagDecl *D) {
2879 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2881 static TagDecl *castFromDeclContext(const DeclContext *DC) {
2882 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2885 friend class ASTDeclReader;
2886 friend class ASTDeclWriter;
2889 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
2890 /// with a fixed underlying type, and in C we allow them to be forward-declared
2891 /// with no underlying type as an extension.
2892 class EnumDecl : public TagDecl {
2893 void anchor() override;
2894 /// IntegerType - This represent the integer type that the enum corresponds
2895 /// to for code generation purposes. Note that the enumerator constants may
2896 /// have a different type than this does.
2898 /// If the underlying integer type was explicitly stated in the source
2899 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2900 /// was automatically deduced somehow, and this is a Type*.
2902 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2903 /// some cases it won't.
2905 /// The underlying type of an enumeration never has any qualifiers, so
2906 /// we can get away with just storing a raw Type*, and thus save an
2907 /// extra pointer when TypeSourceInfo is needed.
2909 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2911 /// PromotionType - The integer type that values of this type should
2912 /// promote to. In C, enumerators are generally of an integer type
2913 /// directly, but gcc-style large enumerators (and all enumerators
2914 /// in C++) are of the enum type instead.
2915 QualType PromotionType;
2917 /// \brief If this enumeration is an instantiation of a member enumeration
2918 /// of a class template specialization, this is the member specialization
2920 MemberSpecializationInfo *SpecializationInfo;
2922 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2923 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
2924 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2925 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
2926 SpecializationInfo(nullptr) {
2927 assert(Scoped || !ScopedUsingClassTag);
2928 IntegerType = (const Type *)nullptr;
2929 NumNegativeBits = 0;
2930 NumPositiveBits = 0;
2932 IsScopedUsingClassTag = ScopedUsingClassTag;
2936 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2937 TemplateSpecializationKind TSK);
2939 EnumDecl *getCanonicalDecl() override {
2940 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2942 const EnumDecl *getCanonicalDecl() const {
2943 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
2946 EnumDecl *getPreviousDecl() {
2947 return cast_or_null<EnumDecl>(
2948 static_cast<TagDecl *>(this)->getPreviousDecl());
2950 const EnumDecl *getPreviousDecl() const {
2951 return const_cast<EnumDecl*>(this)->getPreviousDecl();
2954 EnumDecl *getMostRecentDecl() {
2955 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
2957 const EnumDecl *getMostRecentDecl() const {
2958 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
2961 EnumDecl *getDefinition() const {
2962 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2965 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2966 SourceLocation StartLoc, SourceLocation IdLoc,
2967 IdentifierInfo *Id, EnumDecl *PrevDecl,
2968 bool IsScoped, bool IsScopedUsingClassTag,
2970 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2972 /// completeDefinition - When created, the EnumDecl corresponds to a
2973 /// forward-declared enum. This method is used to mark the
2974 /// declaration as being defined; it's enumerators have already been
2975 /// added (via DeclContext::addDecl). NewType is the new underlying
2976 /// type of the enumeration type.
2977 void completeDefinition(QualType NewType,
2978 QualType PromotionType,
2979 unsigned NumPositiveBits,
2980 unsigned NumNegativeBits);
2982 // enumerator_iterator - Iterates through the enumerators of this
2984 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2985 typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
2988 enumerator_range enumerators() const {
2989 return enumerator_range(enumerator_begin(), enumerator_end());
2992 enumerator_iterator enumerator_begin() const {
2993 const EnumDecl *E = getDefinition();
2996 return enumerator_iterator(E->decls_begin());
2999 enumerator_iterator enumerator_end() const {
3000 const EnumDecl *E = getDefinition();
3003 return enumerator_iterator(E->decls_end());
3006 /// getPromotionType - Return the integer type that enumerators
3007 /// should promote to.
3008 QualType getPromotionType() const { return PromotionType; }
3010 /// \brief Set the promotion type.
3011 void setPromotionType(QualType T) { PromotionType = T; }
3013 /// getIntegerType - Return the integer type this enum decl corresponds to.
3014 /// This returns a null QualType for an enum forward definition with no fixed
3015 /// underlying type.
3016 QualType getIntegerType() const {
3019 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3020 return QualType(T, 0);
3021 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3024 /// \brief Set the underlying integer type.
3025 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3027 /// \brief Set the underlying integer type source info.
3028 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3030 /// \brief Return the type source info for the underlying integer type,
3031 /// if no type source info exists, return 0.
3032 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3033 return IntegerType.dyn_cast<TypeSourceInfo*>();
3036 /// \brief Retrieve the source range that covers the underlying type if
3038 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3040 /// \brief Returns the width in bits required to store all the
3041 /// non-negative enumerators of this enum.
3042 unsigned getNumPositiveBits() const {
3043 return NumPositiveBits;
3045 void setNumPositiveBits(unsigned Num) {
3046 NumPositiveBits = Num;
3047 assert(NumPositiveBits == Num && "can't store this bitcount");
3050 /// \brief Returns the width in bits required to store all the
3051 /// negative enumerators of this enum. These widths include
3052 /// the rightmost leading 1; that is:
3054 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3055 /// ------------------------ ------- -----------------
3059 unsigned getNumNegativeBits() const {
3060 return NumNegativeBits;
3062 void setNumNegativeBits(unsigned Num) {
3063 NumNegativeBits = Num;
3066 /// \brief Returns true if this is a C++11 scoped enumeration.
3067 bool isScoped() const {
3071 /// \brief Returns true if this is a C++11 scoped enumeration.
3072 bool isScopedUsingClassTag() const {
3073 return IsScopedUsingClassTag;
3076 /// \brief Returns true if this is an Objective-C, C++11, or
3077 /// Microsoft-style enumeration with a fixed underlying type.
3078 bool isFixed() const {
3082 /// \brief Returns true if this can be considered a complete type.
3083 bool isComplete() const {
3084 return isCompleteDefinition() || isFixed();
3087 /// \brief Returns the enumeration (declared within the template)
3088 /// from which this enumeration type was instantiated, or NULL if
3089 /// this enumeration was not instantiated from any template.
3090 EnumDecl *getInstantiatedFromMemberEnum() const;
3092 /// \brief If this enumeration is a member of a specialization of a
3093 /// templated class, determine what kind of template specialization
3094 /// or instantiation this is.
3095 TemplateSpecializationKind getTemplateSpecializationKind() const;
3097 /// \brief For an enumeration member that was instantiated from a member
3098 /// enumeration of a templated class, set the template specialiation kind.
3099 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3100 SourceLocation PointOfInstantiation = SourceLocation());
3102 /// \brief If this enumeration is an instantiation of a member enumeration of
3103 /// a class template specialization, retrieves the member specialization
3105 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3106 return SpecializationInfo;
3109 /// \brief Specify that this enumeration is an instantiation of the
3110 /// member enumeration ED.
3111 void setInstantiationOfMemberEnum(EnumDecl *ED,
3112 TemplateSpecializationKind TSK) {
3113 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3116 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3117 static bool classofKind(Kind K) { return K == Enum; }
3119 friend class ASTDeclReader;
3123 /// RecordDecl - Represents a struct/union/class. For example:
3124 /// struct X; // Forward declaration, no "body".
3125 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3126 /// This decl will be marked invalid if *any* members are invalid.
3128 class RecordDecl : public TagDecl {
3129 // FIXME: This can be packed into the bitfields in Decl.
3130 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3131 /// array member (e.g. int X[]) or if this union contains a struct that does.
3132 /// If so, this cannot be contained in arrays or other structs as a member.
3133 bool HasFlexibleArrayMember : 1;
3135 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3137 bool AnonymousStructOrUnion : 1;
3139 /// HasObjectMember - This is true if this struct has at least one member
3140 /// containing an Objective-C object pointer type.
3141 bool HasObjectMember : 1;
3143 /// HasVolatileMember - This is true if struct has at least one member of
3144 /// 'volatile' type.
3145 bool HasVolatileMember : 1;
3147 /// \brief Whether the field declarations of this record have been loaded
3148 /// from external storage. To avoid unnecessary deserialization of
3149 /// methods/nested types we allow deserialization of just the fields
3151 mutable bool LoadedFieldsFromExternalStorage : 1;
3152 friend class DeclContext;
3155 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3156 SourceLocation StartLoc, SourceLocation IdLoc,
3157 IdentifierInfo *Id, RecordDecl *PrevDecl);
3160 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3161 SourceLocation StartLoc, SourceLocation IdLoc,
3162 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3163 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3165 RecordDecl *getPreviousDecl() {
3166 return cast_or_null<RecordDecl>(
3167 static_cast<TagDecl *>(this)->getPreviousDecl());
3169 const RecordDecl *getPreviousDecl() const {
3170 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3173 RecordDecl *getMostRecentDecl() {
3174 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3176 const RecordDecl *getMostRecentDecl() const {
3177 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3180 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3181 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3183 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3184 /// or union. To be an anonymous struct or union, it must have been
3185 /// declared without a name and there must be no objects of this
3186 /// type declared, e.g.,
3188 /// union { int i; float f; };
3190 /// is an anonymous union but neither of the following are:
3192 /// union X { int i; float f; };
3193 /// union { int i; float f; } obj;
3195 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3196 void setAnonymousStructOrUnion(bool Anon) {
3197 AnonymousStructOrUnion = Anon;
3200 bool hasObjectMember() const { return HasObjectMember; }
3201 void setHasObjectMember (bool val) { HasObjectMember = val; }
3203 bool hasVolatileMember() const { return HasVolatileMember; }
3204 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3206 /// \brief Determines whether this declaration represents the
3207 /// injected class name.
3209 /// The injected class name in C++ is the name of the class that
3210 /// appears inside the class itself. For example:
3214 /// // C is implicitly declared here as a synonym for the class name.
3217 /// C::C c; // same as "C c;"
3219 bool isInjectedClassName() const;
3221 /// \brief Determine whether this record is a class describing a lambda
3222 /// function object.
3223 bool isLambda() const;
3225 /// \brief Determine whether this record is a record for captured variables in
3226 /// CapturedStmt construct.
3227 bool isCapturedRecord() const;
3228 /// \brief Mark the record as a record for captured variables in CapturedStmt
3230 void setCapturedRecord();
3232 /// getDefinition - Returns the RecordDecl that actually defines
3233 /// this struct/union/class. When determining whether or not a
3234 /// struct/union/class is completely defined, one should use this
3235 /// method as opposed to 'isCompleteDefinition'.
3236 /// 'isCompleteDefinition' indicates whether or not a specific
3237 /// RecordDecl is a completed definition, not whether or not the
3238 /// record type is defined. This method returns NULL if there is
3239 /// no RecordDecl that defines the struct/union/tag.
3240 RecordDecl *getDefinition() const {
3241 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3244 // Iterator access to field members. The field iterator only visits
3245 // the non-static data members of this class, ignoring any static
3246 // data members, functions, constructors, destructors, etc.
3247 typedef specific_decl_iterator<FieldDecl> field_iterator;
3248 typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3250 field_range fields() const { return field_range(field_begin(), field_end()); }
3251 field_iterator field_begin() const;
3253 field_iterator field_end() const {
3254 return field_iterator(decl_iterator());
3257 // field_empty - Whether there are any fields (non-static data
3258 // members) in this record.
3259 bool field_empty() const {
3260 return field_begin() == field_end();
3263 /// completeDefinition - Notes that the definition of this type is
3265 virtual void completeDefinition();
3267 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3268 static bool classofKind(Kind K) {
3269 return K >= firstRecord && K <= lastRecord;
3272 /// isMsStrust - Get whether or not this is an ms_struct which can
3273 /// be turned on with an attribute, pragma, or -mms-bitfields
3274 /// commandline option.
3275 bool isMsStruct(const ASTContext &C) const;
3277 /// \brief Whether we are allowed to insert extra padding between fields.
3278 /// These padding are added to help AddressSanitizer detect
3279 /// intra-object-overflow bugs.
3280 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3282 /// Finds the first data member which has a name.
3283 /// nullptr is returned if no named data member exists.
3284 const FieldDecl *findFirstNamedDataMember() const;
3287 /// \brief Deserialize just the fields.
3288 void LoadFieldsFromExternalStorage() const;
3291 class FileScopeAsmDecl : public Decl {
3292 virtual void anchor();
3293 StringLiteral *AsmString;
3294 SourceLocation RParenLoc;
3295 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3296 SourceLocation StartL, SourceLocation EndL)
3297 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3299 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3300 StringLiteral *Str, SourceLocation AsmLoc,
3301 SourceLocation RParenLoc);
3303 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3305 SourceLocation getAsmLoc() const { return getLocation(); }
3306 SourceLocation getRParenLoc() const { return RParenLoc; }
3307 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3308 SourceRange getSourceRange() const override LLVM_READONLY {
3309 return SourceRange(getAsmLoc(), getRParenLoc());
3312 const StringLiteral *getAsmString() const { return AsmString; }
3313 StringLiteral *getAsmString() { return AsmString; }
3314 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3316 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3317 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3320 /// BlockDecl - This represents a block literal declaration, which is like an
3321 /// unnamed FunctionDecl. For example:
3322 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3324 class BlockDecl : public Decl, public DeclContext {
3326 /// A class which contains all the information about a particular
3334 /// The variable being captured.
3335 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3337 /// The copy expression, expressed in terms of a DeclRef (or
3338 /// BlockDeclRef) to the captured variable. Only required if the
3339 /// variable has a C++ class type.
3343 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3344 : VariableAndFlags(variable,
3345 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3348 /// The variable being captured.
3349 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3351 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3353 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3355 /// Whether this is a nested capture, i.e. the variable captured
3356 /// is not from outside the immediately enclosing function/block.
3357 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3359 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3360 Expr *getCopyExpr() const { return CopyExpr; }
3361 void setCopyExpr(Expr *e) { CopyExpr = e; }
3365 // FIXME: This can be packed into the bitfields in Decl.
3366 bool IsVariadic : 1;
3367 bool CapturesCXXThis : 1;
3368 bool BlockMissingReturnType : 1;
3369 bool IsConversionFromLambda : 1;
3370 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3371 /// parameters of this function. This is null if a prototype or if there are
3373 ParmVarDecl **ParamInfo;
3377 TypeSourceInfo *SignatureAsWritten;
3380 unsigned NumCaptures;
3382 unsigned ManglingNumber;
3383 Decl *ManglingContextDecl;
3386 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3387 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3388 IsVariadic(false), CapturesCXXThis(false),
3389 BlockMissingReturnType(true), IsConversionFromLambda(false),
3390 ParamInfo(nullptr), NumParams(0), Body(nullptr),
3391 SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3392 ManglingNumber(0), ManglingContextDecl(nullptr) {}
3395 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3396 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3398 SourceLocation getCaretLocation() const { return getLocation(); }
3400 bool isVariadic() const { return IsVariadic; }
3401 void setIsVariadic(bool value) { IsVariadic = value; }
3403 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3404 Stmt *getBody() const override { return (Stmt*) Body; }
3405 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3407 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3408 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3410 // Iterator access to formal parameters.
3411 unsigned param_size() const { return getNumParams(); }
3412 typedef ParmVarDecl **param_iterator;
3413 typedef ParmVarDecl * const *param_const_iterator;
3414 typedef llvm::iterator_range<param_iterator> param_range;
3415 typedef llvm::iterator_range<param_const_iterator> param_const_range;
3417 // ArrayRef access to formal parameters.
3418 // FIXME: Should eventual replace iterator access.
3419 ArrayRef<ParmVarDecl*> parameters() const {
3420 return llvm::makeArrayRef(ParamInfo, param_size());
3423 bool param_empty() const { return NumParams == 0; }
3424 param_range params() { return param_range(param_begin(), param_end()); }
3425 param_iterator param_begin() { return param_iterator(ParamInfo); }
3426 param_iterator param_end() {
3427 return param_iterator(ParamInfo + param_size());
3430 param_const_range params() const {
3431 return param_const_range(param_begin(), param_end());
3433 param_const_iterator param_begin() const {
3434 return param_const_iterator(ParamInfo);
3436 param_const_iterator param_end() const {
3437 return param_const_iterator(ParamInfo + param_size());
3440 unsigned getNumParams() const { return NumParams; }
3441 const ParmVarDecl *getParamDecl(unsigned i) const {
3442 assert(i < getNumParams() && "Illegal param #");
3443 return ParamInfo[i];
3445 ParmVarDecl *getParamDecl(unsigned i) {
3446 assert(i < getNumParams() && "Illegal param #");
3447 return ParamInfo[i];
3449 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3451 /// hasCaptures - True if this block (or its nested blocks) captures
3452 /// anything of local storage from its enclosing scopes.
3453 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3455 /// getNumCaptures - Returns the number of captured variables.
3456 /// Does not include an entry for 'this'.
3457 unsigned getNumCaptures() const { return NumCaptures; }
3459 typedef const Capture *capture_iterator;
3460 typedef const Capture *capture_const_iterator;
3461 typedef llvm::iterator_range<capture_iterator> capture_range;
3462 typedef llvm::iterator_range<capture_const_iterator> capture_const_range;
3464 capture_range captures() {
3465 return capture_range(capture_begin(), capture_end());
3467 capture_const_range captures() const {
3468 return capture_const_range(capture_begin(), capture_end());
3471 capture_iterator capture_begin() { return Captures; }
3472 capture_iterator capture_end() { return Captures + NumCaptures; }
3473 capture_const_iterator capture_begin() const { return Captures; }
3474 capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3476 bool capturesCXXThis() const { return CapturesCXXThis; }
3477 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3478 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3480 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3481 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3483 bool capturesVariable(const VarDecl *var) const;
3485 void setCaptures(ASTContext &Context,
3486 const Capture *begin,
3488 bool capturesCXXThis);
3490 unsigned getBlockManglingNumber() const {
3491 return ManglingNumber;
3493 Decl *getBlockManglingContextDecl() const {
3494 return ManglingContextDecl;
3497 void setBlockMangling(unsigned Number, Decl *Ctx) {
3498 ManglingNumber = Number;
3499 ManglingContextDecl = Ctx;
3502 SourceRange getSourceRange() const override LLVM_READONLY;
3504 // Implement isa/cast/dyncast/etc.
3505 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3506 static bool classofKind(Kind K) { return K == Block; }
3507 static DeclContext *castToDeclContext(const BlockDecl *D) {
3508 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3510 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3511 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3515 /// \brief This represents the body of a CapturedStmt, and serves as its
3517 class CapturedDecl : public Decl, public DeclContext {
3519 /// \brief The number of parameters to the outlined function.
3521 /// \brief The position of context parameter in list of parameters.
3522 unsigned ContextParam;
3523 /// \brief The body of the outlined function.
3524 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3526 explicit CapturedDecl(DeclContext *DC, unsigned NumParams)
3527 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
3528 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) { }
3530 ImplicitParamDecl **getParams() const {
3531 return reinterpret_cast<ImplicitParamDecl **>(
3532 const_cast<CapturedDecl *>(this) + 1);
3536 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3537 unsigned NumParams);
3538 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3539 unsigned NumParams);
3541 Stmt *getBody() const override { return BodyAndNothrow.getPointer(); }
3542 void setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
3544 bool isNothrow() const { return BodyAndNothrow.getInt(); }
3545 void setNothrow(bool Nothrow = true) { BodyAndNothrow.setInt(Nothrow); }
3547 unsigned getNumParams() const { return NumParams; }
3549 ImplicitParamDecl *getParam(unsigned i) const {
3550 assert(i < NumParams);
3551 return getParams()[i];
3553 void setParam(unsigned i, ImplicitParamDecl *P) {
3554 assert(i < NumParams);
3558 /// \brief Retrieve the parameter containing captured variables.
3559 ImplicitParamDecl *getContextParam() const {
3560 assert(ContextParam < NumParams);
3561 return getParam(ContextParam);
3563 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3564 assert(i < NumParams);
3568 unsigned getContextParamPosition() const { return ContextParam; }
3570 typedef ImplicitParamDecl **param_iterator;
3571 typedef llvm::iterator_range<param_iterator> param_range;
3573 /// \brief Retrieve an iterator pointing to the first parameter decl.
3574 param_iterator param_begin() const { return getParams(); }
3575 /// \brief Retrieve an iterator one past the last parameter decl.
3576 param_iterator param_end() const { return getParams() + NumParams; }
3578 /// \brief Retrieve an iterator range for the parameter declarations.
3579 param_range params() const { return param_range(param_begin(), param_end()); }
3581 // Implement isa/cast/dyncast/etc.
3582 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3583 static bool classofKind(Kind K) { return K == Captured; }
3584 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3585 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3587 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3588 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3591 friend class ASTDeclReader;
3592 friend class ASTDeclWriter;
3595 /// \brief Describes a module import declaration, which makes the contents
3596 /// of the named module visible in the current translation unit.
3598 /// An import declaration imports the named module (or submodule). For example:
3600 /// @import std.vector;
3603 /// Import declarations can also be implicitly generated from
3604 /// \#include/\#import directives.
3605 class ImportDecl : public Decl {
3606 /// \brief The imported module, along with a bit that indicates whether
3607 /// we have source-location information for each identifier in the module
3610 /// When the bit is false, we only have a single source location for the
3611 /// end of the import declaration.
3612 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3614 /// \brief The next import in the list of imports local to the translation
3615 /// unit being parsed (not loaded from an AST file).
3616 ImportDecl *NextLocalImport;
3618 friend class ASTReader;
3619 friend class ASTDeclReader;
3620 friend class ASTContext;
3622 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3623 ArrayRef<SourceLocation> IdentifierLocs);
3625 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3626 SourceLocation EndLoc);
3628 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3631 /// \brief Create a new module import declaration.
3632 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3633 SourceLocation StartLoc, Module *Imported,
3634 ArrayRef<SourceLocation> IdentifierLocs);
3636 /// \brief Create a new module import declaration for an implicitly-generated
3638 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3639 SourceLocation StartLoc, Module *Imported,
3640 SourceLocation EndLoc);
3642 /// \brief Create a new, deserialized module import declaration.
3643 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3644 unsigned NumLocations);
3646 /// \brief Retrieve the module that was imported by the import declaration.
3647 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3649 /// \brief Retrieves the locations of each of the identifiers that make up
3650 /// the complete module name in the import declaration.
3652 /// This will return an empty array if the locations of the individual
3653 /// identifiers aren't available.
3654 ArrayRef<SourceLocation> getIdentifierLocs() const;
3656 SourceRange getSourceRange() const override LLVM_READONLY;
3658 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3659 static bool classofKind(Kind K) { return K == Import; }
3662 /// \brief Represents an empty-declaration.
3663 class EmptyDecl : public Decl {
3664 virtual void anchor();
3665 EmptyDecl(DeclContext *DC, SourceLocation L)
3666 : Decl(Empty, DC, L) { }
3669 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3671 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3673 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3674 static bool classofKind(Kind K) { return K == Empty; }
3677 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3678 /// into a diagnostic with <<.
3679 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3680 const NamedDecl* ND) {
3681 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3682 DiagnosticsEngine::ak_nameddecl);
3685 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3686 const NamedDecl* ND) {
3687 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3688 DiagnosticsEngine::ak_nameddecl);
3692 template<typename decl_type>
3693 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3694 // Note: This routine is implemented here because we need both NamedDecl
3695 // and Redeclarable to be defined.
3696 assert(RedeclLink.NextIsLatest() &&
3697 "setPreviousDecl on a decl already in a redeclaration chain");
3702 // Point to previous. Make sure that this is actually the most recent
3703 // redeclaration, or we can build invalid chains. If the most recent
3704 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3705 First = PrevDecl->getFirstDecl();
3706 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3707 decl_type *MostRecent = First->getNextRedeclaration();
3708 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3710 // If the declaration was previously visible, a redeclaration of it remains
3711 // visible even if it wouldn't be visible by itself.
3712 static_cast<decl_type*>(this)->IdentifierNamespace |=
3713 MostRecent->getIdentifierNamespace() &
3714 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3717 First = static_cast<decl_type*>(this);
3720 // First one will point to this one as latest.
3721 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3723 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3724 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3727 // Inline function definitions.
3729 /// \brief Check if the given decl is complete.
3731 /// We use this function to break a cycle between the inline definitions in
3732 /// Type.h and Decl.h.
3733 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3734 return ED->isComplete();
3737 /// \brief Check if the given decl is scoped.
3739 /// We use this function to break a cycle between the inline definitions in
3740 /// Type.h and Decl.h.
3741 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3742 return ED->isScoped();
3745 } // end namespace clang