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