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