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