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