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