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