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