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