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