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