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