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