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