Decl.h revision d0629eb137d06bf6d46a430abdb7fa044909298b
16f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//===--- Decl.h - Classes for representing declarations ---------*- C++ -*-===//
26f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//
36f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//                     The LLVM Compiler Infrastructure
46f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//
56f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org// This file is distributed under the University of Illinois Open Source
66f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org// License. See LICENSE.TXT for details.
76f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//
86f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//===----------------------------------------------------------------------===//
96f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//
106f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//  This file defines the Decl subclasses.
116f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//
126f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org//===----------------------------------------------------------------------===//
136f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
146f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#ifndef LLVM_CLANG_AST_DECL_H
156f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#define LLVM_CLANG_AST_DECL_H
166f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
176f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/APValue.h"
186f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/DeclBase.h"
196f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/DeclarationName.h"
206f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/ExternalASTSource.h"
216f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/Redeclarable.h"
226f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/AST/Type.h"
236f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "clang/Basic/Linkage.h"
246f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "llvm/ADT/ArrayRef.h"
256f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "llvm/ADT/Optional.h"
266f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "llvm/Support/Compiler.h"
276f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org#include "llvm/Support/raw_ostream.h"
286f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
296f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgnamespace clang {
306f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgstruct ASTTemplateArgumentListInfo;
316f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass CXXTemporary;
326f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass CompoundStmt;
336f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass DependentFunctionTemplateSpecializationInfo;
346f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass Expr;
356f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass FunctionTemplateDecl;
366f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass FunctionTemplateSpecializationInfo;
376f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass LabelStmt;
386f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass MemberSpecializationInfo;
396f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass Module;
406f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass NestedNameSpecifier;
416f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass Stmt;
426f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass StringLiteral;
436f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass TemplateArgumentList;
446f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass TemplateParameterList;
456f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass TypeLoc;
466f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass UnresolvedSetImpl;
476f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass VarTemplateDecl;
486f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
496f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// \brief A container of type source information.
506f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org///
516f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// A client can read the relevant info using TypeLoc wrappers, e.g:
526f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// @code
536f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
546f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
556f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org///   PL->getStarLoc().print(OS, SrcMgr);
566f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// @endcode
576f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org///
586f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass TypeSourceInfo {
596f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  QualType Ty;
606f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // Contains a memory block after the class, used for type source information,
616f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // allocated by ASTContext.
626f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  friend class ASTContext;
636f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  TypeSourceInfo(QualType ty) : Ty(ty) { }
646f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgpublic:
656f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Return the type wrapped by this type source info.
666f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  QualType getType() const { return Ty; }
676f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
686f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Return the TypeLoc wrapper for the type source info.
696f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
706f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org};
716f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
726f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// TranslationUnitDecl - The top declaration context.
736f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass TranslationUnitDecl : public Decl, public DeclContext {
746f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  virtual void anchor();
756f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  ASTContext &Ctx;
766f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
776f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// The (most recently entered) anonymous namespace for this
786f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// translation unit, if one has been created.
796f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  NamespaceDecl *AnonymousNamespace;
806f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
816f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  explicit TranslationUnitDecl(ASTContext &ctx)
826f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    : Decl(TranslationUnit, 0, SourceLocation()),
836f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org      DeclContext(TranslationUnit),
846f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org      Ctx(ctx), AnonymousNamespace(0) {}
856f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgpublic:
866f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  ASTContext &getASTContext() const { return Ctx; }
876f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
886f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
896f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
906f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
916f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  static TranslationUnitDecl *Create(ASTContext &C);
926f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // Implement isa/cast/dyncast/etc.
936f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
946f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  static bool classofKind(Kind K) { return K == TranslationUnit; }
956f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
966f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
976f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  }
986f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
996f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
1006f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  }
1016f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org};
1026f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1036f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// NamedDecl - This represents a decl with a name.  Many decls have names such
1046f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org/// as ObjCMethodDecl, but not \@class, etc.
1056f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgclass NamedDecl : public Decl {
1066f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  virtual void anchor();
1076f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// Name - The name of this declaration, which is typically a normal
1086f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// identifier but may also be a special kind of name (C++
1096f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// constructor, Objective-C selector, etc.)
1106f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  DeclarationName Name;
1116f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1126f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgprivate:
1136f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  NamedDecl *getUnderlyingDeclImpl();
1146f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1156f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgprotected:
1166f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
1176f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    : Decl(DK, DC, L), Name(N) { }
1186f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1196f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.orgpublic:
1206f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// getIdentifier - Get the identifier that names this declaration,
1216f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// if there is one. This will return NULL if this declaration has
1226f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// no name (e.g., for an unnamed class) or if the name is a special
1236f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// name (C++ constructor, Objective-C selector, etc.).
1246f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
1256f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1266f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// getName - Get the name of identifier for this declaration as a StringRef.
1276f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// This requires that the declaration have a name and that it be a simple
1286f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// identifier.
1296f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  StringRef getName() const {
1306f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    assert(Name.isIdentifier() && "Name is not a simple identifier");
1316f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    return getIdentifier() ? getIdentifier()->getName() : "";
1326f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  }
1336f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1346f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// getNameAsString - Get a human-readable name for the declaration, even if
1356f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// it is one of the special kinds of names (C++ constructor, Objective-C
1366f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// selector, etc).  Creating this name requires expensive string
1376f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// manipulation, so it should be called only when performance doesn't matter.
1386f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// For simple declarations, getNameAsCString() should suffice.
1396f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  //
1406f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // FIXME: This function should be renamed to indicate that it is not just an
1416f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // alternate form of getName(), and clients should move as appropriate.
1426f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  //
1436f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // FIXME: Deprecated, move clients to getName().
1446f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  std::string getNameAsString() const { return Name.getAsString(); }
1456f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1466f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void printName(raw_ostream &os) const { os << Name; }
1476f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1486f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// getDeclName - Get the actual, stored name of the declaration,
1496f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// which may be a special name.
1506f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  DeclarationName getDeclName() const { return Name; }
1516f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1526f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Set the name of this declaration.
1536f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void setDeclName(DeclarationName N) { Name = N; }
1546f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1556f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// printQualifiedName - Returns human-readable qualified name for
1566f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// declaration, like A::B::i, for i being member of namespace A::B.
1576f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// If declaration is not member of context which can be named (record,
1586f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// namespace), it will return same result as printName().
1596f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// Creating this name is expensive, so it should be called only when
1606f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// performance doesn't matter.
1616f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void printQualifiedName(raw_ostream &OS) const;
1626f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
1636f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1646f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  // FIXME: Remove string versions.
1656f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  std::string getQualifiedNameAsString() const;
1666f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
1676f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1686f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// getNameForDiagnostic - Appends a human-readable name for this
1696f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// declaration into the given stream.
1706f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  ///
1716f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// This is the method invoked by Sema when displaying a NamedDecl
1726f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// in a diagnostic.  It does not necessarily produce the same
1736f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// result as printName(); for example, class template
1746f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// specializations are printed with their template arguments.
1756f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  virtual void getNameForDiagnostic(raw_ostream &OS,
1766f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org                                    const PrintingPolicy &Policy,
1776f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org                                    bool Qualified) const;
1786f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1796f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// declarationReplaces - Determine whether this declaration, if
1806f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// known to be well-formed within its context, will replace the
1816f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// declaration OldD if introduced into scope. A declaration will
1826f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// replace another declaration if, for example, it is a
1836f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// redeclaration of the same variable or function, but not if it is
1846f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// a declaration of a different kind (function vs. class) or an
1856f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// overloaded function.
1866f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  bool declarationReplaces(NamedDecl *OldD) const;
1876f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1886f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Determine whether this declaration has linkage.
1896f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  bool hasLinkage() const;
1906f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1916f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  using Decl::isModulePrivate;
1926f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  using Decl::setModulePrivate;
1936f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1946f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Determine whether this declaration is hidden from name lookup.
1956f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  bool isHidden() const { return Hidden; }
1966f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
1976f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Set whether this declaration is hidden from name lookup.
1986f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  void setHidden(bool Hide) { Hidden = Hide; }
1996f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
2006f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  /// \brief Determine whether this declaration is a C++ class member.
2016f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org  bool isCXXClassMember() const {
2026f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    const DeclContext *DC = getDeclContext();
2036f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org
2046f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    // C++0x [class.mem]p1:
2056f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    //   The enumerators of an unscoped enumeration defined in
2066f31ac30b9092fd02a8c97e5216cf53f3e4fae4jshin@chromium.org    //   the class are members of the class.
207    // FIXME: support C++0x scoped enumerations.
208    if (isa<EnumDecl>(DC))
209      DC = DC->getParent();
210
211    return DC->isRecord();
212  }
213
214  /// \brief Determine whether the given declaration is an instance member of
215  /// a C++ class.
216  bool isCXXInstanceMember() const;
217
218  /// \brief Determine what kind of linkage this entity has.
219  /// This is not the linkage as defined by the standard or the codegen notion
220  /// of linkage. It is just an implementation detail that is used to compute
221  /// those.
222  Linkage getLinkageInternal() const;
223
224  /// \brief Get the linkage from a semantic point of view. Entities in
225  /// anonymous namespaces are external (in c++98).
226  Linkage getFormalLinkage() const {
227    return clang::getFormalLinkage(getLinkageInternal());
228  }
229
230  /// \brief True if this decl has external linkage.
231  bool hasExternalFormalLinkage() const {
232    return isExternalFormalLinkage(getLinkageInternal());
233  }
234
235  bool isExternallyVisible() const {
236    return clang::isExternallyVisible(getLinkageInternal());
237  }
238
239  /// \brief Determines the visibility of this entity.
240  Visibility getVisibility() const {
241    return getLinkageAndVisibility().getVisibility();
242  }
243
244  /// \brief Determines the linkage and visibility of this entity.
245  LinkageInfo getLinkageAndVisibility() const;
246
247  /// Kinds of explicit visibility.
248  enum ExplicitVisibilityKind {
249    VisibilityForType,
250    VisibilityForValue
251  };
252
253  /// \brief If visibility was explicitly specified for this
254  /// declaration, return that visibility.
255  Optional<Visibility>
256  getExplicitVisibility(ExplicitVisibilityKind kind) const;
257
258  /// \brief True if the computed linkage is valid. Used for consistency
259  /// checking. Should always return true.
260  bool isLinkageValid() const;
261
262  /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
263  /// the underlying named decl.
264  NamedDecl *getUnderlyingDecl() {
265    // Fast-path the common case.
266    if (this->getKind() != UsingShadow &&
267        this->getKind() != ObjCCompatibleAlias)
268      return this;
269
270    return getUnderlyingDeclImpl();
271  }
272  const NamedDecl *getUnderlyingDecl() const {
273    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
274  }
275
276  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
277  static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
278};
279
280inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
281  ND.printName(OS);
282  return OS;
283}
284
285/// LabelDecl - Represents the declaration of a label.  Labels also have a
286/// corresponding LabelStmt, which indicates the position that the label was
287/// defined at.  For normal labels, the location of the decl is the same as the
288/// location of the statement.  For GNU local labels (__label__), the decl
289/// location is where the __label__ is.
290class LabelDecl : public NamedDecl {
291  virtual void anchor();
292  LabelStmt *TheStmt;
293  /// LocStart - For normal labels, this is the same as the main declaration
294  /// label, i.e., the location of the identifier; for GNU local labels,
295  /// this is the location of the __label__ keyword.
296  SourceLocation LocStart;
297
298  LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
299            LabelStmt *S, SourceLocation StartL)
300    : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
301
302public:
303  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
304                           SourceLocation IdentL, IdentifierInfo *II);
305  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
306                           SourceLocation IdentL, IdentifierInfo *II,
307                           SourceLocation GnuLabelL);
308  static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
309
310  LabelStmt *getStmt() const { return TheStmt; }
311  void setStmt(LabelStmt *T) { TheStmt = T; }
312
313  bool isGnuLocal() const { return LocStart != getLocation(); }
314  void setLocStart(SourceLocation L) { LocStart = L; }
315
316  SourceRange getSourceRange() const LLVM_READONLY {
317    return SourceRange(LocStart, getLocation());
318  }
319
320  // Implement isa/cast/dyncast/etc.
321  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
322  static bool classofKind(Kind K) { return K == Label; }
323};
324
325/// NamespaceDecl - Represent a C++ namespace.
326class NamespaceDecl : public NamedDecl, public DeclContext,
327                      public Redeclarable<NamespaceDecl>
328{
329  virtual void anchor();
330
331  /// LocStart - The starting location of the source range, pointing
332  /// to either the namespace or the inline keyword.
333  SourceLocation LocStart;
334  /// RBraceLoc - The ending location of the source range.
335  SourceLocation RBraceLoc;
336
337  /// \brief A pointer to either the anonymous namespace that lives just inside
338  /// this namespace or to the first namespace in the chain (the latter case
339  /// only when this is not the first in the chain), along with a
340  /// boolean value indicating whether this is an inline namespace.
341  llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
342
343  NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
344                SourceLocation IdLoc, IdentifierInfo *Id,
345                NamespaceDecl *PrevDecl);
346
347  typedef Redeclarable<NamespaceDecl> redeclarable_base;
348  virtual NamespaceDecl *getNextRedeclaration() {
349    return RedeclLink.getNext();
350  }
351  virtual NamespaceDecl *getPreviousDeclImpl() {
352    return getPreviousDecl();
353  }
354  virtual NamespaceDecl *getMostRecentDeclImpl() {
355    return getMostRecentDecl();
356  }
357
358public:
359  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
360                               bool Inline, SourceLocation StartLoc,
361                               SourceLocation IdLoc, IdentifierInfo *Id,
362                               NamespaceDecl *PrevDecl);
363
364  static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
365
366  typedef redeclarable_base::redecl_iterator redecl_iterator;
367  using redeclarable_base::redecls_begin;
368  using redeclarable_base::redecls_end;
369  using redeclarable_base::getPreviousDecl;
370  using redeclarable_base::getMostRecentDecl;
371
372  /// \brief Returns true if this is an anonymous namespace declaration.
373  ///
374  /// For example:
375  /// \code
376  ///   namespace {
377  ///     ...
378  ///   };
379  /// \endcode
380  /// q.v. C++ [namespace.unnamed]
381  bool isAnonymousNamespace() const {
382    return !getIdentifier();
383  }
384
385  /// \brief Returns true if this is an inline namespace declaration.
386  bool isInline() const {
387    return AnonOrFirstNamespaceAndInline.getInt();
388  }
389
390  /// \brief Set whether this is an inline namespace declaration.
391  void setInline(bool Inline) {
392    AnonOrFirstNamespaceAndInline.setInt(Inline);
393  }
394
395  /// \brief Get the original (first) namespace declaration.
396  NamespaceDecl *getOriginalNamespace() {
397    if (isFirstDeclaration())
398      return this;
399
400    return AnonOrFirstNamespaceAndInline.getPointer();
401  }
402
403  /// \brief Get the original (first) namespace declaration.
404  const NamespaceDecl *getOriginalNamespace() const {
405    if (isFirstDeclaration())
406      return this;
407
408    return AnonOrFirstNamespaceAndInline.getPointer();
409  }
410
411  /// \brief Return true if this declaration is an original (first) declaration
412  /// of the namespace. This is false for non-original (subsequent) namespace
413  /// declarations and anonymous namespaces.
414  bool isOriginalNamespace() const {
415    return isFirstDeclaration();
416  }
417
418  /// \brief Retrieve the anonymous namespace nested inside this namespace,
419  /// if any.
420  NamespaceDecl *getAnonymousNamespace() const {
421    return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
422  }
423
424  void setAnonymousNamespace(NamespaceDecl *D) {
425    getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
426  }
427
428  /// Retrieves the canonical declaration of this namespace.
429  NamespaceDecl *getCanonicalDecl() {
430    return getOriginalNamespace();
431  }
432  const NamespaceDecl *getCanonicalDecl() const {
433    return getOriginalNamespace();
434  }
435
436  virtual SourceRange getSourceRange() const LLVM_READONLY {
437    return SourceRange(LocStart, RBraceLoc);
438  }
439
440  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
441  SourceLocation getRBraceLoc() const { return RBraceLoc; }
442  void setLocStart(SourceLocation L) { LocStart = L; }
443  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
444
445  // Implement isa/cast/dyncast/etc.
446  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
447  static bool classofKind(Kind K) { return K == Namespace; }
448  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
449    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
450  }
451  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
452    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
453  }
454
455  friend class ASTDeclReader;
456  friend class ASTDeclWriter;
457};
458
459/// ValueDecl - Represent the declaration of a variable (in which case it is
460/// an lvalue) a function (in which case it is a function designator) or
461/// an enum constant.
462class ValueDecl : public NamedDecl {
463  virtual void anchor();
464  QualType DeclType;
465
466protected:
467  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
468            DeclarationName N, QualType T)
469    : NamedDecl(DK, DC, L, N), DeclType(T) {}
470public:
471  QualType getType() const { return DeclType; }
472  void setType(QualType newType) { DeclType = newType; }
473
474  /// \brief Determine whether this symbol is weakly-imported,
475  ///        or declared with the weak or weak-ref attr.
476  bool isWeak() const;
477
478  // Implement isa/cast/dyncast/etc.
479  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
480  static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
481};
482
483/// QualifierInfo - A struct with extended info about a syntactic
484/// name qualifier, to be used for the case of out-of-line declarations.
485struct QualifierInfo {
486  NestedNameSpecifierLoc QualifierLoc;
487
488  /// NumTemplParamLists - The number of "outer" template parameter lists.
489  /// The count includes all of the template parameter lists that were matched
490  /// against the template-ids occurring into the NNS and possibly (in the
491  /// case of an explicit specialization) a final "template <>".
492  unsigned NumTemplParamLists;
493
494  /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
495  /// containing pointers to the "outer" template parameter lists.
496  /// It includes all of the template parameter lists that were matched
497  /// against the template-ids occurring into the NNS and possibly (in the
498  /// case of an explicit specialization) a final "template <>".
499  TemplateParameterList** TemplParamLists;
500
501  /// Default constructor.
502  QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
503
504  /// setTemplateParameterListsInfo - Sets info about "outer" template
505  /// parameter lists.
506  void setTemplateParameterListsInfo(ASTContext &Context,
507                                     unsigned NumTPLists,
508                                     TemplateParameterList **TPLists);
509
510private:
511  // Copy constructor and copy assignment are disabled.
512  QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION;
513  QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION;
514};
515
516/// \brief Represents a ValueDecl that came out of a declarator.
517/// Contains type source information through TypeSourceInfo.
518class DeclaratorDecl : public ValueDecl {
519  // A struct representing both a TInfo and a syntactic qualifier,
520  // to be used for the (uncommon) case of out-of-line declarations.
521  struct ExtInfo : public QualifierInfo {
522    TypeSourceInfo *TInfo;
523  };
524
525  llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
526
527  /// InnerLocStart - The start of the source range for this declaration,
528  /// ignoring outer template declarations.
529  SourceLocation InnerLocStart;
530
531  bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
532  ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
533  const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
534
535protected:
536  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
537                 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
538                 SourceLocation StartL)
539    : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
540  }
541
542public:
543  TypeSourceInfo *getTypeSourceInfo() const {
544    return hasExtInfo()
545      ? getExtInfo()->TInfo
546      : DeclInfo.get<TypeSourceInfo*>();
547  }
548  void setTypeSourceInfo(TypeSourceInfo *TI) {
549    if (hasExtInfo())
550      getExtInfo()->TInfo = TI;
551    else
552      DeclInfo = TI;
553  }
554
555  /// getInnerLocStart - Return SourceLocation representing start of source
556  /// range ignoring outer template declarations.
557  SourceLocation getInnerLocStart() const { return InnerLocStart; }
558  void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
559
560  /// getOuterLocStart - Return SourceLocation representing start of source
561  /// range taking into account any outer template declarations.
562  SourceLocation getOuterLocStart() const;
563
564  virtual SourceRange getSourceRange() const LLVM_READONLY;
565  SourceLocation getLocStart() const LLVM_READONLY {
566    return getOuterLocStart();
567  }
568
569  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
570  /// declaration, if it was present in the source.
571  NestedNameSpecifier *getQualifier() const {
572    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
573                        : 0;
574  }
575
576  /// \brief Retrieve the nested-name-specifier (with source-location
577  /// information) that qualifies the name of this declaration, if it was
578  /// present in the source.
579  NestedNameSpecifierLoc getQualifierLoc() const {
580    return hasExtInfo() ? getExtInfo()->QualifierLoc
581                        : NestedNameSpecifierLoc();
582  }
583
584  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
585
586  unsigned getNumTemplateParameterLists() const {
587    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
588  }
589  TemplateParameterList *getTemplateParameterList(unsigned index) const {
590    assert(index < getNumTemplateParameterLists());
591    return getExtInfo()->TemplParamLists[index];
592  }
593  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
594                                     TemplateParameterList **TPLists);
595
596  SourceLocation getTypeSpecStartLoc() const;
597
598  // Implement isa/cast/dyncast/etc.
599  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
600  static bool classofKind(Kind K) {
601    return K >= firstDeclarator && K <= lastDeclarator;
602  }
603
604  friend class ASTDeclReader;
605  friend class ASTDeclWriter;
606};
607
608/// \brief Structure used to store a statement, the constant value to
609/// which it was evaluated (if any), and whether or not the statement
610/// is an integral constant expression (if known).
611struct EvaluatedStmt {
612  EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
613                    CheckingICE(false), IsICE(false) { }
614
615  /// \brief Whether this statement was already evaluated.
616  bool WasEvaluated : 1;
617
618  /// \brief Whether this statement is being evaluated.
619  bool IsEvaluating : 1;
620
621  /// \brief Whether we already checked whether this statement was an
622  /// integral constant expression.
623  bool CheckedICE : 1;
624
625  /// \brief Whether we are checking whether this statement is an
626  /// integral constant expression.
627  bool CheckingICE : 1;
628
629  /// \brief Whether this statement is an integral constant expression,
630  /// or in C++11, whether the statement is a constant expression. Only
631  /// valid if CheckedICE is true.
632  bool IsICE : 1;
633
634  Stmt *Value;
635  APValue Evaluated;
636};
637
638/// VarDecl - An instance of this class is created to represent a variable
639/// declaration or definition.
640class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
641public:
642  typedef clang::StorageClass StorageClass;
643
644  /// getStorageClassSpecifierString - Return the string used to
645  /// specify the storage class \p SC.
646  ///
647  /// It is illegal to call this function with SC == None.
648  static const char *getStorageClassSpecifierString(StorageClass SC);
649
650  /// \brief Initialization styles.
651  enum InitializationStyle {
652    CInit,    ///< C-style initialization with assignment
653    CallInit, ///< Call-style initialization (C++98)
654    ListInit  ///< Direct list-initialization (C++11)
655  };
656
657  /// \brief Kinds of thread-local storage.
658  enum TLSKind {
659    TLS_None,   ///< Not a TLS variable.
660    TLS_Static, ///< TLS with a known-constant initializer.
661    TLS_Dynamic ///< TLS with a dynamic initializer.
662  };
663
664protected:
665  /// \brief Placeholder type used in Init to denote an unparsed C++ default
666  /// argument.
667  struct UnparsedDefaultArgument;
668
669  /// \brief Placeholder type used in Init to denote an uninstantiated C++
670  /// default argument.
671  struct UninstantiatedDefaultArgument;
672
673  typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
674                              UnparsedDefaultArgument *,
675                              UninstantiatedDefaultArgument *> InitType;
676
677  /// \brief The initializer for this variable or, for a ParmVarDecl, the
678  /// C++ default argument.
679  mutable InitType Init;
680
681private:
682  class VarDeclBitfields {
683    friend class VarDecl;
684    friend class ASTDeclReader;
685
686    unsigned SClass : 3;
687    unsigned TSCSpec : 2;
688    unsigned InitStyle : 2;
689
690    /// \brief Whether this variable is the exception variable in a C++ catch
691    /// or an Objective-C @catch statement.
692    unsigned ExceptionVar : 1;
693
694    /// \brief Whether this local variable could be allocated in the return
695    /// slot of its function, enabling the named return value optimization
696    /// (NRVO).
697    unsigned NRVOVariable : 1;
698
699    /// \brief Whether this variable is the for-range-declaration in a C++0x
700    /// for-range statement.
701    unsigned CXXForRangeDecl : 1;
702
703    /// \brief Whether this variable is an ARC pseudo-__strong
704    /// variable;  see isARCPseudoStrong() for details.
705    unsigned ARCPseudoStrong : 1;
706
707    /// \brief Whether this variable is (C++0x) constexpr.
708    unsigned IsConstexpr : 1;
709
710    /// \brief Whether this local extern variable's previous declaration was
711    /// declared in the same block scope. This controls whether we should merge
712    /// the type of this declaration with its previous declaration.
713    unsigned PreviousDeclInSameBlockScope : 1;
714  };
715  enum { NumVarDeclBits = 13 };
716
717  friend class ASTDeclReader;
718  friend class StmtIteratorBase;
719  friend class ASTNodeImporter;
720
721protected:
722  enum { NumParameterIndexBits = 8 };
723
724  class ParmVarDeclBitfields {
725    friend class ParmVarDecl;
726    friend class ASTDeclReader;
727
728    unsigned : NumVarDeclBits;
729
730    /// Whether this parameter inherits a default argument from a
731    /// prior declaration.
732    unsigned HasInheritedDefaultArg : 1;
733
734    /// Whether this parameter undergoes K&R argument promotion.
735    unsigned IsKNRPromoted : 1;
736
737    /// Whether this parameter is an ObjC method parameter or not.
738    unsigned IsObjCMethodParam : 1;
739
740    /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
741    /// Otherwise, the number of function parameter scopes enclosing
742    /// the function parameter scope in which this parameter was
743    /// declared.
744    unsigned ScopeDepthOrObjCQuals : 7;
745
746    /// The number of parameters preceding this parameter in the
747    /// function parameter scope in which it was declared.
748    unsigned ParameterIndex : NumParameterIndexBits;
749  };
750
751  union {
752    unsigned AllBits;
753    VarDeclBitfields VarDeclBits;
754    ParmVarDeclBitfields ParmVarDeclBits;
755  };
756
757  VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
758          SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
759          TypeSourceInfo *TInfo, StorageClass SC);
760
761  typedef Redeclarable<VarDecl> redeclarable_base;
762  virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
763  virtual VarDecl *getPreviousDeclImpl() {
764    return getPreviousDecl();
765  }
766  virtual VarDecl *getMostRecentDeclImpl() {
767    return getMostRecentDecl();
768  }
769
770public:
771  typedef redeclarable_base::redecl_iterator redecl_iterator;
772  using redeclarable_base::redecls_begin;
773  using redeclarable_base::redecls_end;
774  using redeclarable_base::getPreviousDecl;
775  using redeclarable_base::getMostRecentDecl;
776
777  static VarDecl *Create(ASTContext &C, DeclContext *DC,
778                         SourceLocation StartLoc, SourceLocation IdLoc,
779                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
780                         StorageClass S);
781
782  static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
783
784  virtual SourceRange getSourceRange() const LLVM_READONLY;
785
786  /// \brief Returns the storage class as written in the source. For the
787  /// computed linkage of symbol, see getLinkage.
788  StorageClass getStorageClass() const {
789    return (StorageClass) VarDeclBits.SClass;
790  }
791  void setStorageClass(StorageClass SC);
792
793  void setTSCSpec(ThreadStorageClassSpecifier TSC) {
794    VarDeclBits.TSCSpec = TSC;
795  }
796  ThreadStorageClassSpecifier getTSCSpec() const {
797    return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
798  }
799  TLSKind getTLSKind() const {
800    switch (VarDeclBits.TSCSpec) {
801    case TSCS_unspecified:
802      return TLS_None;
803    case TSCS___thread: // Fall through.
804    case TSCS__Thread_local:
805      return TLS_Static;
806    case TSCS_thread_local:
807      return TLS_Dynamic;
808    }
809    llvm_unreachable("Unknown thread storage class specifier!");
810  }
811
812  /// hasLocalStorage - Returns true if a variable with function scope
813  ///  is a non-static local variable.
814  bool hasLocalStorage() const {
815    if (getStorageClass() == SC_None)
816      // Second check is for C++11 [dcl.stc]p4.
817      return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
818
819    // Return true for:  Auto, Register.
820    // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
821
822    return getStorageClass() >= SC_Auto;
823  }
824
825  /// isStaticLocal - Returns true if a variable with function scope is a
826  /// static local variable.
827  bool isStaticLocal() const {
828    return (getStorageClass() == SC_Static ||
829            // C++11 [dcl.stc]p4
830            (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
831      && !isFileVarDecl();
832  }
833
834  /// \brief Returns true if a variable has extern or __private_extern__
835  /// storage.
836  bool hasExternalStorage() const {
837    return getStorageClass() == SC_Extern ||
838           getStorageClass() == SC_PrivateExtern;
839  }
840
841  /// hasGlobalStorage - Returns true for all variables that do not
842  ///  have local storage.  This includs all global variables as well
843  ///  as static variables declared within a function.
844  bool hasGlobalStorage() const { return !hasLocalStorage(); }
845
846  /// \brief Get the storage duration of this variable, per C++ [basid.stc].
847  StorageDuration getStorageDuration() const {
848    return hasLocalStorage() ? SD_Automatic :
849           getTSCSpec() ? SD_Thread : SD_Static;
850  }
851
852  /// Compute the language linkage.
853  LanguageLinkage getLanguageLinkage() const;
854
855  /// \brief Determines whether this variable is a variable with
856  /// external, C linkage.
857  bool isExternC() const;
858
859  /// \brief Determines whether this variable's context is, or is nested within,
860  /// a C++ extern "C" linkage spec.
861  bool isInExternCContext() const;
862
863  /// \brief Determines whether this variable's context is, or is nested within,
864  /// a C++ extern "C++" linkage spec.
865  bool isInExternCXXContext() const;
866
867  /// isLocalVarDecl - Returns true for local variable declarations
868  /// other than parameters.  Note that this includes static variables
869  /// inside of functions. It also includes variables inside blocks.
870  ///
871  ///   void foo() { int x; static int y; extern int z; }
872  ///
873  bool isLocalVarDecl() const {
874    if (getKind() != Decl::Var)
875      return false;
876    if (const DeclContext *DC = getLexicalDeclContext())
877      return DC->getRedeclContext()->isFunctionOrMethod();
878    return false;
879  }
880
881  /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
882  /// excludes variables declared in blocks.
883  bool isFunctionOrMethodVarDecl() const {
884    if (getKind() != Decl::Var)
885      return false;
886    const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
887    return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
888  }
889
890  /// \brief Determines whether this is a static data member.
891  ///
892  /// This will only be true in C++, and applies to, e.g., the
893  /// variable 'x' in:
894  /// \code
895  /// struct S {
896  ///   static int x;
897  /// };
898  /// \endcode
899  bool isStaticDataMember() const {
900    // If it wasn't static, it would be a FieldDecl.
901    return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
902  }
903
904  virtual VarDecl *getCanonicalDecl();
905  const VarDecl *getCanonicalDecl() const {
906    return const_cast<VarDecl*>(this)->getCanonicalDecl();
907  }
908
909  enum DefinitionKind {
910    DeclarationOnly,      ///< This declaration is only a declaration.
911    TentativeDefinition,  ///< This declaration is a tentative definition.
912    Definition            ///< This declaration is definitely a definition.
913  };
914
915  /// \brief Check whether this declaration is a definition. If this could be
916  /// a tentative definition (in C), don't check whether there's an overriding
917  /// definition.
918  DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
919  DefinitionKind isThisDeclarationADefinition() const {
920    return isThisDeclarationADefinition(getASTContext());
921  }
922
923  /// \brief Check whether this variable is defined in this
924  /// translation unit.
925  DefinitionKind hasDefinition(ASTContext &) const;
926  DefinitionKind hasDefinition() const {
927    return hasDefinition(getASTContext());
928  }
929
930  /// \brief Get the tentative definition that acts as the real definition in
931  /// a TU. Returns null if there is a proper definition available.
932  VarDecl *getActingDefinition();
933  const VarDecl *getActingDefinition() const {
934    return const_cast<VarDecl*>(this)->getActingDefinition();
935  }
936
937  /// \brief Get the real (not just tentative) definition for this declaration.
938  VarDecl *getDefinition(ASTContext &);
939  const VarDecl *getDefinition(ASTContext &C) const {
940    return const_cast<VarDecl*>(this)->getDefinition(C);
941  }
942  VarDecl *getDefinition() {
943    return getDefinition(getASTContext());
944  }
945  const VarDecl *getDefinition() const {
946    return const_cast<VarDecl*>(this)->getDefinition();
947  }
948
949  /// \brief Determine whether this is or was instantiated from an out-of-line
950  /// definition of a static data member.
951  virtual bool isOutOfLine() const;
952
953  /// \brief If this is a static data member, find its out-of-line definition.
954  VarDecl *getOutOfLineDefinition();
955
956  /// isFileVarDecl - Returns true for file scoped variable declaration.
957  bool isFileVarDecl() const {
958    Kind K = getKind();
959    if (K == ParmVar || K == ImplicitParam)
960      return false;
961
962    if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
963      return true;
964
965    if (isStaticDataMember())
966      return true;
967
968    return false;
969  }
970
971  /// getAnyInitializer - Get the initializer for this variable, no matter which
972  /// declaration it is attached to.
973  const Expr *getAnyInitializer() const {
974    const VarDecl *D;
975    return getAnyInitializer(D);
976  }
977
978  /// getAnyInitializer - Get the initializer for this variable, no matter which
979  /// declaration it is attached to. Also get that declaration.
980  const Expr *getAnyInitializer(const VarDecl *&D) const;
981
982  bool hasInit() const {
983    return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
984  }
985  const Expr *getInit() const {
986    if (Init.isNull())
987      return 0;
988
989    const Stmt *S = Init.dyn_cast<Stmt *>();
990    if (!S) {
991      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
992        S = ES->Value;
993    }
994    return (const Expr*) S;
995  }
996  Expr *getInit() {
997    if (Init.isNull())
998      return 0;
999
1000    Stmt *S = Init.dyn_cast<Stmt *>();
1001    if (!S) {
1002      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1003        S = ES->Value;
1004    }
1005
1006    return (Expr*) S;
1007  }
1008
1009  /// \brief Retrieve the address of the initializer expression.
1010  Stmt **getInitAddress() {
1011    if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1012      return &ES->Value;
1013
1014    // This union hack tip-toes around strict-aliasing rules.
1015    union {
1016      InitType *InitPtr;
1017      Stmt **StmtPtr;
1018    };
1019
1020    InitPtr = &Init;
1021    return StmtPtr;
1022  }
1023
1024  void setInit(Expr *I);
1025
1026  /// \brief Determine whether this variable's value can be used in a
1027  /// constant expression, according to the relevant language standard.
1028  /// This only checks properties of the declaration, and does not check
1029  /// whether the initializer is in fact a constant expression.
1030  bool isUsableInConstantExpressions(ASTContext &C) const;
1031
1032  EvaluatedStmt *ensureEvaluatedStmt() const;
1033
1034  /// \brief Attempt to evaluate the value of the initializer attached to this
1035  /// declaration, and produce notes explaining why it cannot be evaluated or is
1036  /// not a constant expression. Returns a pointer to the value if evaluation
1037  /// succeeded, 0 otherwise.
1038  APValue *evaluateValue() const;
1039  APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1040
1041  /// \brief Return the already-evaluated value of this variable's
1042  /// initializer, or NULL if the value is not yet known. Returns pointer
1043  /// to untyped APValue if the value could not be evaluated.
1044  APValue *getEvaluatedValue() const {
1045    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1046      if (Eval->WasEvaluated)
1047        return &Eval->Evaluated;
1048
1049    return 0;
1050  }
1051
1052  /// \brief Determines whether it is already known whether the
1053  /// initializer is an integral constant expression or not.
1054  bool isInitKnownICE() const {
1055    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1056      return Eval->CheckedICE;
1057
1058    return false;
1059  }
1060
1061  /// \brief Determines whether the initializer is an integral constant
1062  /// expression, or in C++11, whether the initializer is a constant
1063  /// expression.
1064  ///
1065  /// \pre isInitKnownICE()
1066  bool isInitICE() const {
1067    assert(isInitKnownICE() &&
1068           "Check whether we already know that the initializer is an ICE");
1069    return Init.get<EvaluatedStmt *>()->IsICE;
1070  }
1071
1072  /// \brief Determine whether the value of the initializer attached to this
1073  /// declaration is an integral constant expression.
1074  bool checkInitIsICE() const;
1075
1076  void setInitStyle(InitializationStyle Style) {
1077    VarDeclBits.InitStyle = Style;
1078  }
1079
1080  /// \brief The style of initialization for this declaration.
1081  ///
1082  /// C-style initialization is "int x = 1;". Call-style initialization is
1083  /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1084  /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1085  /// expression for class types. List-style initialization is C++11 syntax,
1086  /// e.g. "int x{1};". Clients can distinguish between different forms of
1087  /// initialization by checking this value. In particular, "int x = {1};" is
1088  /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1089  /// Init expression in all three cases is an InitListExpr.
1090  InitializationStyle getInitStyle() const {
1091    return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1092  }
1093
1094  /// \brief Whether the initializer is a direct-initializer (list or call).
1095  bool isDirectInit() const {
1096    return getInitStyle() != CInit;
1097  }
1098
1099  /// \brief Determine whether this variable is the exception variable in a
1100  /// C++ catch statememt or an Objective-C \@catch statement.
1101  bool isExceptionVariable() const {
1102    return VarDeclBits.ExceptionVar;
1103  }
1104  void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1105
1106  /// \brief Determine whether this local variable can be used with the named
1107  /// return value optimization (NRVO).
1108  ///
1109  /// The named return value optimization (NRVO) works by marking certain
1110  /// non-volatile local variables of class type as NRVO objects. These
1111  /// locals can be allocated within the return slot of their containing
1112  /// function, in which case there is no need to copy the object to the
1113  /// return slot when returning from the function. Within the function body,
1114  /// each return that returns the NRVO object will have this variable as its
1115  /// NRVO candidate.
1116  bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1117  void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1118
1119  /// \brief Determine whether this variable is the for-range-declaration in
1120  /// a C++0x for-range statement.
1121  bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1122  void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1123
1124  /// \brief Determine whether this variable is an ARC pseudo-__strong
1125  /// variable.  A pseudo-__strong variable has a __strong-qualified
1126  /// type but does not actually retain the object written into it.
1127  /// Generally such variables are also 'const' for safety.
1128  bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1129  void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1130
1131  /// Whether this variable is (C++11) constexpr.
1132  bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1133  void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1134
1135  /// Whether this local extern variable declaration's previous declaration
1136  /// was declared in the same block scope. Only correct in C++.
1137  bool isPreviousDeclInSameBlockScope() const {
1138    return VarDeclBits.PreviousDeclInSameBlockScope;
1139  }
1140  void setPreviousDeclInSameBlockScope(bool Same) {
1141    VarDeclBits.PreviousDeclInSameBlockScope = Same;
1142  }
1143
1144  /// \brief If this variable is an instantiated static data member of a
1145  /// class template specialization, returns the templated static data member
1146  /// from which it was instantiated.
1147  VarDecl *getInstantiatedFromStaticDataMember() const;
1148
1149  /// \brief If this variable is an instantiation of a variable template or a
1150  /// static data member of a class template, determine what kind of
1151  /// template specialization or instantiation this is.
1152  TemplateSpecializationKind getTemplateSpecializationKind() const;
1153
1154  /// \brief If this variable is an instantiation of a variable template or a
1155  /// static data member of a class template, determine its point of
1156  /// instantiation.
1157  SourceLocation getPointOfInstantiation() const;
1158
1159  /// \brief If this variable is an instantiation of a static data member of a
1160  /// class template specialization, retrieves the member specialization
1161  /// information.
1162  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1163
1164  /// \brief For a static data member that was instantiated from a static
1165  /// data member of a class template, set the template specialiation kind.
1166  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1167                        SourceLocation PointOfInstantiation = SourceLocation());
1168
1169  /// \brief Specify that this variable is an instantiation of the
1170  /// static data member VD.
1171  void setInstantiationOfStaticDataMember(VarDecl *VD,
1172                                          TemplateSpecializationKind TSK);
1173
1174  /// \brief Retrieves the variable template that is described by this
1175  /// variable declaration.
1176  ///
1177  /// Every variable template is represented as a VarTemplateDecl and a
1178  /// VarDecl. The former contains template properties (such as
1179  /// the template parameter lists) while the latter contains the
1180  /// actual description of the template's
1181  /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1182  /// VarDecl that from a VarTemplateDecl, while
1183  /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1184  /// a VarDecl.
1185  VarTemplateDecl *getDescribedVarTemplate() const;
1186
1187  void setDescribedVarTemplate(VarTemplateDecl *Template);
1188
1189  // Implement isa/cast/dyncast/etc.
1190  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1191  static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1192};
1193
1194class ImplicitParamDecl : public VarDecl {
1195  virtual void anchor();
1196public:
1197  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1198                                   SourceLocation IdLoc, IdentifierInfo *Id,
1199                                   QualType T);
1200
1201  static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1202
1203  ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1204                    IdentifierInfo *Id, QualType Type)
1205    : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1206              /*tinfo*/ 0, SC_None) {
1207    setImplicit();
1208  }
1209
1210  // Implement isa/cast/dyncast/etc.
1211  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1212  static bool classofKind(Kind K) { return K == ImplicitParam; }
1213};
1214
1215/// ParmVarDecl - Represents a parameter to a function.
1216class ParmVarDecl : public VarDecl {
1217public:
1218  enum { MaxFunctionScopeDepth = 255 };
1219  enum { MaxFunctionScopeIndex = 255 };
1220
1221protected:
1222  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1223              SourceLocation IdLoc, IdentifierInfo *Id,
1224              QualType T, TypeSourceInfo *TInfo,
1225              StorageClass S, Expr *DefArg)
1226    : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1227    assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1228    assert(ParmVarDeclBits.IsKNRPromoted == false);
1229    assert(ParmVarDeclBits.IsObjCMethodParam == false);
1230    setDefaultArg(DefArg);
1231  }
1232
1233public:
1234  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1235                             SourceLocation StartLoc,
1236                             SourceLocation IdLoc, IdentifierInfo *Id,
1237                             QualType T, TypeSourceInfo *TInfo,
1238                             StorageClass S, Expr *DefArg);
1239
1240  static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1241
1242  virtual SourceRange getSourceRange() const LLVM_READONLY;
1243
1244  void setObjCMethodScopeInfo(unsigned parameterIndex) {
1245    ParmVarDeclBits.IsObjCMethodParam = true;
1246    setParameterIndex(parameterIndex);
1247  }
1248
1249  void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1250    assert(!ParmVarDeclBits.IsObjCMethodParam);
1251
1252    ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1253    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1254           && "truncation!");
1255
1256    setParameterIndex(parameterIndex);
1257  }
1258
1259  bool isObjCMethodParameter() const {
1260    return ParmVarDeclBits.IsObjCMethodParam;
1261  }
1262
1263  unsigned getFunctionScopeDepth() const {
1264    if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1265    return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1266  }
1267
1268  /// Returns the index of this parameter in its prototype or method scope.
1269  unsigned getFunctionScopeIndex() const {
1270    return getParameterIndex();
1271  }
1272
1273  ObjCDeclQualifier getObjCDeclQualifier() const {
1274    if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1275    return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1276  }
1277  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1278    assert(ParmVarDeclBits.IsObjCMethodParam);
1279    ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1280  }
1281
1282  /// True if the value passed to this parameter must undergo
1283  /// K&R-style default argument promotion:
1284  ///
1285  /// C99 6.5.2.2.
1286  ///   If the expression that denotes the called function has a type
1287  ///   that does not include a prototype, the integer promotions are
1288  ///   performed on each argument, and arguments that have type float
1289  ///   are promoted to double.
1290  bool isKNRPromoted() const {
1291    return ParmVarDeclBits.IsKNRPromoted;
1292  }
1293  void setKNRPromoted(bool promoted) {
1294    ParmVarDeclBits.IsKNRPromoted = promoted;
1295  }
1296
1297  Expr *getDefaultArg();
1298  const Expr *getDefaultArg() const {
1299    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1300  }
1301
1302  void setDefaultArg(Expr *defarg) {
1303    Init = reinterpret_cast<Stmt *>(defarg);
1304  }
1305
1306  /// \brief Retrieve the source range that covers the entire default
1307  /// argument.
1308  SourceRange getDefaultArgRange() const;
1309  void setUninstantiatedDefaultArg(Expr *arg) {
1310    Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1311  }
1312  Expr *getUninstantiatedDefaultArg() {
1313    return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1314  }
1315  const Expr *getUninstantiatedDefaultArg() const {
1316    return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1317  }
1318
1319  /// hasDefaultArg - Determines whether this parameter has a default argument,
1320  /// either parsed or not.
1321  bool hasDefaultArg() const {
1322    return getInit() || hasUnparsedDefaultArg() ||
1323      hasUninstantiatedDefaultArg();
1324  }
1325
1326  /// hasUnparsedDefaultArg - Determines whether this parameter has a
1327  /// default argument that has not yet been parsed. This will occur
1328  /// during the processing of a C++ class whose member functions have
1329  /// default arguments, e.g.,
1330  /// @code
1331  ///   class X {
1332  ///   public:
1333  ///     void f(int x = 17); // x has an unparsed default argument now
1334  ///   }; // x has a regular default argument now
1335  /// @endcode
1336  bool hasUnparsedDefaultArg() const {
1337    return Init.is<UnparsedDefaultArgument*>();
1338  }
1339
1340  bool hasUninstantiatedDefaultArg() const {
1341    return Init.is<UninstantiatedDefaultArgument*>();
1342  }
1343
1344  /// setUnparsedDefaultArg - Specify that this parameter has an
1345  /// unparsed default argument. The argument will be replaced with a
1346  /// real default argument via setDefaultArg when the class
1347  /// definition enclosing the function declaration that owns this
1348  /// default argument is completed.
1349  void setUnparsedDefaultArg() {
1350    Init = (UnparsedDefaultArgument *)0;
1351  }
1352
1353  bool hasInheritedDefaultArg() const {
1354    return ParmVarDeclBits.HasInheritedDefaultArg;
1355  }
1356
1357  void setHasInheritedDefaultArg(bool I = true) {
1358    ParmVarDeclBits.HasInheritedDefaultArg = I;
1359  }
1360
1361  QualType getOriginalType() const;
1362
1363  /// \brief Determine whether this parameter is actually a function
1364  /// parameter pack.
1365  bool isParameterPack() const;
1366
1367  /// setOwningFunction - Sets the function declaration that owns this
1368  /// ParmVarDecl. Since ParmVarDecls are often created before the
1369  /// FunctionDecls that own them, this routine is required to update
1370  /// the DeclContext appropriately.
1371  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1372
1373  // Implement isa/cast/dyncast/etc.
1374  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1375  static bool classofKind(Kind K) { return K == ParmVar; }
1376
1377private:
1378  enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1379
1380  void setParameterIndex(unsigned parameterIndex) {
1381    if (parameterIndex >= ParameterIndexSentinel) {
1382      setParameterIndexLarge(parameterIndex);
1383      return;
1384    }
1385
1386    ParmVarDeclBits.ParameterIndex = parameterIndex;
1387    assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1388  }
1389  unsigned getParameterIndex() const {
1390    unsigned d = ParmVarDeclBits.ParameterIndex;
1391    return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1392  }
1393
1394  void setParameterIndexLarge(unsigned parameterIndex);
1395  unsigned getParameterIndexLarge() const;
1396};
1397
1398/// FunctionDecl - An instance of this class is created to represent a
1399/// function declaration or definition.
1400///
1401/// Since a given function can be declared several times in a program,
1402/// there may be several FunctionDecls that correspond to that
1403/// function. Only one of those FunctionDecls will be found when
1404/// traversing the list of declarations in the context of the
1405/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1406/// contains all of the information known about the function. Other,
1407/// previous declarations of the function are available via the
1408/// getPreviousDecl() chain.
1409class FunctionDecl : public DeclaratorDecl, public DeclContext,
1410                     public Redeclarable<FunctionDecl> {
1411public:
1412  typedef clang::StorageClass StorageClass;
1413
1414  /// \brief The kind of templated function a FunctionDecl can be.
1415  enum TemplatedKind {
1416    TK_NonTemplate,
1417    TK_FunctionTemplate,
1418    TK_MemberSpecialization,
1419    TK_FunctionTemplateSpecialization,
1420    TK_DependentFunctionTemplateSpecialization
1421  };
1422
1423private:
1424  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1425  /// parameters of this function.  This is null if a prototype or if there are
1426  /// no formals.
1427  ParmVarDecl **ParamInfo;
1428
1429  /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1430  /// decls defined in the function prototype that are not parameters. E.g.
1431  /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1432  ArrayRef<NamedDecl *> DeclsInPrototypeScope;
1433
1434  LazyDeclStmtPtr Body;
1435
1436  // FIXME: This can be packed into the bitfields in Decl.
1437  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1438  unsigned SClass : 2;
1439  bool IsInline : 1;
1440  bool IsInlineSpecified : 1;
1441  bool IsVirtualAsWritten : 1;
1442  bool IsPure : 1;
1443  bool HasInheritedPrototype : 1;
1444  bool HasWrittenPrototype : 1;
1445  bool IsDeleted : 1;
1446  bool IsTrivial : 1; // sunk from CXXMethodDecl
1447  bool IsDefaulted : 1; // sunk from CXXMethoDecl
1448  bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1449  bool HasImplicitReturnZero : 1;
1450  bool IsLateTemplateParsed : 1;
1451  bool IsConstexpr : 1;
1452
1453  /// \brief Indicates if the function was a definition but its body was
1454  /// skipped.
1455  unsigned HasSkippedBody : 1;
1456
1457  /// \brief End part of this FunctionDecl's source range.
1458  ///
1459  /// We could compute the full range in getSourceRange(). However, when we're
1460  /// dealing with a function definition deserialized from a PCH/AST file,
1461  /// we can only compute the full range once the function body has been
1462  /// de-serialized, so it's far better to have the (sometimes-redundant)
1463  /// EndRangeLoc.
1464  SourceLocation EndRangeLoc;
1465
1466  /// \brief The template or declaration that this declaration
1467  /// describes or was instantiated from, respectively.
1468  ///
1469  /// For non-templates, this value will be NULL. For function
1470  /// declarations that describe a function template, this will be a
1471  /// pointer to a FunctionTemplateDecl. For member functions
1472  /// of class template specializations, this will be a MemberSpecializationInfo
1473  /// pointer containing information about the specialization.
1474  /// For function template specializations, this will be a
1475  /// FunctionTemplateSpecializationInfo, which contains information about
1476  /// the template being specialized and the template arguments involved in
1477  /// that specialization.
1478  llvm::PointerUnion4<FunctionTemplateDecl *,
1479                      MemberSpecializationInfo *,
1480                      FunctionTemplateSpecializationInfo *,
1481                      DependentFunctionTemplateSpecializationInfo *>
1482    TemplateOrSpecialization;
1483
1484  /// DNLoc - Provides source/type location info for the
1485  /// declaration name embedded in the DeclaratorDecl base class.
1486  DeclarationNameLoc DNLoc;
1487
1488  /// \brief Specify that this function declaration is actually a function
1489  /// template specialization.
1490  ///
1491  /// \param C the ASTContext.
1492  ///
1493  /// \param Template the function template that this function template
1494  /// specialization specializes.
1495  ///
1496  /// \param TemplateArgs the template arguments that produced this
1497  /// function template specialization from the template.
1498  ///
1499  /// \param InsertPos If non-NULL, the position in the function template
1500  /// specialization set where the function template specialization data will
1501  /// be inserted.
1502  ///
1503  /// \param TSK the kind of template specialization this is.
1504  ///
1505  /// \param TemplateArgsAsWritten location info of template arguments.
1506  ///
1507  /// \param PointOfInstantiation point at which the function template
1508  /// specialization was first instantiated.
1509  void setFunctionTemplateSpecialization(ASTContext &C,
1510                                         FunctionTemplateDecl *Template,
1511                                       const TemplateArgumentList *TemplateArgs,
1512                                         void *InsertPos,
1513                                         TemplateSpecializationKind TSK,
1514                          const TemplateArgumentListInfo *TemplateArgsAsWritten,
1515                                         SourceLocation PointOfInstantiation);
1516
1517  /// \brief Specify that this record is an instantiation of the
1518  /// member function FD.
1519  void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1520                                        TemplateSpecializationKind TSK);
1521
1522  void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1523
1524protected:
1525  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1526               const DeclarationNameInfo &NameInfo,
1527               QualType T, TypeSourceInfo *TInfo,
1528               StorageClass S, bool isInlineSpecified,
1529               bool isConstexprSpecified)
1530    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1531                     StartLoc),
1532      DeclContext(DK),
1533      ParamInfo(0), Body(),
1534      SClass(S),
1535      IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1536      IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1537      HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1538      IsDefaulted(false), IsExplicitlyDefaulted(false),
1539      HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1540      IsConstexpr(isConstexprSpecified), HasSkippedBody(false),
1541      EndRangeLoc(NameInfo.getEndLoc()),
1542      TemplateOrSpecialization(),
1543      DNLoc(NameInfo.getInfo()) {}
1544
1545  typedef Redeclarable<FunctionDecl> redeclarable_base;
1546  virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1547  virtual FunctionDecl *getPreviousDeclImpl() {
1548    return getPreviousDecl();
1549  }
1550  virtual FunctionDecl *getMostRecentDeclImpl() {
1551    return getMostRecentDecl();
1552  }
1553
1554public:
1555  typedef redeclarable_base::redecl_iterator redecl_iterator;
1556  using redeclarable_base::redecls_begin;
1557  using redeclarable_base::redecls_end;
1558  using redeclarable_base::getPreviousDecl;
1559  using redeclarable_base::getMostRecentDecl;
1560
1561  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1562                              SourceLocation StartLoc, SourceLocation NLoc,
1563                              DeclarationName N, QualType T,
1564                              TypeSourceInfo *TInfo,
1565                              StorageClass SC,
1566                              bool isInlineSpecified = false,
1567                              bool hasWrittenPrototype = true,
1568                              bool isConstexprSpecified = false) {
1569    DeclarationNameInfo NameInfo(N, NLoc);
1570    return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1571                                SC,
1572                                isInlineSpecified, hasWrittenPrototype,
1573                                isConstexprSpecified);
1574  }
1575
1576  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1577                              SourceLocation StartLoc,
1578                              const DeclarationNameInfo &NameInfo,
1579                              QualType T, TypeSourceInfo *TInfo,
1580                              StorageClass SC,
1581                              bool isInlineSpecified,
1582                              bool hasWrittenPrototype,
1583                              bool isConstexprSpecified = false);
1584
1585  static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1586
1587  DeclarationNameInfo getNameInfo() const {
1588    return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1589  }
1590
1591  virtual void getNameForDiagnostic(raw_ostream &OS,
1592                                    const PrintingPolicy &Policy,
1593                                    bool Qualified) const;
1594
1595  void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1596
1597  virtual SourceRange getSourceRange() const LLVM_READONLY;
1598
1599  /// \brief Returns true if the function has a body (definition). The
1600  /// function body might be in any of the (re-)declarations of this
1601  /// function. The variant that accepts a FunctionDecl pointer will
1602  /// set that function declaration to the actual declaration
1603  /// containing the body (if there is one).
1604  bool hasBody(const FunctionDecl *&Definition) const;
1605
1606  virtual bool hasBody() const {
1607    const FunctionDecl* Definition;
1608    return hasBody(Definition);
1609  }
1610
1611  /// hasTrivialBody - Returns whether the function has a trivial body that does
1612  /// not require any specific codegen.
1613  bool hasTrivialBody() const;
1614
1615  /// isDefined - Returns true if the function is defined at all, including
1616  /// a deleted definition. Except for the behavior when the function is
1617  /// deleted, behaves like hasBody.
1618  bool isDefined(const FunctionDecl *&Definition) const;
1619
1620  virtual bool isDefined() const {
1621    const FunctionDecl* Definition;
1622    return isDefined(Definition);
1623  }
1624
1625  /// getBody - Retrieve the body (definition) of the function. The
1626  /// function body might be in any of the (re-)declarations of this
1627  /// function. The variant that accepts a FunctionDecl pointer will
1628  /// set that function declaration to the actual declaration
1629  /// containing the body (if there is one).
1630  /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1631  /// unnecessary AST de-serialization of the body.
1632  Stmt *getBody(const FunctionDecl *&Definition) const;
1633
1634  virtual Stmt *getBody() const {
1635    const FunctionDecl* Definition;
1636    return getBody(Definition);
1637  }
1638
1639  /// isThisDeclarationADefinition - Returns whether this specific
1640  /// declaration of the function is also a definition. This does not
1641  /// determine whether the function has been defined (e.g., in a
1642  /// previous definition); for that information, use isDefined. Note
1643  /// that this returns false for a defaulted function unless that function
1644  /// has been implicitly defined (possibly as deleted).
1645  bool isThisDeclarationADefinition() const {
1646    return IsDeleted || Body || IsLateTemplateParsed;
1647  }
1648
1649  /// doesThisDeclarationHaveABody - Returns whether this specific
1650  /// declaration of the function has a body - that is, if it is a non-
1651  /// deleted definition.
1652  bool doesThisDeclarationHaveABody() const {
1653    return Body || IsLateTemplateParsed;
1654  }
1655
1656  void setBody(Stmt *B);
1657  void setLazyBody(uint64_t Offset) { Body = Offset; }
1658
1659  /// Whether this function is variadic.
1660  bool isVariadic() const;
1661
1662  /// Whether this function is marked as virtual explicitly.
1663  bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1664  void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1665
1666  /// Whether this virtual function is pure, i.e. makes the containing class
1667  /// abstract.
1668  bool isPure() const { return IsPure; }
1669  void setPure(bool P = true);
1670
1671  /// Whether this templated function will be late parsed.
1672  bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1673  void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1674
1675  /// Whether this function is "trivial" in some specialized C++ senses.
1676  /// Can only be true for default constructors, copy constructors,
1677  /// copy assignment operators, and destructors.  Not meaningful until
1678  /// the class has been fully built by Sema.
1679  bool isTrivial() const { return IsTrivial; }
1680  void setTrivial(bool IT) { IsTrivial = IT; }
1681
1682  /// Whether this function is defaulted per C++0x. Only valid for
1683  /// special member functions.
1684  bool isDefaulted() const { return IsDefaulted; }
1685  void setDefaulted(bool D = true) { IsDefaulted = D; }
1686
1687  /// Whether this function is explicitly defaulted per C++0x. Only valid
1688  /// for special member functions.
1689  bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1690  void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1691
1692  /// Whether falling off this function implicitly returns null/zero.
1693  /// If a more specific implicit return value is required, front-ends
1694  /// should synthesize the appropriate return statements.
1695  bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1696  void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1697
1698  /// \brief Whether this function has a prototype, either because one
1699  /// was explicitly written or because it was "inherited" by merging
1700  /// a declaration without a prototype with a declaration that has a
1701  /// prototype.
1702  bool hasPrototype() const {
1703    return HasWrittenPrototype || HasInheritedPrototype;
1704  }
1705
1706  bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1707
1708  /// \brief Whether this function inherited its prototype from a
1709  /// previous declaration.
1710  bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1711  void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1712
1713  /// Whether this is a (C++11) constexpr function or constexpr constructor.
1714  bool isConstexpr() const { return IsConstexpr; }
1715  void setConstexpr(bool IC) { IsConstexpr = IC; }
1716
1717  /// \brief Whether this function has been deleted.
1718  ///
1719  /// A function that is "deleted" (via the C++0x "= delete" syntax)
1720  /// acts like a normal function, except that it cannot actually be
1721  /// called or have its address taken. Deleted functions are
1722  /// typically used in C++ overload resolution to attract arguments
1723  /// whose type or lvalue/rvalue-ness would permit the use of a
1724  /// different overload that would behave incorrectly. For example,
1725  /// one might use deleted functions to ban implicit conversion from
1726  /// a floating-point number to an Integer type:
1727  ///
1728  /// @code
1729  /// struct Integer {
1730  ///   Integer(long); // construct from a long
1731  ///   Integer(double) = delete; // no construction from float or double
1732  ///   Integer(long double) = delete; // no construction from long double
1733  /// };
1734  /// @endcode
1735  // If a function is deleted, its first declaration must be.
1736  bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1737  bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1738  void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1739
1740  /// \brief Determines whether this function is "main", which is the
1741  /// entry point into an executable program.
1742  bool isMain() const;
1743
1744  /// \brief Determines whether this function is a MSVCRT user defined entry
1745  /// point.
1746  bool isMSVCRTEntryPoint() const;
1747
1748  /// \brief Determines whether this operator new or delete is one
1749  /// of the reserved global placement operators:
1750  ///    void *operator new(size_t, void *);
1751  ///    void *operator new[](size_t, void *);
1752  ///    void operator delete(void *, void *);
1753  ///    void operator delete[](void *, void *);
1754  /// These functions have special behavior under [new.delete.placement]:
1755  ///    These functions are reserved, a C++ program may not define
1756  ///    functions that displace the versions in the Standard C++ library.
1757  ///    The provisions of [basic.stc.dynamic] do not apply to these
1758  ///    reserved placement forms of operator new and operator delete.
1759  ///
1760  /// This function must be an allocation or deallocation function.
1761  bool isReservedGlobalPlacementOperator() const;
1762
1763  /// \brief Determines whether this function is one of the replaceable
1764  /// global allocation functions:
1765  ///    void *operator new(size_t);
1766  ///    void *operator new(size_t, const std::nothrow_t &) noexcept;
1767  ///    void *operator new[](size_t);
1768  ///    void *operator new[](size_t, const std::nothrow_t &) noexcept;
1769  ///    void operator delete(void *) noexcept;
1770  ///    void operator delete(void *, const std::nothrow_t &) noexcept;
1771  ///    void operator delete[](void *) noexcept;
1772  ///    void operator delete[](void *, const std::nothrow_t &) noexcept;
1773  /// These functions have special behavior under C++1y [expr.new]:
1774  ///    An implementation is allowed to omit a call to a replaceable global
1775  ///    allocation function. [...]
1776  bool isReplaceableGlobalAllocationFunction() const;
1777
1778  /// Compute the language linkage.
1779  LanguageLinkage getLanguageLinkage() const;
1780
1781  /// \brief Determines whether this function is a function with
1782  /// external, C linkage.
1783  bool isExternC() const;
1784
1785  /// \brief Determines whether this function's context is, or is nested within,
1786  /// a C++ extern "C" linkage spec.
1787  bool isInExternCContext() const;
1788
1789  /// \brief Determines whether this function's context is, or is nested within,
1790  /// a C++ extern "C++" linkage spec.
1791  bool isInExternCXXContext() const;
1792
1793  /// \brief Determines whether this is a global function.
1794  bool isGlobal() const;
1795
1796  /// \brief Determines whether this function is known to be 'noreturn', through
1797  /// an attribute on its declaration or its type.
1798  bool isNoReturn() const;
1799
1800  /// \brief True if the function was a definition but its body was skipped.
1801  bool hasSkippedBody() const { return HasSkippedBody; }
1802  void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
1803
1804  void setPreviousDeclaration(FunctionDecl * PrevDecl);
1805
1806  virtual const FunctionDecl *getCanonicalDecl() const;
1807  virtual FunctionDecl *getCanonicalDecl();
1808
1809  unsigned getBuiltinID() const;
1810
1811  // Iterator access to formal parameters.
1812  unsigned param_size() const { return getNumParams(); }
1813  typedef ParmVarDecl **param_iterator;
1814  typedef ParmVarDecl * const *param_const_iterator;
1815
1816  param_iterator param_begin() { return ParamInfo; }
1817  param_iterator param_end()   { return ParamInfo+param_size(); }
1818
1819  param_const_iterator param_begin() const { return ParamInfo; }
1820  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1821
1822  /// getNumParams - Return the number of parameters this function must have
1823  /// based on its FunctionType.  This is the length of the ParamInfo array
1824  /// after it has been created.
1825  unsigned getNumParams() const;
1826
1827  const ParmVarDecl *getParamDecl(unsigned i) const {
1828    assert(i < getNumParams() && "Illegal param #");
1829    return ParamInfo[i];
1830  }
1831  ParmVarDecl *getParamDecl(unsigned i) {
1832    assert(i < getNumParams() && "Illegal param #");
1833    return ParamInfo[i];
1834  }
1835  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
1836    setParams(getASTContext(), NewParamInfo);
1837  }
1838
1839  const ArrayRef<NamedDecl *> &getDeclsInPrototypeScope() const {
1840    return DeclsInPrototypeScope;
1841  }
1842  void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
1843
1844  /// getMinRequiredArguments - Returns the minimum number of arguments
1845  /// needed to call this function. This may be fewer than the number of
1846  /// function parameters, if some of the parameters have default
1847  /// arguments (in C++).
1848  unsigned getMinRequiredArguments() const;
1849
1850  QualType getResultType() const {
1851    return getType()->getAs<FunctionType>()->getResultType();
1852  }
1853
1854  /// \brief Determine the type of an expression that calls this function.
1855  QualType getCallResultType() const {
1856    return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1857  }
1858
1859  /// \brief Returns the storage class as written in the source. For the
1860  /// computed linkage of symbol, see getLinkage.
1861  StorageClass getStorageClass() const { return StorageClass(SClass); }
1862
1863  /// \brief Determine whether the "inline" keyword was specified for this
1864  /// function.
1865  bool isInlineSpecified() const { return IsInlineSpecified; }
1866
1867  /// Set whether the "inline" keyword was specified for this function.
1868  void setInlineSpecified(bool I) {
1869    IsInlineSpecified = I;
1870    IsInline = I;
1871  }
1872
1873  /// Flag that this function is implicitly inline.
1874  void setImplicitlyInline() {
1875    IsInline = true;
1876  }
1877
1878  /// \brief Determine whether this function should be inlined, because it is
1879  /// either marked "inline" or "constexpr" or is a member function of a class
1880  /// that was defined in the class body.
1881  bool isInlined() const { return IsInline; }
1882
1883  bool isInlineDefinitionExternallyVisible() const;
1884
1885  bool doesDeclarationForceExternallyVisibleDefinition() const;
1886
1887  /// isOverloadedOperator - Whether this function declaration
1888  /// represents an C++ overloaded operator, e.g., "operator+".
1889  bool isOverloadedOperator() const {
1890    return getOverloadedOperator() != OO_None;
1891  }
1892
1893  OverloadedOperatorKind getOverloadedOperator() const;
1894
1895  const IdentifierInfo *getLiteralIdentifier() const;
1896
1897  /// \brief If this function is an instantiation of a member function
1898  /// of a class template specialization, retrieves the function from
1899  /// which it was instantiated.
1900  ///
1901  /// This routine will return non-NULL for (non-templated) member
1902  /// functions of class templates and for instantiations of function
1903  /// templates. For example, given:
1904  ///
1905  /// \code
1906  /// template<typename T>
1907  /// struct X {
1908  ///   void f(T);
1909  /// };
1910  /// \endcode
1911  ///
1912  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1913  /// whose parent is the class template specialization X<int>. For
1914  /// this declaration, getInstantiatedFromFunction() will return
1915  /// the FunctionDecl X<T>::A. When a complete definition of
1916  /// X<int>::A is required, it will be instantiated from the
1917  /// declaration returned by getInstantiatedFromMemberFunction().
1918  FunctionDecl *getInstantiatedFromMemberFunction() const;
1919
1920  /// \brief What kind of templated function this is.
1921  TemplatedKind getTemplatedKind() const;
1922
1923  /// \brief If this function is an instantiation of a member function of a
1924  /// class template specialization, retrieves the member specialization
1925  /// information.
1926  MemberSpecializationInfo *getMemberSpecializationInfo() const {
1927    return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1928  }
1929
1930  /// \brief Specify that this record is an instantiation of the
1931  /// member function FD.
1932  void setInstantiationOfMemberFunction(FunctionDecl *FD,
1933                                        TemplateSpecializationKind TSK) {
1934    setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1935  }
1936
1937  /// \brief Retrieves the function template that is described by this
1938  /// function declaration.
1939  ///
1940  /// Every function template is represented as a FunctionTemplateDecl
1941  /// and a FunctionDecl (or something derived from FunctionDecl). The
1942  /// former contains template properties (such as the template
1943  /// parameter lists) while the latter contains the actual
1944  /// description of the template's
1945  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1946  /// FunctionDecl that describes the function template,
1947  /// getDescribedFunctionTemplate() retrieves the
1948  /// FunctionTemplateDecl from a FunctionDecl.
1949  FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1950    return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1951  }
1952
1953  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1954    TemplateOrSpecialization = Template;
1955  }
1956
1957  /// \brief Determine whether this function is a function template
1958  /// specialization.
1959  bool isFunctionTemplateSpecialization() const {
1960    return getPrimaryTemplate() != 0;
1961  }
1962
1963  /// \brief Retrieve the class scope template pattern that this function
1964  ///  template specialization is instantiated from.
1965  FunctionDecl *getClassScopeSpecializationPattern() const;
1966
1967  /// \brief If this function is actually a function template specialization,
1968  /// retrieve information about this function template specialization.
1969  /// Otherwise, returns NULL.
1970  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1971    return TemplateOrSpecialization.
1972             dyn_cast<FunctionTemplateSpecializationInfo*>();
1973  }
1974
1975  /// \brief Determines whether this function is a function template
1976  /// specialization or a member of a class template specialization that can
1977  /// be implicitly instantiated.
1978  bool isImplicitlyInstantiable() const;
1979
1980  /// \brief Determines if the given function was instantiated from a
1981  /// function template.
1982  bool isTemplateInstantiation() const;
1983
1984  /// \brief Retrieve the function declaration from which this function could
1985  /// be instantiated, if it is an instantiation (rather than a non-template
1986  /// or a specialization, for example).
1987  FunctionDecl *getTemplateInstantiationPattern() const;
1988
1989  /// \brief Retrieve the primary template that this function template
1990  /// specialization either specializes or was instantiated from.
1991  ///
1992  /// If this function declaration is not a function template specialization,
1993  /// returns NULL.
1994  FunctionTemplateDecl *getPrimaryTemplate() const;
1995
1996  /// \brief Retrieve the template arguments used to produce this function
1997  /// template specialization from the primary template.
1998  ///
1999  /// If this function declaration is not a function template specialization,
2000  /// returns NULL.
2001  const TemplateArgumentList *getTemplateSpecializationArgs() const;
2002
2003  /// \brief Retrieve the template argument list as written in the sources,
2004  /// if any.
2005  ///
2006  /// If this function declaration is not a function template specialization
2007  /// or if it had no explicit template argument list, returns NULL.
2008  /// Note that it an explicit template argument list may be written empty,
2009  /// e.g., template<> void foo<>(char* s);
2010  const ASTTemplateArgumentListInfo*
2011  getTemplateSpecializationArgsAsWritten() const;
2012
2013  /// \brief Specify that this function declaration is actually a function
2014  /// template specialization.
2015  ///
2016  /// \param Template the function template that this function template
2017  /// specialization specializes.
2018  ///
2019  /// \param TemplateArgs the template arguments that produced this
2020  /// function template specialization from the template.
2021  ///
2022  /// \param InsertPos If non-NULL, the position in the function template
2023  /// specialization set where the function template specialization data will
2024  /// be inserted.
2025  ///
2026  /// \param TSK the kind of template specialization this is.
2027  ///
2028  /// \param TemplateArgsAsWritten location info of template arguments.
2029  ///
2030  /// \param PointOfInstantiation point at which the function template
2031  /// specialization was first instantiated.
2032  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2033                                      const TemplateArgumentList *TemplateArgs,
2034                                         void *InsertPos,
2035                    TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2036                    const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
2037                    SourceLocation PointOfInstantiation = SourceLocation()) {
2038    setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2039                                      InsertPos, TSK, TemplateArgsAsWritten,
2040                                      PointOfInstantiation);
2041  }
2042
2043  /// \brief Specifies that this function declaration is actually a
2044  /// dependent function template specialization.
2045  void setDependentTemplateSpecialization(ASTContext &Context,
2046                             const UnresolvedSetImpl &Templates,
2047                      const TemplateArgumentListInfo &TemplateArgs);
2048
2049  DependentFunctionTemplateSpecializationInfo *
2050  getDependentSpecializationInfo() const {
2051    return TemplateOrSpecialization.
2052             dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
2053  }
2054
2055  /// \brief Determine what kind of template instantiation this function
2056  /// represents.
2057  TemplateSpecializationKind getTemplateSpecializationKind() const;
2058
2059  /// \brief Determine what kind of template instantiation this function
2060  /// represents.
2061  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2062                        SourceLocation PointOfInstantiation = SourceLocation());
2063
2064  /// \brief Retrieve the (first) point of instantiation of a function template
2065  /// specialization or a member of a class template specialization.
2066  ///
2067  /// \returns the first point of instantiation, if this function was
2068  /// instantiated from a template; otherwise, returns an invalid source
2069  /// location.
2070  SourceLocation getPointOfInstantiation() const;
2071
2072  /// \brief Determine whether this is or was instantiated from an out-of-line
2073  /// definition of a member function.
2074  virtual bool isOutOfLine() const;
2075
2076  /// \brief Identify a memory copying or setting function.
2077  /// If the given function is a memory copy or setting function, returns
2078  /// the corresponding Builtin ID. If the function is not a memory function,
2079  /// returns 0.
2080  unsigned getMemoryFunctionKind() const;
2081
2082  // Implement isa/cast/dyncast/etc.
2083  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2084  static bool classofKind(Kind K) {
2085    return K >= firstFunction && K <= lastFunction;
2086  }
2087  static DeclContext *castToDeclContext(const FunctionDecl *D) {
2088    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2089  }
2090  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2091    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2092  }
2093
2094  friend class ASTDeclReader;
2095  friend class ASTDeclWriter;
2096};
2097
2098
2099/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2100/// represent a member of a struct/union/class.
2101class FieldDecl : public DeclaratorDecl {
2102  // FIXME: This can be packed into the bitfields in Decl.
2103  bool Mutable : 1;
2104  mutable unsigned CachedFieldIndex : 31;
2105
2106  /// \brief An InClassInitStyle value, and either a bit width expression (if
2107  /// the InClassInitStyle value is ICIS_NoInit), or a pointer to the in-class
2108  /// initializer for this field (otherwise).
2109  ///
2110  /// We can safely combine these two because in-class initializers are not
2111  /// permitted for bit-fields.
2112  ///
2113  /// If the InClassInitStyle is not ICIS_NoInit and the initializer is null,
2114  /// then this field has an in-class initializer which has not yet been parsed
2115  /// and attached.
2116  llvm::PointerIntPair<Expr *, 2, unsigned> InitializerOrBitWidth;
2117protected:
2118  FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2119            SourceLocation IdLoc, IdentifierInfo *Id,
2120            QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2121            InClassInitStyle InitStyle)
2122    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2123      Mutable(Mutable), CachedFieldIndex(0),
2124      InitializerOrBitWidth(BW, InitStyle) {
2125    assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2126  }
2127
2128public:
2129  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2130                           SourceLocation StartLoc, SourceLocation IdLoc,
2131                           IdentifierInfo *Id, QualType T,
2132                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2133                           InClassInitStyle InitStyle);
2134
2135  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2136
2137  /// getFieldIndex - Returns the index of this field within its record,
2138  /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2139  unsigned getFieldIndex() const;
2140
2141  /// isMutable - Determines whether this field is mutable (C++ only).
2142  bool isMutable() const { return Mutable; }
2143
2144  /// isBitfield - Determines whether this field is a bitfield.
2145  bool isBitField() const {
2146    return getInClassInitStyle() == ICIS_NoInit &&
2147           InitializerOrBitWidth.getPointer();
2148  }
2149
2150  /// @brief Determines whether this is an unnamed bitfield.
2151  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2152
2153  /// isAnonymousStructOrUnion - Determines whether this field is a
2154  /// representative for an anonymous struct or union. Such fields are
2155  /// unnamed and are implicitly generated by the implementation to
2156  /// store the data for the anonymous union or struct.
2157  bool isAnonymousStructOrUnion() const;
2158
2159  Expr *getBitWidth() const {
2160    return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2161  }
2162  unsigned getBitWidthValue(const ASTContext &Ctx) const;
2163
2164  /// setBitWidth - Set the bit-field width for this member.
2165  // Note: used by some clients (i.e., do not remove it).
2166  void setBitWidth(Expr *Width);
2167  /// removeBitWidth - Remove the bit-field width from this member.
2168  // Note: used by some clients (i.e., do not remove it).
2169  void removeBitWidth() {
2170    assert(isBitField() && "no bitfield width to remove");
2171    InitializerOrBitWidth.setPointer(0);
2172  }
2173
2174  /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2175  /// this field has.
2176  InClassInitStyle getInClassInitStyle() const {
2177    return static_cast<InClassInitStyle>(InitializerOrBitWidth.getInt());
2178  }
2179
2180  /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2181  /// initializer.
2182  bool hasInClassInitializer() const {
2183    return getInClassInitStyle() != ICIS_NoInit;
2184  }
2185  /// getInClassInitializer - Get the C++11 in-class initializer for this
2186  /// member, or null if one has not been set. If a valid declaration has an
2187  /// in-class initializer, but this returns null, then we have not parsed and
2188  /// attached it yet.
2189  Expr *getInClassInitializer() const {
2190    return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2191  }
2192  /// setInClassInitializer - Set the C++11 in-class initializer for this
2193  /// member.
2194  void setInClassInitializer(Expr *Init);
2195  /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2196  /// member.
2197  void removeInClassInitializer() {
2198    assert(hasInClassInitializer() && "no initializer to remove");
2199    InitializerOrBitWidth.setPointer(0);
2200    InitializerOrBitWidth.setInt(ICIS_NoInit);
2201  }
2202
2203  /// getParent - Returns the parent of this field declaration, which
2204  /// is the struct in which this method is defined.
2205  const RecordDecl *getParent() const {
2206    return cast<RecordDecl>(getDeclContext());
2207  }
2208
2209  RecordDecl *getParent() {
2210    return cast<RecordDecl>(getDeclContext());
2211  }
2212
2213  SourceRange getSourceRange() const LLVM_READONLY;
2214
2215  // Implement isa/cast/dyncast/etc.
2216  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2217  static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2218
2219  friend class ASTDeclReader;
2220  friend class ASTDeclWriter;
2221};
2222
2223/// EnumConstantDecl - An instance of this object exists for each enum constant
2224/// that is defined.  For example, in "enum X {a,b}", each of a/b are
2225/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2226/// TagType for the X EnumDecl.
2227class EnumConstantDecl : public ValueDecl {
2228  Stmt *Init; // an integer constant expression
2229  llvm::APSInt Val; // The value.
2230protected:
2231  EnumConstantDecl(DeclContext *DC, SourceLocation L,
2232                   IdentifierInfo *Id, QualType T, Expr *E,
2233                   const llvm::APSInt &V)
2234    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2235
2236public:
2237
2238  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2239                                  SourceLocation L, IdentifierInfo *Id,
2240                                  QualType T, Expr *E,
2241                                  const llvm::APSInt &V);
2242  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2243
2244  const Expr *getInitExpr() const { return (const Expr*) Init; }
2245  Expr *getInitExpr() { return (Expr*) Init; }
2246  const llvm::APSInt &getInitVal() const { return Val; }
2247
2248  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2249  void setInitVal(const llvm::APSInt &V) { Val = V; }
2250
2251  SourceRange getSourceRange() const LLVM_READONLY;
2252
2253  // Implement isa/cast/dyncast/etc.
2254  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2255  static bool classofKind(Kind K) { return K == EnumConstant; }
2256
2257  friend class StmtIteratorBase;
2258};
2259
2260/// IndirectFieldDecl - An instance of this class is created to represent a
2261/// field injected from an anonymous union/struct into the parent scope.
2262/// IndirectFieldDecl are always implicit.
2263class IndirectFieldDecl : public ValueDecl {
2264  virtual void anchor();
2265  NamedDecl **Chaining;
2266  unsigned ChainingSize;
2267
2268  IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2269                    DeclarationName N, QualType T,
2270                    NamedDecl **CH, unsigned CHS)
2271    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2272
2273public:
2274  static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2275                                   SourceLocation L, IdentifierInfo *Id,
2276                                   QualType T, NamedDecl **CH, unsigned CHS);
2277
2278  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2279
2280  typedef NamedDecl * const *chain_iterator;
2281  chain_iterator chain_begin() const { return Chaining; }
2282  chain_iterator chain_end() const  { return Chaining+ChainingSize; }
2283
2284  unsigned getChainingSize() const { return ChainingSize; }
2285
2286  FieldDecl *getAnonField() const {
2287    assert(ChainingSize >= 2);
2288    return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2289  }
2290
2291  VarDecl *getVarDecl() const {
2292    assert(ChainingSize >= 2);
2293    return dyn_cast<VarDecl>(*chain_begin());
2294  }
2295
2296  // Implement isa/cast/dyncast/etc.
2297  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2298  static bool classofKind(Kind K) { return K == IndirectField; }
2299  friend class ASTDeclReader;
2300};
2301
2302/// TypeDecl - Represents a declaration of a type.
2303///
2304class TypeDecl : public NamedDecl {
2305  virtual void anchor();
2306  /// TypeForDecl - This indicates the Type object that represents
2307  /// this TypeDecl.  It is a cache maintained by
2308  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2309  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2310  mutable const Type *TypeForDecl;
2311  /// LocStart - The start of the source range for this declaration.
2312  SourceLocation LocStart;
2313  friend class ASTContext;
2314  friend class DeclContext;
2315  friend class TagDecl;
2316  friend class TemplateTypeParmDecl;
2317  friend class TagType;
2318  friend class ASTReader;
2319
2320protected:
2321  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2322           SourceLocation StartL = SourceLocation())
2323    : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2324
2325public:
2326  // Low-level accessor. If you just want the type defined by this node,
2327  // check out ASTContext::getTypeDeclType or one of
2328  // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2329  // already know the specific kind of node this is.
2330  const Type *getTypeForDecl() const { return TypeForDecl; }
2331  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2332
2333  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2334  void setLocStart(SourceLocation L) { LocStart = L; }
2335  virtual SourceRange getSourceRange() const LLVM_READONLY {
2336    if (LocStart.isValid())
2337      return SourceRange(LocStart, getLocation());
2338    else
2339      return SourceRange(getLocation());
2340  }
2341
2342  // Implement isa/cast/dyncast/etc.
2343  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2344  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2345};
2346
2347
2348/// Base class for declarations which introduce a typedef-name.
2349class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2350  virtual void anchor();
2351  typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2352  llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2353
2354protected:
2355  TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2356                  SourceLocation IdLoc, IdentifierInfo *Id,
2357                  TypeSourceInfo *TInfo)
2358    : TypeDecl(DK, DC, IdLoc, Id, StartLoc), MaybeModedTInfo(TInfo) {}
2359
2360  typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2361  virtual TypedefNameDecl *getNextRedeclaration() {
2362    return RedeclLink.getNext();
2363  }
2364  virtual TypedefNameDecl *getPreviousDeclImpl() {
2365    return getPreviousDecl();
2366  }
2367  virtual TypedefNameDecl *getMostRecentDeclImpl() {
2368    return getMostRecentDecl();
2369  }
2370
2371public:
2372  typedef redeclarable_base::redecl_iterator redecl_iterator;
2373  using redeclarable_base::redecls_begin;
2374  using redeclarable_base::redecls_end;
2375  using redeclarable_base::getPreviousDecl;
2376  using redeclarable_base::getMostRecentDecl;
2377
2378  bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2379
2380  TypeSourceInfo *getTypeSourceInfo() const {
2381    return isModed()
2382      ? MaybeModedTInfo.get<ModedTInfo*>()->first
2383      : MaybeModedTInfo.get<TypeSourceInfo*>();
2384  }
2385  QualType getUnderlyingType() const {
2386    return isModed()
2387      ? MaybeModedTInfo.get<ModedTInfo*>()->second
2388      : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2389  }
2390  void setTypeSourceInfo(TypeSourceInfo *newType) {
2391    MaybeModedTInfo = newType;
2392  }
2393  void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2394    MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2395  }
2396
2397  /// Retrieves the canonical declaration of this typedef-name.
2398  TypedefNameDecl *getCanonicalDecl() {
2399    return getFirstDeclaration();
2400  }
2401  const TypedefNameDecl *getCanonicalDecl() const {
2402    return getFirstDeclaration();
2403  }
2404
2405  // Implement isa/cast/dyncast/etc.
2406  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2407  static bool classofKind(Kind K) {
2408    return K >= firstTypedefName && K <= lastTypedefName;
2409  }
2410};
2411
2412/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2413/// type specifier.
2414class TypedefDecl : public TypedefNameDecl {
2415  TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2416              IdentifierInfo *Id, TypeSourceInfo *TInfo)
2417    : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2418
2419public:
2420  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2421                             SourceLocation StartLoc, SourceLocation IdLoc,
2422                             IdentifierInfo *Id, TypeSourceInfo *TInfo);
2423  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2424
2425  SourceRange getSourceRange() const LLVM_READONLY;
2426
2427  // Implement isa/cast/dyncast/etc.
2428  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2429  static bool classofKind(Kind K) { return K == Typedef; }
2430};
2431
2432/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2433/// alias-declaration.
2434class TypeAliasDecl : public TypedefNameDecl {
2435  TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2436                IdentifierInfo *Id, TypeSourceInfo *TInfo)
2437    : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2438
2439public:
2440  static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2441                               SourceLocation StartLoc, SourceLocation IdLoc,
2442                               IdentifierInfo *Id, TypeSourceInfo *TInfo);
2443  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2444
2445  SourceRange getSourceRange() const LLVM_READONLY;
2446
2447  // Implement isa/cast/dyncast/etc.
2448  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2449  static bool classofKind(Kind K) { return K == TypeAlias; }
2450};
2451
2452/// TagDecl - Represents the declaration of a struct/union/class/enum.
2453class TagDecl
2454  : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2455public:
2456  // This is really ugly.
2457  typedef TagTypeKind TagKind;
2458
2459private:
2460  // FIXME: This can be packed into the bitfields in Decl.
2461  /// TagDeclKind - The TagKind enum.
2462  unsigned TagDeclKind : 3;
2463
2464  /// IsCompleteDefinition - True if this is a definition ("struct foo
2465  /// {};"), false if it is a declaration ("struct foo;").  It is not
2466  /// a definition until the definition has been fully processed.
2467  bool IsCompleteDefinition : 1;
2468
2469protected:
2470  /// IsBeingDefined - True if this is currently being defined.
2471  bool IsBeingDefined : 1;
2472
2473private:
2474  /// IsEmbeddedInDeclarator - True if this tag declaration is
2475  /// "embedded" (i.e., defined or declared for the very first time)
2476  /// in the syntax of a declarator.
2477  bool IsEmbeddedInDeclarator : 1;
2478
2479  /// \brief True if this tag is free standing, e.g. "struct foo;".
2480  bool IsFreeStanding : 1;
2481
2482protected:
2483  // These are used by (and only defined for) EnumDecl.
2484  unsigned NumPositiveBits : 8;
2485  unsigned NumNegativeBits : 8;
2486
2487  /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2488  /// possible in C++11 mode.
2489  bool IsScoped : 1;
2490  /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2491  /// then this is true if the scoped enum was declared using the class
2492  /// tag, false if it was declared with the struct tag. No meaning is
2493  /// associated if this tag declaration is not a scoped enum.
2494  bool IsScopedUsingClassTag : 1;
2495
2496  /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2497  /// possible in C++11, Microsoft extensions, or Objective C mode.
2498  bool IsFixed : 1;
2499
2500  /// \brief Indicates whether it is possible for declarations of this kind
2501  /// to have an out-of-date definition.
2502  ///
2503  /// This option is only enabled when modules are enabled.
2504  bool MayHaveOutOfDateDef : 1;
2505
2506  /// Has the full definition of this type been required by a use somewhere in
2507  /// the TU.
2508  bool IsCompleteDefinitionRequired : 1;
2509private:
2510  SourceLocation RBraceLoc;
2511
2512  // A struct representing syntactic qualifier info,
2513  // to be used for the (uncommon) case of out-of-line declarations.
2514  typedef QualifierInfo ExtInfo;
2515
2516  /// \brief If the (out-of-line) tag declaration name
2517  /// is qualified, it points to the qualifier info (nns and range);
2518  /// otherwise, if the tag declaration is anonymous and it is part of
2519  /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2520  /// otherwise, if the tag declaration is anonymous and it is used as a
2521  /// declaration specifier for variables, it points to the first VarDecl (used
2522  /// for mangling);
2523  /// otherwise, it is a null (TypedefNameDecl) pointer.
2524  llvm::PointerUnion<NamedDecl *, ExtInfo *> NamedDeclOrQualifier;
2525
2526  bool hasExtInfo() const { return NamedDeclOrQualifier.is<ExtInfo *>(); }
2527  ExtInfo *getExtInfo() { return NamedDeclOrQualifier.get<ExtInfo *>(); }
2528  const ExtInfo *getExtInfo() const {
2529    return NamedDeclOrQualifier.get<ExtInfo *>();
2530  }
2531
2532protected:
2533  TagDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
2534          IdentifierInfo *Id, TagDecl *PrevDecl, SourceLocation StartL)
2535      : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), TagDeclKind(TK),
2536        IsCompleteDefinition(false), IsBeingDefined(false),
2537        IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2538        IsCompleteDefinitionRequired(false),
2539        NamedDeclOrQualifier((NamedDecl *)0) {
2540    assert((DK != Enum || TK == TTK_Enum) &&
2541           "EnumDecl not matched with TTK_Enum");
2542    setPreviousDeclaration(PrevDecl);
2543  }
2544
2545  typedef Redeclarable<TagDecl> redeclarable_base;
2546  virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2547  virtual TagDecl *getPreviousDeclImpl() {
2548    return getPreviousDecl();
2549  }
2550  virtual TagDecl *getMostRecentDeclImpl() {
2551    return getMostRecentDecl();
2552  }
2553
2554  /// @brief Completes the definition of this tag declaration.
2555  ///
2556  /// This is a helper function for derived classes.
2557  void completeDefinition();
2558
2559public:
2560  typedef redeclarable_base::redecl_iterator redecl_iterator;
2561  using redeclarable_base::redecls_begin;
2562  using redeclarable_base::redecls_end;
2563  using redeclarable_base::getPreviousDecl;
2564  using redeclarable_base::getMostRecentDecl;
2565
2566  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2567  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2568
2569  /// getInnerLocStart - Return SourceLocation representing start of source
2570  /// range ignoring outer template declarations.
2571  SourceLocation getInnerLocStart() const { return getLocStart(); }
2572
2573  /// getOuterLocStart - Return SourceLocation representing start of source
2574  /// range taking into account any outer template declarations.
2575  SourceLocation getOuterLocStart() const;
2576  virtual SourceRange getSourceRange() const LLVM_READONLY;
2577
2578  virtual TagDecl* getCanonicalDecl();
2579  const TagDecl* getCanonicalDecl() const {
2580    return const_cast<TagDecl*>(this)->getCanonicalDecl();
2581  }
2582
2583  /// isThisDeclarationADefinition() - Return true if this declaration
2584  /// is a completion definintion of the type.  Provided for consistency.
2585  bool isThisDeclarationADefinition() const {
2586    return isCompleteDefinition();
2587  }
2588
2589  /// isCompleteDefinition - Return true if this decl has its body
2590  /// fully specified.
2591  bool isCompleteDefinition() const {
2592    return IsCompleteDefinition;
2593  }
2594
2595  /// \brief Return true if this complete decl is
2596  /// required to be complete for some existing use.
2597  bool isCompleteDefinitionRequired() const {
2598    return IsCompleteDefinitionRequired;
2599  }
2600
2601  /// isBeingDefined - Return true if this decl is currently being defined.
2602  bool isBeingDefined() const {
2603    return IsBeingDefined;
2604  }
2605
2606  bool isEmbeddedInDeclarator() const {
2607    return IsEmbeddedInDeclarator;
2608  }
2609  void setEmbeddedInDeclarator(bool isInDeclarator) {
2610    IsEmbeddedInDeclarator = isInDeclarator;
2611  }
2612
2613  bool isFreeStanding() const { return IsFreeStanding; }
2614  void setFreeStanding(bool isFreeStanding = true) {
2615    IsFreeStanding = isFreeStanding;
2616  }
2617
2618  /// \brief Whether this declaration declares a type that is
2619  /// dependent, i.e., a type that somehow depends on template
2620  /// parameters.
2621  bool isDependentType() const { return isDependentContext(); }
2622
2623  /// @brief Starts the definition of this tag declaration.
2624  ///
2625  /// This method should be invoked at the beginning of the definition
2626  /// of this tag declaration. It will set the tag type into a state
2627  /// where it is in the process of being defined.
2628  void startDefinition();
2629
2630  /// getDefinition - Returns the TagDecl that actually defines this
2631  ///  struct/union/class/enum.  When determining whether or not a
2632  ///  struct/union/class/enum has a definition, one should use this
2633  ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2634  ///  whether or not a specific TagDecl is defining declaration, not
2635  ///  whether or not the struct/union/class/enum type is defined.
2636  ///  This method returns NULL if there is no TagDecl that defines
2637  ///  the struct/union/class/enum.
2638  TagDecl *getDefinition() const;
2639
2640  void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2641
2642  void setCompleteDefinitionRequired(bool V = true) {
2643    IsCompleteDefinitionRequired = V;
2644  }
2645
2646  // FIXME: Return StringRef;
2647  const char *getKindName() const {
2648    return TypeWithKeyword::getTagTypeKindName(getTagKind());
2649  }
2650
2651  TagKind getTagKind() const {
2652    return TagKind(TagDeclKind);
2653  }
2654
2655  void setTagKind(TagKind TK) { TagDeclKind = TK; }
2656
2657  bool isStruct() const { return getTagKind() == TTK_Struct; }
2658  bool isInterface() const { return getTagKind() == TTK_Interface; }
2659  bool isClass()  const { return getTagKind() == TTK_Class; }
2660  bool isUnion()  const { return getTagKind() == TTK_Union; }
2661  bool isEnum()   const { return getTagKind() == TTK_Enum; }
2662
2663  /// Is this tag type named, either directly or via being defined in
2664  /// a typedef of this type?
2665  ///
2666  /// C++11 [basic.link]p8:
2667  ///   A type is said to have linkage if and only if:
2668  ///     - it is a class or enumeration type that is named (or has a
2669  ///       name for linkage purposes) and the name has linkage; ...
2670  /// C++11 [dcl.typedef]p9:
2671  ///   If the typedef declaration defines an unnamed class (or enum),
2672  ///   the first typedef-name declared by the declaration to be that
2673  ///   class type (or enum type) is used to denote the class type (or
2674  ///   enum type) for linkage purposes only.
2675  ///
2676  /// C does not have an analogous rule, but the same concept is
2677  /// nonetheless useful in some places.
2678  bool hasNameForLinkage() const {
2679    return (getDeclName() || getTypedefNameForAnonDecl());
2680  }
2681
2682  bool hasDeclaratorForAnonDecl() const {
2683    return dyn_cast_or_null<DeclaratorDecl>(
2684        NamedDeclOrQualifier.get<NamedDecl *>());
2685  }
2686  DeclaratorDecl *getDeclaratorForAnonDecl() const {
2687    return hasExtInfo() ? 0 : dyn_cast_or_null<DeclaratorDecl>(
2688                                  NamedDeclOrQualifier.get<NamedDecl *>());
2689  }
2690
2691  TypedefNameDecl *getTypedefNameForAnonDecl() const {
2692    return hasExtInfo() ? 0 : dyn_cast_or_null<TypedefNameDecl>(
2693                                  NamedDeclOrQualifier.get<NamedDecl *>());
2694  }
2695
2696  void setDeclaratorForAnonDecl(DeclaratorDecl *DD) { NamedDeclOrQualifier = DD; }
2697
2698  void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2699
2700  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2701  /// declaration, if it was present in the source.
2702  NestedNameSpecifier *getQualifier() const {
2703    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2704                        : 0;
2705  }
2706
2707  /// \brief Retrieve the nested-name-specifier (with source-location
2708  /// information) that qualifies the name of this declaration, if it was
2709  /// present in the source.
2710  NestedNameSpecifierLoc getQualifierLoc() const {
2711    return hasExtInfo() ? getExtInfo()->QualifierLoc
2712                        : NestedNameSpecifierLoc();
2713  }
2714
2715  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2716
2717  unsigned getNumTemplateParameterLists() const {
2718    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2719  }
2720  TemplateParameterList *getTemplateParameterList(unsigned i) const {
2721    assert(i < getNumTemplateParameterLists());
2722    return getExtInfo()->TemplParamLists[i];
2723  }
2724  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2725                                     TemplateParameterList **TPLists);
2726
2727  // Implement isa/cast/dyncast/etc.
2728  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2729  static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2730
2731  static DeclContext *castToDeclContext(const TagDecl *D) {
2732    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2733  }
2734  static TagDecl *castFromDeclContext(const DeclContext *DC) {
2735    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2736  }
2737
2738  friend class ASTDeclReader;
2739  friend class ASTDeclWriter;
2740};
2741
2742/// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
2743/// with a fixed underlying type, and in C we allow them to be forward-declared
2744/// with no underlying type as an extension.
2745class EnumDecl : public TagDecl {
2746  virtual void anchor();
2747  /// IntegerType - This represent the integer type that the enum corresponds
2748  /// to for code generation purposes.  Note that the enumerator constants may
2749  /// have a different type than this does.
2750  ///
2751  /// If the underlying integer type was explicitly stated in the source
2752  /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2753  /// was automatically deduced somehow, and this is a Type*.
2754  ///
2755  /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2756  /// some cases it won't.
2757  ///
2758  /// The underlying type of an enumeration never has any qualifiers, so
2759  /// we can get away with just storing a raw Type*, and thus save an
2760  /// extra pointer when TypeSourceInfo is needed.
2761
2762  llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2763
2764  /// PromotionType - The integer type that values of this type should
2765  /// promote to.  In C, enumerators are generally of an integer type
2766  /// directly, but gcc-style large enumerators (and all enumerators
2767  /// in C++) are of the enum type instead.
2768  QualType PromotionType;
2769
2770  /// \brief If this enumeration is an instantiation of a member enumeration
2771  /// of a class template specialization, this is the member specialization
2772  /// information.
2773  MemberSpecializationInfo *SpecializationInfo;
2774
2775  EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2776           IdentifierInfo *Id, EnumDecl *PrevDecl,
2777           bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2778    : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2779      SpecializationInfo(0) {
2780    assert(Scoped || !ScopedUsingClassTag);
2781    IntegerType = (const Type*)0;
2782    NumNegativeBits = 0;
2783    NumPositiveBits = 0;
2784    IsScoped = Scoped;
2785    IsScopedUsingClassTag = ScopedUsingClassTag;
2786    IsFixed = Fixed;
2787  }
2788
2789  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2790                                    TemplateSpecializationKind TSK);
2791public:
2792  EnumDecl *getCanonicalDecl() {
2793    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2794  }
2795  const EnumDecl *getCanonicalDecl() const {
2796    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2797  }
2798
2799  const EnumDecl *getPreviousDecl() const {
2800    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2801  }
2802  EnumDecl *getPreviousDecl() {
2803    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2804  }
2805
2806  const EnumDecl *getMostRecentDecl() const {
2807    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2808  }
2809  EnumDecl *getMostRecentDecl() {
2810    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2811  }
2812
2813  EnumDecl *getDefinition() const {
2814    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2815  }
2816
2817  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2818                          SourceLocation StartLoc, SourceLocation IdLoc,
2819                          IdentifierInfo *Id, EnumDecl *PrevDecl,
2820                          bool IsScoped, bool IsScopedUsingClassTag,
2821                          bool IsFixed);
2822  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2823
2824  /// completeDefinition - When created, the EnumDecl corresponds to a
2825  /// forward-declared enum. This method is used to mark the
2826  /// declaration as being defined; it's enumerators have already been
2827  /// added (via DeclContext::addDecl). NewType is the new underlying
2828  /// type of the enumeration type.
2829  void completeDefinition(QualType NewType,
2830                          QualType PromotionType,
2831                          unsigned NumPositiveBits,
2832                          unsigned NumNegativeBits);
2833
2834  // enumerator_iterator - Iterates through the enumerators of this
2835  // enumeration.
2836  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2837
2838  enumerator_iterator enumerator_begin() const {
2839    const EnumDecl *E = getDefinition();
2840    if (!E)
2841      E = this;
2842    return enumerator_iterator(E->decls_begin());
2843  }
2844
2845  enumerator_iterator enumerator_end() const {
2846    const EnumDecl *E = getDefinition();
2847    if (!E)
2848      E = this;
2849    return enumerator_iterator(E->decls_end());
2850  }
2851
2852  /// getPromotionType - Return the integer type that enumerators
2853  /// should promote to.
2854  QualType getPromotionType() const { return PromotionType; }
2855
2856  /// \brief Set the promotion type.
2857  void setPromotionType(QualType T) { PromotionType = T; }
2858
2859  /// getIntegerType - Return the integer type this enum decl corresponds to.
2860  /// This returns a null qualtype for an enum forward definition.
2861  QualType getIntegerType() const {
2862    if (!IntegerType)
2863      return QualType();
2864    if (const Type* T = IntegerType.dyn_cast<const Type*>())
2865      return QualType(T, 0);
2866    return IntegerType.get<TypeSourceInfo*>()->getType();
2867  }
2868
2869  /// \brief Set the underlying integer type.
2870  void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2871
2872  /// \brief Set the underlying integer type source info.
2873  void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2874
2875  /// \brief Return the type source info for the underlying integer type,
2876  /// if no type source info exists, return 0.
2877  TypeSourceInfo* getIntegerTypeSourceInfo() const {
2878    return IntegerType.dyn_cast<TypeSourceInfo*>();
2879  }
2880
2881  /// \brief Returns the width in bits required to store all the
2882  /// non-negative enumerators of this enum.
2883  unsigned getNumPositiveBits() const {
2884    return NumPositiveBits;
2885  }
2886  void setNumPositiveBits(unsigned Num) {
2887    NumPositiveBits = Num;
2888    assert(NumPositiveBits == Num && "can't store this bitcount");
2889  }
2890
2891  /// \brief Returns the width in bits required to store all the
2892  /// negative enumerators of this enum.  These widths include
2893  /// the rightmost leading 1;  that is:
2894  ///
2895  /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
2896  /// ------------------------     -------     -----------------
2897  ///                       -1     1111111                     1
2898  ///                      -10     1110110                     5
2899  ///                     -101     1001011                     8
2900  unsigned getNumNegativeBits() const {
2901    return NumNegativeBits;
2902  }
2903  void setNumNegativeBits(unsigned Num) {
2904    NumNegativeBits = Num;
2905  }
2906
2907  /// \brief Returns true if this is a C++11 scoped enumeration.
2908  bool isScoped() const {
2909    return IsScoped;
2910  }
2911
2912  /// \brief Returns true if this is a C++11 scoped enumeration.
2913  bool isScopedUsingClassTag() const {
2914    return IsScopedUsingClassTag;
2915  }
2916
2917  /// \brief Returns true if this is an Objective-C, C++11, or
2918  /// Microsoft-style enumeration with a fixed underlying type.
2919  bool isFixed() const {
2920    return IsFixed;
2921  }
2922
2923  /// \brief Returns true if this can be considered a complete type.
2924  bool isComplete() const {
2925    return isCompleteDefinition() || isFixed();
2926  }
2927
2928  /// \brief Returns the enumeration (declared within the template)
2929  /// from which this enumeration type was instantiated, or NULL if
2930  /// this enumeration was not instantiated from any template.
2931  EnumDecl *getInstantiatedFromMemberEnum() const;
2932
2933  /// \brief If this enumeration is a member of a specialization of a
2934  /// templated class, determine what kind of template specialization
2935  /// or instantiation this is.
2936  TemplateSpecializationKind getTemplateSpecializationKind() const;
2937
2938  /// \brief For an enumeration member that was instantiated from a member
2939  /// enumeration of a templated class, set the template specialiation kind.
2940  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2941                        SourceLocation PointOfInstantiation = SourceLocation());
2942
2943  /// \brief If this enumeration is an instantiation of a member enumeration of
2944  /// a class template specialization, retrieves the member specialization
2945  /// information.
2946  MemberSpecializationInfo *getMemberSpecializationInfo() const {
2947    return SpecializationInfo;
2948  }
2949
2950  /// \brief Specify that this enumeration is an instantiation of the
2951  /// member enumeration ED.
2952  void setInstantiationOfMemberEnum(EnumDecl *ED,
2953                                    TemplateSpecializationKind TSK) {
2954    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2955  }
2956
2957  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2958  static bool classofKind(Kind K) { return K == Enum; }
2959
2960  friend class ASTDeclReader;
2961};
2962
2963
2964/// RecordDecl - Represents a struct/union/class.  For example:
2965///   struct X;                  // Forward declaration, no "body".
2966///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
2967/// This decl will be marked invalid if *any* members are invalid.
2968///
2969class RecordDecl : public TagDecl {
2970  // FIXME: This can be packed into the bitfields in Decl.
2971  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2972  /// array member (e.g. int X[]) or if this union contains a struct that does.
2973  /// If so, this cannot be contained in arrays or other structs as a member.
2974  bool HasFlexibleArrayMember : 1;
2975
2976  /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2977  /// or union.
2978  bool AnonymousStructOrUnion : 1;
2979
2980  /// HasObjectMember - This is true if this struct has at least one member
2981  /// containing an Objective-C object pointer type.
2982  bool HasObjectMember : 1;
2983
2984  /// HasVolatileMember - This is true if struct has at least one member of
2985  /// 'volatile' type.
2986  bool HasVolatileMember : 1;
2987
2988  /// \brief Whether the field declarations of this record have been loaded
2989  /// from external storage. To avoid unnecessary deserialization of
2990  /// methods/nested types we allow deserialization of just the fields
2991  /// when needed.
2992  mutable bool LoadedFieldsFromExternalStorage : 1;
2993  friend class DeclContext;
2994
2995protected:
2996  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2997             SourceLocation StartLoc, SourceLocation IdLoc,
2998             IdentifierInfo *Id, RecordDecl *PrevDecl);
2999
3000public:
3001  static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3002                            SourceLocation StartLoc, SourceLocation IdLoc,
3003                            IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
3004  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3005
3006  const RecordDecl *getPreviousDecl() const {
3007    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
3008  }
3009  RecordDecl *getPreviousDecl() {
3010    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
3011  }
3012
3013  const RecordDecl *getMostRecentDecl() const {
3014    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
3015  }
3016  RecordDecl *getMostRecentDecl() {
3017    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
3018  }
3019
3020  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3021  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3022
3023  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3024  /// or union. To be an anonymous struct or union, it must have been
3025  /// declared without a name and there must be no objects of this
3026  /// type declared, e.g.,
3027  /// @code
3028  ///   union { int i; float f; };
3029  /// @endcode
3030  /// is an anonymous union but neither of the following are:
3031  /// @code
3032  ///  union X { int i; float f; };
3033  ///  union { int i; float f; } obj;
3034  /// @endcode
3035  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3036  void setAnonymousStructOrUnion(bool Anon) {
3037    AnonymousStructOrUnion = Anon;
3038  }
3039
3040  bool hasObjectMember() const { return HasObjectMember; }
3041  void setHasObjectMember (bool val) { HasObjectMember = val; }
3042
3043  bool hasVolatileMember() const { return HasVolatileMember; }
3044  void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3045
3046  /// \brief Determines whether this declaration represents the
3047  /// injected class name.
3048  ///
3049  /// The injected class name in C++ is the name of the class that
3050  /// appears inside the class itself. For example:
3051  ///
3052  /// \code
3053  /// struct C {
3054  ///   // C is implicitly declared here as a synonym for the class name.
3055  /// };
3056  ///
3057  /// C::C c; // same as "C c;"
3058  /// \endcode
3059  bool isInjectedClassName() const;
3060
3061  /// getDefinition - Returns the RecordDecl that actually defines
3062  ///  this struct/union/class.  When determining whether or not a
3063  ///  struct/union/class is completely defined, one should use this
3064  ///  method as opposed to 'isCompleteDefinition'.
3065  ///  'isCompleteDefinition' indicates whether or not a specific
3066  ///  RecordDecl is a completed definition, not whether or not the
3067  ///  record type is defined.  This method returns NULL if there is
3068  ///  no RecordDecl that defines the struct/union/tag.
3069  RecordDecl *getDefinition() const {
3070    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3071  }
3072
3073  // Iterator access to field members. The field iterator only visits
3074  // the non-static data members of this class, ignoring any static
3075  // data members, functions, constructors, destructors, etc.
3076  typedef specific_decl_iterator<FieldDecl> field_iterator;
3077
3078  field_iterator field_begin() const;
3079
3080  field_iterator field_end() const {
3081    return field_iterator(decl_iterator());
3082  }
3083
3084  // field_empty - Whether there are any fields (non-static data
3085  // members) in this record.
3086  bool field_empty() const {
3087    return field_begin() == field_end();
3088  }
3089
3090  /// completeDefinition - Notes that the definition of this type is
3091  /// now complete.
3092  virtual void completeDefinition();
3093
3094  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3095  static bool classofKind(Kind K) {
3096    return K >= firstRecord && K <= lastRecord;
3097  }
3098
3099  /// isMsStrust - Get whether or not this is an ms_struct which can
3100  /// be turned on with an attribute, pragma, or -mms-bitfields
3101  /// commandline option.
3102  bool isMsStruct(const ASTContext &C) const;
3103
3104private:
3105  /// \brief Deserialize just the fields.
3106  void LoadFieldsFromExternalStorage() const;
3107};
3108
3109class FileScopeAsmDecl : public Decl {
3110  virtual void anchor();
3111  StringLiteral *AsmString;
3112  SourceLocation RParenLoc;
3113  FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3114                   SourceLocation StartL, SourceLocation EndL)
3115    : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3116public:
3117  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3118                                  StringLiteral *Str, SourceLocation AsmLoc,
3119                                  SourceLocation RParenLoc);
3120
3121  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3122
3123  SourceLocation getAsmLoc() const { return getLocation(); }
3124  SourceLocation getRParenLoc() const { return RParenLoc; }
3125  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3126  SourceRange getSourceRange() const LLVM_READONLY {
3127    return SourceRange(getAsmLoc(), getRParenLoc());
3128  }
3129
3130  const StringLiteral *getAsmString() const { return AsmString; }
3131  StringLiteral *getAsmString() { return AsmString; }
3132  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3133
3134  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3135  static bool classofKind(Kind K) { return K == FileScopeAsm; }
3136};
3137
3138/// BlockDecl - This represents a block literal declaration, which is like an
3139/// unnamed FunctionDecl.  For example:
3140/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3141///
3142class BlockDecl : public Decl, public DeclContext {
3143public:
3144  /// A class which contains all the information about a particular
3145  /// captured value.
3146  class Capture {
3147    enum {
3148      flag_isByRef = 0x1,
3149      flag_isNested = 0x2
3150    };
3151
3152    /// The variable being captured.
3153    llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3154
3155    /// The copy expression, expressed in terms of a DeclRef (or
3156    /// BlockDeclRef) to the captured variable.  Only required if the
3157    /// variable has a C++ class type.
3158    Expr *CopyExpr;
3159
3160  public:
3161    Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3162      : VariableAndFlags(variable,
3163                  (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3164        CopyExpr(copy) {}
3165
3166    /// The variable being captured.
3167    VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3168
3169    /// Whether this is a "by ref" capture, i.e. a capture of a __block
3170    /// variable.
3171    bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3172
3173    /// Whether this is a nested capture, i.e. the variable captured
3174    /// is not from outside the immediately enclosing function/block.
3175    bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3176
3177    bool hasCopyExpr() const { return CopyExpr != 0; }
3178    Expr *getCopyExpr() const { return CopyExpr; }
3179    void setCopyExpr(Expr *e) { CopyExpr = e; }
3180  };
3181
3182private:
3183  // FIXME: This can be packed into the bitfields in Decl.
3184  bool IsVariadic : 1;
3185  bool CapturesCXXThis : 1;
3186  bool BlockMissingReturnType : 1;
3187  bool IsConversionFromLambda : 1;
3188  /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3189  /// parameters of this function.  This is null if a prototype or if there are
3190  /// no formals.
3191  ParmVarDecl **ParamInfo;
3192  unsigned NumParams;
3193
3194  Stmt *Body;
3195  TypeSourceInfo *SignatureAsWritten;
3196
3197  Capture *Captures;
3198  unsigned NumCaptures;
3199
3200  unsigned ManglingNumber;
3201  Decl *ManglingContextDecl;
3202
3203protected:
3204  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3205    : Decl(Block, DC, CaretLoc), DeclContext(Block),
3206      IsVariadic(false), CapturesCXXThis(false),
3207      BlockMissingReturnType(true), IsConversionFromLambda(false),
3208      ParamInfo(0), NumParams(0), Body(0),
3209      SignatureAsWritten(0), Captures(0), NumCaptures(0),
3210      ManglingNumber(0), ManglingContextDecl(0) {}
3211
3212public:
3213  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3214  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3215
3216  SourceLocation getCaretLocation() const { return getLocation(); }
3217
3218  bool isVariadic() const { return IsVariadic; }
3219  void setIsVariadic(bool value) { IsVariadic = value; }
3220
3221  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3222  Stmt *getBody() const { return (Stmt*) Body; }
3223  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3224
3225  void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3226  TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3227
3228  // Iterator access to formal parameters.
3229  unsigned param_size() const { return getNumParams(); }
3230  typedef ParmVarDecl **param_iterator;
3231  typedef ParmVarDecl * const *param_const_iterator;
3232
3233  bool param_empty() const { return NumParams == 0; }
3234  param_iterator param_begin()  { return ParamInfo; }
3235  param_iterator param_end()   { return ParamInfo+param_size(); }
3236
3237  param_const_iterator param_begin() const { return ParamInfo; }
3238  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
3239
3240  unsigned getNumParams() const { return NumParams; }
3241  const ParmVarDecl *getParamDecl(unsigned i) const {
3242    assert(i < getNumParams() && "Illegal param #");
3243    return ParamInfo[i];
3244  }
3245  ParmVarDecl *getParamDecl(unsigned i) {
3246    assert(i < getNumParams() && "Illegal param #");
3247    return ParamInfo[i];
3248  }
3249  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3250
3251  /// hasCaptures - True if this block (or its nested blocks) captures
3252  /// anything of local storage from its enclosing scopes.
3253  bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3254
3255  /// getNumCaptures - Returns the number of captured variables.
3256  /// Does not include an entry for 'this'.
3257  unsigned getNumCaptures() const { return NumCaptures; }
3258
3259  typedef const Capture *capture_iterator;
3260  typedef const Capture *capture_const_iterator;
3261  capture_iterator capture_begin() { return Captures; }
3262  capture_iterator capture_end() { return Captures + NumCaptures; }
3263  capture_const_iterator capture_begin() const { return Captures; }
3264  capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3265
3266  bool capturesCXXThis() const { return CapturesCXXThis; }
3267  bool blockMissingReturnType() const { return BlockMissingReturnType; }
3268  void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3269
3270  bool isConversionFromLambda() const { return IsConversionFromLambda; }
3271  void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3272
3273  bool capturesVariable(const VarDecl *var) const;
3274
3275  void setCaptures(ASTContext &Context,
3276                   const Capture *begin,
3277                   const Capture *end,
3278                   bool capturesCXXThis);
3279
3280   unsigned getBlockManglingNumber() const {
3281     return ManglingNumber;
3282   }
3283   Decl *getBlockManglingContextDecl() const {
3284     return ManglingContextDecl;
3285   }
3286
3287  void setBlockMangling(unsigned Number, Decl *Ctx) {
3288    ManglingNumber = Number;
3289    ManglingContextDecl = Ctx;
3290  }
3291
3292  virtual SourceRange getSourceRange() const LLVM_READONLY;
3293
3294  // Implement isa/cast/dyncast/etc.
3295  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3296  static bool classofKind(Kind K) { return K == Block; }
3297  static DeclContext *castToDeclContext(const BlockDecl *D) {
3298    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3299  }
3300  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3301    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3302  }
3303};
3304
3305/// \brief This represents the body of a CapturedStmt, and serves as its
3306/// DeclContext.
3307class CapturedDecl : public Decl, public DeclContext {
3308private:
3309  /// \brief The number of parameters to the outlined function.
3310  unsigned NumParams;
3311  /// \brief The body of the outlined function.
3312  Stmt *Body;
3313
3314  explicit CapturedDecl(DeclContext *DC, unsigned NumParams)
3315    : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
3316      NumParams(NumParams), Body(0) { }
3317
3318  ImplicitParamDecl **getParams() const {
3319    return reinterpret_cast<ImplicitParamDecl **>(
3320             const_cast<CapturedDecl *>(this) + 1);
3321  }
3322
3323public:
3324  static CapturedDecl *Create(ASTContext &C, DeclContext *DC, unsigned NumParams);
3325  static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3326                                          unsigned NumParams);
3327
3328  Stmt *getBody() const { return Body; }
3329  void setBody(Stmt *B) { Body = B; }
3330
3331  unsigned getNumParams() const { return NumParams; }
3332
3333  ImplicitParamDecl *getParam(unsigned i) const {
3334    assert(i < NumParams);
3335    return getParams()[i];
3336  }
3337  void setParam(unsigned i, ImplicitParamDecl *P) {
3338    assert(i < NumParams);
3339    getParams()[i] = P;
3340  }
3341
3342  /// \brief Retrieve the parameter containing captured variables.
3343  ImplicitParamDecl *getContextParam() const { return getParam(0); }
3344  void setContextParam(ImplicitParamDecl *P) { setParam(0, P); }
3345
3346  typedef ImplicitParamDecl **param_iterator;
3347  /// \brief Retrieve an iterator pointing to the first parameter decl.
3348  param_iterator param_begin() const { return getParams(); }
3349  /// \brief Retrieve an iterator one past the last parameter decl.
3350  param_iterator param_end() const { return getParams() + NumParams; }
3351
3352  // Implement isa/cast/dyncast/etc.
3353  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3354  static bool classofKind(Kind K) { return K == Captured; }
3355  static DeclContext *castToDeclContext(const CapturedDecl *D) {
3356    return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3357  }
3358  static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3359    return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3360  }
3361
3362  friend class ASTDeclReader;
3363  friend class ASTDeclWriter;
3364};
3365
3366/// \brief Describes a module import declaration, which makes the contents
3367/// of the named module visible in the current translation unit.
3368///
3369/// An import declaration imports the named module (or submodule). For example:
3370/// \code
3371///   @import std.vector;
3372/// \endcode
3373///
3374/// Import declarations can also be implicitly generated from
3375/// \#include/\#import directives.
3376class ImportDecl : public Decl {
3377  /// \brief The imported module, along with a bit that indicates whether
3378  /// we have source-location information for each identifier in the module
3379  /// name.
3380  ///
3381  /// When the bit is false, we only have a single source location for the
3382  /// end of the import declaration.
3383  llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3384
3385  /// \brief The next import in the list of imports local to the translation
3386  /// unit being parsed (not loaded from an AST file).
3387  ImportDecl *NextLocalImport;
3388
3389  friend class ASTReader;
3390  friend class ASTDeclReader;
3391  friend class ASTContext;
3392
3393  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3394             ArrayRef<SourceLocation> IdentifierLocs);
3395
3396  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3397             SourceLocation EndLoc);
3398
3399  ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3400
3401public:
3402  /// \brief Create a new module import declaration.
3403  static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3404                            SourceLocation StartLoc, Module *Imported,
3405                            ArrayRef<SourceLocation> IdentifierLocs);
3406
3407  /// \brief Create a new module import declaration for an implicitly-generated
3408  /// import.
3409  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3410                                    SourceLocation StartLoc, Module *Imported,
3411                                    SourceLocation EndLoc);
3412
3413  /// \brief Create a new, deserialized module import declaration.
3414  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3415                                        unsigned NumLocations);
3416
3417  /// \brief Retrieve the module that was imported by the import declaration.
3418  Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3419
3420  /// \brief Retrieves the locations of each of the identifiers that make up
3421  /// the complete module name in the import declaration.
3422  ///
3423  /// This will return an empty array if the locations of the individual
3424  /// identifiers aren't available.
3425  ArrayRef<SourceLocation> getIdentifierLocs() const;
3426
3427  virtual SourceRange getSourceRange() const LLVM_READONLY;
3428
3429  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3430  static bool classofKind(Kind K) { return K == Import; }
3431};
3432
3433/// \brief Represents an empty-declaration.
3434class EmptyDecl : public Decl {
3435  virtual void anchor();
3436  EmptyDecl(DeclContext *DC, SourceLocation L)
3437    : Decl(Empty, DC, L) { }
3438
3439public:
3440  static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3441                           SourceLocation L);
3442  static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3443
3444  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3445  static bool classofKind(Kind K) { return K == Empty; }
3446};
3447
3448/// Insertion operator for diagnostics.  This allows sending NamedDecl's
3449/// into a diagnostic with <<.
3450inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3451                                           const NamedDecl* ND) {
3452  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3453                  DiagnosticsEngine::ak_nameddecl);
3454  return DB;
3455}
3456inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3457                                           const NamedDecl* ND) {
3458  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3459                  DiagnosticsEngine::ak_nameddecl);
3460  return PD;
3461}
3462
3463template<typename decl_type>
3464void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3465  // Note: This routine is implemented here because we need both NamedDecl
3466  // and Redeclarable to be defined.
3467
3468  decl_type *First;
3469
3470  if (PrevDecl) {
3471    // Point to previous. Make sure that this is actually the most recent
3472    // redeclaration, or we can build invalid chains. If the most recent
3473    // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3474    First = PrevDecl->getFirstDeclaration();
3475    assert(First->RedeclLink.NextIsLatest() && "Expected first");
3476    decl_type *MostRecent = First->RedeclLink.getNext();
3477    RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3478
3479    // If the declaration was previously visible, a redeclaration of it remains
3480    // visible even if it wouldn't be visible by itself.
3481    static_cast<decl_type*>(this)->IdentifierNamespace |=
3482      MostRecent->getIdentifierNamespace() &
3483      (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3484  } else {
3485    // Make this first.
3486    First = static_cast<decl_type*>(this);
3487  }
3488
3489  // First one will point to this one as latest.
3490  First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3491  assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3492         cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3493}
3494
3495// Inline function definitions.
3496
3497/// \brief Check if the given decl is complete.
3498///
3499/// We use this function to break a cycle between the inline definitions in
3500/// Type.h and Decl.h.
3501inline bool IsEnumDeclComplete(EnumDecl *ED) {
3502  return ED->isComplete();
3503}
3504
3505/// \brief Check if the given decl is scoped.
3506///
3507/// We use this function to break a cycle between the inline definitions in
3508/// Type.h and Decl.h.
3509inline bool IsEnumDeclScoped(EnumDecl *ED) {
3510  return ED->isScoped();
3511}
3512
3513}  // end namespace clang
3514
3515#endif
3516