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