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