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/Module.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PragmaKinds.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/TrailingObjects.h"
34 struct ASTTemplateArgumentListInfo;
37 class DependentFunctionTemplateSpecializationInfo;
39 class FunctionTemplateDecl;
40 class FunctionTemplateSpecializationInfo;
42 class MemberSpecializationInfo;
43 class NestedNameSpecifier;
47 class TemplateArgumentList;
48 class TemplateParameterList;
49 class TypeAliasTemplateDecl;
51 class UnresolvedSetImpl;
52 class VarTemplateDecl;
54 /// \brief A container of type source information.
56 /// A client can read the relevant info using TypeLoc wrappers, e.g:
58 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
59 /// TL.getStartLoc().print(OS, SrcMgr);
62 class TypeSourceInfo {
64 // Contains a memory block after the class, used for type source information,
65 // allocated by ASTContext.
66 friend class ASTContext;
67 TypeSourceInfo(QualType ty) : Ty(ty) { }
69 /// \brief Return the type wrapped by this type source info.
70 QualType getType() const { return Ty; }
72 /// \brief Return the TypeLoc wrapper for the type source info.
73 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
75 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
76 void overrideType(QualType T) { Ty = T; }
79 /// TranslationUnitDecl - The top declaration context.
80 class TranslationUnitDecl : public Decl, public DeclContext {
81 virtual void anchor();
84 /// The (most recently entered) anonymous namespace for this
85 /// translation unit, if one has been created.
86 NamespaceDecl *AnonymousNamespace;
88 explicit TranslationUnitDecl(ASTContext &ctx);
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 /// \brief Represents a `#pragma comment` line. Always a child of
108 /// TranslationUnitDecl.
109 class PragmaCommentDecl final
111 private llvm::TrailingObjects<PragmaCommentDecl, char> {
112 virtual void anchor();
114 PragmaMSCommentKind CommentKind;
116 friend TrailingObjects;
117 friend class ASTDeclReader;
118 friend class ASTDeclWriter;
120 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
121 PragmaMSCommentKind CommentKind)
122 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
125 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
126 SourceLocation CommentLoc,
127 PragmaMSCommentKind CommentKind,
129 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
132 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
134 StringRef getArg() const { return getTrailingObjects<char>(); }
136 // Implement isa/cast/dyncast/etc.
137 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
138 static bool classofKind(Kind K) { return K == PragmaComment; }
141 /// \brief Represents a `#pragma detect_mismatch` line. Always a child of
142 /// TranslationUnitDecl.
143 class PragmaDetectMismatchDecl final
145 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
146 virtual void anchor();
150 friend TrailingObjects;
151 friend class ASTDeclReader;
152 friend class ASTDeclWriter;
154 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
156 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
159 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
160 TranslationUnitDecl *DC,
161 SourceLocation Loc, StringRef Name,
163 static PragmaDetectMismatchDecl *
164 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
166 StringRef getName() const { return getTrailingObjects<char>(); }
167 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
169 // Implement isa/cast/dyncast/etc.
170 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
171 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
174 /// \brief Declaration context for names declared as extern "C" in C++. This
175 /// is neither the semantic nor lexical context for such declarations, but is
176 /// used to check for conflicts with other extern "C" declarations. Example:
179 /// namespace N { extern "C" void f(); } // #1
180 /// void N::f() {} // #2
181 /// namespace M { extern "C" void f(); } // #3
184 /// The semantic context of #1 is namespace N and its lexical context is the
185 /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
186 /// context is the TU. However, both declarations are also visible in the
187 /// extern "C" context.
189 /// The declaration at #3 finds it is a redeclaration of \c N::f through
190 /// lookup in the extern "C" context.
191 class ExternCContextDecl : public Decl, public DeclContext {
192 virtual void anchor();
194 explicit ExternCContextDecl(TranslationUnitDecl *TU)
195 : Decl(ExternCContext, TU, SourceLocation()),
196 DeclContext(ExternCContext) {}
198 static ExternCContextDecl *Create(const ASTContext &C,
199 TranslationUnitDecl *TU);
200 // Implement isa/cast/dyncast/etc.
201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
202 static bool classofKind(Kind K) { return K == ExternCContext; }
203 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
204 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
206 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
207 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
211 /// NamedDecl - This represents a decl with a name. Many decls have names such
212 /// as ObjCMethodDecl, but not \@class, etc.
213 class NamedDecl : public Decl {
214 virtual void anchor();
215 /// Name - The name of this declaration, which is typically a normal
216 /// identifier but may also be a special kind of name (C++
217 /// constructor, Objective-C selector, etc.)
218 DeclarationName Name;
221 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
224 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
225 : Decl(DK, DC, L), Name(N) { }
228 /// getIdentifier - Get the identifier that names this declaration,
229 /// if there is one. This will return NULL if this declaration has
230 /// no name (e.g., for an unnamed class) or if the name is a special
231 /// name (C++ constructor, Objective-C selector, etc.).
232 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
234 /// getName - Get the name of identifier for this declaration as a StringRef.
235 /// This requires that the declaration have a name and that it be a simple
237 StringRef getName() const {
238 assert(Name.isIdentifier() && "Name is not a simple identifier");
239 return getIdentifier() ? getIdentifier()->getName() : "";
242 /// getNameAsString - Get a human-readable name for the declaration, even if
243 /// it is one of the special kinds of names (C++ constructor, Objective-C
244 /// selector, etc). Creating this name requires expensive string
245 /// manipulation, so it should be called only when performance doesn't matter.
246 /// For simple declarations, getNameAsCString() should suffice.
248 // FIXME: This function should be renamed to indicate that it is not just an
249 // alternate form of getName(), and clients should move as appropriate.
251 // FIXME: Deprecated, move clients to getName().
252 std::string getNameAsString() const { return Name.getAsString(); }
254 virtual void printName(raw_ostream &os) const;
256 /// getDeclName - Get the actual, stored name of the declaration,
257 /// which may be a special name.
258 DeclarationName getDeclName() const { return Name; }
260 /// \brief Set the name of this declaration.
261 void setDeclName(DeclarationName N) { Name = N; }
263 /// printQualifiedName - Returns human-readable qualified name for
264 /// declaration, like A::B::i, for i being member of namespace A::B.
265 /// If declaration is not member of context which can be named (record,
266 /// namespace), it will return same result as printName().
267 /// Creating this name is expensive, so it should be called only when
268 /// performance doesn't matter.
269 void printQualifiedName(raw_ostream &OS) const;
270 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
272 // FIXME: Remove string version.
273 std::string getQualifiedNameAsString() const;
275 /// getNameForDiagnostic - Appends a human-readable name for this
276 /// declaration into the given stream.
278 /// This is the method invoked by Sema when displaying a NamedDecl
279 /// in a diagnostic. It does not necessarily produce the same
280 /// result as printName(); for example, class template
281 /// specializations are printed with their template arguments.
282 virtual void getNameForDiagnostic(raw_ostream &OS,
283 const PrintingPolicy &Policy,
284 bool Qualified) const;
286 /// \brief Determine whether this declaration, if
287 /// known to be well-formed within its context, will replace the
288 /// declaration OldD if introduced into scope. A declaration will
289 /// replace another declaration if, for example, it is a
290 /// redeclaration of the same variable or function, but not if it is
291 /// a declaration of a different kind (function vs. class) or an
292 /// overloaded function.
294 /// \param IsKnownNewer \c true if this declaration is known to be newer
295 /// than \p OldD (for instance, if this declaration is newly-created).
296 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
298 /// \brief Determine whether this declaration has linkage.
299 bool hasLinkage() const;
301 using Decl::isModulePrivate;
302 using Decl::setModulePrivate;
304 /// \brief Determine whether this declaration is a C++ class member.
305 bool isCXXClassMember() const {
306 const DeclContext *DC = getDeclContext();
308 // C++0x [class.mem]p1:
309 // The enumerators of an unscoped enumeration defined in
310 // the class are members of the class.
311 if (isa<EnumDecl>(DC))
312 DC = DC->getRedeclContext();
314 return DC->isRecord();
317 /// \brief Determine whether the given declaration is an instance member of
319 bool isCXXInstanceMember() const;
321 /// \brief Determine what kind of linkage this entity has.
322 /// This is not the linkage as defined by the standard or the codegen notion
323 /// of linkage. It is just an implementation detail that is used to compute
325 Linkage getLinkageInternal() const;
327 /// \brief Get the linkage from a semantic point of view. Entities in
328 /// anonymous namespaces are external (in c++98).
329 Linkage getFormalLinkage() const {
330 return clang::getFormalLinkage(getLinkageInternal());
333 /// \brief True if this decl has external linkage.
334 bool hasExternalFormalLinkage() const {
335 return isExternalFormalLinkage(getLinkageInternal());
338 bool isExternallyVisible() const {
339 return clang::isExternallyVisible(getLinkageInternal());
342 /// \brief Determines the visibility of this entity.
343 Visibility getVisibility() const {
344 return getLinkageAndVisibility().getVisibility();
347 /// \brief Determines the linkage and visibility of this entity.
348 LinkageInfo getLinkageAndVisibility() const;
350 /// Kinds of explicit visibility.
351 enum ExplicitVisibilityKind {
356 /// \brief If visibility was explicitly specified for this
357 /// declaration, return that visibility.
359 getExplicitVisibility(ExplicitVisibilityKind kind) const;
361 /// \brief True if the computed linkage is valid. Used for consistency
362 /// checking. Should always return true.
363 bool isLinkageValid() const;
365 /// \brief True if something has required us to compute the linkage
366 /// of this declaration.
368 /// Language features which can retroactively change linkage (like a
369 /// typedef name for linkage purposes) may need to consider this,
370 /// but hopefully only in transitory ways during parsing.
371 bool hasLinkageBeenComputed() const {
372 return hasCachedLinkage();
375 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
376 /// the underlying named decl.
377 NamedDecl *getUnderlyingDecl() {
378 // Fast-path the common case.
379 if (this->getKind() != UsingShadow &&
380 this->getKind() != ConstructorUsingShadow &&
381 this->getKind() != ObjCCompatibleAlias &&
382 this->getKind() != NamespaceAlias)
385 return getUnderlyingDeclImpl();
387 const NamedDecl *getUnderlyingDecl() const {
388 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
391 NamedDecl *getMostRecentDecl() {
392 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
394 const NamedDecl *getMostRecentDecl() const {
395 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
398 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
400 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
401 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
404 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
409 /// LabelDecl - Represents the declaration of a label. Labels also have a
410 /// corresponding LabelStmt, which indicates the position that the label was
411 /// defined at. For normal labels, the location of the decl is the same as the
412 /// location of the statement. For GNU local labels (__label__), the decl
413 /// location is where the __label__ is.
414 class LabelDecl : public NamedDecl {
415 void anchor() override;
418 bool MSAsmNameResolved;
419 /// LocStart - For normal labels, this is the same as the main declaration
420 /// label, i.e., the location of the identifier; for GNU local labels,
421 /// this is the location of the __label__ keyword.
422 SourceLocation LocStart;
424 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
425 LabelStmt *S, SourceLocation StartL)
426 : NamedDecl(Label, DC, IdentL, II),
428 MSAsmNameResolved(false),
432 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
433 SourceLocation IdentL, IdentifierInfo *II);
434 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
435 SourceLocation IdentL, IdentifierInfo *II,
436 SourceLocation GnuLabelL);
437 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
439 LabelStmt *getStmt() const { return TheStmt; }
440 void setStmt(LabelStmt *T) { TheStmt = T; }
442 bool isGnuLocal() const { return LocStart != getLocation(); }
443 void setLocStart(SourceLocation L) { LocStart = L; }
445 SourceRange getSourceRange() const override LLVM_READONLY {
446 return SourceRange(LocStart, getLocation());
449 bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
450 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
451 void setMSAsmLabel(StringRef Name);
452 StringRef getMSAsmLabel() const { return MSAsmName; }
453 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
457 static bool classofKind(Kind K) { return K == Label; }
460 /// NamespaceDecl - Represent a C++ namespace.
461 class NamespaceDecl : public NamedDecl, public DeclContext,
462 public Redeclarable<NamespaceDecl>
464 /// LocStart - The starting location of the source range, pointing
465 /// to either the namespace or the inline keyword.
466 SourceLocation LocStart;
467 /// RBraceLoc - The ending location of the source range.
468 SourceLocation RBraceLoc;
470 /// \brief A pointer to either the anonymous namespace that lives just inside
471 /// this namespace or to the first namespace in the chain (the latter case
472 /// only when this is not the first in the chain), along with a
473 /// boolean value indicating whether this is an inline namespace.
474 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
476 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
477 SourceLocation StartLoc, SourceLocation IdLoc,
478 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
480 typedef Redeclarable<NamespaceDecl> redeclarable_base;
481 NamespaceDecl *getNextRedeclarationImpl() override;
482 NamespaceDecl *getPreviousDeclImpl() override;
483 NamespaceDecl *getMostRecentDeclImpl() override;
486 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
487 bool Inline, SourceLocation StartLoc,
488 SourceLocation IdLoc, IdentifierInfo *Id,
489 NamespaceDecl *PrevDecl);
491 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
493 typedef redeclarable_base::redecl_range redecl_range;
494 typedef redeclarable_base::redecl_iterator redecl_iterator;
495 using redeclarable_base::redecls_begin;
496 using redeclarable_base::redecls_end;
497 using redeclarable_base::redecls;
498 using redeclarable_base::getPreviousDecl;
499 using redeclarable_base::getMostRecentDecl;
500 using redeclarable_base::isFirstDecl;
502 /// \brief Returns true if this is an anonymous namespace declaration.
510 /// q.v. C++ [namespace.unnamed]
511 bool isAnonymousNamespace() const {
512 return !getIdentifier();
515 /// \brief Returns true if this is an inline namespace declaration.
516 bool isInline() const {
517 return AnonOrFirstNamespaceAndInline.getInt();
520 /// \brief Set whether this is an inline namespace declaration.
521 void setInline(bool Inline) {
522 AnonOrFirstNamespaceAndInline.setInt(Inline);
525 /// \brief Get the original (first) namespace declaration.
526 NamespaceDecl *getOriginalNamespace();
528 /// \brief Get the original (first) namespace declaration.
529 const NamespaceDecl *getOriginalNamespace() const;
531 /// \brief Return true if this declaration is an original (first) declaration
532 /// of the namespace. This is false for non-original (subsequent) namespace
533 /// declarations and anonymous namespaces.
534 bool isOriginalNamespace() const;
536 /// \brief Retrieve the anonymous namespace nested inside this namespace,
538 NamespaceDecl *getAnonymousNamespace() const {
539 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
542 void setAnonymousNamespace(NamespaceDecl *D) {
543 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
546 /// Retrieves the canonical declaration of this namespace.
547 NamespaceDecl *getCanonicalDecl() override {
548 return getOriginalNamespace();
550 const NamespaceDecl *getCanonicalDecl() const {
551 return getOriginalNamespace();
554 SourceRange getSourceRange() const override LLVM_READONLY {
555 return SourceRange(LocStart, RBraceLoc);
558 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
559 SourceLocation getRBraceLoc() const { return RBraceLoc; }
560 void setLocStart(SourceLocation L) { LocStart = L; }
561 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
563 // Implement isa/cast/dyncast/etc.
564 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
565 static bool classofKind(Kind K) { return K == Namespace; }
566 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
567 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
569 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
570 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
573 friend class ASTDeclReader;
574 friend class ASTDeclWriter;
577 /// ValueDecl - Represent the declaration of a variable (in which case it is
578 /// an lvalue) a function (in which case it is a function designator) or
579 /// an enum constant.
580 class ValueDecl : public NamedDecl {
581 void anchor() override;
585 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
586 DeclarationName N, QualType T)
587 : NamedDecl(DK, DC, L, N), DeclType(T) {}
589 QualType getType() const { return DeclType; }
590 void setType(QualType newType) { DeclType = newType; }
592 /// \brief Determine whether this symbol is weakly-imported,
593 /// or declared with the weak or weak-ref attr.
596 // Implement isa/cast/dyncast/etc.
597 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
598 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
601 /// QualifierInfo - A struct with extended info about a syntactic
602 /// name qualifier, to be used for the case of out-of-line declarations.
603 struct QualifierInfo {
604 NestedNameSpecifierLoc QualifierLoc;
606 /// NumTemplParamLists - The number of "outer" template parameter lists.
607 /// The count includes all of the template parameter lists that were matched
608 /// against the template-ids occurring into the NNS and possibly (in the
609 /// case of an explicit specialization) a final "template <>".
610 unsigned NumTemplParamLists;
612 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
613 /// containing pointers to the "outer" template parameter lists.
614 /// It includes all of the template parameter lists that were matched
615 /// against the template-ids occurring into the NNS and possibly (in the
616 /// case of an explicit specialization) a final "template <>".
617 TemplateParameterList** TemplParamLists;
619 /// Default constructor.
621 : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(nullptr) {}
623 /// setTemplateParameterListsInfo - Sets info about "outer" template
625 void setTemplateParameterListsInfo(ASTContext &Context,
626 ArrayRef<TemplateParameterList *> TPLists);
629 // Copy constructor and copy assignment are disabled.
630 QualifierInfo(const QualifierInfo&) = delete;
631 QualifierInfo& operator=(const QualifierInfo&) = delete;
634 /// \brief Represents a ValueDecl that came out of a declarator.
635 /// Contains type source information through TypeSourceInfo.
636 class DeclaratorDecl : public ValueDecl {
637 // A struct representing both a TInfo and a syntactic qualifier,
638 // to be used for the (uncommon) case of out-of-line declarations.
639 struct ExtInfo : public QualifierInfo {
640 TypeSourceInfo *TInfo;
643 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
645 /// InnerLocStart - The start of the source range for this declaration,
646 /// ignoring outer template declarations.
647 SourceLocation InnerLocStart;
649 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
650 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
651 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
654 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
655 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
656 SourceLocation StartL)
657 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
661 TypeSourceInfo *getTypeSourceInfo() const {
663 ? getExtInfo()->TInfo
664 : DeclInfo.get<TypeSourceInfo*>();
666 void setTypeSourceInfo(TypeSourceInfo *TI) {
668 getExtInfo()->TInfo = TI;
673 /// getInnerLocStart - Return SourceLocation representing start of source
674 /// range ignoring outer template declarations.
675 SourceLocation getInnerLocStart() const { return InnerLocStart; }
676 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
678 /// getOuterLocStart - Return SourceLocation representing start of source
679 /// range taking into account any outer template declarations.
680 SourceLocation getOuterLocStart() const;
682 SourceRange getSourceRange() const override LLVM_READONLY;
683 SourceLocation getLocStart() const LLVM_READONLY {
684 return getOuterLocStart();
687 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
688 /// declaration, if it was present in the source.
689 NestedNameSpecifier *getQualifier() const {
690 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
694 /// \brief Retrieve the nested-name-specifier (with source-location
695 /// information) that qualifies the name of this declaration, if it was
696 /// present in the source.
697 NestedNameSpecifierLoc getQualifierLoc() const {
698 return hasExtInfo() ? getExtInfo()->QualifierLoc
699 : NestedNameSpecifierLoc();
702 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
704 unsigned getNumTemplateParameterLists() const {
705 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
707 TemplateParameterList *getTemplateParameterList(unsigned index) const {
708 assert(index < getNumTemplateParameterLists());
709 return getExtInfo()->TemplParamLists[index];
711 void setTemplateParameterListsInfo(ASTContext &Context,
712 ArrayRef<TemplateParameterList *> TPLists);
714 SourceLocation getTypeSpecStartLoc() const;
716 // Implement isa/cast/dyncast/etc.
717 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
718 static bool classofKind(Kind K) {
719 return K >= firstDeclarator && K <= lastDeclarator;
722 friend class ASTDeclReader;
723 friend class ASTDeclWriter;
726 /// \brief Structure used to store a statement, the constant value to
727 /// which it was evaluated (if any), and whether or not the statement
728 /// is an integral constant expression (if known).
729 struct EvaluatedStmt {
730 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
731 CheckingICE(false), IsICE(false) { }
733 /// \brief Whether this statement was already evaluated.
734 bool WasEvaluated : 1;
736 /// \brief Whether this statement is being evaluated.
737 bool IsEvaluating : 1;
739 /// \brief Whether we already checked whether this statement was an
740 /// integral constant expression.
743 /// \brief Whether we are checking whether this statement is an
744 /// integral constant expression.
745 bool CheckingICE : 1;
747 /// \brief Whether this statement is an integral constant expression,
748 /// or in C++11, whether the statement is a constant expression. Only
749 /// valid if CheckedICE is true.
756 /// VarDecl - An instance of this class is created to represent a variable
757 /// declaration or definition.
758 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
760 /// getStorageClassSpecifierString - Return the string used to
761 /// specify the storage class \p SC.
763 /// It is illegal to call this function with SC == None.
764 static const char *getStorageClassSpecifierString(StorageClass SC);
766 /// \brief Initialization styles.
767 enum InitializationStyle {
768 CInit, ///< C-style initialization with assignment
769 CallInit, ///< Call-style initialization (C++98)
770 ListInit ///< Direct list-initialization (C++11)
773 /// \brief Kinds of thread-local storage.
775 TLS_None, ///< Not a TLS variable.
776 TLS_Static, ///< TLS with a known-constant initializer.
777 TLS_Dynamic ///< TLS with a dynamic initializer.
781 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
782 // have allocated the auxiliary struct of information there.
784 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
785 // this as *many* VarDecls are ParmVarDecls that don't have default
786 // arguments. We could save some space by moving this pointer union to be
787 // allocated in trailing space when necessary.
788 typedef llvm::PointerUnion<Stmt *, EvaluatedStmt *> InitType;
790 /// \brief The initializer for this variable or, for a ParmVarDecl, the
791 /// C++ default argument.
792 mutable InitType Init;
795 class VarDeclBitfields {
796 friend class VarDecl;
797 friend class ASTDeclReader;
800 unsigned TSCSpec : 2;
801 unsigned InitStyle : 2;
803 enum { NumVarDeclBits = 7 };
805 friend class ASTDeclReader;
806 friend class StmtIteratorBase;
807 friend class ASTNodeImporter;
810 enum { NumParameterIndexBits = 8 };
812 enum DefaultArgKind {
819 class ParmVarDeclBitfields {
820 friend class ParmVarDecl;
821 friend class ASTDeclReader;
823 unsigned : NumVarDeclBits;
825 /// Whether this parameter inherits a default argument from a
826 /// prior declaration.
827 unsigned HasInheritedDefaultArg : 1;
829 /// Describes the kind of default argument for this parameter. By default
830 /// this is none. If this is normal, then the default argument is stored in
831 /// the \c VarDecl initializer expression unless we were unable to parse
832 /// (even an invalid) expression for the default argument.
833 unsigned DefaultArgKind : 2;
835 /// Whether this parameter undergoes K&R argument promotion.
836 unsigned IsKNRPromoted : 1;
838 /// Whether this parameter is an ObjC method parameter or not.
839 unsigned IsObjCMethodParam : 1;
841 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
842 /// Otherwise, the number of function parameter scopes enclosing
843 /// the function parameter scope in which this parameter was
845 unsigned ScopeDepthOrObjCQuals : 7;
847 /// The number of parameters preceding this parameter in the
848 /// function parameter scope in which it was declared.
849 unsigned ParameterIndex : NumParameterIndexBits;
852 class NonParmVarDeclBitfields {
853 friend class VarDecl;
854 friend class ImplicitParamDecl;
855 friend class ASTDeclReader;
857 unsigned : NumVarDeclBits;
859 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
860 /// \brief Whether this variable is a definition which was demoted due to
862 unsigned IsThisDeclarationADemotedDefinition : 1;
864 /// \brief Whether this variable is the exception variable in a C++ catch
865 /// or an Objective-C @catch statement.
866 unsigned ExceptionVar : 1;
868 /// \brief Whether this local variable could be allocated in the return
869 /// slot of its function, enabling the named return value optimization
871 unsigned NRVOVariable : 1;
873 /// \brief Whether this variable is the for-range-declaration in a C++0x
874 /// for-range statement.
875 unsigned CXXForRangeDecl : 1;
877 /// \brief Whether this variable is an ARC pseudo-__strong
878 /// variable; see isARCPseudoStrong() for details.
879 unsigned ARCPseudoStrong : 1;
881 /// \brief Whether this variable is (C++1z) inline.
882 unsigned IsInline : 1;
884 /// \brief Whether this variable has (C++1z) inline explicitly specified.
885 unsigned IsInlineSpecified : 1;
887 /// \brief Whether this variable is (C++0x) constexpr.
888 unsigned IsConstexpr : 1;
890 /// \brief Whether this variable is the implicit variable for a lambda
892 unsigned IsInitCapture : 1;
894 /// \brief Whether this local extern variable's previous declaration was
895 /// declared in the same block scope. This controls whether we should merge
896 /// the type of this declaration with its previous declaration.
897 unsigned PreviousDeclInSameBlockScope : 1;
899 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
901 unsigned ImplicitParamKind : 3;
906 VarDeclBitfields VarDeclBits;
907 ParmVarDeclBitfields ParmVarDeclBits;
908 NonParmVarDeclBitfields NonParmVarDeclBits;
911 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
912 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
913 TypeSourceInfo *TInfo, StorageClass SC);
915 typedef Redeclarable<VarDecl> redeclarable_base;
916 VarDecl *getNextRedeclarationImpl() override {
917 return getNextRedeclaration();
919 VarDecl *getPreviousDeclImpl() override {
920 return getPreviousDecl();
922 VarDecl *getMostRecentDeclImpl() override {
923 return getMostRecentDecl();
927 typedef redeclarable_base::redecl_range redecl_range;
928 typedef redeclarable_base::redecl_iterator redecl_iterator;
929 using redeclarable_base::redecls_begin;
930 using redeclarable_base::redecls_end;
931 using redeclarable_base::redecls;
932 using redeclarable_base::getPreviousDecl;
933 using redeclarable_base::getMostRecentDecl;
934 using redeclarable_base::isFirstDecl;
936 static VarDecl *Create(ASTContext &C, DeclContext *DC,
937 SourceLocation StartLoc, SourceLocation IdLoc,
938 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
941 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
943 SourceRange getSourceRange() const override LLVM_READONLY;
945 /// \brief Returns the storage class as written in the source. For the
946 /// computed linkage of symbol, see getLinkage.
947 StorageClass getStorageClass() const {
948 return (StorageClass) VarDeclBits.SClass;
950 void setStorageClass(StorageClass SC);
952 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
953 VarDeclBits.TSCSpec = TSC;
954 assert(VarDeclBits.TSCSpec == TSC && "truncation");
956 ThreadStorageClassSpecifier getTSCSpec() const {
957 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
959 TLSKind getTLSKind() const;
961 /// hasLocalStorage - Returns true if a variable with function scope
962 /// is a non-static local variable.
963 bool hasLocalStorage() const {
964 if (getStorageClass() == SC_None) {
965 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
966 // used to describe variables allocated in global memory and which are
967 // accessed inside a kernel(s) as read-only variables. As such, variables
968 // in constant address space cannot have local storage.
969 if (getType().getAddressSpace() == LangAS::opencl_constant)
971 // Second check is for C++11 [dcl.stc]p4.
972 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
975 // Global Named Register (GNU extension)
976 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
979 // Return true for: Auto, Register.
980 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
982 return getStorageClass() >= SC_Auto;
985 /// isStaticLocal - Returns true if a variable with function scope is a
986 /// static local variable.
987 bool isStaticLocal() const {
988 return (getStorageClass() == SC_Static ||
990 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
994 /// \brief Returns true if a variable has extern or __private_extern__
996 bool hasExternalStorage() const {
997 return getStorageClass() == SC_Extern ||
998 getStorageClass() == SC_PrivateExtern;
1001 /// \brief Returns true for all variables that do not have local storage.
1003 /// This includes all global variables as well as static variables declared
1004 /// within a function.
1005 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1007 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1008 StorageDuration getStorageDuration() const {
1009 return hasLocalStorage() ? SD_Automatic :
1010 getTSCSpec() ? SD_Thread : SD_Static;
1013 /// \brief Compute the language linkage.
1014 LanguageLinkage getLanguageLinkage() const;
1016 /// \brief Determines whether this variable is a variable with
1017 /// external, C linkage.
1018 bool isExternC() const;
1020 /// \brief Determines whether this variable's context is, or is nested within,
1021 /// a C++ extern "C" linkage spec.
1022 bool isInExternCContext() const;
1024 /// \brief Determines whether this variable's context is, or is nested within,
1025 /// a C++ extern "C++" linkage spec.
1026 bool isInExternCXXContext() const;
1028 /// isLocalVarDecl - Returns true for local variable declarations
1029 /// other than parameters. Note that this includes static variables
1030 /// inside of functions. It also includes variables inside blocks.
1032 /// void foo() { int x; static int y; extern int z; }
1034 bool isLocalVarDecl() const {
1035 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1037 if (const DeclContext *DC = getLexicalDeclContext())
1038 return DC->getRedeclContext()->isFunctionOrMethod();
1042 /// \brief Similar to isLocalVarDecl but also includes parameters.
1043 bool isLocalVarDeclOrParm() const {
1044 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1047 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1048 /// excludes variables declared in blocks.
1049 bool isFunctionOrMethodVarDecl() const {
1050 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1052 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1053 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1056 /// \brief Determines whether this is a static data member.
1058 /// This will only be true in C++, and applies to, e.g., the
1059 /// variable 'x' in:
1065 bool isStaticDataMember() const {
1066 // If it wasn't static, it would be a FieldDecl.
1067 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1070 VarDecl *getCanonicalDecl() override;
1071 const VarDecl *getCanonicalDecl() const {
1072 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1075 enum DefinitionKind {
1076 DeclarationOnly, ///< This declaration is only a declaration.
1077 TentativeDefinition, ///< This declaration is a tentative definition.
1078 Definition ///< This declaration is definitely a definition.
1081 /// \brief Check whether this declaration is a definition. If this could be
1082 /// a tentative definition (in C), don't check whether there's an overriding
1084 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1085 DefinitionKind isThisDeclarationADefinition() const {
1086 return isThisDeclarationADefinition(getASTContext());
1089 /// \brief Check whether this variable is defined in this
1090 /// translation unit.
1091 DefinitionKind hasDefinition(ASTContext &) const;
1092 DefinitionKind hasDefinition() const {
1093 return hasDefinition(getASTContext());
1096 /// \brief Get the tentative definition that acts as the real definition in
1097 /// a TU. Returns null if there is a proper definition available.
1098 VarDecl *getActingDefinition();
1099 const VarDecl *getActingDefinition() const {
1100 return const_cast<VarDecl*>(this)->getActingDefinition();
1103 /// \brief Get the real (not just tentative) definition for this declaration.
1104 VarDecl *getDefinition(ASTContext &);
1105 const VarDecl *getDefinition(ASTContext &C) const {
1106 return const_cast<VarDecl*>(this)->getDefinition(C);
1108 VarDecl *getDefinition() {
1109 return getDefinition(getASTContext());
1111 const VarDecl *getDefinition() const {
1112 return const_cast<VarDecl*>(this)->getDefinition();
1115 /// \brief Determine whether this is or was instantiated from an out-of-line
1116 /// definition of a static data member.
1117 bool isOutOfLine() const override;
1119 /// isFileVarDecl - Returns true for file scoped variable declaration.
1120 bool isFileVarDecl() const {
1122 if (K == ParmVar || K == ImplicitParam)
1125 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1128 if (isStaticDataMember())
1134 /// getAnyInitializer - Get the initializer for this variable, no matter which
1135 /// declaration it is attached to.
1136 const Expr *getAnyInitializer() const {
1138 return getAnyInitializer(D);
1141 /// getAnyInitializer - Get the initializer for this variable, no matter which
1142 /// declaration it is attached to. Also get that declaration.
1143 const Expr *getAnyInitializer(const VarDecl *&D) const;
1145 bool hasInit() const;
1146 const Expr *getInit() const {
1147 return const_cast<VarDecl *>(this)->getInit();
1151 /// \brief Retrieve the address of the initializer expression.
1152 Stmt **getInitAddress();
1154 void setInit(Expr *I);
1156 /// \brief Determine whether this variable's value can be used in a
1157 /// constant expression, according to the relevant language standard.
1158 /// This only checks properties of the declaration, and does not check
1159 /// whether the initializer is in fact a constant expression.
1160 bool isUsableInConstantExpressions(ASTContext &C) const;
1162 EvaluatedStmt *ensureEvaluatedStmt() const;
1164 /// \brief Attempt to evaluate the value of the initializer attached to this
1165 /// declaration, and produce notes explaining why it cannot be evaluated or is
1166 /// not a constant expression. Returns a pointer to the value if evaluation
1167 /// succeeded, 0 otherwise.
1168 APValue *evaluateValue() const;
1169 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1171 /// \brief Return the already-evaluated value of this variable's
1172 /// initializer, or NULL if the value is not yet known. Returns pointer
1173 /// to untyped APValue if the value could not be evaluated.
1174 APValue *getEvaluatedValue() const;
1176 /// \brief Determines whether it is already known whether the
1177 /// initializer is an integral constant expression or not.
1178 bool isInitKnownICE() const;
1180 /// \brief Determines whether the initializer is an integral constant
1181 /// expression, or in C++11, whether the initializer is a constant
1184 /// \pre isInitKnownICE()
1185 bool isInitICE() const;
1187 /// \brief Determine whether the value of the initializer attached to this
1188 /// declaration is an integral constant expression.
1189 bool checkInitIsICE() const;
1191 void setInitStyle(InitializationStyle Style) {
1192 VarDeclBits.InitStyle = Style;
1195 /// \brief The style of initialization for this declaration.
1197 /// C-style initialization is "int x = 1;". Call-style initialization is
1198 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1199 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1200 /// expression for class types. List-style initialization is C++11 syntax,
1201 /// e.g. "int x{1};". Clients can distinguish between different forms of
1202 /// initialization by checking this value. In particular, "int x = {1};" is
1203 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1204 /// Init expression in all three cases is an InitListExpr.
1205 InitializationStyle getInitStyle() const {
1206 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1208 /// \brief Whether the initializer is a direct-initializer (list or call).
1209 bool isDirectInit() const {
1210 return getInitStyle() != CInit;
1213 /// \brief If this definition should pretend to be a declaration.
1214 bool isThisDeclarationADemotedDefinition() const {
1215 return isa<ParmVarDecl>(this) ? false :
1216 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1219 /// \brief This is a definition which should be demoted to a declaration.
1221 /// In some cases (mostly module merging) we can end up with two visible
1222 /// definitions one of which needs to be demoted to a declaration to keep
1223 /// the AST invariants.
1224 void demoteThisDefinitionToDeclaration() {
1225 assert (isThisDeclarationADefinition() && "Not a definition!");
1226 assert (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1227 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1230 /// \brief Determine whether this variable is the exception variable in a
1231 /// C++ catch statememt or an Objective-C \@catch statement.
1232 bool isExceptionVariable() const {
1233 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1235 void setExceptionVariable(bool EV) {
1236 assert(!isa<ParmVarDecl>(this));
1237 NonParmVarDeclBits.ExceptionVar = EV;
1240 /// \brief Determine whether this local variable can be used with the named
1241 /// return value optimization (NRVO).
1243 /// The named return value optimization (NRVO) works by marking certain
1244 /// non-volatile local variables of class type as NRVO objects. These
1245 /// locals can be allocated within the return slot of their containing
1246 /// function, in which case there is no need to copy the object to the
1247 /// return slot when returning from the function. Within the function body,
1248 /// each return that returns the NRVO object will have this variable as its
1250 bool isNRVOVariable() const {
1251 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1253 void setNRVOVariable(bool NRVO) {
1254 assert(!isa<ParmVarDecl>(this));
1255 NonParmVarDeclBits.NRVOVariable = NRVO;
1258 /// \brief Determine whether this variable is the for-range-declaration in
1259 /// a C++0x for-range statement.
1260 bool isCXXForRangeDecl() const {
1261 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1263 void setCXXForRangeDecl(bool FRD) {
1264 assert(!isa<ParmVarDecl>(this));
1265 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1268 /// \brief Determine whether this variable is an ARC pseudo-__strong
1269 /// variable. A pseudo-__strong variable has a __strong-qualified
1270 /// type but does not actually retain the object written into it.
1271 /// Generally such variables are also 'const' for safety.
1272 bool isARCPseudoStrong() const {
1273 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1275 void setARCPseudoStrong(bool ps) {
1276 assert(!isa<ParmVarDecl>(this));
1277 NonParmVarDeclBits.ARCPseudoStrong = ps;
1280 /// Whether this variable is (C++1z) inline.
1281 bool isInline() const {
1282 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1284 bool isInlineSpecified() const {
1285 return isa<ParmVarDecl>(this) ? false
1286 : NonParmVarDeclBits.IsInlineSpecified;
1288 void setInlineSpecified() {
1289 assert(!isa<ParmVarDecl>(this));
1290 NonParmVarDeclBits.IsInline = true;
1291 NonParmVarDeclBits.IsInlineSpecified = true;
1293 void setImplicitlyInline() {
1294 assert(!isa<ParmVarDecl>(this));
1295 NonParmVarDeclBits.IsInline = true;
1298 /// Whether this variable is (C++11) constexpr.
1299 bool isConstexpr() const {
1300 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1302 void setConstexpr(bool IC) {
1303 assert(!isa<ParmVarDecl>(this));
1304 NonParmVarDeclBits.IsConstexpr = IC;
1307 /// Whether this variable is the implicit variable for a lambda init-capture.
1308 bool isInitCapture() const {
1309 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1311 void setInitCapture(bool IC) {
1312 assert(!isa<ParmVarDecl>(this));
1313 NonParmVarDeclBits.IsInitCapture = IC;
1316 /// Whether this local extern variable declaration's previous declaration
1317 /// was declared in the same block scope. Only correct in C++.
1318 bool isPreviousDeclInSameBlockScope() const {
1319 return isa<ParmVarDecl>(this)
1321 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1323 void setPreviousDeclInSameBlockScope(bool Same) {
1324 assert(!isa<ParmVarDecl>(this));
1325 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1328 /// \brief Retrieve the variable declaration from which this variable could
1329 /// be instantiated, if it is an instantiation (rather than a non-template).
1330 VarDecl *getTemplateInstantiationPattern() const;
1332 /// \brief If this variable is an instantiated static data member of a
1333 /// class template specialization, returns the templated static data member
1334 /// from which it was instantiated.
1335 VarDecl *getInstantiatedFromStaticDataMember() const;
1337 /// \brief If this variable is an instantiation of a variable template or a
1338 /// static data member of a class template, determine what kind of
1339 /// template specialization or instantiation this is.
1340 TemplateSpecializationKind getTemplateSpecializationKind() const;
1342 /// \brief If this variable is an instantiation of a variable template or a
1343 /// static data member of a class template, determine its point of
1345 SourceLocation getPointOfInstantiation() const;
1347 /// \brief If this variable is an instantiation of a static data member of a
1348 /// class template specialization, retrieves the member specialization
1350 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1352 /// \brief For a static data member that was instantiated from a static
1353 /// data member of a class template, set the template specialiation kind.
1354 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1355 SourceLocation PointOfInstantiation = SourceLocation());
1357 /// \brief Specify that this variable is an instantiation of the
1358 /// static data member VD.
1359 void setInstantiationOfStaticDataMember(VarDecl *VD,
1360 TemplateSpecializationKind TSK);
1362 /// \brief Retrieves the variable template that is described by this
1363 /// variable declaration.
1365 /// Every variable template is represented as a VarTemplateDecl and a
1366 /// VarDecl. The former contains template properties (such as
1367 /// the template parameter lists) while the latter contains the
1368 /// actual description of the template's
1369 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1370 /// VarDecl that from a VarTemplateDecl, while
1371 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1373 VarTemplateDecl *getDescribedVarTemplate() const;
1375 void setDescribedVarTemplate(VarTemplateDecl *Template);
1377 // Implement isa/cast/dyncast/etc.
1378 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1379 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1382 class ImplicitParamDecl : public VarDecl {
1383 void anchor() override;
1386 /// Defines the kind of the implicit parameter: is this an implicit parameter
1387 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1388 /// context or something else.
1389 enum ImplicitParamKind : unsigned {
1390 ObjCSelf, /// Parameter for Objective-C 'self' argument
1391 ObjCCmd, /// Parameter for Objective-C '_cmd' argument
1392 CXXThis, /// Parameter for C++ 'this' argument
1393 CXXVTT, /// Parameter for C++ virtual table pointers
1394 CapturedContext, /// Parameter for captured context
1395 Other, /// Other implicit parameter
1398 /// Create implicit parameter.
1399 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1400 SourceLocation IdLoc, IdentifierInfo *Id,
1401 QualType T, ImplicitParamKind ParamKind);
1402 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1403 ImplicitParamKind ParamKind);
1405 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1407 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1408 IdentifierInfo *Id, QualType Type,
1409 ImplicitParamKind ParamKind)
1410 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1411 /*TInfo=*/nullptr, SC_None) {
1412 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1416 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1417 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1418 SourceLocation(), /*Id=*/nullptr, Type,
1419 /*TInfo=*/nullptr, SC_None) {
1420 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1424 /// Returns the implicit parameter kind.
1425 ImplicitParamKind getParameterKind() const {
1426 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1428 // Implement isa/cast/dyncast/etc.
1429 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1430 static bool classofKind(Kind K) { return K == ImplicitParam; }
1433 /// ParmVarDecl - Represents a parameter to a function.
1434 class ParmVarDecl : public VarDecl {
1436 enum { MaxFunctionScopeDepth = 255 };
1437 enum { MaxFunctionScopeIndex = 255 };
1440 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1441 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1442 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1443 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1444 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1445 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1446 assert(ParmVarDeclBits.IsKNRPromoted == false);
1447 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1448 setDefaultArg(DefArg);
1452 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1453 SourceLocation StartLoc,
1454 SourceLocation IdLoc, IdentifierInfo *Id,
1455 QualType T, TypeSourceInfo *TInfo,
1456 StorageClass S, Expr *DefArg);
1458 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1460 SourceRange getSourceRange() const override LLVM_READONLY;
1462 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1463 ParmVarDeclBits.IsObjCMethodParam = true;
1464 setParameterIndex(parameterIndex);
1467 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1468 assert(!ParmVarDeclBits.IsObjCMethodParam);
1470 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1471 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1474 setParameterIndex(parameterIndex);
1477 bool isObjCMethodParameter() const {
1478 return ParmVarDeclBits.IsObjCMethodParam;
1481 unsigned getFunctionScopeDepth() const {
1482 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1483 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1486 /// Returns the index of this parameter in its prototype or method scope.
1487 unsigned getFunctionScopeIndex() const {
1488 return getParameterIndex();
1491 ObjCDeclQualifier getObjCDeclQualifier() const {
1492 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1493 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1495 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1496 assert(ParmVarDeclBits.IsObjCMethodParam);
1497 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1500 /// True if the value passed to this parameter must undergo
1501 /// K&R-style default argument promotion:
1504 /// If the expression that denotes the called function has a type
1505 /// that does not include a prototype, the integer promotions are
1506 /// performed on each argument, and arguments that have type float
1507 /// are promoted to double.
1508 bool isKNRPromoted() const {
1509 return ParmVarDeclBits.IsKNRPromoted;
1511 void setKNRPromoted(bool promoted) {
1512 ParmVarDeclBits.IsKNRPromoted = promoted;
1515 Expr *getDefaultArg();
1516 const Expr *getDefaultArg() const {
1517 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1520 void setDefaultArg(Expr *defarg);
1522 /// \brief Retrieve the source range that covers the entire default
1524 SourceRange getDefaultArgRange() const;
1525 void setUninstantiatedDefaultArg(Expr *arg);
1526 Expr *getUninstantiatedDefaultArg();
1527 const Expr *getUninstantiatedDefaultArg() const {
1528 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1531 /// hasDefaultArg - Determines whether this parameter has a default argument,
1532 /// either parsed or not.
1533 bool hasDefaultArg() const;
1535 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1536 /// default argument that has not yet been parsed. This will occur
1537 /// during the processing of a C++ class whose member functions have
1538 /// default arguments, e.g.,
1542 /// void f(int x = 17); // x has an unparsed default argument now
1543 /// }; // x has a regular default argument now
1545 bool hasUnparsedDefaultArg() const {
1546 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1549 bool hasUninstantiatedDefaultArg() const {
1550 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1553 /// setUnparsedDefaultArg - Specify that this parameter has an
1554 /// unparsed default argument. The argument will be replaced with a
1555 /// real default argument via setDefaultArg when the class
1556 /// definition enclosing the function declaration that owns this
1557 /// default argument is completed.
1558 void setUnparsedDefaultArg() {
1559 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1562 bool hasInheritedDefaultArg() const {
1563 return ParmVarDeclBits.HasInheritedDefaultArg;
1566 void setHasInheritedDefaultArg(bool I = true) {
1567 ParmVarDeclBits.HasInheritedDefaultArg = I;
1570 QualType getOriginalType() const;
1572 /// \brief Determine whether this parameter is actually a function
1574 bool isParameterPack() const;
1576 /// setOwningFunction - Sets the function declaration that owns this
1577 /// ParmVarDecl. Since ParmVarDecls are often created before the
1578 /// FunctionDecls that own them, this routine is required to update
1579 /// the DeclContext appropriately.
1580 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1582 // Implement isa/cast/dyncast/etc.
1583 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1584 static bool classofKind(Kind K) { return K == ParmVar; }
1587 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1589 void setParameterIndex(unsigned parameterIndex) {
1590 if (parameterIndex >= ParameterIndexSentinel) {
1591 setParameterIndexLarge(parameterIndex);
1595 ParmVarDeclBits.ParameterIndex = parameterIndex;
1596 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1598 unsigned getParameterIndex() const {
1599 unsigned d = ParmVarDeclBits.ParameterIndex;
1600 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1603 void setParameterIndexLarge(unsigned parameterIndex);
1604 unsigned getParameterIndexLarge() const;
1607 /// FunctionDecl - An instance of this class is created to represent a
1608 /// function declaration or definition.
1610 /// Since a given function can be declared several times in a program,
1611 /// there may be several FunctionDecls that correspond to that
1612 /// function. Only one of those FunctionDecls will be found when
1613 /// traversing the list of declarations in the context of the
1614 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1615 /// contains all of the information known about the function. Other,
1616 /// previous declarations of the function are available via the
1617 /// getPreviousDecl() chain.
1618 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1619 public Redeclarable<FunctionDecl> {
1621 /// \brief The kind of templated function a FunctionDecl can be.
1622 enum TemplatedKind {
1624 TK_FunctionTemplate,
1625 TK_MemberSpecialization,
1626 TK_FunctionTemplateSpecialization,
1627 TK_DependentFunctionTemplateSpecialization
1631 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1632 /// parameters of this function. This is null if a prototype or if there are
1634 ParmVarDecl **ParamInfo;
1636 LazyDeclStmtPtr Body;
1638 // FIXME: This can be packed into the bitfields in DeclContext.
1639 // NOTE: VC++ packs bitfields poorly if the types differ.
1640 unsigned SClass : 3;
1641 unsigned IsInline : 1;
1642 unsigned IsInlineSpecified : 1;
1644 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1645 // CXXDeductionGuideDecl.
1646 unsigned IsExplicitSpecified : 1;
1648 unsigned IsVirtualAsWritten : 1;
1649 unsigned IsPure : 1;
1650 unsigned HasInheritedPrototype : 1;
1651 unsigned HasWrittenPrototype : 1;
1652 unsigned IsDeleted : 1;
1653 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1654 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1655 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1656 unsigned HasImplicitReturnZero : 1;
1657 unsigned IsLateTemplateParsed : 1;
1658 unsigned IsConstexpr : 1;
1659 unsigned InstantiationIsPending:1;
1661 /// \brief Indicates if the function uses __try.
1662 unsigned UsesSEHTry : 1;
1664 /// \brief Indicates if the function was a definition but its body was
1666 unsigned HasSkippedBody : 1;
1668 /// Indicates if the function declaration will have a body, once we're done
1669 /// parsing it. (We don't set it to false when we're done parsing, in the
1670 /// hopes this is simpler.)
1671 unsigned WillHaveBody : 1;
1673 /// \brief End part of this FunctionDecl's source range.
1675 /// We could compute the full range in getSourceRange(). However, when we're
1676 /// dealing with a function definition deserialized from a PCH/AST file,
1677 /// we can only compute the full range once the function body has been
1678 /// de-serialized, so it's far better to have the (sometimes-redundant)
1680 SourceLocation EndRangeLoc;
1682 /// \brief The template or declaration that this declaration
1683 /// describes or was instantiated from, respectively.
1685 /// For non-templates, this value will be NULL. For function
1686 /// declarations that describe a function template, this will be a
1687 /// pointer to a FunctionTemplateDecl. For member functions
1688 /// of class template specializations, this will be a MemberSpecializationInfo
1689 /// pointer containing information about the specialization.
1690 /// For function template specializations, this will be a
1691 /// FunctionTemplateSpecializationInfo, which contains information about
1692 /// the template being specialized and the template arguments involved in
1693 /// that specialization.
1694 llvm::PointerUnion4<FunctionTemplateDecl *,
1695 MemberSpecializationInfo *,
1696 FunctionTemplateSpecializationInfo *,
1697 DependentFunctionTemplateSpecializationInfo *>
1698 TemplateOrSpecialization;
1700 /// DNLoc - Provides source/type location info for the
1701 /// declaration name embedded in the DeclaratorDecl base class.
1702 DeclarationNameLoc DNLoc;
1704 /// \brief Specify that this function declaration is actually a function
1705 /// template specialization.
1707 /// \param C the ASTContext.
1709 /// \param Template the function template that this function template
1710 /// specialization specializes.
1712 /// \param TemplateArgs the template arguments that produced this
1713 /// function template specialization from the template.
1715 /// \param InsertPos If non-NULL, the position in the function template
1716 /// specialization set where the function template specialization data will
1719 /// \param TSK the kind of template specialization this is.
1721 /// \param TemplateArgsAsWritten location info of template arguments.
1723 /// \param PointOfInstantiation point at which the function template
1724 /// specialization was first instantiated.
1725 void setFunctionTemplateSpecialization(ASTContext &C,
1726 FunctionTemplateDecl *Template,
1727 const TemplateArgumentList *TemplateArgs,
1729 TemplateSpecializationKind TSK,
1730 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1731 SourceLocation PointOfInstantiation);
1733 /// \brief Specify that this record is an instantiation of the
1734 /// member function FD.
1735 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1736 TemplateSpecializationKind TSK);
1738 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1741 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1742 const DeclarationNameInfo &NameInfo, QualType T,
1743 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1744 bool isConstexprSpecified)
1745 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1747 DeclContext(DK), redeclarable_base(C), ParamInfo(nullptr), Body(),
1748 SClass(S), IsInline(isInlineSpecified),
1749 IsInlineSpecified(isInlineSpecified), IsExplicitSpecified(false),
1750 IsVirtualAsWritten(false), IsPure(false),
1751 HasInheritedPrototype(false), HasWrittenPrototype(true),
1752 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1753 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1754 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1755 InstantiationIsPending(false),
1756 UsesSEHTry(false), HasSkippedBody(false), WillHaveBody(false),
1757 EndRangeLoc(NameInfo.getEndLoc()), TemplateOrSpecialization(),
1758 DNLoc(NameInfo.getInfo()) {}
1760 typedef Redeclarable<FunctionDecl> redeclarable_base;
1761 FunctionDecl *getNextRedeclarationImpl() override {
1762 return getNextRedeclaration();
1764 FunctionDecl *getPreviousDeclImpl() override {
1765 return getPreviousDecl();
1767 FunctionDecl *getMostRecentDeclImpl() override {
1768 return getMostRecentDecl();
1772 typedef redeclarable_base::redecl_range redecl_range;
1773 typedef redeclarable_base::redecl_iterator redecl_iterator;
1774 using redeclarable_base::redecls_begin;
1775 using redeclarable_base::redecls_end;
1776 using redeclarable_base::redecls;
1777 using redeclarable_base::getPreviousDecl;
1778 using redeclarable_base::getMostRecentDecl;
1779 using redeclarable_base::isFirstDecl;
1781 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1782 SourceLocation StartLoc, SourceLocation NLoc,
1783 DeclarationName N, QualType T,
1784 TypeSourceInfo *TInfo,
1786 bool isInlineSpecified = false,
1787 bool hasWrittenPrototype = true,
1788 bool isConstexprSpecified = false) {
1789 DeclarationNameInfo NameInfo(N, NLoc);
1790 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1792 isInlineSpecified, hasWrittenPrototype,
1793 isConstexprSpecified);
1796 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1797 SourceLocation StartLoc,
1798 const DeclarationNameInfo &NameInfo,
1799 QualType T, TypeSourceInfo *TInfo,
1801 bool isInlineSpecified,
1802 bool hasWrittenPrototype,
1803 bool isConstexprSpecified = false);
1805 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1807 DeclarationNameInfo getNameInfo() const {
1808 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1811 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1812 bool Qualified) const override;
1814 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1816 SourceRange getSourceRange() const override LLVM_READONLY;
1818 /// \brief Returns true if the function has a body (definition). The
1819 /// function body might be in any of the (re-)declarations of this
1820 /// function. The variant that accepts a FunctionDecl pointer will
1821 /// set that function declaration to the actual declaration
1822 /// containing the body (if there is one).
1823 bool hasBody(const FunctionDecl *&Definition) const;
1825 bool hasBody() const override {
1826 const FunctionDecl* Definition;
1827 return hasBody(Definition);
1830 /// hasTrivialBody - Returns whether the function has a trivial body that does
1831 /// not require any specific codegen.
1832 bool hasTrivialBody() const;
1834 /// isDefined - Returns true if the function is defined at all, including
1835 /// a deleted definition. Except for the behavior when the function is
1836 /// deleted, behaves like hasBody.
1837 bool isDefined(const FunctionDecl *&Definition) const;
1839 virtual bool isDefined() const {
1840 const FunctionDecl* Definition;
1841 return isDefined(Definition);
1844 /// \brief Get the definition for this declaration.
1845 FunctionDecl *getDefinition() {
1846 const FunctionDecl *Definition;
1847 if (isDefined(Definition))
1848 return const_cast<FunctionDecl *>(Definition);
1851 const FunctionDecl *getDefinition() const {
1852 return const_cast<FunctionDecl *>(this)->getDefinition();
1855 /// getBody - Retrieve the body (definition) of the function. The
1856 /// function body might be in any of the (re-)declarations of this
1857 /// function. The variant that accepts a FunctionDecl pointer will
1858 /// set that function declaration to the actual declaration
1859 /// containing the body (if there is one).
1860 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1861 /// unnecessary AST de-serialization of the body.
1862 Stmt *getBody(const FunctionDecl *&Definition) const;
1864 Stmt *getBody() const override {
1865 const FunctionDecl* Definition;
1866 return getBody(Definition);
1869 /// Returns whether this specific declaration of the function is also a
1870 /// definition that does not contain uninstantiated body.
1872 /// This does not determine whether the function has been defined (e.g., in a
1873 /// previous definition); for that information, use isDefined.
1875 bool isThisDeclarationADefinition() const {
1876 return IsDeleted || IsDefaulted || Body || IsLateTemplateParsed ||
1877 WillHaveBody || hasDefiningAttr();
1880 /// doesThisDeclarationHaveABody - Returns whether this specific
1881 /// declaration of the function has a body - that is, if it is a non-
1882 /// deleted definition.
1883 bool doesThisDeclarationHaveABody() const {
1884 return Body || IsLateTemplateParsed;
1887 void setBody(Stmt *B);
1888 void setLazyBody(uint64_t Offset) { Body = Offset; }
1890 /// Whether this function is variadic.
1891 bool isVariadic() const;
1893 /// Whether this function is marked as virtual explicitly.
1894 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1895 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1897 /// Whether this virtual function is pure, i.e. makes the containing class
1899 bool isPure() const { return IsPure; }
1900 void setPure(bool P = true);
1902 /// Whether this templated function will be late parsed.
1903 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1904 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1906 /// Whether this function is "trivial" in some specialized C++ senses.
1907 /// Can only be true for default constructors, copy constructors,
1908 /// copy assignment operators, and destructors. Not meaningful until
1909 /// the class has been fully built by Sema.
1910 bool isTrivial() const { return IsTrivial; }
1911 void setTrivial(bool IT) { IsTrivial = IT; }
1913 /// Whether this function is defaulted per C++0x. Only valid for
1914 /// special member functions.
1915 bool isDefaulted() const { return IsDefaulted; }
1916 void setDefaulted(bool D = true) { IsDefaulted = D; }
1918 /// Whether this function is explicitly defaulted per C++0x. Only valid
1919 /// for special member functions.
1920 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1921 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1923 /// Whether falling off this function implicitly returns null/zero.
1924 /// If a more specific implicit return value is required, front-ends
1925 /// should synthesize the appropriate return statements.
1926 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1927 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1929 /// \brief Whether this function has a prototype, either because one
1930 /// was explicitly written or because it was "inherited" by merging
1931 /// a declaration without a prototype with a declaration that has a
1933 bool hasPrototype() const {
1934 return HasWrittenPrototype || HasInheritedPrototype;
1937 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1939 /// \brief Whether this function inherited its prototype from a
1940 /// previous declaration.
1941 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1942 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1944 /// Whether this is a (C++11) constexpr function or constexpr constructor.
1945 bool isConstexpr() const { return IsConstexpr; }
1946 void setConstexpr(bool IC) { IsConstexpr = IC; }
1948 /// \brief Whether the instantiation of this function is pending.
1949 /// This bit is set when the decision to instantiate this function is made
1950 /// and unset if and when the function body is created. That leaves out
1951 /// cases where instantiation did not happen because the template definition
1952 /// was not seen in this TU. This bit remains set in those cases, under the
1953 /// assumption that the instantiation will happen in some other TU.
1954 bool instantiationIsPending() const { return InstantiationIsPending; }
1955 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
1957 /// \brief Indicates the function uses __try.
1958 bool usesSEHTry() const { return UsesSEHTry; }
1959 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
1961 /// \brief Whether this function has been deleted.
1963 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1964 /// acts like a normal function, except that it cannot actually be
1965 /// called or have its address taken. Deleted functions are
1966 /// typically used in C++ overload resolution to attract arguments
1967 /// whose type or lvalue/rvalue-ness would permit the use of a
1968 /// different overload that would behave incorrectly. For example,
1969 /// one might use deleted functions to ban implicit conversion from
1970 /// a floating-point number to an Integer type:
1973 /// struct Integer {
1974 /// Integer(long); // construct from a long
1975 /// Integer(double) = delete; // no construction from float or double
1976 /// Integer(long double) = delete; // no construction from long double
1979 // If a function is deleted, its first declaration must be.
1980 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1981 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1982 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1984 /// \brief Determines whether this function is "main", which is the
1985 /// entry point into an executable program.
1986 bool isMain() const;
1988 /// \brief Determines whether this function is a MSVCRT user defined entry
1990 bool isMSVCRTEntryPoint() const;
1992 /// \brief Determines whether this operator new or delete is one
1993 /// of the reserved global placement operators:
1994 /// void *operator new(size_t, void *);
1995 /// void *operator new[](size_t, void *);
1996 /// void operator delete(void *, void *);
1997 /// void operator delete[](void *, void *);
1998 /// These functions have special behavior under [new.delete.placement]:
1999 /// These functions are reserved, a C++ program may not define
2000 /// functions that displace the versions in the Standard C++ library.
2001 /// The provisions of [basic.stc.dynamic] do not apply to these
2002 /// reserved placement forms of operator new and operator delete.
2004 /// This function must be an allocation or deallocation function.
2005 bool isReservedGlobalPlacementOperator() const;
2007 /// \brief Determines whether this function is one of the replaceable
2008 /// global allocation functions:
2009 /// void *operator new(size_t);
2010 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2011 /// void *operator new[](size_t);
2012 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2013 /// void operator delete(void *) noexcept;
2014 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2015 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2016 /// void operator delete[](void *) noexcept;
2017 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2018 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2019 /// These functions have special behavior under C++1y [expr.new]:
2020 /// An implementation is allowed to omit a call to a replaceable global
2021 /// allocation function. [...]
2023 /// If this function is an aligned allocation/deallocation function, return
2024 /// true through IsAligned.
2025 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2027 /// Compute the language linkage.
2028 LanguageLinkage getLanguageLinkage() const;
2030 /// \brief Determines whether this function is a function with
2031 /// external, C linkage.
2032 bool isExternC() const;
2034 /// \brief Determines whether this function's context is, or is nested within,
2035 /// a C++ extern "C" linkage spec.
2036 bool isInExternCContext() const;
2038 /// \brief Determines whether this function's context is, or is nested within,
2039 /// a C++ extern "C++" linkage spec.
2040 bool isInExternCXXContext() const;
2042 /// \brief Determines whether this is a global function.
2043 bool isGlobal() const;
2045 /// \brief Determines whether this function is known to be 'noreturn', through
2046 /// an attribute on its declaration or its type.
2047 bool isNoReturn() const;
2049 /// \brief True if the function was a definition but its body was skipped.
2050 bool hasSkippedBody() const { return HasSkippedBody; }
2051 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2053 /// True if this function will eventually have a body, once it's fully parsed.
2054 bool willHaveBody() const { return WillHaveBody; }
2055 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2057 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2059 FunctionDecl *getCanonicalDecl() override;
2060 const FunctionDecl *getCanonicalDecl() const {
2061 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2064 unsigned getBuiltinID() const;
2066 // ArrayRef interface to parameters.
2067 ArrayRef<ParmVarDecl *> parameters() const {
2068 return {ParamInfo, getNumParams()};
2070 MutableArrayRef<ParmVarDecl *> parameters() {
2071 return {ParamInfo, getNumParams()};
2074 // Iterator access to formal parameters.
2075 typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
2076 typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
2077 bool param_empty() const { return parameters().empty(); }
2078 param_iterator param_begin() { return parameters().begin(); }
2079 param_iterator param_end() { return parameters().end(); }
2080 param_const_iterator param_begin() const { return parameters().begin(); }
2081 param_const_iterator param_end() const { return parameters().end(); }
2082 size_t param_size() const { return parameters().size(); }
2084 /// getNumParams - Return the number of parameters this function must have
2085 /// based on its FunctionType. This is the length of the ParamInfo array
2086 /// after it has been created.
2087 unsigned getNumParams() const;
2089 const ParmVarDecl *getParamDecl(unsigned i) const {
2090 assert(i < getNumParams() && "Illegal param #");
2091 return ParamInfo[i];
2093 ParmVarDecl *getParamDecl(unsigned i) {
2094 assert(i < getNumParams() && "Illegal param #");
2095 return ParamInfo[i];
2097 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2098 setParams(getASTContext(), NewParamInfo);
2101 /// getMinRequiredArguments - Returns the minimum number of arguments
2102 /// needed to call this function. This may be fewer than the number of
2103 /// function parameters, if some of the parameters have default
2104 /// arguments (in C++).
2105 unsigned getMinRequiredArguments() const;
2107 QualType getReturnType() const {
2108 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2109 return getType()->getAs<FunctionType>()->getReturnType();
2112 /// \brief Attempt to compute an informative source range covering the
2113 /// function return type. This may omit qualifiers and other information with
2114 /// limited representation in the AST.
2115 SourceRange getReturnTypeSourceRange() const;
2117 /// \brief Attempt to compute an informative source range covering the
2118 /// function exception specification, if any.
2119 SourceRange getExceptionSpecSourceRange() const;
2121 /// \brief Determine the type of an expression that calls this function.
2122 QualType getCallResultType() const {
2123 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2124 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2127 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2128 /// function, or its return type declaration.
2129 const Attr *getUnusedResultAttr() const;
2131 /// \brief Returns true if this function or its return type has the
2132 /// warn_unused_result attribute.
2133 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2135 /// \brief Returns the storage class as written in the source. For the
2136 /// computed linkage of symbol, see getLinkage.
2137 StorageClass getStorageClass() const { return StorageClass(SClass); }
2139 /// \brief Determine whether the "inline" keyword was specified for this
2141 bool isInlineSpecified() const { return IsInlineSpecified; }
2143 /// Set whether the "inline" keyword was specified for this function.
2144 void setInlineSpecified(bool I) {
2145 IsInlineSpecified = I;
2149 /// Flag that this function is implicitly inline.
2150 void setImplicitlyInline() {
2154 /// \brief Determine whether this function should be inlined, because it is
2155 /// either marked "inline" or "constexpr" or is a member function of a class
2156 /// that was defined in the class body.
2157 bool isInlined() const { return IsInline; }
2159 bool isInlineDefinitionExternallyVisible() const;
2161 bool isMSExternInline() const;
2163 bool doesDeclarationForceExternallyVisibleDefinition() const;
2165 /// isOverloadedOperator - Whether this function declaration
2166 /// represents an C++ overloaded operator, e.g., "operator+".
2167 bool isOverloadedOperator() const {
2168 return getOverloadedOperator() != OO_None;
2171 OverloadedOperatorKind getOverloadedOperator() const;
2173 const IdentifierInfo *getLiteralIdentifier() const;
2175 /// \brief If this function is an instantiation of a member function
2176 /// of a class template specialization, retrieves the function from
2177 /// which it was instantiated.
2179 /// This routine will return non-NULL for (non-templated) member
2180 /// functions of class templates and for instantiations of function
2181 /// templates. For example, given:
2184 /// template<typename T>
2190 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2191 /// whose parent is the class template specialization X<int>. For
2192 /// this declaration, getInstantiatedFromFunction() will return
2193 /// the FunctionDecl X<T>::A. When a complete definition of
2194 /// X<int>::A is required, it will be instantiated from the
2195 /// declaration returned by getInstantiatedFromMemberFunction().
2196 FunctionDecl *getInstantiatedFromMemberFunction() const;
2198 /// \brief What kind of templated function this is.
2199 TemplatedKind getTemplatedKind() const;
2201 /// \brief If this function is an instantiation of a member function of a
2202 /// class template specialization, retrieves the member specialization
2204 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2206 /// \brief Specify that this record is an instantiation of the
2207 /// member function FD.
2208 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2209 TemplateSpecializationKind TSK) {
2210 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2213 /// \brief Retrieves the function template that is described by this
2214 /// function declaration.
2216 /// Every function template is represented as a FunctionTemplateDecl
2217 /// and a FunctionDecl (or something derived from FunctionDecl). The
2218 /// former contains template properties (such as the template
2219 /// parameter lists) while the latter contains the actual
2220 /// description of the template's
2221 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2222 /// FunctionDecl that describes the function template,
2223 /// getDescribedFunctionTemplate() retrieves the
2224 /// FunctionTemplateDecl from a FunctionDecl.
2225 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2227 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2229 /// \brief Determine whether this function is a function template
2231 bool isFunctionTemplateSpecialization() const {
2232 return getPrimaryTemplate() != nullptr;
2235 /// \brief Retrieve the class scope template pattern that this function
2236 /// template specialization is instantiated from.
2237 FunctionDecl *getClassScopeSpecializationPattern() const;
2239 /// \brief If this function is actually a function template specialization,
2240 /// retrieve information about this function template specialization.
2241 /// Otherwise, returns NULL.
2242 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2244 /// \brief Determines whether this function is a function template
2245 /// specialization or a member of a class template specialization that can
2246 /// be implicitly instantiated.
2247 bool isImplicitlyInstantiable() const;
2249 /// \brief Determines if the given function was instantiated from a
2250 /// function template.
2251 bool isTemplateInstantiation() const;
2253 /// \brief Retrieve the function declaration from which this function could
2254 /// be instantiated, if it is an instantiation (rather than a non-template
2255 /// or a specialization, for example).
2256 FunctionDecl *getTemplateInstantiationPattern() const;
2258 /// \brief Retrieve the primary template that this function template
2259 /// specialization either specializes or was instantiated from.
2261 /// If this function declaration is not a function template specialization,
2263 FunctionTemplateDecl *getPrimaryTemplate() const;
2265 /// \brief Retrieve the template arguments used to produce this function
2266 /// template specialization from the primary template.
2268 /// If this function declaration is not a function template specialization,
2270 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2272 /// \brief Retrieve the template argument list as written in the sources,
2275 /// If this function declaration is not a function template specialization
2276 /// or if it had no explicit template argument list, returns NULL.
2277 /// Note that it an explicit template argument list may be written empty,
2278 /// e.g., template<> void foo<>(char* s);
2279 const ASTTemplateArgumentListInfo*
2280 getTemplateSpecializationArgsAsWritten() const;
2282 /// \brief Specify that this function declaration is actually a function
2283 /// template specialization.
2285 /// \param Template the function template that this function template
2286 /// specialization specializes.
2288 /// \param TemplateArgs the template arguments that produced this
2289 /// function template specialization from the template.
2291 /// \param InsertPos If non-NULL, the position in the function template
2292 /// specialization set where the function template specialization data will
2295 /// \param TSK the kind of template specialization this is.
2297 /// \param TemplateArgsAsWritten location info of template arguments.
2299 /// \param PointOfInstantiation point at which the function template
2300 /// specialization was first instantiated.
2301 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2302 const TemplateArgumentList *TemplateArgs,
2304 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2305 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2306 SourceLocation PointOfInstantiation = SourceLocation()) {
2307 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2308 InsertPos, TSK, TemplateArgsAsWritten,
2309 PointOfInstantiation);
2312 /// \brief Specifies that this function declaration is actually a
2313 /// dependent function template specialization.
2314 void setDependentTemplateSpecialization(ASTContext &Context,
2315 const UnresolvedSetImpl &Templates,
2316 const TemplateArgumentListInfo &TemplateArgs);
2318 DependentFunctionTemplateSpecializationInfo *
2319 getDependentSpecializationInfo() const;
2321 /// \brief Determine what kind of template instantiation this function
2323 TemplateSpecializationKind getTemplateSpecializationKind() const;
2325 /// \brief Determine what kind of template instantiation this function
2327 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2328 SourceLocation PointOfInstantiation = SourceLocation());
2330 /// \brief Retrieve the (first) point of instantiation of a function template
2331 /// specialization or a member of a class template specialization.
2333 /// \returns the first point of instantiation, if this function was
2334 /// instantiated from a template; otherwise, returns an invalid source
2336 SourceLocation getPointOfInstantiation() const;
2338 /// \brief Determine whether this is or was instantiated from an out-of-line
2339 /// definition of a member function.
2340 bool isOutOfLine() const override;
2342 /// \brief Identify a memory copying or setting function.
2343 /// If the given function is a memory copy or setting function, returns
2344 /// the corresponding Builtin ID. If the function is not a memory function,
2346 unsigned getMemoryFunctionKind() const;
2348 // Implement isa/cast/dyncast/etc.
2349 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2350 static bool classofKind(Kind K) {
2351 return K >= firstFunction && K <= lastFunction;
2353 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2354 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2356 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2357 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2360 friend class ASTDeclReader;
2361 friend class ASTDeclWriter;
2365 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2366 /// represent a member of a struct/union/class.
2367 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2368 // FIXME: This can be packed into the bitfields in Decl.
2369 unsigned Mutable : 1;
2370 mutable unsigned CachedFieldIndex : 31;
2372 /// The kinds of value we can store in InitializerOrBitWidth.
2374 /// Note that this is compatible with InClassInitStyle except for
2375 /// ISK_CapturedVLAType.
2376 enum InitStorageKind {
2377 /// If the pointer is null, there's nothing special. Otherwise,
2378 /// this is a bitfield and the pointer is the Expr* storing the
2380 ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2382 /// The pointer is an (optional due to delayed parsing) Expr*
2383 /// holding the copy-initializer.
2384 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2386 /// The pointer is an (optional due to delayed parsing) Expr*
2387 /// holding the list-initializer.
2388 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2390 /// The pointer is a VariableArrayType* that's been captured;
2391 /// the enclosing context is a lambda or captured statement.
2392 ISK_CapturedVLAType,
2395 /// \brief Storage for either the bit-width, the in-class
2396 /// initializer, or the captured variable length array bound.
2398 /// We can safely combine these because in-class initializers are
2399 /// not permitted for bit-fields, and both are exclusive with VLA
2402 /// If the storage kind is ISK_InClassCopyInit or
2403 /// ISK_InClassListInit, but the initializer is null, then this
2404 /// field has an in-class initializer which has not yet been parsed
2406 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2408 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2409 SourceLocation IdLoc, IdentifierInfo *Id,
2410 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2411 InClassInitStyle InitStyle)
2412 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2413 Mutable(Mutable), CachedFieldIndex(0),
2414 InitStorage(BW, (InitStorageKind) InitStyle) {
2415 assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2419 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2420 SourceLocation StartLoc, SourceLocation IdLoc,
2421 IdentifierInfo *Id, QualType T,
2422 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2423 InClassInitStyle InitStyle);
2425 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2427 /// getFieldIndex - Returns the index of this field within its record,
2428 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2429 unsigned getFieldIndex() const;
2431 /// isMutable - Determines whether this field is mutable (C++ only).
2432 bool isMutable() const { return Mutable; }
2434 /// \brief Determines whether this field is a bitfield.
2435 bool isBitField() const {
2436 return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2437 InitStorage.getPointer() != nullptr;
2440 /// @brief Determines whether this is an unnamed bitfield.
2441 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2443 /// isAnonymousStructOrUnion - Determines whether this field is a
2444 /// representative for an anonymous struct or union. Such fields are
2445 /// unnamed and are implicitly generated by the implementation to
2446 /// store the data for the anonymous union or struct.
2447 bool isAnonymousStructOrUnion() const;
2449 Expr *getBitWidth() const {
2451 ? static_cast<Expr *>(InitStorage.getPointer())
2454 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2456 /// setBitWidth - Set the bit-field width for this member.
2457 // Note: used by some clients (i.e., do not remove it).
2458 void setBitWidth(Expr *Width) {
2459 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2460 InitStorage.getPointer() == nullptr &&
2461 "bit width, initializer or captured type already set");
2462 InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2465 /// removeBitWidth - Remove the bit-field width from this member.
2466 // Note: used by some clients (i.e., do not remove it).
2467 void removeBitWidth() {
2468 assert(isBitField() && "no bitfield width to remove");
2469 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2472 /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2474 InClassInitStyle getInClassInitStyle() const {
2475 InitStorageKind storageKind = InitStorage.getInt();
2476 return (storageKind == ISK_CapturedVLAType
2477 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2480 /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2482 bool hasInClassInitializer() const {
2483 return getInClassInitStyle() != ICIS_NoInit;
2486 /// getInClassInitializer - Get the C++11 in-class initializer for this
2487 /// member, or null if one has not been set. If a valid declaration has an
2488 /// in-class initializer, but this returns null, then we have not parsed and
2489 /// attached it yet.
2490 Expr *getInClassInitializer() const {
2491 return hasInClassInitializer()
2492 ? static_cast<Expr *>(InitStorage.getPointer())
2496 /// setInClassInitializer - Set the C++11 in-class initializer for this
2498 void setInClassInitializer(Expr *Init) {
2499 assert(hasInClassInitializer() &&
2500 InitStorage.getPointer() == nullptr &&
2501 "bit width, initializer or captured type already set");
2502 InitStorage.setPointer(Init);
2505 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2507 void removeInClassInitializer() {
2508 assert(hasInClassInitializer() && "no initializer to remove");
2509 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2512 /// \brief Determine whether this member captures the variable length array
2514 bool hasCapturedVLAType() const {
2515 return InitStorage.getInt() == ISK_CapturedVLAType;
2518 /// \brief Get the captured variable length array type.
2519 const VariableArrayType *getCapturedVLAType() const {
2520 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2521 InitStorage.getPointer())
2524 /// \brief Set the captured variable length array type for this field.
2525 void setCapturedVLAType(const VariableArrayType *VLAType);
2527 /// getParent - Returns the parent of this field declaration, which
2528 /// is the struct in which this field is defined.
2529 const RecordDecl *getParent() const {
2530 return cast<RecordDecl>(getDeclContext());
2533 RecordDecl *getParent() {
2534 return cast<RecordDecl>(getDeclContext());
2537 SourceRange getSourceRange() const override LLVM_READONLY;
2539 /// Retrieves the canonical declaration of this field.
2540 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2541 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2543 // Implement isa/cast/dyncast/etc.
2544 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2545 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2547 friend class ASTDeclReader;
2548 friend class ASTDeclWriter;
2551 /// EnumConstantDecl - An instance of this object exists for each enum constant
2552 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2553 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2554 /// TagType for the X EnumDecl.
2555 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2556 Stmt *Init; // an integer constant expression
2557 llvm::APSInt Val; // The value.
2559 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2560 IdentifierInfo *Id, QualType T, Expr *E,
2561 const llvm::APSInt &V)
2562 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2566 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2567 SourceLocation L, IdentifierInfo *Id,
2568 QualType T, Expr *E,
2569 const llvm::APSInt &V);
2570 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2572 const Expr *getInitExpr() const { return (const Expr*) Init; }
2573 Expr *getInitExpr() { return (Expr*) Init; }
2574 const llvm::APSInt &getInitVal() const { return Val; }
2576 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2577 void setInitVal(const llvm::APSInt &V) { Val = V; }
2579 SourceRange getSourceRange() const override LLVM_READONLY;
2581 /// Retrieves the canonical declaration of this enumerator.
2582 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2583 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2585 // Implement isa/cast/dyncast/etc.
2586 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2587 static bool classofKind(Kind K) { return K == EnumConstant; }
2589 friend class StmtIteratorBase;
2592 /// IndirectFieldDecl - An instance of this class is created to represent a
2593 /// field injected from an anonymous union/struct into the parent scope.
2594 /// IndirectFieldDecl are always implicit.
2595 class IndirectFieldDecl : public ValueDecl,
2596 public Mergeable<IndirectFieldDecl> {
2597 void anchor() override;
2598 NamedDecl **Chaining;
2599 unsigned ChainingSize;
2601 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2602 DeclarationName N, QualType T,
2603 MutableArrayRef<NamedDecl *> CH);
2606 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2607 SourceLocation L, IdentifierInfo *Id,
2608 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2610 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2612 typedef ArrayRef<NamedDecl *>::const_iterator chain_iterator;
2614 ArrayRef<NamedDecl *> chain() const {
2615 return llvm::makeArrayRef(Chaining, ChainingSize);
2617 chain_iterator chain_begin() const { return chain().begin(); }
2618 chain_iterator chain_end() const { return chain().end(); }
2620 unsigned getChainingSize() const { return ChainingSize; }
2622 FieldDecl *getAnonField() const {
2623 assert(chain().size() >= 2);
2624 return cast<FieldDecl>(chain().back());
2627 VarDecl *getVarDecl() const {
2628 assert(chain().size() >= 2);
2629 return dyn_cast<VarDecl>(chain().front());
2632 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2633 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2635 // Implement isa/cast/dyncast/etc.
2636 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2637 static bool classofKind(Kind K) { return K == IndirectField; }
2638 friend class ASTDeclReader;
2641 /// TypeDecl - Represents a declaration of a type.
2643 class TypeDecl : public NamedDecl {
2644 void anchor() override;
2645 /// TypeForDecl - This indicates the Type object that represents
2646 /// this TypeDecl. It is a cache maintained by
2647 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2648 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2649 mutable const Type *TypeForDecl;
2650 /// LocStart - The start of the source range for this declaration.
2651 SourceLocation LocStart;
2652 friend class ASTContext;
2655 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2656 SourceLocation StartL = SourceLocation())
2657 : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2660 // Low-level accessor. If you just want the type defined by this node,
2661 // check out ASTContext::getTypeDeclType or one of
2662 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2663 // already know the specific kind of node this is.
2664 const Type *getTypeForDecl() const { return TypeForDecl; }
2665 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2667 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2668 void setLocStart(SourceLocation L) { LocStart = L; }
2669 SourceRange getSourceRange() const override LLVM_READONLY {
2670 if (LocStart.isValid())
2671 return SourceRange(LocStart, getLocation());
2673 return SourceRange(getLocation());
2676 // Implement isa/cast/dyncast/etc.
2677 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2678 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2682 /// Base class for declarations which introduce a typedef-name.
2683 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2684 void anchor() override;
2685 typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2686 llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2688 // FIXME: This can be packed into the bitfields in Decl.
2689 /// If 0, we have not computed IsTransparentTag.
2690 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2691 mutable unsigned CacheIsTransparentTag : 2;
2694 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2695 SourceLocation StartLoc, SourceLocation IdLoc,
2696 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2697 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2698 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2700 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2701 TypedefNameDecl *getNextRedeclarationImpl() override {
2702 return getNextRedeclaration();
2704 TypedefNameDecl *getPreviousDeclImpl() override {
2705 return getPreviousDecl();
2707 TypedefNameDecl *getMostRecentDeclImpl() override {
2708 return getMostRecentDecl();
2712 typedef redeclarable_base::redecl_range redecl_range;
2713 typedef redeclarable_base::redecl_iterator redecl_iterator;
2714 using redeclarable_base::redecls_begin;
2715 using redeclarable_base::redecls_end;
2716 using redeclarable_base::redecls;
2717 using redeclarable_base::getPreviousDecl;
2718 using redeclarable_base::getMostRecentDecl;
2719 using redeclarable_base::isFirstDecl;
2721 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2723 TypeSourceInfo *getTypeSourceInfo() const {
2725 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2726 : MaybeModedTInfo.get<TypeSourceInfo*>();
2728 QualType getUnderlyingType() const {
2730 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2731 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2733 void setTypeSourceInfo(TypeSourceInfo *newType) {
2734 MaybeModedTInfo = newType;
2736 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2737 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2740 /// Retrieves the canonical declaration of this typedef-name.
2741 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2742 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2744 /// Retrieves the tag declaration for which this is the typedef name for
2745 /// linkage purposes, if any.
2747 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2748 /// this typedef declaration.
2749 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2751 /// Determines if this typedef shares a name and spelling location with its
2752 /// underlying tag type, as is the case with the NS_ENUM macro.
2753 bool isTransparentTag() const {
2754 if (CacheIsTransparentTag)
2755 return CacheIsTransparentTag & 0x2;
2756 return isTransparentTagSlow();
2759 // Implement isa/cast/dyncast/etc.
2760 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2761 static bool classofKind(Kind K) {
2762 return K >= firstTypedefName && K <= lastTypedefName;
2766 bool isTransparentTagSlow() const;
2769 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2771 class TypedefDecl : public TypedefNameDecl {
2772 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2773 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2774 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2777 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2778 SourceLocation StartLoc, SourceLocation IdLoc,
2779 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2780 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2782 SourceRange getSourceRange() const override LLVM_READONLY;
2784 // Implement isa/cast/dyncast/etc.
2785 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2786 static bool classofKind(Kind K) { return K == Typedef; }
2789 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2790 /// alias-declaration.
2791 class TypeAliasDecl : public TypedefNameDecl {
2792 /// The template for which this is the pattern, if any.
2793 TypeAliasTemplateDecl *Template;
2795 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2796 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2797 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2798 Template(nullptr) {}
2801 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2802 SourceLocation StartLoc, SourceLocation IdLoc,
2803 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2804 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2806 SourceRange getSourceRange() const override LLVM_READONLY;
2808 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2809 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2811 // Implement isa/cast/dyncast/etc.
2812 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2813 static bool classofKind(Kind K) { return K == TypeAlias; }
2816 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2818 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2820 // This is really ugly.
2821 typedef TagTypeKind TagKind;
2824 // FIXME: This can be packed into the bitfields in Decl.
2825 /// TagDeclKind - The TagKind enum.
2826 unsigned TagDeclKind : 3;
2828 /// IsCompleteDefinition - True if this is a definition ("struct foo
2829 /// {};"), false if it is a declaration ("struct foo;"). It is not
2830 /// a definition until the definition has been fully processed.
2831 unsigned IsCompleteDefinition : 1;
2834 /// IsBeingDefined - True if this is currently being defined.
2835 unsigned IsBeingDefined : 1;
2838 /// IsEmbeddedInDeclarator - True if this tag declaration is
2839 /// "embedded" (i.e., defined or declared for the very first time)
2840 /// in the syntax of a declarator.
2841 unsigned IsEmbeddedInDeclarator : 1;
2843 /// \brief True if this tag is free standing, e.g. "struct foo;".
2844 unsigned IsFreeStanding : 1;
2847 // These are used by (and only defined for) EnumDecl.
2848 unsigned NumPositiveBits : 8;
2849 unsigned NumNegativeBits : 8;
2851 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2852 /// possible in C++11 mode.
2853 unsigned IsScoped : 1;
2854 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2855 /// then this is true if the scoped enum was declared using the class
2856 /// tag, false if it was declared with the struct tag. No meaning is
2857 /// associated if this tag declaration is not a scoped enum.
2858 unsigned IsScopedUsingClassTag : 1;
2860 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2861 /// possible in C++11, Microsoft extensions, or Objective C mode.
2862 unsigned IsFixed : 1;
2864 /// \brief Indicates whether it is possible for declarations of this kind
2865 /// to have an out-of-date definition.
2867 /// This option is only enabled when modules are enabled.
2868 unsigned MayHaveOutOfDateDef : 1;
2870 /// Has the full definition of this type been required by a use somewhere in
2872 unsigned IsCompleteDefinitionRequired : 1;
2874 SourceRange BraceRange;
2876 // A struct representing syntactic qualifier info,
2877 // to be used for the (uncommon) case of out-of-line declarations.
2878 typedef QualifierInfo ExtInfo;
2880 /// \brief If the (out-of-line) tag declaration name
2881 /// is qualified, it points to the qualifier info (nns and range);
2882 /// otherwise, if the tag declaration is anonymous and it is part of
2883 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2884 /// otherwise, if the tag declaration is anonymous and it is used as a
2885 /// declaration specifier for variables, it points to the first VarDecl (used
2887 /// otherwise, it is a null (TypedefNameDecl) pointer.
2888 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
2890 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
2891 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
2892 const ExtInfo *getExtInfo() const {
2893 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
2897 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2898 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2899 SourceLocation StartL)
2900 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2901 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2902 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2903 IsCompleteDefinitionRequired(false),
2904 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
2905 assert((DK != Enum || TK == TTK_Enum) &&
2906 "EnumDecl not matched with TTK_Enum");
2907 setPreviousDecl(PrevDecl);
2910 typedef Redeclarable<TagDecl> redeclarable_base;
2911 TagDecl *getNextRedeclarationImpl() override {
2912 return getNextRedeclaration();
2914 TagDecl *getPreviousDeclImpl() override {
2915 return getPreviousDecl();
2917 TagDecl *getMostRecentDeclImpl() override {
2918 return getMostRecentDecl();
2921 /// @brief Completes the definition of this tag declaration.
2923 /// This is a helper function for derived classes.
2924 void completeDefinition();
2927 typedef redeclarable_base::redecl_range redecl_range;
2928 typedef redeclarable_base::redecl_iterator redecl_iterator;
2929 using redeclarable_base::redecls_begin;
2930 using redeclarable_base::redecls_end;
2931 using redeclarable_base::redecls;
2932 using redeclarable_base::getPreviousDecl;
2933 using redeclarable_base::getMostRecentDecl;
2934 using redeclarable_base::isFirstDecl;
2936 SourceRange getBraceRange() const { return BraceRange; }
2937 void setBraceRange(SourceRange R) { BraceRange = R; }
2939 /// getInnerLocStart - Return SourceLocation representing start of source
2940 /// range ignoring outer template declarations.
2941 SourceLocation getInnerLocStart() const { return getLocStart(); }
2943 /// getOuterLocStart - Return SourceLocation representing start of source
2944 /// range taking into account any outer template declarations.
2945 SourceLocation getOuterLocStart() const;
2946 SourceRange getSourceRange() const override LLVM_READONLY;
2948 TagDecl *getCanonicalDecl() override;
2949 const TagDecl *getCanonicalDecl() const {
2950 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2953 /// isThisDeclarationADefinition() - Return true if this declaration
2954 /// is a completion definition of the type. Provided for consistency.
2955 bool isThisDeclarationADefinition() const {
2956 return isCompleteDefinition();
2959 /// isCompleteDefinition - Return true if this decl has its body
2960 /// fully specified.
2961 bool isCompleteDefinition() const {
2962 return IsCompleteDefinition;
2965 /// \brief Return true if this complete decl is
2966 /// required to be complete for some existing use.
2967 bool isCompleteDefinitionRequired() const {
2968 return IsCompleteDefinitionRequired;
2971 /// isBeingDefined - Return true if this decl is currently being defined.
2972 bool isBeingDefined() const {
2973 return IsBeingDefined;
2976 bool isEmbeddedInDeclarator() const {
2977 return IsEmbeddedInDeclarator;
2979 void setEmbeddedInDeclarator(bool isInDeclarator) {
2980 IsEmbeddedInDeclarator = isInDeclarator;
2983 bool isFreeStanding() const { return IsFreeStanding; }
2984 void setFreeStanding(bool isFreeStanding = true) {
2985 IsFreeStanding = isFreeStanding;
2988 /// \brief Whether this declaration declares a type that is
2989 /// dependent, i.e., a type that somehow depends on template
2991 bool isDependentType() const { return isDependentContext(); }
2993 /// @brief Starts the definition of this tag declaration.
2995 /// This method should be invoked at the beginning of the definition
2996 /// of this tag declaration. It will set the tag type into a state
2997 /// where it is in the process of being defined.
2998 void startDefinition();
3000 /// getDefinition - Returns the TagDecl that actually defines this
3001 /// struct/union/class/enum. When determining whether or not a
3002 /// struct/union/class/enum has a definition, one should use this
3003 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3004 /// whether or not a specific TagDecl is defining declaration, not
3005 /// whether or not the struct/union/class/enum type is defined.
3006 /// This method returns NULL if there is no TagDecl that defines
3007 /// the struct/union/class/enum.
3008 TagDecl *getDefinition() const;
3010 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3012 void setCompleteDefinitionRequired(bool V = true) {
3013 IsCompleteDefinitionRequired = V;
3016 StringRef getKindName() const {
3017 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3020 TagKind getTagKind() const {
3021 return TagKind(TagDeclKind);
3024 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3026 bool isStruct() const { return getTagKind() == TTK_Struct; }
3027 bool isInterface() const { return getTagKind() == TTK_Interface; }
3028 bool isClass() const { return getTagKind() == TTK_Class; }
3029 bool isUnion() const { return getTagKind() == TTK_Union; }
3030 bool isEnum() const { return getTagKind() == TTK_Enum; }
3032 /// Is this tag type named, either directly or via being defined in
3033 /// a typedef of this type?
3035 /// C++11 [basic.link]p8:
3036 /// A type is said to have linkage if and only if:
3037 /// - it is a class or enumeration type that is named (or has a
3038 /// name for linkage purposes) and the name has linkage; ...
3039 /// C++11 [dcl.typedef]p9:
3040 /// If the typedef declaration defines an unnamed class (or enum),
3041 /// the first typedef-name declared by the declaration to be that
3042 /// class type (or enum type) is used to denote the class type (or
3043 /// enum type) for linkage purposes only.
3045 /// C does not have an analogous rule, but the same concept is
3046 /// nonetheless useful in some places.
3047 bool hasNameForLinkage() const {
3048 return (getDeclName() || getTypedefNameForAnonDecl());
3051 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3052 return hasExtInfo() ? nullptr
3053 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3056 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3058 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3059 /// declaration, if it was present in the source.
3060 NestedNameSpecifier *getQualifier() const {
3061 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3065 /// \brief Retrieve the nested-name-specifier (with source-location
3066 /// information) that qualifies the name of this declaration, if it was
3067 /// present in the source.
3068 NestedNameSpecifierLoc getQualifierLoc() const {
3069 return hasExtInfo() ? getExtInfo()->QualifierLoc
3070 : NestedNameSpecifierLoc();
3073 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3075 unsigned getNumTemplateParameterLists() const {
3076 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3078 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3079 assert(i < getNumTemplateParameterLists());
3080 return getExtInfo()->TemplParamLists[i];
3082 void setTemplateParameterListsInfo(ASTContext &Context,
3083 ArrayRef<TemplateParameterList *> TPLists);
3085 // Implement isa/cast/dyncast/etc.
3086 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3087 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3089 static DeclContext *castToDeclContext(const TagDecl *D) {
3090 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3092 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3093 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3096 friend class ASTDeclReader;
3097 friend class ASTDeclWriter;
3100 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
3101 /// with a fixed underlying type, and in C we allow them to be forward-declared
3102 /// with no underlying type as an extension.
3103 class EnumDecl : public TagDecl {
3104 void anchor() override;
3105 /// IntegerType - This represent the integer type that the enum corresponds
3106 /// to for code generation purposes. Note that the enumerator constants may
3107 /// have a different type than this does.
3109 /// If the underlying integer type was explicitly stated in the source
3110 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3111 /// was automatically deduced somehow, and this is a Type*.
3113 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3114 /// some cases it won't.
3116 /// The underlying type of an enumeration never has any qualifiers, so
3117 /// we can get away with just storing a raw Type*, and thus save an
3118 /// extra pointer when TypeSourceInfo is needed.
3120 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
3122 /// PromotionType - The integer type that values of this type should
3123 /// promote to. In C, enumerators are generally of an integer type
3124 /// directly, but gcc-style large enumerators (and all enumerators
3125 /// in C++) are of the enum type instead.
3126 QualType PromotionType;
3128 /// \brief If this enumeration is an instantiation of a member enumeration
3129 /// of a class template specialization, this is the member specialization
3131 MemberSpecializationInfo *SpecializationInfo;
3133 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3134 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3135 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3136 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3137 SpecializationInfo(nullptr) {
3138 assert(Scoped || !ScopedUsingClassTag);
3139 IntegerType = (const Type *)nullptr;
3140 NumNegativeBits = 0;
3141 NumPositiveBits = 0;
3143 IsScopedUsingClassTag = ScopedUsingClassTag;
3147 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3148 TemplateSpecializationKind TSK);
3150 EnumDecl *getCanonicalDecl() override {
3151 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3153 const EnumDecl *getCanonicalDecl() const {
3154 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3157 EnumDecl *getPreviousDecl() {
3158 return cast_or_null<EnumDecl>(
3159 static_cast<TagDecl *>(this)->getPreviousDecl());
3161 const EnumDecl *getPreviousDecl() const {
3162 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3165 EnumDecl *getMostRecentDecl() {
3166 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3168 const EnumDecl *getMostRecentDecl() const {
3169 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3172 EnumDecl *getDefinition() const {
3173 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3176 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3177 SourceLocation StartLoc, SourceLocation IdLoc,
3178 IdentifierInfo *Id, EnumDecl *PrevDecl,
3179 bool IsScoped, bool IsScopedUsingClassTag,
3181 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3183 /// completeDefinition - When created, the EnumDecl corresponds to a
3184 /// forward-declared enum. This method is used to mark the
3185 /// declaration as being defined; it's enumerators have already been
3186 /// added (via DeclContext::addDecl). NewType is the new underlying
3187 /// type of the enumeration type.
3188 void completeDefinition(QualType NewType,
3189 QualType PromotionType,
3190 unsigned NumPositiveBits,
3191 unsigned NumNegativeBits);
3193 // enumerator_iterator - Iterates through the enumerators of this
3195 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
3196 typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
3199 enumerator_range enumerators() const {
3200 return enumerator_range(enumerator_begin(), enumerator_end());
3203 enumerator_iterator enumerator_begin() const {
3204 const EnumDecl *E = getDefinition();
3207 return enumerator_iterator(E->decls_begin());
3210 enumerator_iterator enumerator_end() const {
3211 const EnumDecl *E = getDefinition();
3214 return enumerator_iterator(E->decls_end());
3217 /// getPromotionType - Return the integer type that enumerators
3218 /// should promote to.
3219 QualType getPromotionType() const { return PromotionType; }
3221 /// \brief Set the promotion type.
3222 void setPromotionType(QualType T) { PromotionType = T; }
3224 /// getIntegerType - Return the integer type this enum decl corresponds to.
3225 /// This returns a null QualType for an enum forward definition with no fixed
3226 /// underlying type.
3227 QualType getIntegerType() const {
3230 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3231 return QualType(T, 0);
3232 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3235 /// \brief Set the underlying integer type.
3236 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3238 /// \brief Set the underlying integer type source info.
3239 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3241 /// \brief Return the type source info for the underlying integer type,
3242 /// if no type source info exists, return 0.
3243 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3244 return IntegerType.dyn_cast<TypeSourceInfo*>();
3247 /// \brief Retrieve the source range that covers the underlying type if
3249 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3251 /// \brief Returns the width in bits required to store all the
3252 /// non-negative enumerators of this enum.
3253 unsigned getNumPositiveBits() const {
3254 return NumPositiveBits;
3256 void setNumPositiveBits(unsigned Num) {
3257 NumPositiveBits = Num;
3258 assert(NumPositiveBits == Num && "can't store this bitcount");
3261 /// \brief Returns the width in bits required to store all the
3262 /// negative enumerators of this enum. These widths include
3263 /// the rightmost leading 1; that is:
3265 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3266 /// ------------------------ ------- -----------------
3270 unsigned getNumNegativeBits() const {
3271 return NumNegativeBits;
3273 void setNumNegativeBits(unsigned Num) {
3274 NumNegativeBits = Num;
3277 /// \brief Returns true if this is a C++11 scoped enumeration.
3278 bool isScoped() const {
3282 /// \brief Returns true if this is a C++11 scoped enumeration.
3283 bool isScopedUsingClassTag() const {
3284 return IsScopedUsingClassTag;
3287 /// \brief Returns true if this is an Objective-C, C++11, or
3288 /// Microsoft-style enumeration with a fixed underlying type.
3289 bool isFixed() const {
3293 /// \brief Returns true if this can be considered a complete type.
3294 bool isComplete() const {
3295 return isCompleteDefinition() || isFixed();
3298 /// Returns true if this enum is either annotated with
3299 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3300 bool isClosed() const;
3302 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3303 /// with enum_extensibility(open).
3304 bool isClosedFlag() const;
3306 /// Returns true if this enum is annotated with neither flag_enum nor
3307 /// enum_extensibility(open).
3308 bool isClosedNonFlag() const;
3310 /// \brief Retrieve the enum definition from which this enumeration could
3311 /// be instantiated, if it is an instantiation (rather than a non-template).
3312 EnumDecl *getTemplateInstantiationPattern() const;
3314 /// \brief Returns the enumeration (declared within the template)
3315 /// from which this enumeration type was instantiated, or NULL if
3316 /// this enumeration was not instantiated from any template.
3317 EnumDecl *getInstantiatedFromMemberEnum() const;
3319 /// \brief If this enumeration is a member of a specialization of a
3320 /// templated class, determine what kind of template specialization
3321 /// or instantiation this is.
3322 TemplateSpecializationKind getTemplateSpecializationKind() const;
3324 /// \brief For an enumeration member that was instantiated from a member
3325 /// enumeration of a templated class, set the template specialiation kind.
3326 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3327 SourceLocation PointOfInstantiation = SourceLocation());
3329 /// \brief If this enumeration is an instantiation of a member enumeration of
3330 /// a class template specialization, retrieves the member specialization
3332 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3333 return SpecializationInfo;
3336 /// \brief Specify that this enumeration is an instantiation of the
3337 /// member enumeration ED.
3338 void setInstantiationOfMemberEnum(EnumDecl *ED,
3339 TemplateSpecializationKind TSK) {
3340 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3343 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3344 static bool classofKind(Kind K) { return K == Enum; }
3346 friend class ASTDeclReader;
3350 /// RecordDecl - Represents a struct/union/class. For example:
3351 /// struct X; // Forward declaration, no "body".
3352 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3353 /// This decl will be marked invalid if *any* members are invalid.
3355 class RecordDecl : public TagDecl {
3356 // FIXME: This can be packed into the bitfields in Decl.
3357 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3358 /// array member (e.g. int X[]) or if this union contains a struct that does.
3359 /// If so, this cannot be contained in arrays or other structs as a member.
3360 bool HasFlexibleArrayMember : 1;
3362 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3364 bool AnonymousStructOrUnion : 1;
3366 /// HasObjectMember - This is true if this struct has at least one member
3367 /// containing an Objective-C object pointer type.
3368 bool HasObjectMember : 1;
3370 /// HasVolatileMember - This is true if struct has at least one member of
3371 /// 'volatile' type.
3372 bool HasVolatileMember : 1;
3374 /// \brief Whether the field declarations of this record have been loaded
3375 /// from external storage. To avoid unnecessary deserialization of
3376 /// methods/nested types we allow deserialization of just the fields
3378 mutable bool LoadedFieldsFromExternalStorage : 1;
3379 friend class DeclContext;
3382 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3383 SourceLocation StartLoc, SourceLocation IdLoc,
3384 IdentifierInfo *Id, RecordDecl *PrevDecl);
3387 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3388 SourceLocation StartLoc, SourceLocation IdLoc,
3389 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3390 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3392 RecordDecl *getPreviousDecl() {
3393 return cast_or_null<RecordDecl>(
3394 static_cast<TagDecl *>(this)->getPreviousDecl());
3396 const RecordDecl *getPreviousDecl() const {
3397 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3400 RecordDecl *getMostRecentDecl() {
3401 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3403 const RecordDecl *getMostRecentDecl() const {
3404 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3407 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3408 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3410 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3411 /// or union. To be an anonymous struct or union, it must have been
3412 /// declared without a name and there must be no objects of this
3413 /// type declared, e.g.,
3415 /// union { int i; float f; };
3417 /// is an anonymous union but neither of the following are:
3419 /// union X { int i; float f; };
3420 /// union { int i; float f; } obj;
3422 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3423 void setAnonymousStructOrUnion(bool Anon) {
3424 AnonymousStructOrUnion = Anon;
3427 bool hasObjectMember() const { return HasObjectMember; }
3428 void setHasObjectMember (bool val) { HasObjectMember = val; }
3430 bool hasVolatileMember() const { return HasVolatileMember; }
3431 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3433 bool hasLoadedFieldsFromExternalStorage() const {
3434 return LoadedFieldsFromExternalStorage;
3436 void setHasLoadedFieldsFromExternalStorage(bool val) {
3437 LoadedFieldsFromExternalStorage = val;
3440 /// \brief Determines whether this declaration represents the
3441 /// injected class name.
3443 /// The injected class name in C++ is the name of the class that
3444 /// appears inside the class itself. For example:
3448 /// // C is implicitly declared here as a synonym for the class name.
3451 /// C::C c; // same as "C c;"
3453 bool isInjectedClassName() const;
3455 /// \brief Determine whether this record is a class describing a lambda
3456 /// function object.
3457 bool isLambda() const;
3459 /// \brief Determine whether this record is a record for captured variables in
3460 /// CapturedStmt construct.
3461 bool isCapturedRecord() const;
3462 /// \brief Mark the record as a record for captured variables in CapturedStmt
3464 void setCapturedRecord();
3466 /// getDefinition - Returns the RecordDecl that actually defines
3467 /// this struct/union/class. When determining whether or not a
3468 /// struct/union/class is completely defined, one should use this
3469 /// method as opposed to 'isCompleteDefinition'.
3470 /// 'isCompleteDefinition' indicates whether or not a specific
3471 /// RecordDecl is a completed definition, not whether or not the
3472 /// record type is defined. This method returns NULL if there is
3473 /// no RecordDecl that defines the struct/union/tag.
3474 RecordDecl *getDefinition() const {
3475 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3478 // Iterator access to field members. The field iterator only visits
3479 // the non-static data members of this class, ignoring any static
3480 // data members, functions, constructors, destructors, etc.
3481 typedef specific_decl_iterator<FieldDecl> field_iterator;
3482 typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3484 field_range fields() const { return field_range(field_begin(), field_end()); }
3485 field_iterator field_begin() const;
3487 field_iterator field_end() const {
3488 return field_iterator(decl_iterator());
3491 // field_empty - Whether there are any fields (non-static data
3492 // members) in this record.
3493 bool field_empty() const {
3494 return field_begin() == field_end();
3497 /// completeDefinition - Notes that the definition of this type is
3499 virtual void completeDefinition();
3501 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3502 static bool classofKind(Kind K) {
3503 return K >= firstRecord && K <= lastRecord;
3506 /// isMsStrust - Get whether or not this is an ms_struct which can
3507 /// be turned on with an attribute, pragma, or -mms-bitfields
3508 /// commandline option.
3509 bool isMsStruct(const ASTContext &C) const;
3511 /// \brief Whether we are allowed to insert extra padding between fields.
3512 /// These padding are added to help AddressSanitizer detect
3513 /// intra-object-overflow bugs.
3514 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3516 /// Finds the first data member which has a name.
3517 /// nullptr is returned if no named data member exists.
3518 const FieldDecl *findFirstNamedDataMember() const;
3521 /// \brief Deserialize just the fields.
3522 void LoadFieldsFromExternalStorage() const;
3525 class FileScopeAsmDecl : public Decl {
3526 virtual void anchor();
3527 StringLiteral *AsmString;
3528 SourceLocation RParenLoc;
3529 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3530 SourceLocation StartL, SourceLocation EndL)
3531 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3533 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3534 StringLiteral *Str, SourceLocation AsmLoc,
3535 SourceLocation RParenLoc);
3537 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3539 SourceLocation getAsmLoc() const { return getLocation(); }
3540 SourceLocation getRParenLoc() const { return RParenLoc; }
3541 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3542 SourceRange getSourceRange() const override LLVM_READONLY {
3543 return SourceRange(getAsmLoc(), getRParenLoc());
3546 const StringLiteral *getAsmString() const { return AsmString; }
3547 StringLiteral *getAsmString() { return AsmString; }
3548 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3550 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3551 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3554 /// BlockDecl - This represents a block literal declaration, which is like an
3555 /// unnamed FunctionDecl. For example:
3556 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3558 class BlockDecl : public Decl, public DeclContext {
3560 /// A class which contains all the information about a particular
3568 /// The variable being captured.
3569 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3571 /// The copy expression, expressed in terms of a DeclRef (or
3572 /// BlockDeclRef) to the captured variable. Only required if the
3573 /// variable has a C++ class type.
3577 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3578 : VariableAndFlags(variable,
3579 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3582 /// The variable being captured.
3583 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3585 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3587 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3589 /// Whether this is a nested capture, i.e. the variable captured
3590 /// is not from outside the immediately enclosing function/block.
3591 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3593 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3594 Expr *getCopyExpr() const { return CopyExpr; }
3595 void setCopyExpr(Expr *e) { CopyExpr = e; }
3599 // FIXME: This can be packed into the bitfields in Decl.
3600 bool IsVariadic : 1;
3601 bool CapturesCXXThis : 1;
3602 bool BlockMissingReturnType : 1;
3603 bool IsConversionFromLambda : 1;
3604 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3605 /// parameters of this function. This is null if a prototype or if there are
3607 ParmVarDecl **ParamInfo;
3611 TypeSourceInfo *SignatureAsWritten;
3613 const Capture *Captures;
3614 unsigned NumCaptures;
3616 unsigned ManglingNumber;
3617 Decl *ManglingContextDecl;
3620 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3621 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3622 IsVariadic(false), CapturesCXXThis(false),
3623 BlockMissingReturnType(true), IsConversionFromLambda(false),
3624 ParamInfo(nullptr), NumParams(0), Body(nullptr),
3625 SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3626 ManglingNumber(0), ManglingContextDecl(nullptr) {}
3629 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3630 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3632 SourceLocation getCaretLocation() const { return getLocation(); }
3634 bool isVariadic() const { return IsVariadic; }
3635 void setIsVariadic(bool value) { IsVariadic = value; }
3637 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3638 Stmt *getBody() const override { return (Stmt*) Body; }
3639 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3641 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3642 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3644 // ArrayRef access to formal parameters.
3645 ArrayRef<ParmVarDecl *> parameters() const {
3646 return {ParamInfo, getNumParams()};
3648 MutableArrayRef<ParmVarDecl *> parameters() {
3649 return {ParamInfo, getNumParams()};
3652 // Iterator access to formal parameters.
3653 typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
3654 typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
3655 bool param_empty() const { return parameters().empty(); }
3656 param_iterator param_begin() { return parameters().begin(); }
3657 param_iterator param_end() { return parameters().end(); }
3658 param_const_iterator param_begin() const { return parameters().begin(); }
3659 param_const_iterator param_end() const { return parameters().end(); }
3660 size_t param_size() const { return parameters().size(); }
3662 unsigned getNumParams() const { return NumParams; }
3663 const ParmVarDecl *getParamDecl(unsigned i) const {
3664 assert(i < getNumParams() && "Illegal param #");
3665 return ParamInfo[i];
3667 ParmVarDecl *getParamDecl(unsigned i) {
3668 assert(i < getNumParams() && "Illegal param #");
3669 return ParamInfo[i];
3671 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3673 /// hasCaptures - True if this block (or its nested blocks) captures
3674 /// anything of local storage from its enclosing scopes.
3675 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3677 /// getNumCaptures - Returns the number of captured variables.
3678 /// Does not include an entry for 'this'.
3679 unsigned getNumCaptures() const { return NumCaptures; }
3681 typedef ArrayRef<Capture>::const_iterator capture_const_iterator;
3683 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3685 capture_const_iterator capture_begin() const { return captures().begin(); }
3686 capture_const_iterator capture_end() const { return captures().end(); }
3688 bool capturesCXXThis() const { return CapturesCXXThis; }
3689 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3690 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3692 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3693 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3695 bool capturesVariable(const VarDecl *var) const;
3697 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3698 bool CapturesCXXThis);
3700 unsigned getBlockManglingNumber() const {
3701 return ManglingNumber;
3703 Decl *getBlockManglingContextDecl() const {
3704 return ManglingContextDecl;
3707 void setBlockMangling(unsigned Number, Decl *Ctx) {
3708 ManglingNumber = Number;
3709 ManglingContextDecl = Ctx;
3712 SourceRange getSourceRange() const override LLVM_READONLY;
3714 // Implement isa/cast/dyncast/etc.
3715 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3716 static bool classofKind(Kind K) { return K == Block; }
3717 static DeclContext *castToDeclContext(const BlockDecl *D) {
3718 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3720 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3721 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3725 /// \brief This represents the body of a CapturedStmt, and serves as its
3727 class CapturedDecl final
3730 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3732 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3737 /// \brief The number of parameters to the outlined function.
3739 /// \brief The position of context parameter in list of parameters.
3740 unsigned ContextParam;
3741 /// \brief The body of the outlined function.
3742 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3744 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3746 ImplicitParamDecl *const *getParams() const {
3747 return getTrailingObjects<ImplicitParamDecl *>();
3750 ImplicitParamDecl **getParams() {
3751 return getTrailingObjects<ImplicitParamDecl *>();
3755 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3756 unsigned NumParams);
3757 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3758 unsigned NumParams);
3760 Stmt *getBody() const override;
3761 void setBody(Stmt *B);
3763 bool isNothrow() const;
3764 void setNothrow(bool Nothrow = true);
3766 unsigned getNumParams() const { return NumParams; }
3768 ImplicitParamDecl *getParam(unsigned i) const {
3769 assert(i < NumParams);
3770 return getParams()[i];
3772 void setParam(unsigned i, ImplicitParamDecl *P) {
3773 assert(i < NumParams);
3777 // ArrayRef interface to parameters.
3778 ArrayRef<ImplicitParamDecl *> parameters() const {
3779 return {getParams(), getNumParams()};
3781 MutableArrayRef<ImplicitParamDecl *> parameters() {
3782 return {getParams(), getNumParams()};
3785 /// \brief Retrieve the parameter containing captured variables.
3786 ImplicitParamDecl *getContextParam() const {
3787 assert(ContextParam < NumParams);
3788 return getParam(ContextParam);
3790 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3791 assert(i < NumParams);
3795 unsigned getContextParamPosition() const { return ContextParam; }
3797 typedef ImplicitParamDecl *const *param_iterator;
3798 typedef llvm::iterator_range<param_iterator> param_range;
3800 /// \brief Retrieve an iterator pointing to the first parameter decl.
3801 param_iterator param_begin() const { return getParams(); }
3802 /// \brief Retrieve an iterator one past the last parameter decl.
3803 param_iterator param_end() const { return getParams() + NumParams; }
3805 // Implement isa/cast/dyncast/etc.
3806 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3807 static bool classofKind(Kind K) { return K == Captured; }
3808 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3809 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3811 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3812 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3815 friend class ASTDeclReader;
3816 friend class ASTDeclWriter;
3817 friend TrailingObjects;
3820 /// \brief Describes a module import declaration, which makes the contents
3821 /// of the named module visible in the current translation unit.
3823 /// An import declaration imports the named module (or submodule). For example:
3825 /// @import std.vector;
3828 /// Import declarations can also be implicitly generated from
3829 /// \#include/\#import directives.
3830 class ImportDecl final : public Decl,
3831 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3832 /// \brief The imported module, along with a bit that indicates whether
3833 /// we have source-location information for each identifier in the module
3836 /// When the bit is false, we only have a single source location for the
3837 /// end of the import declaration.
3838 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3840 /// \brief The next import in the list of imports local to the translation
3841 /// unit being parsed (not loaded from an AST file).
3842 ImportDecl *NextLocalImport;
3844 friend class ASTReader;
3845 friend class ASTDeclReader;
3846 friend class ASTContext;
3847 friend TrailingObjects;
3849 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3850 ArrayRef<SourceLocation> IdentifierLocs);
3852 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3853 SourceLocation EndLoc);
3855 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3858 /// \brief Create a new module import declaration.
3859 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3860 SourceLocation StartLoc, Module *Imported,
3861 ArrayRef<SourceLocation> IdentifierLocs);
3863 /// \brief Create a new module import declaration for an implicitly-generated
3865 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3866 SourceLocation StartLoc, Module *Imported,
3867 SourceLocation EndLoc);
3869 /// \brief Create a new, deserialized module import declaration.
3870 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3871 unsigned NumLocations);
3873 /// \brief Retrieve the module that was imported by the import declaration.
3874 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3876 /// \brief Retrieves the locations of each of the identifiers that make up
3877 /// the complete module name in the import declaration.
3879 /// This will return an empty array if the locations of the individual
3880 /// identifiers aren't available.
3881 ArrayRef<SourceLocation> getIdentifierLocs() const;
3883 SourceRange getSourceRange() const override LLVM_READONLY;
3885 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3886 static bool classofKind(Kind K) { return K == Import; }
3889 /// \brief Represents a C++ Modules TS module export declaration.
3893 /// export void foo();
3895 class ExportDecl final : public Decl, public DeclContext {
3896 virtual void anchor();
3898 /// \brief The source location for the right brace (if valid).
3899 SourceLocation RBraceLoc;
3901 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
3902 : Decl(Export, DC, ExportLoc), DeclContext(Export),
3903 RBraceLoc(SourceLocation()) { }
3905 friend class ASTDeclReader;
3908 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
3909 SourceLocation ExportLoc);
3910 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3912 SourceLocation getExportLoc() const { return getLocation(); }
3913 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3914 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
3916 SourceLocation getLocEnd() const LLVM_READONLY {
3917 if (RBraceLoc.isValid())
3919 // No braces: get the end location of the (only) declaration in context
3921 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
3924 SourceRange getSourceRange() const override LLVM_READONLY {
3925 return SourceRange(getLocation(), getLocEnd());
3928 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3929 static bool classofKind(Kind K) { return K == Export; }
3930 static DeclContext *castToDeclContext(const ExportDecl *D) {
3931 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
3933 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
3934 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
3938 /// \brief Represents an empty-declaration.
3939 class EmptyDecl : public Decl {
3940 virtual void anchor();
3941 EmptyDecl(DeclContext *DC, SourceLocation L)
3942 : Decl(Empty, DC, L) { }
3945 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3947 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3949 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3950 static bool classofKind(Kind K) { return K == Empty; }
3953 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3954 /// into a diagnostic with <<.
3955 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3956 const NamedDecl* ND) {
3957 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3958 DiagnosticsEngine::ak_nameddecl);
3961 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3962 const NamedDecl* ND) {
3963 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3964 DiagnosticsEngine::ak_nameddecl);
3968 template<typename decl_type>
3969 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3970 // Note: This routine is implemented here because we need both NamedDecl
3971 // and Redeclarable to be defined.
3972 assert(RedeclLink.NextIsLatest() &&
3973 "setPreviousDecl on a decl already in a redeclaration chain");
3976 // Point to previous. Make sure that this is actually the most recent
3977 // redeclaration, or we can build invalid chains. If the most recent
3978 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3979 First = PrevDecl->getFirstDecl();
3980 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3981 decl_type *MostRecent = First->getNextRedeclaration();
3982 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3984 // If the declaration was previously visible, a redeclaration of it remains
3985 // visible even if it wouldn't be visible by itself.
3986 static_cast<decl_type*>(this)->IdentifierNamespace |=
3987 MostRecent->getIdentifierNamespace() &
3988 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3991 First = static_cast<decl_type*>(this);
3994 // First one will point to this one as latest.
3995 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3997 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3998 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4001 // Inline function definitions.
4003 /// \brief Check if the given decl is complete.
4005 /// We use this function to break a cycle between the inline definitions in
4006 /// Type.h and Decl.h.
4007 inline bool IsEnumDeclComplete(EnumDecl *ED) {
4008 return ED->isComplete();
4011 /// \brief Check if the given decl is scoped.
4013 /// We use this function to break a cycle between the inline definitions in
4014 /// Type.h and Decl.h.
4015 inline bool IsEnumDeclScoped(EnumDecl *ED) {
4016 return ED->isScoped();
4019 } // end namespace clang