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