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