Decl.h revision 69d66b28dc953ae7c2c0b877c78ccd9c691b44f1
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 TemplateArgumentList;
32class MemberSpecializationInfo;
33class FunctionTemplateSpecializationInfo;
34class TypeLoc;
35
36/// \brief A container of type source information.
37///
38/// A client can read the relevant info using TypeLoc wrappers, e.g:
39/// @code
40/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
41/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
42///   PL->getStarLoc().print(OS, SrcMgr);
43/// @endcode
44///
45class TypeSourceInfo {
46  QualType Ty;
47  // Contains a memory block after the class, used for type source information,
48  // allocated by ASTContext.
49  friend class ASTContext;
50  TypeSourceInfo(QualType ty) : Ty(ty) { }
51public:
52  /// \brief Return the type wrapped by this type source info.
53  QualType getType() const { return Ty; }
54
55  /// \brief Return the TypeLoc wrapper for the type source info.
56  TypeLoc getTypeLoc() const;
57};
58
59/// TranslationUnitDecl - The top declaration context.
60class TranslationUnitDecl : public Decl, public DeclContext {
61  ASTContext &Ctx;
62
63  /// The (most recently entered) anonymous namespace for this
64  /// translation unit, if one has been created.
65  NamespaceDecl *AnonymousNamespace;
66
67  explicit TranslationUnitDecl(ASTContext &ctx)
68    : Decl(TranslationUnit, 0, SourceLocation()),
69      DeclContext(TranslationUnit),
70      Ctx(ctx), AnonymousNamespace(0) {}
71public:
72  ASTContext &getASTContext() const { return Ctx; }
73
74  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
75  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
76
77  static TranslationUnitDecl *Create(ASTContext &C);
78  // Implement isa/cast/dyncast/etc.
79  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
80  static bool classof(const TranslationUnitDecl *D) { return true; }
81  static bool classofKind(Kind K) { return K == TranslationUnit; }
82  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
83    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
84  }
85  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
86    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
87  }
88};
89
90/// NamedDecl - This represents a decl with a name.  Many decls have names such
91/// as ObjCMethodDecl, but not @class, etc.
92class NamedDecl : public Decl {
93  /// Name - The name of this declaration, which is typically a normal
94  /// identifier but may also be a special kind of name (C++
95  /// constructor, Objective-C selector, etc.)
96  DeclarationName Name;
97
98protected:
99  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
100    : Decl(DK, DC, L), Name(N) { }
101
102public:
103  /// getIdentifier - Get the identifier that names this declaration,
104  /// if there is one. This will return NULL if this declaration has
105  /// no name (e.g., for an unnamed class) or if the name is a special
106  /// name (C++ constructor, Objective-C selector, etc.).
107  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
108
109  /// getName - Get the name of identifier for this declaration as a StringRef.
110  /// This requires that the declaration have a name and that it be a simple
111  /// identifier.
112  llvm::StringRef getName() const {
113    assert(Name.isIdentifier() && "Name is not a simple identifier");
114    return getIdentifier() ? getIdentifier()->getName() : "";
115  }
116
117  /// getNameAsCString - Get the name of identifier for this declaration as a
118  /// C string (const char*).  This requires that the declaration have a name
119  /// and that it be a simple identifier.
120  //
121  // FIXME: Deprecated, move clients to getName().
122  const char *getNameAsCString() const {
123    assert(Name.isIdentifier() && "Name is not a simple identifier");
124    return getIdentifier() ? getIdentifier()->getNameStart() : "";
125  }
126
127  /// getNameAsString - Get a human-readable name for the declaration, even if
128  /// it is one of the special kinds of names (C++ constructor, Objective-C
129  /// selector, etc).  Creating this name requires expensive string
130  /// manipulation, so it should be called only when performance doesn't matter.
131  /// For simple declarations, getNameAsCString() should suffice.
132  //
133  // FIXME: This function should be renamed to indicate that it is not just an
134  // alternate form of getName(), and clients should move as appropriate.
135  //
136  // FIXME: Deprecated, move clients to getName().
137  std::string getNameAsString() const { return Name.getAsString(); }
138
139  /// getDeclName - Get the actual, stored name of the declaration,
140  /// which may be a special name.
141  DeclarationName getDeclName() const { return Name; }
142
143  /// \brief Set the name of this declaration.
144  void setDeclName(DeclarationName N) { Name = N; }
145
146  /// getQualifiedNameAsString - Returns human-readable qualified name for
147  /// declaration, like A::B::i, for i being member of namespace A::B.
148  /// If declaration is not member of context which can be named (record,
149  /// namespace), it will return same result as getNameAsString().
150  /// Creating this name is expensive, so it should be called only when
151  /// performance doesn't matter.
152  std::string getQualifiedNameAsString() const;
153  std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
154
155  /// getNameForDiagnostic - Appends a human-readable name for this
156  /// declaration into the given string.
157  ///
158  /// This is the method invoked by Sema when displaying a NamedDecl
159  /// in a diagnostic.  It does not necessarily produce the same
160  /// result as getNameAsString(); for example, class template
161  /// specializations are printed with their template arguments.
162  ///
163  /// TODO: use an API that doesn't require so many temporary strings
164  virtual void getNameForDiagnostic(std::string &S,
165                                    const PrintingPolicy &Policy,
166                                    bool Qualified) const {
167    if (Qualified)
168      S += getQualifiedNameAsString(Policy);
169    else
170      S += getNameAsString();
171  }
172
173  /// declarationReplaces - Determine whether this declaration, if
174  /// known to be well-formed within its context, will replace the
175  /// declaration OldD if introduced into scope. A declaration will
176  /// replace another declaration if, for example, it is a
177  /// redeclaration of the same variable or function, but not if it is
178  /// a declaration of a different kind (function vs. class) or an
179  /// overloaded function.
180  bool declarationReplaces(NamedDecl *OldD) const;
181
182  /// \brief Determine whether this declaration has linkage.
183  bool hasLinkage() const;
184
185  /// \brief Determine whether this declaration is a C++ class member.
186  bool isCXXClassMember() const {
187    const DeclContext *DC = getDeclContext();
188
189    // C++0x [class.mem]p1:
190    //   The enumerators of an unscoped enumeration defined in
191    //   the class are members of the class.
192    // FIXME: support C++0x scoped enumerations.
193    if (isa<EnumDecl>(DC))
194      DC = DC->getParent();
195
196    return DC->isRecord();
197  }
198
199  /// \brief Determine what kind of linkage this entity has.
200  Linkage getLinkage() const;
201
202  /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
203  /// the underlying named decl.
204  NamedDecl *getUnderlyingDecl();
205  const NamedDecl *getUnderlyingDecl() const {
206    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
207  }
208
209  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
210  static bool classof(const NamedDecl *D) { return true; }
211  static bool classofKind(Kind K) { return K >= NamedFirst && K <= NamedLast; }
212};
213
214/// NamespaceDecl - Represent a C++ namespace.
215class NamespaceDecl : public NamedDecl, public DeclContext {
216  SourceLocation LBracLoc, RBracLoc;
217
218  // For extended namespace definitions:
219  //
220  // namespace A { int x; }
221  // namespace A { int y; }
222  //
223  // there will be one NamespaceDecl for each declaration.
224  // NextNamespace points to the next extended declaration.
225  // OrigNamespace points to the original namespace declaration.
226  // OrigNamespace of the first namespace decl points to itself.
227  NamespaceDecl *NextNamespace;
228
229  /// \brief A pointer to either the original namespace definition for
230  /// this namespace (if the boolean value is false) or the anonymous
231  /// namespace that lives just inside this namespace (if the boolean
232  /// value is true).
233  ///
234  /// We can combine these two notions because the anonymous namespace
235  /// must only be stored in one of the namespace declarations (so all
236  /// of the namespace declarations can find it). We therefore choose
237  /// the original namespace declaration, since all of the namespace
238  /// declarations have a link directly to it; the original namespace
239  /// declaration itself only needs to know that it is the original
240  /// namespace declaration (which the boolean indicates).
241  llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
242
243  NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
244    : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace),
245      NextNamespace(0), OrigOrAnonNamespace(0, true) { }
246
247public:
248  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
249                               SourceLocation L, IdentifierInfo *Id);
250
251  virtual void Destroy(ASTContext& C);
252
253  // \brief Returns true if this is an anonymous namespace declaration.
254  //
255  // For example:
256  //   namespace {
257  //     ...
258  //   };
259  // q.v. C++ [namespace.unnamed]
260  bool isAnonymousNamespace() const {
261    return !getIdentifier();
262  }
263
264  NamespaceDecl *getNextNamespace() { return NextNamespace; }
265  const NamespaceDecl *getNextNamespace() const { return NextNamespace; }
266  void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
267
268  NamespaceDecl *getOriginalNamespace() const {
269    if (OrigOrAnonNamespace.getInt())
270      return const_cast<NamespaceDecl *>(this);
271
272    return OrigOrAnonNamespace.getPointer();
273  }
274
275  void setOriginalNamespace(NamespaceDecl *ND) {
276    if (ND != this) {
277      OrigOrAnonNamespace.setPointer(ND);
278      OrigOrAnonNamespace.setInt(false);
279    }
280  }
281
282  NamespaceDecl *getAnonymousNamespace() const {
283    return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
284  }
285
286  void setAnonymousNamespace(NamespaceDecl *D) {
287    assert(!D || D->isAnonymousNamespace());
288    assert(!D || D->getParent() == this);
289    getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
290  }
291
292  virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); }
293  const NamespaceDecl *getCanonicalDecl() const {
294    return getOriginalNamespace();
295  }
296
297  virtual SourceRange getSourceRange() const {
298    return SourceRange(getLocation(), RBracLoc);
299  }
300
301  SourceLocation getLBracLoc() const { return LBracLoc; }
302  SourceLocation getRBracLoc() const { return RBracLoc; }
303  void setLBracLoc(SourceLocation LBrace) { LBracLoc = LBrace; }
304  void setRBracLoc(SourceLocation RBrace) { RBracLoc = RBrace; }
305
306  // Implement isa/cast/dyncast/etc.
307  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
308  static bool classof(const NamespaceDecl *D) { return true; }
309  static bool classofKind(Kind K) { return K == Namespace; }
310  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
311    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
312  }
313  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
314    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
315  }
316};
317
318/// ValueDecl - Represent the declaration of a variable (in which case it is
319/// an lvalue) a function (in which case it is a function designator) or
320/// an enum constant.
321class ValueDecl : public NamedDecl {
322  QualType DeclType;
323
324protected:
325  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
326            DeclarationName N, QualType T)
327    : NamedDecl(DK, DC, L, N), DeclType(T) {}
328public:
329  QualType getType() const { return DeclType; }
330  void setType(QualType newType) { DeclType = newType; }
331
332  // Implement isa/cast/dyncast/etc.
333  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
334  static bool classof(const ValueDecl *D) { return true; }
335  static bool classofKind(Kind K) { return K >= ValueFirst && K <= ValueLast; }
336};
337
338/// \brief Represents a ValueDecl that came out of a declarator.
339/// Contains type source information through TypeSourceInfo.
340class DeclaratorDecl : public ValueDecl {
341  // A struct representing both a TInfo and a syntactic qualifier,
342  // to be used for the (uncommon) case of out-of-line declarations.
343  struct ExtInfo {
344    TypeSourceInfo *TInfo;
345    NestedNameSpecifier *NNS;
346    SourceRange NNSRange;
347  };
348
349  llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
350
351  bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
352  ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
353  const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
354
355protected:
356  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
357                 DeclarationName N, QualType T, TypeSourceInfo *TInfo)
358    : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo) {}
359
360public:
361  virtual ~DeclaratorDecl();
362  virtual void Destroy(ASTContext &C);
363
364  TypeSourceInfo *getTypeSourceInfo() const {
365    return hasExtInfo()
366      ? DeclInfo.get<ExtInfo*>()->TInfo
367      : DeclInfo.get<TypeSourceInfo*>();
368  }
369  void setTypeSourceInfo(TypeSourceInfo *TI) {
370    if (hasExtInfo())
371      DeclInfo.get<ExtInfo*>()->TInfo = TI;
372    else
373      DeclInfo = TI;
374  }
375
376  NestedNameSpecifier *getQualifier() const {
377    return hasExtInfo() ? DeclInfo.get<ExtInfo*>()->NNS : 0;
378  }
379  SourceRange getQualifierRange() const {
380    return hasExtInfo() ? DeclInfo.get<ExtInfo*>()->NNSRange : SourceRange();
381  }
382  void setQualifierInfo(NestedNameSpecifier *Qualifier,
383                        SourceRange QualifierRange);
384
385  SourceLocation getTypeSpecStartLoc() const;
386
387  // Implement isa/cast/dyncast/etc.
388  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
389  static bool classof(const DeclaratorDecl *D) { return true; }
390  static bool classofKind(Kind K) {
391    return K >= DeclaratorFirst && K <= DeclaratorLast;
392  }
393};
394
395/// \brief Structure used to store a statement, the constant value to
396/// which it was evaluated (if any), and whether or not the statement
397/// is an integral constant expression (if known).
398struct EvaluatedStmt {
399  EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
400                    CheckingICE(false), IsICE(false) { }
401
402  /// \brief Whether this statement was already evaluated.
403  bool WasEvaluated : 1;
404
405  /// \brief Whether this statement is being evaluated.
406  bool IsEvaluating : 1;
407
408  /// \brief Whether we already checked whether this statement was an
409  /// integral constant expression.
410  bool CheckedICE : 1;
411
412  /// \brief Whether we are checking whether this statement is an
413  /// integral constant expression.
414  bool CheckingICE : 1;
415
416  /// \brief Whether this statement is an integral constant
417  /// expression. Only valid if CheckedICE is true.
418  bool IsICE : 1;
419
420  Stmt *Value;
421  APValue Evaluated;
422};
423
424// \brief Describes the kind of template specialization that a
425// particular template specialization declaration represents.
426enum TemplateSpecializationKind {
427  /// This template specialization was formed from a template-id but
428  /// has not yet been declared, defined, or instantiated.
429  TSK_Undeclared = 0,
430  /// This template specialization was implicitly instantiated from a
431  /// template. (C++ [temp.inst]).
432  TSK_ImplicitInstantiation,
433  /// This template specialization was declared or defined by an
434  /// explicit specialization (C++ [temp.expl.spec]) or partial
435  /// specialization (C++ [temp.class.spec]).
436  TSK_ExplicitSpecialization,
437  /// This template specialization was instantiated from a template
438  /// due to an explicit instantiation declaration request
439  /// (C++0x [temp.explicit]).
440  TSK_ExplicitInstantiationDeclaration,
441  /// This template specialization was instantiated from a template
442  /// due to an explicit instantiation definition request
443  /// (C++ [temp.explicit]).
444  TSK_ExplicitInstantiationDefinition
445};
446
447/// VarDecl - An instance of this class is created to represent a variable
448/// declaration or definition.
449class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
450public:
451  enum StorageClass {
452    None, Auto, Register, Extern, Static, PrivateExtern
453  };
454
455  /// getStorageClassSpecifierString - Return the string used to
456  /// specify the storage class \arg SC.
457  ///
458  /// It is illegal to call this function with SC == None.
459  static const char *getStorageClassSpecifierString(StorageClass SC);
460
461protected:
462  /// \brief Placeholder type used in Init to denote an unparsed C++ default
463  /// argument.
464  struct UnparsedDefaultArgument;
465
466  /// \brief Placeholder type used in Init to denote an uninstantiated C++
467  /// default argument.
468  struct UninstantiatedDefaultArgument;
469
470  typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
471                              UnparsedDefaultArgument *,
472                              UninstantiatedDefaultArgument *> InitType;
473
474  /// \brief The initializer for this variable or, for a ParmVarDecl, the
475  /// C++ default argument.
476  mutable InitType Init;
477
478private:
479  // FIXME: This can be packed into the bitfields in Decl.
480  unsigned SClass : 3;
481  bool ThreadSpecified : 1;
482  bool HasCXXDirectInit : 1;
483
484  /// DeclaredInCondition - Whether this variable was declared in a
485  /// condition, e.g., if (int x = foo()) { ... }.
486  bool DeclaredInCondition : 1;
487
488  friend class StmtIteratorBase;
489protected:
490  VarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
491          QualType T, TypeSourceInfo *TInfo, StorageClass SC)
492    : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Init(),
493      ThreadSpecified(false), HasCXXDirectInit(false),
494      DeclaredInCondition(false) {
495    SClass = SC;
496  }
497
498  typedef Redeclarable<VarDecl> redeclarable_base;
499  virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
500
501public:
502  typedef redeclarable_base::redecl_iterator redecl_iterator;
503  redecl_iterator redecls_begin() const {
504    return redeclarable_base::redecls_begin();
505  }
506  redecl_iterator redecls_end() const {
507    return redeclarable_base::redecls_end();
508  }
509
510  static VarDecl *Create(ASTContext &C, DeclContext *DC,
511                         SourceLocation L, IdentifierInfo *Id,
512                         QualType T, TypeSourceInfo *TInfo, StorageClass S);
513
514  virtual void Destroy(ASTContext& C);
515  virtual ~VarDecl();
516
517  virtual SourceRange getSourceRange() const;
518
519  StorageClass getStorageClass() const { return (StorageClass)SClass; }
520  void setStorageClass(StorageClass SC) { SClass = SC; }
521
522  void setThreadSpecified(bool T) { ThreadSpecified = T; }
523  bool isThreadSpecified() const {
524    return ThreadSpecified;
525  }
526
527  /// hasLocalStorage - Returns true if a variable with function scope
528  ///  is a non-static local variable.
529  bool hasLocalStorage() const {
530    if (getStorageClass() == None)
531      return !isFileVarDecl();
532
533    // Return true for:  Auto, Register.
534    // Return false for: Extern, Static, PrivateExtern.
535
536    return getStorageClass() <= Register;
537  }
538
539  /// hasExternStorage - Returns true if a variable has extern or
540  /// __private_extern__ storage.
541  bool hasExternalStorage() const {
542    return getStorageClass() == Extern || getStorageClass() == PrivateExtern;
543  }
544
545  /// hasGlobalStorage - Returns true for all variables that do not
546  ///  have local storage.  This includs all global variables as well
547  ///  as static variables declared within a function.
548  bool hasGlobalStorage() const { return !hasLocalStorage(); }
549
550  /// \brief Determines whether this variable is a variable with
551  /// external, C linkage.
552  bool isExternC() const;
553
554  /// isBlockVarDecl - Returns true for local variable declarations.  Note that
555  /// this includes static variables inside of functions. It also includes
556  /// variables inside blocks.
557  ///
558  ///   void foo() { int x; static int y; extern int z; }
559  ///
560  bool isBlockVarDecl() const {
561    if (getKind() != Decl::Var)
562      return false;
563    if (const DeclContext *DC = getDeclContext())
564      return DC->getLookupContext()->isFunctionOrMethod();
565    return false;
566  }
567
568  /// isFunctionOrMethodVarDecl - Similar to isBlockVarDecl, but excludes
569  /// variables declared in blocks.
570  bool isFunctionOrMethodVarDecl() const {
571    if (getKind() != Decl::Var)
572      return false;
573    if (const DeclContext *DC = getDeclContext())
574      return DC->getLookupContext()->isFunctionOrMethod() &&
575             DC->getLookupContext()->getDeclKind() != Decl::Block;
576    return false;
577  }
578
579  /// \brief Determines whether this is a static data member.
580  ///
581  /// This will only be true in C++, and applies to, e.g., the
582  /// variable 'x' in:
583  /// \code
584  /// struct S {
585  ///   static int x;
586  /// };
587  /// \endcode
588  bool isStaticDataMember() const {
589    // If it wasn't static, it would be a FieldDecl.
590    return getDeclContext()->isRecord();
591  }
592
593  virtual VarDecl *getCanonicalDecl();
594  const VarDecl *getCanonicalDecl() const {
595    return const_cast<VarDecl*>(this)->getCanonicalDecl();
596  }
597
598  enum DefinitionKind {
599    DeclarationOnly,      ///< This declaration is only a declaration.
600    TentativeDefinition,  ///< This declaration is a tentative definition.
601    Definition            ///< This declaration is definitely a definition.
602  };
603
604  /// \brief Check whether this declaration is a definition. If this could be
605  /// a tentative definition (in C), don't check whether there's an overriding
606  /// definition.
607  DefinitionKind isThisDeclarationADefinition() const;
608
609  /// \brief Get the tentative definition that acts as the real definition in
610  /// a TU. Returns null if there is a proper definition available.
611  VarDecl *getActingDefinition();
612  const VarDecl *getActingDefinition() const {
613    return const_cast<VarDecl*>(this)->getActingDefinition();
614  }
615
616  /// \brief Determine whether this is a tentative definition of a
617  /// variable in C.
618  bool isTentativeDefinitionNow() const;
619
620  /// \brief Get the real (not just tentative) definition for this declaration.
621  VarDecl *getDefinition();
622  const VarDecl *getDefinition() const {
623    return const_cast<VarDecl*>(this)->getDefinition();
624  }
625
626  /// \brief Determine whether this is or was instantiated from an out-of-line
627  /// definition of a static data member.
628  virtual bool isOutOfLine() const;
629
630  /// \brief If this is a static data member, find its out-of-line definition.
631  VarDecl *getOutOfLineDefinition();
632
633  /// isFileVarDecl - Returns true for file scoped variable declaration.
634  bool isFileVarDecl() const {
635    if (getKind() != Decl::Var)
636      return false;
637    if (const DeclContext *Ctx = getDeclContext()) {
638      Ctx = Ctx->getLookupContext();
639      if (isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx) )
640        return true;
641    }
642    if (isStaticDataMember())
643      return true;
644
645    return false;
646  }
647
648  /// getAnyInitializer - Get the initializer for this variable, no matter which
649  /// declaration it is attached to.
650  const Expr *getAnyInitializer() const {
651    const VarDecl *D;
652    return getAnyInitializer(D);
653  }
654
655  /// getAnyInitializer - Get the initializer for this variable, no matter which
656  /// declaration it is attached to. Also get that declaration.
657  const Expr *getAnyInitializer(const VarDecl *&D) const;
658
659  bool hasInit() const {
660    return !Init.isNull();
661  }
662  const Expr *getInit() const {
663    if (Init.isNull())
664      return 0;
665
666    const Stmt *S = Init.dyn_cast<Stmt *>();
667    if (!S) {
668      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
669        S = ES->Value;
670    }
671    return (const Expr*) S;
672  }
673  Expr *getInit() {
674    if (Init.isNull())
675      return 0;
676
677    Stmt *S = Init.dyn_cast<Stmt *>();
678    if (!S) {
679      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
680        S = ES->Value;
681    }
682
683    return (Expr*) S;
684  }
685
686  /// \brief Retrieve the address of the initializer expression.
687  Stmt **getInitAddress() {
688    if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
689      return &ES->Value;
690
691    // This union hack tip-toes around strict-aliasing rules.
692    union {
693      InitType *InitPtr;
694      Stmt **StmtPtr;
695    };
696
697    InitPtr = &Init;
698    return StmtPtr;
699  }
700
701  void setInit(Expr *I);
702
703  EvaluatedStmt *EnsureEvaluatedStmt() const {
704    EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
705    if (!Eval) {
706      Stmt *S = Init.get<Stmt *>();
707      Eval = new (getASTContext()) EvaluatedStmt;
708      Eval->Value = S;
709      Init = Eval;
710    }
711    return Eval;
712  }
713
714  /// \brief Check whether we are in the process of checking whether the
715  /// initializer can be evaluated.
716  bool isEvaluatingValue() const {
717    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
718      return Eval->IsEvaluating;
719
720    return false;
721  }
722
723  /// \brief Note that we now are checking whether the initializer can be
724  /// evaluated.
725  void setEvaluatingValue() const {
726    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
727    Eval->IsEvaluating = true;
728  }
729
730  /// \brief Note that constant evaluation has computed the given
731  /// value for this variable's initializer.
732  void setEvaluatedValue(const APValue &Value) const {
733    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
734    Eval->IsEvaluating = false;
735    Eval->WasEvaluated = true;
736    Eval->Evaluated = Value;
737  }
738
739  /// \brief Return the already-evaluated value of this variable's
740  /// initializer, or NULL if the value is not yet known. Returns pointer
741  /// to untyped APValue if the value could not be evaluated.
742  APValue *getEvaluatedValue() const {
743    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
744      if (Eval->WasEvaluated)
745        return &Eval->Evaluated;
746
747    return 0;
748  }
749
750  /// \brief Determines whether it is already known whether the
751  /// initializer is an integral constant expression or not.
752  bool isInitKnownICE() const {
753    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
754      return Eval->CheckedICE;
755
756    return false;
757  }
758
759  /// \brief Determines whether the initializer is an integral
760  /// constant expression.
761  ///
762  /// \pre isInitKnownICE()
763  bool isInitICE() const {
764    assert(isInitKnownICE() &&
765           "Check whether we already know that the initializer is an ICE");
766    return Init.get<EvaluatedStmt *>()->IsICE;
767  }
768
769  /// \brief Check whether we are in the process of checking the initializer
770  /// is an integral constant expression.
771  bool isCheckingICE() const {
772    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
773      return Eval->CheckingICE;
774
775    return false;
776  }
777
778  /// \brief Note that we now are checking whether the initializer is an
779  /// integral constant expression.
780  void setCheckingICE() const {
781    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
782    Eval->CheckingICE = true;
783  }
784
785  /// \brief Note that we now know whether the initializer is an
786  /// integral constant expression.
787  void setInitKnownICE(bool IsICE) const {
788    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
789    Eval->CheckingICE = false;
790    Eval->CheckedICE = true;
791    Eval->IsICE = IsICE;
792  }
793
794  void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; }
795
796  /// hasCXXDirectInitializer - If true, the initializer was a direct
797  /// initializer, e.g: "int x(1);". The Init expression will be the expression
798  /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
799  /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
800  /// by checking hasCXXDirectInitializer.
801  ///
802  bool hasCXXDirectInitializer() const {
803    return HasCXXDirectInit;
804  }
805
806  /// isDeclaredInCondition - Whether this variable was declared as
807  /// part of a condition in an if/switch/while statement, e.g.,
808  /// @code
809  /// if (int x = foo()) { ... }
810  /// @endcode
811  bool isDeclaredInCondition() const {
812    return DeclaredInCondition;
813  }
814  void setDeclaredInCondition(bool InCondition) {
815    DeclaredInCondition = InCondition;
816  }
817
818  /// \brief If this variable is an instantiated static data member of a
819  /// class template specialization, returns the templated static data member
820  /// from which it was instantiated.
821  VarDecl *getInstantiatedFromStaticDataMember() const;
822
823  /// \brief If this variable is a static data member, determine what kind of
824  /// template specialization or instantiation this is.
825  TemplateSpecializationKind getTemplateSpecializationKind() const;
826
827  /// \brief If this variable is an instantiation of a static data member of a
828  /// class template specialization, retrieves the member specialization
829  /// information.
830  MemberSpecializationInfo *getMemberSpecializationInfo() const;
831
832  /// \brief For a static data member that was instantiated from a static
833  /// data member of a class template, set the template specialiation kind.
834  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
835                        SourceLocation PointOfInstantiation = SourceLocation());
836
837  // Implement isa/cast/dyncast/etc.
838  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
839  static bool classof(const VarDecl *D) { return true; }
840  static bool classofKind(Kind K) { return K >= VarFirst && K <= VarLast; }
841};
842
843class ImplicitParamDecl : public VarDecl {
844protected:
845  ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L,
846                    IdentifierInfo *Id, QualType Tw)
847    : VarDecl(DK, DC, L, Id, Tw, /*TInfo=*/0, VarDecl::None) {}
848public:
849  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
850                                   SourceLocation L, IdentifierInfo *Id,
851                                   QualType T);
852  // Implement isa/cast/dyncast/etc.
853  static bool classof(const ImplicitParamDecl *D) { return true; }
854  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
855  static bool classofKind(Kind K) { return K == ImplicitParam; }
856};
857
858/// ParmVarDecl - Represent a parameter to a function.
859class ParmVarDecl : public VarDecl {
860  // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
861  /// FIXME: Also can be paced into the bitfields in Decl.
862  /// in, inout, etc.
863  unsigned objcDeclQualifier : 6;
864  bool HasInheritedDefaultArg : 1;
865
866protected:
867  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L,
868              IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
869              StorageClass S, Expr *DefArg)
870  : VarDecl(DK, DC, L, Id, T, TInfo, S),
871    objcDeclQualifier(OBJC_TQ_None), HasInheritedDefaultArg(false) {
872    setDefaultArg(DefArg);
873  }
874
875public:
876  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
877                             SourceLocation L,IdentifierInfo *Id,
878                             QualType T, TypeSourceInfo *TInfo,
879                             StorageClass S, Expr *DefArg);
880
881  ObjCDeclQualifier getObjCDeclQualifier() const {
882    return ObjCDeclQualifier(objcDeclQualifier);
883  }
884  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
885    objcDeclQualifier = QTVal;
886  }
887
888  Expr *getDefaultArg();
889  const Expr *getDefaultArg() const {
890    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
891  }
892
893  void setDefaultArg(Expr *defarg) {
894    Init = reinterpret_cast<Stmt *>(defarg);
895  }
896
897  unsigned getNumDefaultArgTemporaries() const;
898  CXXTemporary *getDefaultArgTemporary(unsigned i);
899  const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
900    return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
901  }
902
903  /// \brief Retrieve the source range that covers the entire default
904  /// argument.
905  SourceRange getDefaultArgRange() const;
906  void setUninstantiatedDefaultArg(Expr *arg) {
907    Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
908  }
909  Expr *getUninstantiatedDefaultArg() {
910    return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
911  }
912  const Expr *getUninstantiatedDefaultArg() const {
913    return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
914  }
915
916  /// hasDefaultArg - Determines whether this parameter has a default argument,
917  /// either parsed or not.
918  bool hasDefaultArg() const {
919    return getInit() || hasUnparsedDefaultArg() ||
920      hasUninstantiatedDefaultArg();
921  }
922
923  /// hasUnparsedDefaultArg - Determines whether this parameter has a
924  /// default argument that has not yet been parsed. This will occur
925  /// during the processing of a C++ class whose member functions have
926  /// default arguments, e.g.,
927  /// @code
928  ///   class X {
929  ///   public:
930  ///     void f(int x = 17); // x has an unparsed default argument now
931  ///   }; // x has a regular default argument now
932  /// @endcode
933  bool hasUnparsedDefaultArg() const {
934    return Init.is<UnparsedDefaultArgument*>();
935  }
936
937  bool hasUninstantiatedDefaultArg() const {
938    return Init.is<UninstantiatedDefaultArgument*>();
939  }
940
941  /// setUnparsedDefaultArg - Specify that this parameter has an
942  /// unparsed default argument. The argument will be replaced with a
943  /// real default argument via setDefaultArg when the class
944  /// definition enclosing the function declaration that owns this
945  /// default argument is completed.
946  void setUnparsedDefaultArg() {
947    Init = (UnparsedDefaultArgument *)0;
948  }
949
950  bool hasInheritedDefaultArg() const {
951    return HasInheritedDefaultArg;
952  }
953
954  void setHasInheritedDefaultArg(bool I = true) {
955    HasInheritedDefaultArg = I;
956  }
957
958  QualType getOriginalType() const {
959    if (getTypeSourceInfo())
960      return getTypeSourceInfo()->getType();
961    return getType();
962  }
963
964  /// setOwningFunction - Sets the function declaration that owns this
965  /// ParmVarDecl. Since ParmVarDecls are often created before the
966  /// FunctionDecls that own them, this routine is required to update
967  /// the DeclContext appropriately.
968  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
969
970  // Implement isa/cast/dyncast/etc.
971  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
972  static bool classof(const ParmVarDecl *D) { return true; }
973  static bool classofKind(Kind K) { return K == ParmVar; }
974};
975
976/// FunctionDecl - An instance of this class is created to represent a
977/// function declaration or definition.
978///
979/// Since a given function can be declared several times in a program,
980/// there may be several FunctionDecls that correspond to that
981/// function. Only one of those FunctionDecls will be found when
982/// traversing the list of declarations in the context of the
983/// FunctionDecl (e.g., the translation unit); this FunctionDecl
984/// contains all of the information known about the function. Other,
985/// previous declarations of the function are available via the
986/// getPreviousDeclaration() chain.
987class FunctionDecl : public DeclaratorDecl, public DeclContext,
988                     public Redeclarable<FunctionDecl> {
989public:
990  enum StorageClass {
991    None, Extern, Static, PrivateExtern
992  };
993
994private:
995  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
996  /// parameters of this function.  This is null if a prototype or if there are
997  /// no formals.
998  ParmVarDecl **ParamInfo;
999
1000  LazyDeclStmtPtr Body;
1001
1002  // FIXME: This can be packed into the bitfields in Decl.
1003  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1004  unsigned SClass : 2;
1005  bool IsInline : 1;
1006  bool IsVirtualAsWritten : 1;
1007  bool IsPure : 1;
1008  bool HasInheritedPrototype : 1;
1009  bool HasWrittenPrototype : 1;
1010  bool IsDeleted : 1;
1011  bool IsTrivial : 1; // sunk from CXXMethodDecl
1012  bool IsCopyAssignment : 1;  // sunk from CXXMethodDecl
1013  bool HasImplicitReturnZero : 1;
1014
1015  /// \brief End part of this FunctionDecl's source range.
1016  ///
1017  /// We could compute the full range in getSourceRange(). However, when we're
1018  /// dealing with a function definition deserialized from a PCH/AST file,
1019  /// we can only compute the full range once the function body has been
1020  /// de-serialized, so it's far better to have the (sometimes-redundant)
1021  /// EndRangeLoc.
1022  SourceLocation EndRangeLoc;
1023
1024  /// \brief The template or declaration that this declaration
1025  /// describes or was instantiated from, respectively.
1026  ///
1027  /// For non-templates, this value will be NULL. For function
1028  /// declarations that describe a function template, this will be a
1029  /// pointer to a FunctionTemplateDecl. For member functions
1030  /// of class template specializations, this will be a MemberSpecializationInfo
1031  /// pointer containing information about the specialization.
1032  /// For function template specializations, this will be a
1033  /// FunctionTemplateSpecializationInfo, which contains information about
1034  /// the template being specialized and the template arguments involved in
1035  /// that specialization.
1036  llvm::PointerUnion3<FunctionTemplateDecl *,
1037                      MemberSpecializationInfo *,
1038                      FunctionTemplateSpecializationInfo *>
1039    TemplateOrSpecialization;
1040
1041protected:
1042  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L,
1043               DeclarationName N, QualType T, TypeSourceInfo *TInfo,
1044               StorageClass S, bool isInline)
1045    : DeclaratorDecl(DK, DC, L, N, T, TInfo),
1046      DeclContext(DK),
1047      ParamInfo(0), Body(),
1048      SClass(S), IsInline(isInline),
1049      IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1050      HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1051      IsCopyAssignment(false),
1052      HasImplicitReturnZero(false),
1053      EndRangeLoc(L), TemplateOrSpecialization() {}
1054
1055  virtual ~FunctionDecl() {}
1056  virtual void Destroy(ASTContext& C);
1057
1058  typedef Redeclarable<FunctionDecl> redeclarable_base;
1059  virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1060
1061public:
1062  typedef redeclarable_base::redecl_iterator redecl_iterator;
1063  redecl_iterator redecls_begin() const {
1064    return redeclarable_base::redecls_begin();
1065  }
1066  redecl_iterator redecls_end() const {
1067    return redeclarable_base::redecls_end();
1068  }
1069
1070  static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1071                              DeclarationName N, QualType T,
1072                              TypeSourceInfo *TInfo,
1073                              StorageClass S = None, bool isInline = false,
1074                              bool hasWrittenPrototype = true);
1075
1076  virtual void getNameForDiagnostic(std::string &S,
1077                                    const PrintingPolicy &Policy,
1078                                    bool Qualified) const;
1079
1080  virtual SourceRange getSourceRange() const {
1081    return SourceRange(getLocation(), EndRangeLoc);
1082  }
1083  void setLocEnd(SourceLocation E) {
1084    EndRangeLoc = E;
1085  }
1086
1087  /// getBody - Retrieve the body (definition) of the function. The
1088  /// function body might be in any of the (re-)declarations of this
1089  /// function. The variant that accepts a FunctionDecl pointer will
1090  /// set that function declaration to the actual declaration
1091  /// containing the body (if there is one).
1092  Stmt *getBody(const FunctionDecl *&Definition) const;
1093
1094  virtual Stmt *getBody() const {
1095    const FunctionDecl* Definition;
1096    return getBody(Definition);
1097  }
1098
1099  /// isThisDeclarationADefinition - Returns whether this specific
1100  /// declaration of the function is also a definition. This does not
1101  /// determine whether the function has been defined (e.g., in a
1102  /// previous definition); for that information, use getBody.
1103  /// FIXME: Should return true if function is deleted or defaulted. However,
1104  /// CodeGenModule.cpp uses it, and I don't know if this would break it.
1105  bool isThisDeclarationADefinition() const { return Body; }
1106
1107  void setBody(Stmt *B);
1108  void setLazyBody(uint64_t Offset) { Body = Offset; }
1109
1110  /// Whether this function is marked as virtual explicitly.
1111  bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1112  void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1113
1114  /// Whether this virtual function is pure, i.e. makes the containing class
1115  /// abstract.
1116  bool isPure() const { return IsPure; }
1117  void setPure(bool P = true) { IsPure = P; }
1118
1119  /// Whether this function is "trivial" in some specialized C++ senses.
1120  /// Can only be true for default constructors, copy constructors,
1121  /// copy assignment operators, and destructors.  Not meaningful until
1122  /// the class has been fully built by Sema.
1123  bool isTrivial() const { return IsTrivial; }
1124  void setTrivial(bool IT) { IsTrivial = IT; }
1125
1126  bool isCopyAssignment() const { return IsCopyAssignment; }
1127  void setCopyAssignment(bool CA) { IsCopyAssignment = CA; }
1128
1129  /// Whether falling off this function implicitly returns null/zero.
1130  /// If a more specific implicit return value is required, front-ends
1131  /// should synthesize the appropriate return statements.
1132  bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1133  void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1134
1135  /// \brief Whether this function has a prototype, either because one
1136  /// was explicitly written or because it was "inherited" by merging
1137  /// a declaration without a prototype with a declaration that has a
1138  /// prototype.
1139  bool hasPrototype() const {
1140    return HasWrittenPrototype || HasInheritedPrototype;
1141  }
1142
1143  bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1144  void setHasWrittenPrototype(bool P) { HasWrittenPrototype = P; }
1145
1146  /// \brief Whether this function inherited its prototype from a
1147  /// previous declaration.
1148  bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1149  void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1150
1151  /// \brief Whether this function has been deleted.
1152  ///
1153  /// A function that is "deleted" (via the C++0x "= delete" syntax)
1154  /// acts like a normal function, except that it cannot actually be
1155  /// called or have its address taken. Deleted functions are
1156  /// typically used in C++ overload resolution to attract arguments
1157  /// whose type or lvalue/rvalue-ness would permit the use of a
1158  /// different overload that would behave incorrectly. For example,
1159  /// one might use deleted functions to ban implicit conversion from
1160  /// a floating-point number to an Integer type:
1161  ///
1162  /// @code
1163  /// struct Integer {
1164  ///   Integer(long); // construct from a long
1165  ///   Integer(double) = delete; // no construction from float or double
1166  ///   Integer(long double) = delete; // no construction from long double
1167  /// };
1168  /// @endcode
1169  bool isDeleted() const { return IsDeleted; }
1170  void setDeleted(bool D = true) { IsDeleted = D; }
1171
1172  /// \brief Determines whether this is a function "main", which is
1173  /// the entry point into an executable program.
1174  bool isMain() const;
1175
1176  /// \brief Determines whether this function is a function with
1177  /// external, C linkage.
1178  bool isExternC() const;
1179
1180  /// \brief Determines whether this is a global function.
1181  bool isGlobal() const;
1182
1183  void setPreviousDeclaration(FunctionDecl * PrevDecl);
1184
1185  virtual const FunctionDecl *getCanonicalDecl() const;
1186  virtual FunctionDecl *getCanonicalDecl();
1187
1188  unsigned getBuiltinID() const;
1189
1190  // Iterator access to formal parameters.
1191  unsigned param_size() const { return getNumParams(); }
1192  typedef ParmVarDecl **param_iterator;
1193  typedef ParmVarDecl * const *param_const_iterator;
1194
1195  param_iterator param_begin() { return ParamInfo; }
1196  param_iterator param_end()   { return ParamInfo+param_size(); }
1197
1198  param_const_iterator param_begin() const { return ParamInfo; }
1199  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1200
1201  /// getNumParams - Return the number of parameters this function must have
1202  /// based on its FunctionType.  This is the length of the ParamInfo array
1203  /// after it has been created.
1204  unsigned getNumParams() const;
1205
1206  const ParmVarDecl *getParamDecl(unsigned i) const {
1207    assert(i < getNumParams() && "Illegal param #");
1208    return ParamInfo[i];
1209  }
1210  ParmVarDecl *getParamDecl(unsigned i) {
1211    assert(i < getNumParams() && "Illegal param #");
1212    return ParamInfo[i];
1213  }
1214  void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
1215
1216  /// getMinRequiredArguments - Returns the minimum number of arguments
1217  /// needed to call this function. This may be fewer than the number of
1218  /// function parameters, if some of the parameters have default
1219  /// arguments (in C++).
1220  unsigned getMinRequiredArguments() const;
1221
1222  QualType getResultType() const {
1223    return getType()->getAs<FunctionType>()->getResultType();
1224  }
1225  StorageClass getStorageClass() const { return StorageClass(SClass); }
1226  void setStorageClass(StorageClass SC) { SClass = SC; }
1227
1228  /// \brief Determine whether the "inline" keyword was specified for this
1229  /// function.
1230  bool isInlineSpecified() const { return IsInline; }
1231
1232  /// Set whether the "inline" keyword was specified for this function.
1233  void setInlineSpecified(bool I) { IsInline = I; }
1234
1235  /// \brief Determine whether this function should be inlined, because it is
1236  /// either marked "inline" or is a member function of a C++ class that
1237  /// was defined in the class body.
1238  bool isInlined() const;
1239
1240  bool isInlineDefinitionExternallyVisible() const;
1241
1242  /// isOverloadedOperator - Whether this function declaration
1243  /// represents an C++ overloaded operator, e.g., "operator+".
1244  bool isOverloadedOperator() const {
1245    return getOverloadedOperator() != OO_None;
1246  }
1247
1248  OverloadedOperatorKind getOverloadedOperator() const;
1249
1250  const IdentifierInfo *getLiteralIdentifier() const;
1251
1252  /// \brief If this function is an instantiation of a member function
1253  /// of a class template specialization, retrieves the function from
1254  /// which it was instantiated.
1255  ///
1256  /// This routine will return non-NULL for (non-templated) member
1257  /// functions of class templates and for instantiations of function
1258  /// templates. For example, given:
1259  ///
1260  /// \code
1261  /// template<typename T>
1262  /// struct X {
1263  ///   void f(T);
1264  /// };
1265  /// \endcode
1266  ///
1267  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1268  /// whose parent is the class template specialization X<int>. For
1269  /// this declaration, getInstantiatedFromFunction() will return
1270  /// the FunctionDecl X<T>::A. When a complete definition of
1271  /// X<int>::A is required, it will be instantiated from the
1272  /// declaration returned by getInstantiatedFromMemberFunction().
1273  FunctionDecl *getInstantiatedFromMemberFunction() const;
1274
1275  /// \brief If this function is an instantiation of a member function of a
1276  /// class template specialization, retrieves the member specialization
1277  /// information.
1278  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1279
1280  /// \brief Specify that this record is an instantiation of the
1281  /// member function FD.
1282  void setInstantiationOfMemberFunction(FunctionDecl *FD,
1283                                        TemplateSpecializationKind TSK);
1284
1285  /// \brief Retrieves the function template that is described by this
1286  /// function declaration.
1287  ///
1288  /// Every function template is represented as a FunctionTemplateDecl
1289  /// and a FunctionDecl (or something derived from FunctionDecl). The
1290  /// former contains template properties (such as the template
1291  /// parameter lists) while the latter contains the actual
1292  /// description of the template's
1293  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1294  /// FunctionDecl that describes the function template,
1295  /// getDescribedFunctionTemplate() retrieves the
1296  /// FunctionTemplateDecl from a FunctionDecl.
1297  FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1298    return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1299  }
1300
1301  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1302    TemplateOrSpecialization = Template;
1303  }
1304
1305  /// \brief Determine whether this function is a function template
1306  /// specialization.
1307  bool isFunctionTemplateSpecialization() const {
1308    return getPrimaryTemplate() != 0;
1309  }
1310
1311  /// \brief If this function is actually a function template specialization,
1312  /// retrieve information about this function template specialization.
1313  /// Otherwise, returns NULL.
1314  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1315    return TemplateOrSpecialization.
1316             dyn_cast<FunctionTemplateSpecializationInfo*>();
1317  }
1318
1319  /// \brief Determines whether this function is a function template
1320  /// specialization or a member of a class template specialization that can
1321  /// be implicitly instantiated.
1322  bool isImplicitlyInstantiable() const;
1323
1324  /// \brief Retrieve the function declaration from which this function could
1325  /// be instantiated, if it is an instantiation (rather than a non-template
1326  /// or a specialization, for example).
1327  FunctionDecl *getTemplateInstantiationPattern() const;
1328
1329  /// \brief Retrieve the primary template that this function template
1330  /// specialization either specializes or was instantiated from.
1331  ///
1332  /// If this function declaration is not a function template specialization,
1333  /// returns NULL.
1334  FunctionTemplateDecl *getPrimaryTemplate() const;
1335
1336  /// \brief Retrieve the template arguments used to produce this function
1337  /// template specialization from the primary template.
1338  ///
1339  /// If this function declaration is not a function template specialization,
1340  /// returns NULL.
1341  const TemplateArgumentList *getTemplateSpecializationArgs() const;
1342
1343  /// \brief Specify that this function declaration is actually a function
1344  /// template specialization.
1345  ///
1346  /// \param Context the AST context in which this function resides.
1347  ///
1348  /// \param Template the function template that this function template
1349  /// specialization specializes.
1350  ///
1351  /// \param TemplateArgs the template arguments that produced this
1352  /// function template specialization from the template.
1353  ///
1354  /// \param InsertPos If non-NULL, the position in the function template
1355  /// specialization set where the function template specialization data will
1356  /// be inserted.
1357  ///
1358  /// \param TSK the kind of template specialization this is.
1359  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1360                                      const TemplateArgumentList *TemplateArgs,
1361                                         void *InsertPos,
1362                    TemplateSpecializationKind TSK = TSK_ImplicitInstantiation);
1363
1364  /// \brief Determine what kind of template instantiation this function
1365  /// represents.
1366  TemplateSpecializationKind getTemplateSpecializationKind() const;
1367
1368  /// \brief Determine what kind of template instantiation this function
1369  /// represents.
1370  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1371                        SourceLocation PointOfInstantiation = SourceLocation());
1372
1373  /// \brief Retrieve the (first) point of instantiation of a function template
1374  /// specialization or a member of a class template specialization.
1375  ///
1376  /// \returns the first point of instantiation, if this function was
1377  /// instantiated from a template; otherwie, returns an invalid source
1378  /// location.
1379  SourceLocation getPointOfInstantiation() const;
1380
1381  /// \brief Determine whether this is or was instantiated from an out-of-line
1382  /// definition of a member function.
1383  virtual bool isOutOfLine() const;
1384
1385  // Implement isa/cast/dyncast/etc.
1386  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1387  static bool classof(const FunctionDecl *D) { return true; }
1388  static bool classofKind(Kind K) {
1389    return K >= FunctionFirst && K <= FunctionLast;
1390  }
1391  static DeclContext *castToDeclContext(const FunctionDecl *D) {
1392    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1393  }
1394  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1395    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1396  }
1397};
1398
1399
1400/// FieldDecl - An instance of this class is created by Sema::ActOnField to
1401/// represent a member of a struct/union/class.
1402class FieldDecl : public DeclaratorDecl {
1403  // FIXME: This can be packed into the bitfields in Decl.
1404  bool Mutable : 1;
1405  Expr *BitWidth;
1406protected:
1407  FieldDecl(Kind DK, DeclContext *DC, SourceLocation L,
1408            IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1409            Expr *BW, bool Mutable)
1410    : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Mutable(Mutable), BitWidth(BW) {
1411  }
1412
1413public:
1414  static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1415                           IdentifierInfo *Id, QualType T,
1416                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable);
1417
1418  /// isMutable - Determines whether this field is mutable (C++ only).
1419  bool isMutable() const { return Mutable; }
1420
1421  /// \brief Set whether this field is mutable (C++ only).
1422  void setMutable(bool M) { Mutable = M; }
1423
1424  /// isBitfield - Determines whether this field is a bitfield.
1425  bool isBitField() const { return BitWidth != NULL; }
1426
1427  /// @brief Determines whether this is an unnamed bitfield.
1428  bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); }
1429
1430  /// isAnonymousStructOrUnion - Determines whether this field is a
1431  /// representative for an anonymous struct or union. Such fields are
1432  /// unnamed and are implicitly generated by the implementation to
1433  /// store the data for the anonymous union or struct.
1434  bool isAnonymousStructOrUnion() const;
1435
1436  Expr *getBitWidth() const { return BitWidth; }
1437  void setBitWidth(Expr *BW) { BitWidth = BW; }
1438
1439  /// getParent - Returns the parent of this field declaration, which
1440  /// is the struct in which this method is defined.
1441  const RecordDecl *getParent() const {
1442    return cast<RecordDecl>(getDeclContext());
1443  }
1444
1445  RecordDecl *getParent() {
1446    return cast<RecordDecl>(getDeclContext());
1447  }
1448
1449  // Implement isa/cast/dyncast/etc.
1450  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1451  static bool classof(const FieldDecl *D) { return true; }
1452  static bool classofKind(Kind K) { return K >= FieldFirst && K <= FieldLast; }
1453};
1454
1455/// EnumConstantDecl - An instance of this object exists for each enum constant
1456/// that is defined.  For example, in "enum X {a,b}", each of a/b are
1457/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
1458/// TagType for the X EnumDecl.
1459class EnumConstantDecl : public ValueDecl {
1460  Stmt *Init; // an integer constant expression
1461  llvm::APSInt Val; // The value.
1462protected:
1463  EnumConstantDecl(DeclContext *DC, SourceLocation L,
1464                   IdentifierInfo *Id, QualType T, Expr *E,
1465                   const llvm::APSInt &V)
1466    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
1467
1468  virtual ~EnumConstantDecl() {}
1469public:
1470
1471  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
1472                                  SourceLocation L, IdentifierInfo *Id,
1473                                  QualType T, Expr *E,
1474                                  const llvm::APSInt &V);
1475
1476  virtual void Destroy(ASTContext& C);
1477
1478  const Expr *getInitExpr() const { return (const Expr*) Init; }
1479  Expr *getInitExpr() { return (Expr*) Init; }
1480  const llvm::APSInt &getInitVal() const { return Val; }
1481
1482  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
1483  void setInitVal(const llvm::APSInt &V) { Val = V; }
1484
1485  // Implement isa/cast/dyncast/etc.
1486  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1487  static bool classof(const EnumConstantDecl *D) { return true; }
1488  static bool classofKind(Kind K) { return K == EnumConstant; }
1489
1490  friend class StmtIteratorBase;
1491};
1492
1493
1494/// TypeDecl - Represents a declaration of a type.
1495///
1496class TypeDecl : public NamedDecl {
1497  /// TypeForDecl - This indicates the Type object that represents
1498  /// this TypeDecl.  It is a cache maintained by
1499  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
1500  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
1501  mutable Type *TypeForDecl;
1502  friend class ASTContext;
1503  friend class DeclContext;
1504  friend class TagDecl;
1505  friend class TemplateTypeParmDecl;
1506  friend class TagType;
1507
1508protected:
1509  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L,
1510           IdentifierInfo *Id)
1511    : NamedDecl(DK, DC, L, Id), TypeForDecl(0) {}
1512
1513public:
1514  // Low-level accessor
1515  Type *getTypeForDecl() const { return TypeForDecl; }
1516  void setTypeForDecl(Type *TD) { TypeForDecl = TD; }
1517
1518  // Implement isa/cast/dyncast/etc.
1519  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1520  static bool classof(const TypeDecl *D) { return true; }
1521  static bool classofKind(Kind K) { return K >= TypeFirst && K <= TypeLast; }
1522};
1523
1524
1525class TypedefDecl : public TypeDecl, public Redeclarable<TypedefDecl> {
1526  /// UnderlyingType - This is the type the typedef is set to.
1527  TypeSourceInfo *TInfo;
1528
1529  TypedefDecl(DeclContext *DC, SourceLocation L,
1530              IdentifierInfo *Id, TypeSourceInfo *TInfo)
1531    : TypeDecl(Typedef, DC, L, Id), TInfo(TInfo) {}
1532
1533  virtual ~TypedefDecl();
1534public:
1535
1536  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
1537                             SourceLocation L, IdentifierInfo *Id,
1538                             TypeSourceInfo *TInfo);
1539
1540  TypeSourceInfo *getTypeSourceInfo() const {
1541    return TInfo;
1542  }
1543
1544  /// Retrieves the canonical declaration of this typedef.
1545  TypedefDecl *getCanonicalDecl() {
1546    return getFirstDeclaration();
1547  }
1548  const TypedefDecl *getCanonicalDecl() const {
1549    return getFirstDeclaration();
1550  }
1551
1552  QualType getUnderlyingType() const {
1553    return TInfo->getType();
1554  }
1555  void setTypeSourceInfo(TypeSourceInfo *newType) {
1556    TInfo = newType;
1557  }
1558
1559  // Implement isa/cast/dyncast/etc.
1560  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1561  static bool classof(const TypedefDecl *D) { return true; }
1562  static bool classofKind(Kind K) { return K == Typedef; }
1563};
1564
1565class TypedefDecl;
1566
1567/// TagDecl - Represents the declaration of a struct/union/class/enum.
1568class TagDecl
1569  : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
1570public:
1571  // This is really ugly.
1572  typedef ElaboratedType::TagKind TagKind;
1573  static const TagKind TK_struct = ElaboratedType::TK_struct;
1574  static const TagKind TK_union = ElaboratedType::TK_union;
1575  static const TagKind TK_class = ElaboratedType::TK_class;
1576  static const TagKind TK_enum = ElaboratedType::TK_enum;
1577
1578private:
1579  // FIXME: This can be packed into the bitfields in Decl.
1580  /// TagDeclKind - The TagKind enum.
1581  unsigned TagDeclKind : 2;
1582
1583  /// IsDefinition - True if this is a definition ("struct foo {};"), false if
1584  /// it is a declaration ("struct foo;").
1585  bool IsDefinition : 1;
1586
1587  /// IsEmbeddedInDeclarator - True if this tag declaration is
1588  /// "embedded" (i.e., defined or declared for the very first time)
1589  /// in the syntax of a declarator.
1590  bool IsEmbeddedInDeclarator : 1;
1591
1592  SourceLocation TagKeywordLoc;
1593  SourceLocation RBraceLoc;
1594
1595  // A struct representing syntactic qualifier info,
1596  // to be used for the (uncommon) case of out-of-line declarations.
1597  struct ExtInfo {
1598    NestedNameSpecifier *NNS;
1599    SourceRange NNSRange;
1600  };
1601
1602  /// TypedefDeclOrQualifier - If the (out-of-line) tag declaration name
1603  /// is qualified, it points to the qualifier info (nns and range);
1604  /// otherwise, if the tag declaration is anonymous and it is part of
1605  /// a typedef, it points to the TypedefDecl (used for mangling);
1606  /// otherwise, it is a null (TypedefDecl) pointer.
1607  llvm::PointerUnion<TypedefDecl*, ExtInfo*> TypedefDeclOrQualifier;
1608
1609  bool hasExtInfo() const { return TypedefDeclOrQualifier.is<ExtInfo*>(); }
1610  ExtInfo *getExtInfo() { return TypedefDeclOrQualifier.get<ExtInfo*>(); }
1611  const ExtInfo *getExtInfo() const {
1612    return TypedefDeclOrQualifier.get<ExtInfo*>();
1613  }
1614
1615protected:
1616  TagDecl(Kind DK, TagKind TK, DeclContext *DC,
1617          SourceLocation L, IdentifierInfo *Id,
1618          TagDecl *PrevDecl, SourceLocation TKL = SourceLocation())
1619    : TypeDecl(DK, DC, L, Id), DeclContext(DK), TagKeywordLoc(TKL),
1620      TypedefDeclOrQualifier((TypedefDecl*) 0) {
1621    assert((DK != Enum || TK == TK_enum) &&"EnumDecl not matched with TK_enum");
1622    TagDeclKind = TK;
1623    IsDefinition = false;
1624    IsEmbeddedInDeclarator = false;
1625    setPreviousDeclaration(PrevDecl);
1626  }
1627
1628  typedef Redeclarable<TagDecl> redeclarable_base;
1629  virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1630
1631public:
1632  void Destroy(ASTContext &C);
1633
1634  typedef redeclarable_base::redecl_iterator redecl_iterator;
1635  redecl_iterator redecls_begin() const {
1636    return redeclarable_base::redecls_begin();
1637  }
1638  redecl_iterator redecls_end() const {
1639    return redeclarable_base::redecls_end();
1640  }
1641
1642  SourceLocation getRBraceLoc() const { return RBraceLoc; }
1643  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
1644
1645  SourceLocation getTagKeywordLoc() const { return TagKeywordLoc; }
1646  void setTagKeywordLoc(SourceLocation TKL) { TagKeywordLoc = TKL; }
1647
1648  virtual SourceRange getSourceRange() const;
1649
1650  virtual TagDecl* getCanonicalDecl();
1651  const TagDecl* getCanonicalDecl() const {
1652    return const_cast<TagDecl*>(this)->getCanonicalDecl();
1653  }
1654
1655  /// isDefinition - Return true if this decl has its body specified.
1656  bool isDefinition() const {
1657    return IsDefinition;
1658  }
1659
1660  bool isEmbeddedInDeclarator() const {
1661    return IsEmbeddedInDeclarator;
1662  }
1663  void setEmbeddedInDeclarator(bool isInDeclarator) {
1664    IsEmbeddedInDeclarator = isInDeclarator;
1665  }
1666
1667  /// \brief Whether this declaration declares a type that is
1668  /// dependent, i.e., a type that somehow depends on template
1669  /// parameters.
1670  bool isDependentType() const { return isDependentContext(); }
1671
1672  /// @brief Starts the definition of this tag declaration.
1673  ///
1674  /// This method should be invoked at the beginning of the definition
1675  /// of this tag declaration. It will set the tag type into a state
1676  /// where it is in the process of being defined.
1677  void startDefinition();
1678
1679  /// @brief Completes the definition of this tag declaration.
1680  void completeDefinition();
1681
1682  /// getDefinition - Returns the TagDecl that actually defines this
1683  ///  struct/union/class/enum.  When determining whether or not a
1684  ///  struct/union/class/enum is completely defined, one should use this method
1685  ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
1686  ///  specific TagDecl is defining declaration, not whether or not the
1687  ///  struct/union/class/enum type is defined.  This method returns NULL if
1688  ///  there is no TagDecl that defines the struct/union/class/enum.
1689  TagDecl* getDefinition() const;
1690
1691  void setDefinition(bool V) { IsDefinition = V; }
1692
1693  const char *getKindName() const {
1694    return ElaboratedType::getNameForTagKind(getTagKind());
1695  }
1696
1697  /// getTagKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
1698  /// into a tag kind.  It is an error to provide a type specifier
1699  /// which *isn't* a tag kind here.
1700  static TagKind getTagKindForTypeSpec(unsigned TypeSpec);
1701
1702  TagKind getTagKind() const {
1703    return TagKind(TagDeclKind);
1704  }
1705
1706  void setTagKind(TagKind TK) { TagDeclKind = TK; }
1707
1708  bool isStruct() const { return getTagKind() == TK_struct; }
1709  bool isClass()  const { return getTagKind() == TK_class; }
1710  bool isUnion()  const { return getTagKind() == TK_union; }
1711  bool isEnum()   const { return getTagKind() == TK_enum; }
1712
1713  TypedefDecl *getTypedefForAnonDecl() const {
1714    return hasExtInfo() ? 0 : TypedefDeclOrQualifier.get<TypedefDecl*>();
1715  }
1716  void setTypedefForAnonDecl(TypedefDecl *TDD) { TypedefDeclOrQualifier = TDD; }
1717
1718  NestedNameSpecifier *getQualifier() const {
1719    return hasExtInfo() ? TypedefDeclOrQualifier.get<ExtInfo*>()->NNS : 0;
1720  }
1721  SourceRange getQualifierRange() const {
1722    return hasExtInfo()
1723      ? TypedefDeclOrQualifier.get<ExtInfo*>()->NNSRange
1724      : SourceRange();
1725  }
1726  void setQualifierInfo(NestedNameSpecifier *Qualifier,
1727                        SourceRange QualifierRange);
1728
1729  // Implement isa/cast/dyncast/etc.
1730  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1731  static bool classof(const TagDecl *D) { return true; }
1732  static bool classofKind(Kind K) { return K >= TagFirst && K <= TagLast; }
1733
1734  static DeclContext *castToDeclContext(const TagDecl *D) {
1735    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
1736  }
1737  static TagDecl *castFromDeclContext(const DeclContext *DC) {
1738    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
1739  }
1740};
1741
1742/// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
1743/// enums.
1744class EnumDecl : public TagDecl {
1745  /// IntegerType - This represent the integer type that the enum corresponds
1746  /// to for code generation purposes.  Note that the enumerator constants may
1747  /// have a different type than this does.
1748  QualType IntegerType;
1749
1750  /// PromotionType - The integer type that values of this type should
1751  /// promote to.  In C, enumerators are generally of an integer type
1752  /// directly, but gcc-style large enumerators (and all enumerators
1753  /// in C++) are of the enum type instead.
1754  QualType PromotionType;
1755
1756  /// \brief If the enumeration was instantiated from an enumeration
1757  /// within a class or function template, this pointer refers to the
1758  /// enumeration declared within the template.
1759  EnumDecl *InstantiatedFrom;
1760
1761  EnumDecl(DeclContext *DC, SourceLocation L,
1762           IdentifierInfo *Id, EnumDecl *PrevDecl, SourceLocation TKL)
1763    : TagDecl(Enum, TK_enum, DC, L, Id, PrevDecl, TKL), InstantiatedFrom(0) {
1764      IntegerType = QualType();
1765    }
1766public:
1767  EnumDecl *getCanonicalDecl() {
1768    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
1769  }
1770  const EnumDecl *getCanonicalDecl() const {
1771    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
1772  }
1773
1774  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
1775                          SourceLocation L, IdentifierInfo *Id,
1776                          SourceLocation TKL, EnumDecl *PrevDecl);
1777
1778  virtual void Destroy(ASTContext& C);
1779
1780  /// completeDefinition - When created, the EnumDecl corresponds to a
1781  /// forward-declared enum. This method is used to mark the
1782  /// declaration as being defined; it's enumerators have already been
1783  /// added (via DeclContext::addDecl). NewType is the new underlying
1784  /// type of the enumeration type.
1785  void completeDefinition(QualType NewType,
1786                          QualType PromotionType);
1787
1788  // enumerator_iterator - Iterates through the enumerators of this
1789  // enumeration.
1790  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
1791
1792  enumerator_iterator enumerator_begin() const {
1793    return enumerator_iterator(this->decls_begin());
1794  }
1795
1796  enumerator_iterator enumerator_end() const {
1797    return enumerator_iterator(this->decls_end());
1798  }
1799
1800  /// getPromotionType - Return the integer type that enumerators
1801  /// should promote to.
1802  QualType getPromotionType() const { return PromotionType; }
1803
1804  /// \brief Set the promotion type.
1805  void setPromotionType(QualType T) { PromotionType = T; }
1806
1807  /// getIntegerType - Return the integer type this enum decl corresponds to.
1808  /// This returns a null qualtype for an enum forward definition.
1809  QualType getIntegerType() const { return IntegerType; }
1810
1811  /// \brief Set the underlying integer type.
1812  void setIntegerType(QualType T) { IntegerType = T; }
1813
1814  /// \brief Returns the enumeration (declared within the template)
1815  /// from which this enumeration type was instantiated, or NULL if
1816  /// this enumeration was not instantiated from any template.
1817  EnumDecl *getInstantiatedFromMemberEnum() const {
1818    return InstantiatedFrom;
1819  }
1820
1821  void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
1822
1823  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1824  static bool classof(const EnumDecl *D) { return true; }
1825  static bool classofKind(Kind K) { return K == Enum; }
1826};
1827
1828
1829/// RecordDecl - Represents a struct/union/class.  For example:
1830///   struct X;                  // Forward declaration, no "body".
1831///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
1832/// This decl will be marked invalid if *any* members are invalid.
1833///
1834class RecordDecl : public TagDecl {
1835  // FIXME: This can be packed into the bitfields in Decl.
1836  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
1837  /// array member (e.g. int X[]) or if this union contains a struct that does.
1838  /// If so, this cannot be contained in arrays or other structs as a member.
1839  bool HasFlexibleArrayMember : 1;
1840
1841  /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
1842  /// or union.
1843  bool AnonymousStructOrUnion : 1;
1844
1845  /// HasObjectMember - This is true if this struct has at least one member
1846  /// containing an object.
1847  bool HasObjectMember : 1;
1848
1849protected:
1850  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
1851             SourceLocation L, IdentifierInfo *Id,
1852             RecordDecl *PrevDecl, SourceLocation TKL);
1853  virtual ~RecordDecl();
1854
1855public:
1856  static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
1857                            SourceLocation L, IdentifierInfo *Id,
1858                            SourceLocation TKL = SourceLocation(),
1859                            RecordDecl* PrevDecl = 0);
1860
1861  virtual void Destroy(ASTContext& C);
1862
1863  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
1864  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
1865
1866  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
1867  /// or union. To be an anonymous struct or union, it must have been
1868  /// declared without a name and there must be no objects of this
1869  /// type declared, e.g.,
1870  /// @code
1871  ///   union { int i; float f; };
1872  /// @endcode
1873  /// is an anonymous union but neither of the following are:
1874  /// @code
1875  ///  union X { int i; float f; };
1876  ///  union { int i; float f; } obj;
1877  /// @endcode
1878  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
1879  void setAnonymousStructOrUnion(bool Anon) {
1880    AnonymousStructOrUnion = Anon;
1881  }
1882
1883  bool hasObjectMember() const { return HasObjectMember; }
1884  void setHasObjectMember (bool val) { HasObjectMember = val; }
1885
1886  /// \brief Determines whether this declaration represents the
1887  /// injected class name.
1888  ///
1889  /// The injected class name in C++ is the name of the class that
1890  /// appears inside the class itself. For example:
1891  ///
1892  /// \code
1893  /// struct C {
1894  ///   // C is implicitly declared here as a synonym for the class name.
1895  /// };
1896  ///
1897  /// C::C c; // same as "C c;"
1898  /// \endcode
1899  bool isInjectedClassName() const;
1900
1901  /// getDefinition - Returns the RecordDecl that actually defines this
1902  ///  struct/union/class.  When determining whether or not a struct/union/class
1903  ///  is completely defined, one should use this method as opposed to
1904  ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
1905  ///  RecordDecl is defining declaration, not whether or not the record
1906  ///  type is defined.  This method returns NULL if there is no RecordDecl
1907  ///  that defines the struct/union/tag.
1908  RecordDecl* getDefinition() const {
1909    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
1910  }
1911
1912  // Iterator access to field members. The field iterator only visits
1913  // the non-static data members of this class, ignoring any static
1914  // data members, functions, constructors, destructors, etc.
1915  typedef specific_decl_iterator<FieldDecl> field_iterator;
1916
1917  field_iterator field_begin() const {
1918    return field_iterator(decls_begin());
1919  }
1920  field_iterator field_end() const {
1921    return field_iterator(decls_end());
1922  }
1923
1924  // field_empty - Whether there are any fields (non-static data
1925  // members) in this record.
1926  bool field_empty() const {
1927    return field_begin() == field_end();
1928  }
1929
1930  /// completeDefinition - Notes that the definition of this type is
1931  /// now complete.
1932  void completeDefinition();
1933
1934  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1935  static bool classof(const RecordDecl *D) { return true; }
1936  static bool classofKind(Kind K) {
1937    return K >= RecordFirst && K <= RecordLast;
1938  }
1939};
1940
1941class FileScopeAsmDecl : public Decl {
1942  StringLiteral *AsmString;
1943  FileScopeAsmDecl(DeclContext *DC, SourceLocation L, StringLiteral *asmstring)
1944    : Decl(FileScopeAsm, DC, L), AsmString(asmstring) {}
1945public:
1946  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
1947                                  SourceLocation L, StringLiteral *Str);
1948
1949  const StringLiteral *getAsmString() const { return AsmString; }
1950  StringLiteral *getAsmString() { return AsmString; }
1951  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
1952
1953  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1954  static bool classof(const FileScopeAsmDecl *D) { return true; }
1955  static bool classofKind(Kind K) { return K == FileScopeAsm; }
1956};
1957
1958/// BlockDecl - This represents a block literal declaration, which is like an
1959/// unnamed FunctionDecl.  For example:
1960/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1961///
1962class BlockDecl : public Decl, public DeclContext {
1963  // FIXME: This can be packed into the bitfields in Decl.
1964  bool isVariadic : 1;
1965  /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
1966  /// parameters of this function.  This is null if a prototype or if there are
1967  /// no formals.
1968  ParmVarDecl **ParamInfo;
1969  unsigned NumParams;
1970
1971  Stmt *Body;
1972
1973protected:
1974  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
1975    : Decl(Block, DC, CaretLoc), DeclContext(Block),
1976      isVariadic(false), ParamInfo(0), NumParams(0), Body(0) {}
1977
1978  virtual ~BlockDecl();
1979  virtual void Destroy(ASTContext& C);
1980
1981public:
1982  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
1983
1984  SourceLocation getCaretLocation() const { return getLocation(); }
1985
1986  bool IsVariadic() const { return isVariadic; }
1987  void setIsVariadic(bool value) { isVariadic = value; }
1988
1989  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
1990  Stmt *getBody() const { return (Stmt*) Body; }
1991  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
1992
1993  // Iterator access to formal parameters.
1994  unsigned param_size() const { return getNumParams(); }
1995  typedef ParmVarDecl **param_iterator;
1996  typedef ParmVarDecl * const *param_const_iterator;
1997
1998  bool param_empty() const { return NumParams == 0; }
1999  param_iterator param_begin()  { return ParamInfo; }
2000  param_iterator param_end()   { return ParamInfo+param_size(); }
2001
2002  param_const_iterator param_begin() const { return ParamInfo; }
2003  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
2004
2005  unsigned getNumParams() const;
2006  const ParmVarDecl *getParamDecl(unsigned i) const {
2007    assert(i < getNumParams() && "Illegal param #");
2008    return ParamInfo[i];
2009  }
2010  ParmVarDecl *getParamDecl(unsigned i) {
2011    assert(i < getNumParams() && "Illegal param #");
2012    return ParamInfo[i];
2013  }
2014  void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
2015
2016  // Implement isa/cast/dyncast/etc.
2017  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2018  static bool classof(const BlockDecl *D) { return true; }
2019  static bool classofKind(Kind K) { return K == Block; }
2020  static DeclContext *castToDeclContext(const BlockDecl *D) {
2021    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
2022  }
2023  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
2024    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
2025  }
2026};
2027
2028/// Insertion operator for diagnostics.  This allows sending NamedDecl's
2029/// into a diagnostic with <<.
2030inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2031                                           NamedDecl* ND) {
2032  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl);
2033  return DB;
2034}
2035
2036}  // end namespace clang
2037
2038#endif
2039