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