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