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