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