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