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