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