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