Decl.h revision 8f187f62cb0487d31bc4afdfcd47e11fe9a51d05
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/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/Redeclarable.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Linkage.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/Optional.h"
26#include "llvm/Support/Compiler.h"
27
28namespace clang {
29struct ASTTemplateArgumentListInfo;
30class CXXTemporary;
31class CompoundStmt;
32class DependentFunctionTemplateSpecializationInfo;
33class Expr;
34class FunctionTemplateDecl;
35class FunctionTemplateSpecializationInfo;
36class LabelStmt;
37class MemberSpecializationInfo;
38class Module;
39class NestedNameSpecifier;
40class Stmt;
41class StringLiteral;
42class TemplateArgumentList;
43class TemplateParameterList;
44class TypeLoc;
45class UnresolvedSetImpl;
46
47/// \brief A container of type source information.
48///
49/// A client can read the relevant info using TypeLoc wrappers, e.g:
50/// @code
51/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
52/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
53///   PL->getStarLoc().print(OS, SrcMgr);
54/// @endcode
55///
56class TypeSourceInfo {
57  QualType Ty;
58  // Contains a memory block after the class, used for type source information,
59  // allocated by ASTContext.
60  friend class ASTContext;
61  TypeSourceInfo(QualType ty) : Ty(ty) { }
62public:
63  /// \brief Return the type wrapped by this type source info.
64  QualType getType() const { return Ty; }
65
66  /// \brief Return the TypeLoc wrapper for the type source info.
67  TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
68};
69
70/// TranslationUnitDecl - The top declaration context.
71class TranslationUnitDecl : public Decl, public DeclContext {
72  virtual void anchor();
73  ASTContext &Ctx;
74
75  /// The (most recently entered) anonymous namespace for this
76  /// translation unit, if one has been created.
77  NamespaceDecl *AnonymousNamespace;
78
79  explicit TranslationUnitDecl(ASTContext &ctx)
80    : Decl(TranslationUnit, 0, SourceLocation()),
81      DeclContext(TranslationUnit),
82      Ctx(ctx), AnonymousNamespace(0) {}
83public:
84  ASTContext &getASTContext() const { return Ctx; }
85
86  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
87  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
88
89  static TranslationUnitDecl *Create(ASTContext &C);
90  // Implement isa/cast/dyncast/etc.
91  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
92  static bool classofKind(Kind K) { return K == TranslationUnit; }
93  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
94    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
95  }
96  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
97    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
98  }
99};
100
101/// NamedDecl - This represents a decl with a name.  Many decls have names such
102/// as ObjCMethodDecl, but not \@class, etc.
103class NamedDecl : public Decl {
104  virtual void anchor();
105  /// Name - The name of this declaration, which is typically a normal
106  /// identifier but may also be a special kind of name (C++
107  /// constructor, Objective-C selector, etc.)
108  DeclarationName Name;
109
110private:
111  NamedDecl *getUnderlyingDeclImpl();
112  void verifyLinkage() const;
113
114protected:
115  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
116    : Decl(DK, DC, L), Name(N) { }
117
118public:
119  /// getIdentifier - Get the identifier that names this declaration,
120  /// if there is one. This will return NULL if this declaration has
121  /// no name (e.g., for an unnamed class) or if the name is a special
122  /// name (C++ constructor, Objective-C selector, etc.).
123  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
124
125  /// getName - Get the name of identifier for this declaration as a StringRef.
126  /// This requires that the declaration have a name and that it be a simple
127  /// identifier.
128  StringRef getName() const {
129    assert(Name.isIdentifier() && "Name is not a simple identifier");
130    return getIdentifier() ? getIdentifier()->getName() : "";
131  }
132
133  /// getNameAsString - Get a human-readable name for the declaration, even if
134  /// it is one of the special kinds of names (C++ constructor, Objective-C
135  /// selector, etc).  Creating this name requires expensive string
136  /// manipulation, so it should be called only when performance doesn't matter.
137  /// For simple declarations, getNameAsCString() should suffice.
138  //
139  // FIXME: This function should be renamed to indicate that it is not just an
140  // alternate form of getName(), and clients should move as appropriate.
141  //
142  // FIXME: Deprecated, move clients to getName().
143  std::string getNameAsString() const { return Name.getAsString(); }
144
145  void printName(raw_ostream &os) const { return Name.printName(os); }
146
147  /// getDeclName - Get the actual, stored name of the declaration,
148  /// which may be a special name.
149  DeclarationName getDeclName() const { return Name; }
150
151  /// \brief Set the name of this declaration.
152  void setDeclName(DeclarationName N) { Name = N; }
153
154  /// printQualifiedName - Returns human-readable qualified name for
155  /// declaration, like A::B::i, for i being member of namespace A::B.
156  /// If declaration is not member of context which can be named (record,
157  /// namespace), it will return same result as printName().
158  /// Creating this name is expensive, so it should be called only when
159  /// performance doesn't matter.
160  void printQualifiedName(raw_ostream &OS) const;
161  void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
162
163  // FIXME: Remove string versions.
164  std::string getQualifiedNameAsString() const;
165  std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
166
167  /// getNameForDiagnostic - Appends a human-readable name for this
168  /// declaration into the given stream.
169  ///
170  /// This is the method invoked by Sema when displaying a NamedDecl
171  /// in a diagnostic.  It does not necessarily produce the same
172  /// result as printName(); for example, class template
173  /// specializations are printed with their template arguments.
174  virtual void getNameForDiagnostic(raw_ostream &OS,
175                                    const PrintingPolicy &Policy,
176                                    bool Qualified) const;
177
178  /// declarationReplaces - Determine whether this declaration, if
179  /// known to be well-formed within its context, will replace the
180  /// declaration OldD if introduced into scope. A declaration will
181  /// replace another declaration if, for example, it is a
182  /// redeclaration of the same variable or function, but not if it is
183  /// a declaration of a different kind (function vs. class) or an
184  /// overloaded function.
185  bool declarationReplaces(NamedDecl *OldD) const;
186
187  /// \brief Determine whether this declaration has linkage.
188  bool hasLinkage() const;
189
190  using Decl::isModulePrivate;
191  using Decl::setModulePrivate;
192
193  /// \brief Determine whether this declaration is hidden from name lookup.
194  bool isHidden() const { return Hidden; }
195
196  /// \brief Determine whether this declaration is a C++ class member.
197  bool isCXXClassMember() const {
198    const DeclContext *DC = getDeclContext();
199
200    // C++0x [class.mem]p1:
201    //   The enumerators of an unscoped enumeration defined in
202    //   the class are members of the class.
203    // FIXME: support C++0x scoped enumerations.
204    if (isa<EnumDecl>(DC))
205      DC = DC->getParent();
206
207    return DC->isRecord();
208  }
209
210  /// \brief Determine whether the given declaration is an instance member of
211  /// a C++ class.
212  bool isCXXInstanceMember() const;
213
214  /// \brief Determine what kind of linkage this entity has.
215  Linkage getLinkage() const;
216
217  /// \brief True if this decl has external linkage.
218  bool hasExternalLinkage() const {
219    return getLinkage() == ExternalLinkage;
220  }
221
222  /// \brief Determines the visibility of this entity.
223  Visibility getVisibility() const {
224    return getLinkageAndVisibility().getVisibility();
225  }
226
227  /// \brief Determines the linkage and visibility of this entity.
228  LinkageInfo getLinkageAndVisibility() const;
229
230  /// Kinds of explicit visibility.
231  enum ExplicitVisibilityKind {
232    VisibilityForType,
233    VisibilityForValue
234  };
235
236  /// \brief If visibility was explicitly specified for this
237  /// declaration, return that visibility.
238  Optional<Visibility>
239  getExplicitVisibility(ExplicitVisibilityKind kind) const;
240
241  /// \brief True if the computed linkage is valid. Used for consistency
242  /// checking. Should always return true.
243  bool isLinkageValid() const;
244
245  /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
246  /// the underlying named decl.
247  NamedDecl *getUnderlyingDecl() {
248    // Fast-path the common case.
249    if (this->getKind() != UsingShadow &&
250        this->getKind() != ObjCCompatibleAlias)
251      return this;
252
253    return getUnderlyingDeclImpl();
254  }
255  const NamedDecl *getUnderlyingDecl() const {
256    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
257  }
258
259  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
260  static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
261};
262
263inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
264  ND.printName(OS);
265  return OS;
266}
267
268/// LabelDecl - Represents the declaration of a label.  Labels also have a
269/// corresponding LabelStmt, which indicates the position that the label was
270/// defined at.  For normal labels, the location of the decl is the same as the
271/// location of the statement.  For GNU local labels (__label__), the decl
272/// location is where the __label__ is.
273class LabelDecl : public NamedDecl {
274  virtual void anchor();
275  LabelStmt *TheStmt;
276  /// LocStart - For normal labels, this is the same as the main declaration
277  /// label, i.e., the location of the identifier; for GNU local labels,
278  /// this is the location of the __label__ keyword.
279  SourceLocation LocStart;
280
281  LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
282            LabelStmt *S, SourceLocation StartL)
283    : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
284
285public:
286  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
287                           SourceLocation IdentL, IdentifierInfo *II);
288  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
289                           SourceLocation IdentL, IdentifierInfo *II,
290                           SourceLocation GnuLabelL);
291  static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
292
293  LabelStmt *getStmt() const { return TheStmt; }
294  void setStmt(LabelStmt *T) { TheStmt = T; }
295
296  bool isGnuLocal() const { return LocStart != getLocation(); }
297  void setLocStart(SourceLocation L) { LocStart = L; }
298
299  SourceRange getSourceRange() const LLVM_READONLY {
300    return SourceRange(LocStart, getLocation());
301  }
302
303  // Implement isa/cast/dyncast/etc.
304  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
305  static bool classofKind(Kind K) { return K == Label; }
306};
307
308/// NamespaceDecl - Represent a C++ namespace.
309class NamespaceDecl : public NamedDecl, public DeclContext,
310                      public Redeclarable<NamespaceDecl>
311{
312  virtual void anchor();
313
314  /// LocStart - The starting location of the source range, pointing
315  /// to either the namespace or the inline keyword.
316  SourceLocation LocStart;
317  /// RBraceLoc - The ending location of the source range.
318  SourceLocation RBraceLoc;
319
320  /// \brief A pointer to either the anonymous namespace that lives just inside
321  /// this namespace or to the first namespace in the chain (the latter case
322  /// only when this is not the first in the chain), along with a
323  /// boolean value indicating whether this is an inline namespace.
324  llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
325
326  NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
327                SourceLocation IdLoc, IdentifierInfo *Id,
328                NamespaceDecl *PrevDecl);
329
330  typedef Redeclarable<NamespaceDecl> redeclarable_base;
331  virtual NamespaceDecl *getNextRedeclaration() {
332    return RedeclLink.getNext();
333  }
334  virtual NamespaceDecl *getPreviousDeclImpl() {
335    return getPreviousDecl();
336  }
337  virtual NamespaceDecl *getMostRecentDeclImpl() {
338    return getMostRecentDecl();
339  }
340
341public:
342  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
343                               bool Inline, SourceLocation StartLoc,
344                               SourceLocation IdLoc, IdentifierInfo *Id,
345                               NamespaceDecl *PrevDecl);
346
347  static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
348
349  typedef redeclarable_base::redecl_iterator redecl_iterator;
350  using redeclarable_base::redecls_begin;
351  using redeclarable_base::redecls_end;
352  using redeclarable_base::getPreviousDecl;
353  using redeclarable_base::getMostRecentDecl;
354
355  /// \brief Returns true if this is an anonymous namespace declaration.
356  ///
357  /// For example:
358  /// \code
359  ///   namespace {
360  ///     ...
361  ///   };
362  /// \endcode
363  /// q.v. C++ [namespace.unnamed]
364  bool isAnonymousNamespace() const {
365    return !getIdentifier();
366  }
367
368  /// \brief Returns true if this is an inline namespace declaration.
369  bool isInline() const {
370    return AnonOrFirstNamespaceAndInline.getInt();
371  }
372
373  /// \brief Set whether this is an inline namespace declaration.
374  void setInline(bool Inline) {
375    AnonOrFirstNamespaceAndInline.setInt(Inline);
376  }
377
378  /// \brief Get the original (first) namespace declaration.
379  NamespaceDecl *getOriginalNamespace() {
380    if (isFirstDeclaration())
381      return this;
382
383    return AnonOrFirstNamespaceAndInline.getPointer();
384  }
385
386  /// \brief Get the original (first) namespace declaration.
387  const NamespaceDecl *getOriginalNamespace() const {
388    if (isFirstDeclaration())
389      return this;
390
391    return AnonOrFirstNamespaceAndInline.getPointer();
392  }
393
394  /// \brief Return true if this declaration is an original (first) declaration
395  /// of the namespace. This is false for non-original (subsequent) namespace
396  /// declarations and anonymous namespaces.
397  bool isOriginalNamespace() const {
398    return isFirstDeclaration();
399  }
400
401  /// \brief Retrieve the anonymous namespace nested inside this namespace,
402  /// if any.
403  NamespaceDecl *getAnonymousNamespace() const {
404    return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
405  }
406
407  void setAnonymousNamespace(NamespaceDecl *D) {
408    getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
409  }
410
411  /// Retrieves the canonical declaration of this namespace.
412  NamespaceDecl *getCanonicalDecl() {
413    return getOriginalNamespace();
414  }
415  const NamespaceDecl *getCanonicalDecl() const {
416    return getOriginalNamespace();
417  }
418
419  virtual SourceRange getSourceRange() const LLVM_READONLY {
420    return SourceRange(LocStart, RBraceLoc);
421  }
422
423  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
424  SourceLocation getRBraceLoc() const { return RBraceLoc; }
425  void setLocStart(SourceLocation L) { LocStart = L; }
426  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
427
428  // Implement isa/cast/dyncast/etc.
429  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
430  static bool classofKind(Kind K) { return K == Namespace; }
431  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
432    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
433  }
434  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
435    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
436  }
437
438  friend class ASTDeclReader;
439  friend class ASTDeclWriter;
440};
441
442/// ValueDecl - Represent the declaration of a variable (in which case it is
443/// an lvalue) a function (in which case it is a function designator) or
444/// an enum constant.
445class ValueDecl : public NamedDecl {
446  virtual void anchor();
447  QualType DeclType;
448
449protected:
450  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
451            DeclarationName N, QualType T)
452    : NamedDecl(DK, DC, L, N), DeclType(T) {}
453public:
454  QualType getType() const { return DeclType; }
455  void setType(QualType newType) { DeclType = newType; }
456
457  /// \brief Determine whether this symbol is weakly-imported,
458  ///        or declared with the weak or weak-ref attr.
459  bool isWeak() const;
460
461  // Implement isa/cast/dyncast/etc.
462  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
463  static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
464};
465
466/// QualifierInfo - A struct with extended info about a syntactic
467/// name qualifier, to be used for the case of out-of-line declarations.
468struct QualifierInfo {
469  NestedNameSpecifierLoc QualifierLoc;
470
471  /// NumTemplParamLists - The number of "outer" template parameter lists.
472  /// The count includes all of the template parameter lists that were matched
473  /// against the template-ids occurring into the NNS and possibly (in the
474  /// case of an explicit specialization) a final "template <>".
475  unsigned NumTemplParamLists;
476
477  /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
478  /// containing pointers to the "outer" template parameter lists.
479  /// It includes all of the template parameter lists that were matched
480  /// against the template-ids occurring into the NNS and possibly (in the
481  /// case of an explicit specialization) a final "template <>".
482  TemplateParameterList** TemplParamLists;
483
484  /// Default constructor.
485  QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
486
487  /// setTemplateParameterListsInfo - Sets info about "outer" template
488  /// parameter lists.
489  void setTemplateParameterListsInfo(ASTContext &Context,
490                                     unsigned NumTPLists,
491                                     TemplateParameterList **TPLists);
492
493private:
494  // Copy constructor and copy assignment are disabled.
495  QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION;
496  QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION;
497};
498
499/// \brief Represents a ValueDecl that came out of a declarator.
500/// Contains type source information through TypeSourceInfo.
501class DeclaratorDecl : public ValueDecl {
502  // A struct representing both a TInfo and a syntactic qualifier,
503  // to be used for the (uncommon) case of out-of-line declarations.
504  struct ExtInfo : public QualifierInfo {
505    TypeSourceInfo *TInfo;
506  };
507
508  llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
509
510  /// InnerLocStart - The start of the source range for this declaration,
511  /// ignoring outer template declarations.
512  SourceLocation InnerLocStart;
513
514  bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
515  ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
516  const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
517
518protected:
519  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
520                 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
521                 SourceLocation StartL)
522    : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
523  }
524
525public:
526  TypeSourceInfo *getTypeSourceInfo() const {
527    return hasExtInfo()
528      ? getExtInfo()->TInfo
529      : DeclInfo.get<TypeSourceInfo*>();
530  }
531  void setTypeSourceInfo(TypeSourceInfo *TI) {
532    if (hasExtInfo())
533      getExtInfo()->TInfo = TI;
534    else
535      DeclInfo = TI;
536  }
537
538  /// getInnerLocStart - Return SourceLocation representing start of source
539  /// range ignoring outer template declarations.
540  SourceLocation getInnerLocStart() const { return InnerLocStart; }
541  void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
542
543  /// getOuterLocStart - Return SourceLocation representing start of source
544  /// range taking into account any outer template declarations.
545  SourceLocation getOuterLocStart() const;
546
547  virtual SourceRange getSourceRange() const LLVM_READONLY;
548  SourceLocation getLocStart() const LLVM_READONLY {
549    return getOuterLocStart();
550  }
551
552  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
553  /// declaration, if it was present in the source.
554  NestedNameSpecifier *getQualifier() const {
555    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
556                        : 0;
557  }
558
559  /// \brief Retrieve the nested-name-specifier (with source-location
560  /// information) that qualifies the name of this declaration, if it was
561  /// present in the source.
562  NestedNameSpecifierLoc getQualifierLoc() const {
563    return hasExtInfo() ? getExtInfo()->QualifierLoc
564                        : NestedNameSpecifierLoc();
565  }
566
567  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
568
569  unsigned getNumTemplateParameterLists() const {
570    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
571  }
572  TemplateParameterList *getTemplateParameterList(unsigned index) const {
573    assert(index < getNumTemplateParameterLists());
574    return getExtInfo()->TemplParamLists[index];
575  }
576  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
577                                     TemplateParameterList **TPLists);
578
579  SourceLocation getTypeSpecStartLoc() const;
580
581  // Implement isa/cast/dyncast/etc.
582  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
583  static bool classofKind(Kind K) {
584    return K >= firstDeclarator && K <= lastDeclarator;
585  }
586
587  friend class ASTDeclReader;
588  friend class ASTDeclWriter;
589};
590
591/// \brief Structure used to store a statement, the constant value to
592/// which it was evaluated (if any), and whether or not the statement
593/// is an integral constant expression (if known).
594struct EvaluatedStmt {
595  EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
596                    CheckingICE(false), IsICE(false) { }
597
598  /// \brief Whether this statement was already evaluated.
599  bool WasEvaluated : 1;
600
601  /// \brief Whether this statement is being evaluated.
602  bool IsEvaluating : 1;
603
604  /// \brief Whether we already checked whether this statement was an
605  /// integral constant expression.
606  bool CheckedICE : 1;
607
608  /// \brief Whether we are checking whether this statement is an
609  /// integral constant expression.
610  bool CheckingICE : 1;
611
612  /// \brief Whether this statement is an integral constant expression,
613  /// or in C++11, whether the statement is a constant expression. Only
614  /// valid if CheckedICE is true.
615  bool IsICE : 1;
616
617  Stmt *Value;
618  APValue Evaluated;
619};
620
621/// VarDecl - An instance of this class is created to represent a variable
622/// declaration or definition.
623class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
624public:
625  typedef clang::StorageClass StorageClass;
626
627  /// getStorageClassSpecifierString - Return the string used to
628  /// specify the storage class \p SC.
629  ///
630  /// It is illegal to call this function with SC == None.
631  static const char *getStorageClassSpecifierString(StorageClass SC);
632
633  /// \brief Initialization styles.
634  enum InitializationStyle {
635    CInit,    ///< C-style initialization with assignment
636    CallInit, ///< Call-style initialization (C++98)
637    ListInit  ///< Direct list-initialization (C++11)
638  };
639
640protected:
641  /// \brief Placeholder type used in Init to denote an unparsed C++ default
642  /// argument.
643  struct UnparsedDefaultArgument;
644
645  /// \brief Placeholder type used in Init to denote an uninstantiated C++
646  /// default argument.
647  struct UninstantiatedDefaultArgument;
648
649  typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
650                              UnparsedDefaultArgument *,
651                              UninstantiatedDefaultArgument *> InitType;
652
653  /// \brief The initializer for this variable or, for a ParmVarDecl, the
654  /// C++ default argument.
655  mutable InitType Init;
656
657private:
658  class VarDeclBitfields {
659    friend class VarDecl;
660    friend class ASTDeclReader;
661
662    unsigned SClass : 3;
663    unsigned ThreadSpecified : 1;
664    unsigned InitStyle : 2;
665
666    /// \brief Whether this variable is the exception variable in a C++ catch
667    /// or an Objective-C @catch statement.
668    unsigned ExceptionVar : 1;
669
670    /// \brief Whether this local variable could be allocated in the return
671    /// slot of its function, enabling the named return value optimization
672    /// (NRVO).
673    unsigned NRVOVariable : 1;
674
675    /// \brief Whether this variable is the for-range-declaration in a C++0x
676    /// for-range statement.
677    unsigned CXXForRangeDecl : 1;
678
679    /// \brief Whether this variable is an ARC pseudo-__strong
680    /// variable;  see isARCPseudoStrong() for details.
681    unsigned ARCPseudoStrong : 1;
682
683    /// \brief Whether this variable is (C++0x) constexpr.
684    unsigned IsConstexpr : 1;
685  };
686  enum { NumVarDeclBits = 14 };
687
688  friend class ASTDeclReader;
689  friend class StmtIteratorBase;
690
691protected:
692  enum { NumParameterIndexBits = 8 };
693
694  class ParmVarDeclBitfields {
695    friend class ParmVarDecl;
696    friend class ASTDeclReader;
697
698    unsigned : NumVarDeclBits;
699
700    /// Whether this parameter inherits a default argument from a
701    /// prior declaration.
702    unsigned HasInheritedDefaultArg : 1;
703
704    /// Whether this parameter undergoes K&R argument promotion.
705    unsigned IsKNRPromoted : 1;
706
707    /// Whether this parameter is an ObjC method parameter or not.
708    unsigned IsObjCMethodParam : 1;
709
710    /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
711    /// Otherwise, the number of function parameter scopes enclosing
712    /// the function parameter scope in which this parameter was
713    /// declared.
714    unsigned ScopeDepthOrObjCQuals : 7;
715
716    /// The number of parameters preceding this parameter in the
717    /// function parameter scope in which it was declared.
718    unsigned ParameterIndex : NumParameterIndexBits;
719  };
720
721  union {
722    unsigned AllBits;
723    VarDeclBitfields VarDeclBits;
724    ParmVarDeclBitfields ParmVarDeclBits;
725  };
726
727  VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
728          SourceLocation IdLoc, IdentifierInfo *Id,
729          QualType T, TypeSourceInfo *TInfo, StorageClass SC)
730    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
731    assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
732    assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
733    AllBits = 0;
734    VarDeclBits.SClass = SC;
735    // Everything else is implicitly initialized to false.
736  }
737
738  typedef Redeclarable<VarDecl> redeclarable_base;
739  virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
740  virtual VarDecl *getPreviousDeclImpl() {
741    return getPreviousDecl();
742  }
743  virtual VarDecl *getMostRecentDeclImpl() {
744    return getMostRecentDecl();
745  }
746
747public:
748  typedef redeclarable_base::redecl_iterator redecl_iterator;
749  using redeclarable_base::redecls_begin;
750  using redeclarable_base::redecls_end;
751  using redeclarable_base::getPreviousDecl;
752  using redeclarable_base::getMostRecentDecl;
753
754  static VarDecl *Create(ASTContext &C, DeclContext *DC,
755                         SourceLocation StartLoc, SourceLocation IdLoc,
756                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
757                         StorageClass S);
758
759  static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
760
761  virtual SourceRange getSourceRange() const LLVM_READONLY;
762
763  /// \brief Returns the storage class as written in the source. For the
764  /// computed linkage of symbol, see getLinkage.
765  StorageClass getStorageClass() const {
766    return (StorageClass) VarDeclBits.SClass;
767  }
768  void setStorageClass(StorageClass SC);
769
770  void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
771  bool isThreadSpecified() const {
772    return VarDeclBits.ThreadSpecified;
773  }
774
775  /// hasLocalStorage - Returns true if a variable with function scope
776  ///  is a non-static local variable.
777  bool hasLocalStorage() const {
778    if (getStorageClass() == SC_None)
779      return !isFileVarDecl();
780
781    // Return true for:  Auto, Register.
782    // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
783
784    return getStorageClass() >= SC_Auto;
785  }
786
787  /// isStaticLocal - Returns true if a variable with function scope is a
788  /// static local variable.
789  bool isStaticLocal() const {
790    return getStorageClass() == SC_Static && !isFileVarDecl();
791  }
792
793  /// \brief Returns true if a variable has extern or __private_extern__
794  /// storage.
795  bool hasExternalStorage() const {
796    return getStorageClass() == SC_Extern ||
797           getStorageClass() == SC_PrivateExtern;
798  }
799
800  /// hasGlobalStorage - Returns true for all variables that do not
801  ///  have local storage.  This includs all global variables as well
802  ///  as static variables declared within a function.
803  bool hasGlobalStorage() const { return !hasLocalStorage(); }
804
805  /// Compute the language linkage.
806  LanguageLinkage getLanguageLinkage() const;
807
808  /// \brief Determines whether this variable is a variable with
809  /// external, C linkage.
810  bool isExternC() const;
811
812  /// isLocalVarDecl - Returns true for local variable declarations
813  /// other than parameters.  Note that this includes static variables
814  /// inside of functions. It also includes variables inside blocks.
815  ///
816  ///   void foo() { int x; static int y; extern int z; }
817  ///
818  bool isLocalVarDecl() const {
819    if (getKind() != Decl::Var)
820      return false;
821    if (const DeclContext *DC = getDeclContext())
822      return DC->getRedeclContext()->isFunctionOrMethod();
823    return false;
824  }
825
826  /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
827  /// excludes variables declared in blocks.
828  bool isFunctionOrMethodVarDecl() const {
829    if (getKind() != Decl::Var)
830      return false;
831    const DeclContext *DC = getDeclContext()->getRedeclContext();
832    return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
833  }
834
835  /// \brief Determines whether this is a static data member.
836  ///
837  /// This will only be true in C++, and applies to, e.g., the
838  /// variable 'x' in:
839  /// \code
840  /// struct S {
841  ///   static int x;
842  /// };
843  /// \endcode
844  bool isStaticDataMember() const {
845    // If it wasn't static, it would be a FieldDecl.
846    return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
847  }
848
849  virtual VarDecl *getCanonicalDecl();
850  const VarDecl *getCanonicalDecl() const {
851    return const_cast<VarDecl*>(this)->getCanonicalDecl();
852  }
853
854  enum DefinitionKind {
855    DeclarationOnly,      ///< This declaration is only a declaration.
856    TentativeDefinition,  ///< This declaration is a tentative definition.
857    Definition            ///< This declaration is definitely a definition.
858  };
859
860  /// \brief Check whether this declaration is a definition. If this could be
861  /// a tentative definition (in C), don't check whether there's an overriding
862  /// definition.
863  DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
864  DefinitionKind isThisDeclarationADefinition() const {
865    return isThisDeclarationADefinition(getASTContext());
866  }
867
868  /// \brief Check whether this variable is defined in this
869  /// translation unit.
870  DefinitionKind hasDefinition(ASTContext &) const;
871  DefinitionKind hasDefinition() const {
872    return hasDefinition(getASTContext());
873  }
874
875  /// \brief Get the tentative definition that acts as the real definition in
876  /// a TU. Returns null if there is a proper definition available.
877  VarDecl *getActingDefinition();
878  const VarDecl *getActingDefinition() const {
879    return const_cast<VarDecl*>(this)->getActingDefinition();
880  }
881
882  /// \brief Determine whether this is a tentative definition of a
883  /// variable in C.
884  bool isTentativeDefinitionNow() const;
885
886  /// \brief Get the real (not just tentative) definition for this declaration.
887  VarDecl *getDefinition(ASTContext &);
888  const VarDecl *getDefinition(ASTContext &C) const {
889    return const_cast<VarDecl*>(this)->getDefinition(C);
890  }
891  VarDecl *getDefinition() {
892    return getDefinition(getASTContext());
893  }
894  const VarDecl *getDefinition() const {
895    return const_cast<VarDecl*>(this)->getDefinition();
896  }
897
898  /// \brief Determine whether this is or was instantiated from an out-of-line
899  /// definition of a static data member.
900  virtual bool isOutOfLine() const;
901
902  /// \brief If this is a static data member, find its out-of-line definition.
903  VarDecl *getOutOfLineDefinition();
904
905  /// isFileVarDecl - Returns true for file scoped variable declaration.
906  bool isFileVarDecl() const {
907    if (getKind() != Decl::Var)
908      return false;
909
910    if (getDeclContext()->getRedeclContext()->isFileContext())
911      return true;
912
913    if (isStaticDataMember())
914      return true;
915
916    return false;
917  }
918
919  /// getAnyInitializer - Get the initializer for this variable, no matter which
920  /// declaration it is attached to.
921  const Expr *getAnyInitializer() const {
922    const VarDecl *D;
923    return getAnyInitializer(D);
924  }
925
926  /// getAnyInitializer - Get the initializer for this variable, no matter which
927  /// declaration it is attached to. Also get that declaration.
928  const Expr *getAnyInitializer(const VarDecl *&D) const;
929
930  bool hasInit() const {
931    return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
932  }
933  const Expr *getInit() const {
934    if (Init.isNull())
935      return 0;
936
937    const Stmt *S = Init.dyn_cast<Stmt *>();
938    if (!S) {
939      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
940        S = ES->Value;
941    }
942    return (const Expr*) S;
943  }
944  Expr *getInit() {
945    if (Init.isNull())
946      return 0;
947
948    Stmt *S = Init.dyn_cast<Stmt *>();
949    if (!S) {
950      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
951        S = ES->Value;
952    }
953
954    return (Expr*) S;
955  }
956
957  /// \brief Retrieve the address of the initializer expression.
958  Stmt **getInitAddress() {
959    if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
960      return &ES->Value;
961
962    // This union hack tip-toes around strict-aliasing rules.
963    union {
964      InitType *InitPtr;
965      Stmt **StmtPtr;
966    };
967
968    InitPtr = &Init;
969    return StmtPtr;
970  }
971
972  void setInit(Expr *I);
973
974  /// \brief Determine whether this variable is a reference that
975  /// extends the lifetime of its temporary initializer.
976  ///
977  /// A reference extends the lifetime of its temporary initializer if
978  /// it's initializer is an rvalue that would normally go out of scope
979  /// at the end of the initializer (a full expression). In such cases,
980  /// the reference itself takes ownership of the temporary, which will
981  /// be destroyed when the reference goes out of scope. For example:
982  ///
983  /// \code
984  /// const int &r = 1.0; // creates a temporary of type 'int'
985  /// \endcode
986  bool extendsLifetimeOfTemporary() const;
987
988  /// \brief Determine whether this variable's value can be used in a
989  /// constant expression, according to the relevant language standard.
990  /// This only checks properties of the declaration, and does not check
991  /// whether the initializer is in fact a constant expression.
992  bool isUsableInConstantExpressions(ASTContext &C) const;
993
994  EvaluatedStmt *ensureEvaluatedStmt() const;
995
996  /// \brief Attempt to evaluate the value of the initializer attached to this
997  /// declaration, and produce notes explaining why it cannot be evaluated or is
998  /// not a constant expression. Returns a pointer to the value if evaluation
999  /// succeeded, 0 otherwise.
1000  APValue *evaluateValue() const;
1001  APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1002
1003  /// \brief Return the already-evaluated value of this variable's
1004  /// initializer, or NULL if the value is not yet known. Returns pointer
1005  /// to untyped APValue if the value could not be evaluated.
1006  APValue *getEvaluatedValue() const {
1007    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1008      if (Eval->WasEvaluated)
1009        return &Eval->Evaluated;
1010
1011    return 0;
1012  }
1013
1014  /// \brief Determines whether it is already known whether the
1015  /// initializer is an integral constant expression or not.
1016  bool isInitKnownICE() const {
1017    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1018      return Eval->CheckedICE;
1019
1020    return false;
1021  }
1022
1023  /// \brief Determines whether the initializer is an integral constant
1024  /// expression, or in C++11, whether the initializer is a constant
1025  /// expression.
1026  ///
1027  /// \pre isInitKnownICE()
1028  bool isInitICE() const {
1029    assert(isInitKnownICE() &&
1030           "Check whether we already know that the initializer is an ICE");
1031    return Init.get<EvaluatedStmt *>()->IsICE;
1032  }
1033
1034  /// \brief Determine whether the value of the initializer attached to this
1035  /// declaration is an integral constant expression.
1036  bool checkInitIsICE() const;
1037
1038  void setInitStyle(InitializationStyle Style) {
1039    VarDeclBits.InitStyle = Style;
1040  }
1041
1042  /// \brief The style of initialization for this declaration.
1043  ///
1044  /// C-style initialization is "int x = 1;". Call-style initialization is
1045  /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1046  /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1047  /// expression for class types. List-style initialization is C++11 syntax,
1048  /// e.g. "int x{1};". Clients can distinguish between different forms of
1049  /// initialization by checking this value. In particular, "int x = {1};" is
1050  /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1051  /// Init expression in all three cases is an InitListExpr.
1052  InitializationStyle getInitStyle() const {
1053    return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1054  }
1055
1056  /// \brief Whether the initializer is a direct-initializer (list or call).
1057  bool isDirectInit() const {
1058    return getInitStyle() != CInit;
1059  }
1060
1061  /// \brief Determine whether this variable is the exception variable in a
1062  /// C++ catch statememt or an Objective-C \@catch statement.
1063  bool isExceptionVariable() const {
1064    return VarDeclBits.ExceptionVar;
1065  }
1066  void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1067
1068  /// \brief Determine whether this local variable can be used with the named
1069  /// return value optimization (NRVO).
1070  ///
1071  /// The named return value optimization (NRVO) works by marking certain
1072  /// non-volatile local variables of class type as NRVO objects. These
1073  /// locals can be allocated within the return slot of their containing
1074  /// function, in which case there is no need to copy the object to the
1075  /// return slot when returning from the function. Within the function body,
1076  /// each return that returns the NRVO object will have this variable as its
1077  /// NRVO candidate.
1078  bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1079  void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1080
1081  /// \brief Determine whether this variable is the for-range-declaration in
1082  /// a C++0x for-range statement.
1083  bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1084  void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1085
1086  /// \brief Determine whether this variable is an ARC pseudo-__strong
1087  /// variable.  A pseudo-__strong variable has a __strong-qualified
1088  /// type but does not actually retain the object written into it.
1089  /// Generally such variables are also 'const' for safety.
1090  bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1091  void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1092
1093  /// Whether this variable is (C++11) constexpr.
1094  bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1095  void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1096
1097  /// \brief If this variable is an instantiated static data member of a
1098  /// class template specialization, returns the templated static data member
1099  /// from which it was instantiated.
1100  VarDecl *getInstantiatedFromStaticDataMember() const;
1101
1102  /// \brief If this variable is a static data member, determine what kind of
1103  /// template specialization or instantiation this is.
1104  TemplateSpecializationKind getTemplateSpecializationKind() const;
1105
1106  /// \brief If this variable is an instantiation of a static data member of a
1107  /// class template specialization, retrieves the member specialization
1108  /// information.
1109  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1110
1111  /// \brief For a static data member that was instantiated from a static
1112  /// data member of a class template, set the template specialiation kind.
1113  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1114                        SourceLocation PointOfInstantiation = SourceLocation());
1115
1116  // Implement isa/cast/dyncast/etc.
1117  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1118  static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1119};
1120
1121class ImplicitParamDecl : public VarDecl {
1122  virtual void anchor();
1123public:
1124  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1125                                   SourceLocation IdLoc, IdentifierInfo *Id,
1126                                   QualType T);
1127
1128  static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1129
1130  ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1131                    IdentifierInfo *Id, QualType Type)
1132    : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1133              /*tinfo*/ 0, SC_None) {
1134    setImplicit();
1135  }
1136
1137  // Implement isa/cast/dyncast/etc.
1138  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1139  static bool classofKind(Kind K) { return K == ImplicitParam; }
1140};
1141
1142/// ParmVarDecl - Represents a parameter to a function.
1143class ParmVarDecl : public VarDecl {
1144public:
1145  enum { MaxFunctionScopeDepth = 255 };
1146  enum { MaxFunctionScopeIndex = 255 };
1147
1148protected:
1149  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1150              SourceLocation IdLoc, IdentifierInfo *Id,
1151              QualType T, TypeSourceInfo *TInfo,
1152              StorageClass S, Expr *DefArg)
1153    : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1154    assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1155    assert(ParmVarDeclBits.IsKNRPromoted == false);
1156    assert(ParmVarDeclBits.IsObjCMethodParam == false);
1157    setDefaultArg(DefArg);
1158  }
1159
1160public:
1161  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1162                             SourceLocation StartLoc,
1163                             SourceLocation IdLoc, IdentifierInfo *Id,
1164                             QualType T, TypeSourceInfo *TInfo,
1165                             StorageClass S, Expr *DefArg);
1166
1167  static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1168
1169  virtual SourceRange getSourceRange() const LLVM_READONLY;
1170
1171  void setObjCMethodScopeInfo(unsigned parameterIndex) {
1172    ParmVarDeclBits.IsObjCMethodParam = true;
1173    setParameterIndex(parameterIndex);
1174  }
1175
1176  void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1177    assert(!ParmVarDeclBits.IsObjCMethodParam);
1178
1179    ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1180    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1181           && "truncation!");
1182
1183    setParameterIndex(parameterIndex);
1184  }
1185
1186  bool isObjCMethodParameter() const {
1187    return ParmVarDeclBits.IsObjCMethodParam;
1188  }
1189
1190  unsigned getFunctionScopeDepth() const {
1191    if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1192    return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1193  }
1194
1195  /// Returns the index of this parameter in its prototype or method scope.
1196  unsigned getFunctionScopeIndex() const {
1197    return getParameterIndex();
1198  }
1199
1200  ObjCDeclQualifier getObjCDeclQualifier() const {
1201    if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1202    return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1203  }
1204  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1205    assert(ParmVarDeclBits.IsObjCMethodParam);
1206    ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1207  }
1208
1209  /// True if the value passed to this parameter must undergo
1210  /// K&R-style default argument promotion:
1211  ///
1212  /// C99 6.5.2.2.
1213  ///   If the expression that denotes the called function has a type
1214  ///   that does not include a prototype, the integer promotions are
1215  ///   performed on each argument, and arguments that have type float
1216  ///   are promoted to double.
1217  bool isKNRPromoted() const {
1218    return ParmVarDeclBits.IsKNRPromoted;
1219  }
1220  void setKNRPromoted(bool promoted) {
1221    ParmVarDeclBits.IsKNRPromoted = promoted;
1222  }
1223
1224  Expr *getDefaultArg();
1225  const Expr *getDefaultArg() const {
1226    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1227  }
1228
1229  void setDefaultArg(Expr *defarg) {
1230    Init = reinterpret_cast<Stmt *>(defarg);
1231  }
1232
1233  /// \brief Retrieve the source range that covers the entire default
1234  /// argument.
1235  SourceRange getDefaultArgRange() const;
1236  void setUninstantiatedDefaultArg(Expr *arg) {
1237    Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1238  }
1239  Expr *getUninstantiatedDefaultArg() {
1240    return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1241  }
1242  const Expr *getUninstantiatedDefaultArg() const {
1243    return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1244  }
1245
1246  /// hasDefaultArg - Determines whether this parameter has a default argument,
1247  /// either parsed or not.
1248  bool hasDefaultArg() const {
1249    return getInit() || hasUnparsedDefaultArg() ||
1250      hasUninstantiatedDefaultArg();
1251  }
1252
1253  /// hasUnparsedDefaultArg - Determines whether this parameter has a
1254  /// default argument that has not yet been parsed. This will occur
1255  /// during the processing of a C++ class whose member functions have
1256  /// default arguments, e.g.,
1257  /// @code
1258  ///   class X {
1259  ///   public:
1260  ///     void f(int x = 17); // x has an unparsed default argument now
1261  ///   }; // x has a regular default argument now
1262  /// @endcode
1263  bool hasUnparsedDefaultArg() const {
1264    return Init.is<UnparsedDefaultArgument*>();
1265  }
1266
1267  bool hasUninstantiatedDefaultArg() const {
1268    return Init.is<UninstantiatedDefaultArgument*>();
1269  }
1270
1271  /// setUnparsedDefaultArg - Specify that this parameter has an
1272  /// unparsed default argument. The argument will be replaced with a
1273  /// real default argument via setDefaultArg when the class
1274  /// definition enclosing the function declaration that owns this
1275  /// default argument is completed.
1276  void setUnparsedDefaultArg() {
1277    Init = (UnparsedDefaultArgument *)0;
1278  }
1279
1280  bool hasInheritedDefaultArg() const {
1281    return ParmVarDeclBits.HasInheritedDefaultArg;
1282  }
1283
1284  void setHasInheritedDefaultArg(bool I = true) {
1285    ParmVarDeclBits.HasInheritedDefaultArg = I;
1286  }
1287
1288  QualType getOriginalType() const {
1289    if (getTypeSourceInfo())
1290      return getTypeSourceInfo()->getType();
1291    return getType();
1292  }
1293
1294  /// \brief Determine whether this parameter is actually a function
1295  /// parameter pack.
1296  bool isParameterPack() const;
1297
1298  /// setOwningFunction - Sets the function declaration that owns this
1299  /// ParmVarDecl. Since ParmVarDecls are often created before the
1300  /// FunctionDecls that own them, this routine is required to update
1301  /// the DeclContext appropriately.
1302  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1303
1304  // Implement isa/cast/dyncast/etc.
1305  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1306  static bool classofKind(Kind K) { return K == ParmVar; }
1307
1308private:
1309  enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1310
1311  void setParameterIndex(unsigned parameterIndex) {
1312    if (parameterIndex >= ParameterIndexSentinel) {
1313      setParameterIndexLarge(parameterIndex);
1314      return;
1315    }
1316
1317    ParmVarDeclBits.ParameterIndex = parameterIndex;
1318    assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1319  }
1320  unsigned getParameterIndex() const {
1321    unsigned d = ParmVarDeclBits.ParameterIndex;
1322    return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1323  }
1324
1325  void setParameterIndexLarge(unsigned parameterIndex);
1326  unsigned getParameterIndexLarge() const;
1327};
1328
1329/// FunctionDecl - An instance of this class is created to represent a
1330/// function declaration or definition.
1331///
1332/// Since a given function can be declared several times in a program,
1333/// there may be several FunctionDecls that correspond to that
1334/// function. Only one of those FunctionDecls will be found when
1335/// traversing the list of declarations in the context of the
1336/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1337/// contains all of the information known about the function. Other,
1338/// previous declarations of the function are available via the
1339/// getPreviousDecl() chain.
1340class FunctionDecl : public DeclaratorDecl, public DeclContext,
1341                     public Redeclarable<FunctionDecl> {
1342public:
1343  typedef clang::StorageClass StorageClass;
1344
1345  /// \brief The kind of templated function a FunctionDecl can be.
1346  enum TemplatedKind {
1347    TK_NonTemplate,
1348    TK_FunctionTemplate,
1349    TK_MemberSpecialization,
1350    TK_FunctionTemplateSpecialization,
1351    TK_DependentFunctionTemplateSpecialization
1352  };
1353
1354private:
1355  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1356  /// parameters of this function.  This is null if a prototype or if there are
1357  /// no formals.
1358  ParmVarDecl **ParamInfo;
1359
1360  /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1361  /// decls defined in the function prototype that are not parameters. E.g.
1362  /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1363  ArrayRef<NamedDecl *> DeclsInPrototypeScope;
1364
1365  LazyDeclStmtPtr Body;
1366
1367  // FIXME: This can be packed into the bitfields in Decl.
1368  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1369  unsigned SClass : 2;
1370  bool IsInline : 1;
1371  bool IsInlineSpecified : 1;
1372  bool IsVirtualAsWritten : 1;
1373  bool IsPure : 1;
1374  bool HasInheritedPrototype : 1;
1375  bool HasWrittenPrototype : 1;
1376  bool IsDeleted : 1;
1377  bool IsTrivial : 1; // sunk from CXXMethodDecl
1378  bool IsDefaulted : 1; // sunk from CXXMethoDecl
1379  bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1380  bool HasImplicitReturnZero : 1;
1381  bool IsLateTemplateParsed : 1;
1382  bool IsConstexpr : 1;
1383
1384  /// \brief Indicates if the function was a definition but its body was
1385  /// skipped.
1386  unsigned HasSkippedBody : 1;
1387
1388  /// \brief End part of this FunctionDecl's source range.
1389  ///
1390  /// We could compute the full range in getSourceRange(). However, when we're
1391  /// dealing with a function definition deserialized from a PCH/AST file,
1392  /// we can only compute the full range once the function body has been
1393  /// de-serialized, so it's far better to have the (sometimes-redundant)
1394  /// EndRangeLoc.
1395  SourceLocation EndRangeLoc;
1396
1397  /// \brief The template or declaration that this declaration
1398  /// describes or was instantiated from, respectively.
1399  ///
1400  /// For non-templates, this value will be NULL. For function
1401  /// declarations that describe a function template, this will be a
1402  /// pointer to a FunctionTemplateDecl. For member functions
1403  /// of class template specializations, this will be a MemberSpecializationInfo
1404  /// pointer containing information about the specialization.
1405  /// For function template specializations, this will be a
1406  /// FunctionTemplateSpecializationInfo, which contains information about
1407  /// the template being specialized and the template arguments involved in
1408  /// that specialization.
1409  llvm::PointerUnion4<FunctionTemplateDecl *,
1410                      MemberSpecializationInfo *,
1411                      FunctionTemplateSpecializationInfo *,
1412                      DependentFunctionTemplateSpecializationInfo *>
1413    TemplateOrSpecialization;
1414
1415  /// DNLoc - Provides source/type location info for the
1416  /// declaration name embedded in the DeclaratorDecl base class.
1417  DeclarationNameLoc DNLoc;
1418
1419  /// \brief Specify that this function declaration is actually a function
1420  /// template specialization.
1421  ///
1422  /// \param C the ASTContext.
1423  ///
1424  /// \param Template the function template that this function template
1425  /// specialization specializes.
1426  ///
1427  /// \param TemplateArgs the template arguments that produced this
1428  /// function template specialization from the template.
1429  ///
1430  /// \param InsertPos If non-NULL, the position in the function template
1431  /// specialization set where the function template specialization data will
1432  /// be inserted.
1433  ///
1434  /// \param TSK the kind of template specialization this is.
1435  ///
1436  /// \param TemplateArgsAsWritten location info of template arguments.
1437  ///
1438  /// \param PointOfInstantiation point at which the function template
1439  /// specialization was first instantiated.
1440  void setFunctionTemplateSpecialization(ASTContext &C,
1441                                         FunctionTemplateDecl *Template,
1442                                       const TemplateArgumentList *TemplateArgs,
1443                                         void *InsertPos,
1444                                         TemplateSpecializationKind TSK,
1445                          const TemplateArgumentListInfo *TemplateArgsAsWritten,
1446                                         SourceLocation PointOfInstantiation);
1447
1448  /// \brief Specify that this record is an instantiation of the
1449  /// member function FD.
1450  void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1451                                        TemplateSpecializationKind TSK);
1452
1453  void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1454
1455protected:
1456  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1457               const DeclarationNameInfo &NameInfo,
1458               QualType T, TypeSourceInfo *TInfo,
1459               StorageClass S, bool isInlineSpecified,
1460               bool isConstexprSpecified)
1461    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1462                     StartLoc),
1463      DeclContext(DK),
1464      ParamInfo(0), Body(),
1465      SClass(S),
1466      IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1467      IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1468      HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1469      IsDefaulted(false), IsExplicitlyDefaulted(false),
1470      HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1471      IsConstexpr(isConstexprSpecified), HasSkippedBody(false),
1472      EndRangeLoc(NameInfo.getEndLoc()),
1473      TemplateOrSpecialization(),
1474      DNLoc(NameInfo.getInfo()) {}
1475
1476  typedef Redeclarable<FunctionDecl> redeclarable_base;
1477  virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1478  virtual FunctionDecl *getPreviousDeclImpl() {
1479    return getPreviousDecl();
1480  }
1481  virtual FunctionDecl *getMostRecentDeclImpl() {
1482    return getMostRecentDecl();
1483  }
1484
1485public:
1486  typedef redeclarable_base::redecl_iterator redecl_iterator;
1487  using redeclarable_base::redecls_begin;
1488  using redeclarable_base::redecls_end;
1489  using redeclarable_base::getPreviousDecl;
1490  using redeclarable_base::getMostRecentDecl;
1491
1492  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1493                              SourceLocation StartLoc, SourceLocation NLoc,
1494                              DeclarationName N, QualType T,
1495                              TypeSourceInfo *TInfo,
1496                              StorageClass SC,
1497                              bool isInlineSpecified = false,
1498                              bool hasWrittenPrototype = true,
1499                              bool isConstexprSpecified = false) {
1500    DeclarationNameInfo NameInfo(N, NLoc);
1501    return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1502                                SC,
1503                                isInlineSpecified, hasWrittenPrototype,
1504                                isConstexprSpecified);
1505  }
1506
1507  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1508                              SourceLocation StartLoc,
1509                              const DeclarationNameInfo &NameInfo,
1510                              QualType T, TypeSourceInfo *TInfo,
1511                              StorageClass SC,
1512                              bool isInlineSpecified,
1513                              bool hasWrittenPrototype,
1514                              bool isConstexprSpecified = false);
1515
1516  static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1517
1518  DeclarationNameInfo getNameInfo() const {
1519    return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1520  }
1521
1522  virtual void getNameForDiagnostic(raw_ostream &OS,
1523                                    const PrintingPolicy &Policy,
1524                                    bool Qualified) const;
1525
1526  void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1527
1528  virtual SourceRange getSourceRange() const LLVM_READONLY;
1529
1530  /// \brief Returns true if the function has a body (definition). The
1531  /// function body might be in any of the (re-)declarations of this
1532  /// function. The variant that accepts a FunctionDecl pointer will
1533  /// set that function declaration to the actual declaration
1534  /// containing the body (if there is one).
1535  bool hasBody(const FunctionDecl *&Definition) const;
1536
1537  virtual bool hasBody() const {
1538    const FunctionDecl* Definition;
1539    return hasBody(Definition);
1540  }
1541
1542  /// hasTrivialBody - Returns whether the function has a trivial body that does
1543  /// not require any specific codegen.
1544  bool hasTrivialBody() const;
1545
1546  /// isDefined - Returns true if the function is defined at all, including
1547  /// a deleted definition. Except for the behavior when the function is
1548  /// deleted, behaves like hasBody.
1549  bool isDefined(const FunctionDecl *&Definition) const;
1550
1551  virtual bool isDefined() const {
1552    const FunctionDecl* Definition;
1553    return isDefined(Definition);
1554  }
1555
1556  /// getBody - Retrieve the body (definition) of the function. The
1557  /// function body might be in any of the (re-)declarations of this
1558  /// function. The variant that accepts a FunctionDecl pointer will
1559  /// set that function declaration to the actual declaration
1560  /// containing the body (if there is one).
1561  /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1562  /// unnecessary AST de-serialization of the body.
1563  Stmt *getBody(const FunctionDecl *&Definition) const;
1564
1565  virtual Stmt *getBody() const {
1566    const FunctionDecl* Definition;
1567    return getBody(Definition);
1568  }
1569
1570  /// isThisDeclarationADefinition - Returns whether this specific
1571  /// declaration of the function is also a definition. This does not
1572  /// determine whether the function has been defined (e.g., in a
1573  /// previous definition); for that information, use isDefined. Note
1574  /// that this returns false for a defaulted function unless that function
1575  /// has been implicitly defined (possibly as deleted).
1576  bool isThisDeclarationADefinition() const {
1577    return IsDeleted || Body || IsLateTemplateParsed;
1578  }
1579
1580  /// doesThisDeclarationHaveABody - Returns whether this specific
1581  /// declaration of the function has a body - that is, if it is a non-
1582  /// deleted definition.
1583  bool doesThisDeclarationHaveABody() const {
1584    return Body || IsLateTemplateParsed;
1585  }
1586
1587  void setBody(Stmt *B);
1588  void setLazyBody(uint64_t Offset) { Body = Offset; }
1589
1590  /// Whether this function is variadic.
1591  bool isVariadic() const;
1592
1593  /// Whether this function is marked as virtual explicitly.
1594  bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1595  void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1596
1597  /// Whether this virtual function is pure, i.e. makes the containing class
1598  /// abstract.
1599  bool isPure() const { return IsPure; }
1600  void setPure(bool P = true);
1601
1602  /// Whether this templated function will be late parsed.
1603  bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1604  void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1605
1606  /// Whether this function is "trivial" in some specialized C++ senses.
1607  /// Can only be true for default constructors, copy constructors,
1608  /// copy assignment operators, and destructors.  Not meaningful until
1609  /// the class has been fully built by Sema.
1610  bool isTrivial() const { return IsTrivial; }
1611  void setTrivial(bool IT) { IsTrivial = IT; }
1612
1613  /// Whether this function is defaulted per C++0x. Only valid for
1614  /// special member functions.
1615  bool isDefaulted() const { return IsDefaulted; }
1616  void setDefaulted(bool D = true) { IsDefaulted = D; }
1617
1618  /// Whether this function is explicitly defaulted per C++0x. Only valid
1619  /// for special member functions.
1620  bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1621  void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1622
1623  /// Whether falling off this function implicitly returns null/zero.
1624  /// If a more specific implicit return value is required, front-ends
1625  /// should synthesize the appropriate return statements.
1626  bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1627  void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1628
1629  /// \brief Whether this function has a prototype, either because one
1630  /// was explicitly written or because it was "inherited" by merging
1631  /// a declaration without a prototype with a declaration that has a
1632  /// prototype.
1633  bool hasPrototype() const {
1634    return HasWrittenPrototype || HasInheritedPrototype;
1635  }
1636
1637  bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1638
1639  /// \brief Whether this function inherited its prototype from a
1640  /// previous declaration.
1641  bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1642  void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1643
1644  /// Whether this is a (C++11) constexpr function or constexpr constructor.
1645  bool isConstexpr() const { return IsConstexpr; }
1646  void setConstexpr(bool IC) { IsConstexpr = IC; }
1647
1648  /// \brief Whether this function has been deleted.
1649  ///
1650  /// A function that is "deleted" (via the C++0x "= delete" syntax)
1651  /// acts like a normal function, except that it cannot actually be
1652  /// called or have its address taken. Deleted functions are
1653  /// typically used in C++ overload resolution to attract arguments
1654  /// whose type or lvalue/rvalue-ness would permit the use of a
1655  /// different overload that would behave incorrectly. For example,
1656  /// one might use deleted functions to ban implicit conversion from
1657  /// a floating-point number to an Integer type:
1658  ///
1659  /// @code
1660  /// struct Integer {
1661  ///   Integer(long); // construct from a long
1662  ///   Integer(double) = delete; // no construction from float or double
1663  ///   Integer(long double) = delete; // no construction from long double
1664  /// };
1665  /// @endcode
1666  // If a function is deleted, its first declaration must be.
1667  bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1668  bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1669  void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1670
1671  /// \brief Determines whether this function is "main", which is the
1672  /// entry point into an executable program.
1673  bool isMain() const;
1674
1675  /// \brief Determines whether this operator new or delete is one
1676  /// of the reserved global placement operators:
1677  ///    void *operator new(size_t, void *);
1678  ///    void *operator new[](size_t, void *);
1679  ///    void operator delete(void *, void *);
1680  ///    void operator delete[](void *, void *);
1681  /// These functions have special behavior under [new.delete.placement]:
1682  ///    These functions are reserved, a C++ program may not define
1683  ///    functions that displace the versions in the Standard C++ library.
1684  ///    The provisions of [basic.stc.dynamic] do not apply to these
1685  ///    reserved placement forms of operator new and operator delete.
1686  ///
1687  /// This function must be an allocation or deallocation function.
1688  bool isReservedGlobalPlacementOperator() const;
1689
1690  /// Compute the language linkage.
1691  LanguageLinkage getLanguageLinkage() const;
1692
1693  /// \brief Determines whether this function is a function with
1694  /// external, C linkage.
1695  bool isExternC() const;
1696
1697  /// \brief Determines whether this is a global function.
1698  bool isGlobal() const;
1699
1700  /// \brief Determines whether this function is known to be 'noreturn', through
1701  /// an attribute on its declaration or its type.
1702  bool isNoReturn() const;
1703
1704  /// \brief True if the function was a definition but its body was skipped.
1705  bool hasSkippedBody() const { return HasSkippedBody; }
1706  void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
1707
1708  void setPreviousDeclaration(FunctionDecl * PrevDecl);
1709
1710  virtual const FunctionDecl *getCanonicalDecl() const;
1711  virtual FunctionDecl *getCanonicalDecl();
1712
1713  unsigned getBuiltinID() const;
1714
1715  // Iterator access to formal parameters.
1716  unsigned param_size() const { return getNumParams(); }
1717  typedef ParmVarDecl **param_iterator;
1718  typedef ParmVarDecl * const *param_const_iterator;
1719
1720  param_iterator param_begin() { return ParamInfo; }
1721  param_iterator param_end()   { return ParamInfo+param_size(); }
1722
1723  param_const_iterator param_begin() const { return ParamInfo; }
1724  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1725
1726  /// getNumParams - Return the number of parameters this function must have
1727  /// based on its FunctionType.  This is the length of the ParamInfo array
1728  /// after it has been created.
1729  unsigned getNumParams() const;
1730
1731  const ParmVarDecl *getParamDecl(unsigned i) const {
1732    assert(i < getNumParams() && "Illegal param #");
1733    return ParamInfo[i];
1734  }
1735  ParmVarDecl *getParamDecl(unsigned i) {
1736    assert(i < getNumParams() && "Illegal param #");
1737    return ParamInfo[i];
1738  }
1739  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
1740    setParams(getASTContext(), NewParamInfo);
1741  }
1742
1743  const ArrayRef<NamedDecl *> &getDeclsInPrototypeScope() const {
1744    return DeclsInPrototypeScope;
1745  }
1746  void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
1747
1748  /// getMinRequiredArguments - Returns the minimum number of arguments
1749  /// needed to call this function. This may be fewer than the number of
1750  /// function parameters, if some of the parameters have default
1751  /// arguments (in C++).
1752  unsigned getMinRequiredArguments() const;
1753
1754  QualType getResultType() const {
1755    return getType()->getAs<FunctionType>()->getResultType();
1756  }
1757
1758  /// \brief Determine the type of an expression that calls this function.
1759  QualType getCallResultType() const {
1760    return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1761  }
1762
1763  /// \brief Returns the storage class as written in the source. For the
1764  /// computed linkage of symbol, see getLinkage.
1765  StorageClass getStorageClass() const { return StorageClass(SClass); }
1766
1767  /// \brief Determine whether the "inline" keyword was specified for this
1768  /// function.
1769  bool isInlineSpecified() const { return IsInlineSpecified; }
1770
1771  /// Set whether the "inline" keyword was specified for this function.
1772  void setInlineSpecified(bool I) {
1773    IsInlineSpecified = I;
1774    IsInline = I;
1775  }
1776
1777  /// Flag that this function is implicitly inline.
1778  void setImplicitlyInline() {
1779    IsInline = true;
1780  }
1781
1782  /// \brief Determine whether this function should be inlined, because it is
1783  /// either marked "inline" or "constexpr" or is a member function of a class
1784  /// that was defined in the class body.
1785  bool isInlined() const { return IsInline; }
1786
1787  bool isInlineDefinitionExternallyVisible() const;
1788
1789  bool doesDeclarationForceExternallyVisibleDefinition() const;
1790
1791  /// isOverloadedOperator - Whether this function declaration
1792  /// represents an C++ overloaded operator, e.g., "operator+".
1793  bool isOverloadedOperator() const {
1794    return getOverloadedOperator() != OO_None;
1795  }
1796
1797  OverloadedOperatorKind getOverloadedOperator() const;
1798
1799  const IdentifierInfo *getLiteralIdentifier() const;
1800
1801  /// \brief If this function is an instantiation of a member function
1802  /// of a class template specialization, retrieves the function from
1803  /// which it was instantiated.
1804  ///
1805  /// This routine will return non-NULL for (non-templated) member
1806  /// functions of class templates and for instantiations of function
1807  /// templates. For example, given:
1808  ///
1809  /// \code
1810  /// template<typename T>
1811  /// struct X {
1812  ///   void f(T);
1813  /// };
1814  /// \endcode
1815  ///
1816  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1817  /// whose parent is the class template specialization X<int>. For
1818  /// this declaration, getInstantiatedFromFunction() will return
1819  /// the FunctionDecl X<T>::A. When a complete definition of
1820  /// X<int>::A is required, it will be instantiated from the
1821  /// declaration returned by getInstantiatedFromMemberFunction().
1822  FunctionDecl *getInstantiatedFromMemberFunction() const;
1823
1824  /// \brief What kind of templated function this is.
1825  TemplatedKind getTemplatedKind() const;
1826
1827  /// \brief If this function is an instantiation of a member function of a
1828  /// class template specialization, retrieves the member specialization
1829  /// information.
1830  MemberSpecializationInfo *getMemberSpecializationInfo() const {
1831    return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1832  }
1833
1834  /// \brief Specify that this record is an instantiation of the
1835  /// member function FD.
1836  void setInstantiationOfMemberFunction(FunctionDecl *FD,
1837                                        TemplateSpecializationKind TSK) {
1838    setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1839  }
1840
1841  /// \brief Retrieves the function template that is described by this
1842  /// function declaration.
1843  ///
1844  /// Every function template is represented as a FunctionTemplateDecl
1845  /// and a FunctionDecl (or something derived from FunctionDecl). The
1846  /// former contains template properties (such as the template
1847  /// parameter lists) while the latter contains the actual
1848  /// description of the template's
1849  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1850  /// FunctionDecl that describes the function template,
1851  /// getDescribedFunctionTemplate() retrieves the
1852  /// FunctionTemplateDecl from a FunctionDecl.
1853  FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1854    return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1855  }
1856
1857  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1858    TemplateOrSpecialization = Template;
1859  }
1860
1861  /// \brief Determine whether this function is a function template
1862  /// specialization.
1863  bool isFunctionTemplateSpecialization() const {
1864    return getPrimaryTemplate() != 0;
1865  }
1866
1867  /// \brief Retrieve the class scope template pattern that this function
1868  ///  template specialization is instantiated from.
1869  FunctionDecl *getClassScopeSpecializationPattern() const;
1870
1871  /// \brief If this function is actually a function template specialization,
1872  /// retrieve information about this function template specialization.
1873  /// Otherwise, returns NULL.
1874  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1875    return TemplateOrSpecialization.
1876             dyn_cast<FunctionTemplateSpecializationInfo*>();
1877  }
1878
1879  /// \brief Determines whether this function is a function template
1880  /// specialization or a member of a class template specialization that can
1881  /// be implicitly instantiated.
1882  bool isImplicitlyInstantiable() const;
1883
1884  /// \brief Determines if the given function was instantiated from a
1885  /// function template.
1886  bool isTemplateInstantiation() const;
1887
1888  /// \brief Retrieve the function declaration from which this function could
1889  /// be instantiated, if it is an instantiation (rather than a non-template
1890  /// or a specialization, for example).
1891  FunctionDecl *getTemplateInstantiationPattern() const;
1892
1893  /// \brief Retrieve the primary template that this function template
1894  /// specialization either specializes or was instantiated from.
1895  ///
1896  /// If this function declaration is not a function template specialization,
1897  /// returns NULL.
1898  FunctionTemplateDecl *getPrimaryTemplate() const;
1899
1900  /// \brief Retrieve the template arguments used to produce this function
1901  /// template specialization from the primary template.
1902  ///
1903  /// If this function declaration is not a function template specialization,
1904  /// returns NULL.
1905  const TemplateArgumentList *getTemplateSpecializationArgs() const;
1906
1907  /// \brief Retrieve the template argument list as written in the sources,
1908  /// if any.
1909  ///
1910  /// If this function declaration is not a function template specialization
1911  /// or if it had no explicit template argument list, returns NULL.
1912  /// Note that it an explicit template argument list may be written empty,
1913  /// e.g., template<> void foo<>(char* s);
1914  const ASTTemplateArgumentListInfo*
1915  getTemplateSpecializationArgsAsWritten() const;
1916
1917  /// \brief Specify that this function declaration is actually a function
1918  /// template specialization.
1919  ///
1920  /// \param Template the function template that this function template
1921  /// specialization specializes.
1922  ///
1923  /// \param TemplateArgs the template arguments that produced this
1924  /// function template specialization from the template.
1925  ///
1926  /// \param InsertPos If non-NULL, the position in the function template
1927  /// specialization set where the function template specialization data will
1928  /// be inserted.
1929  ///
1930  /// \param TSK the kind of template specialization this is.
1931  ///
1932  /// \param TemplateArgsAsWritten location info of template arguments.
1933  ///
1934  /// \param PointOfInstantiation point at which the function template
1935  /// specialization was first instantiated.
1936  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1937                                      const TemplateArgumentList *TemplateArgs,
1938                                         void *InsertPos,
1939                    TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
1940                    const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
1941                    SourceLocation PointOfInstantiation = SourceLocation()) {
1942    setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
1943                                      InsertPos, TSK, TemplateArgsAsWritten,
1944                                      PointOfInstantiation);
1945  }
1946
1947  /// \brief Specifies that this function declaration is actually a
1948  /// dependent function template specialization.
1949  void setDependentTemplateSpecialization(ASTContext &Context,
1950                             const UnresolvedSetImpl &Templates,
1951                      const TemplateArgumentListInfo &TemplateArgs);
1952
1953  DependentFunctionTemplateSpecializationInfo *
1954  getDependentSpecializationInfo() const {
1955    return TemplateOrSpecialization.
1956             dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
1957  }
1958
1959  /// \brief Determine what kind of template instantiation this function
1960  /// represents.
1961  TemplateSpecializationKind getTemplateSpecializationKind() const;
1962
1963  /// \brief Determine what kind of template instantiation this function
1964  /// represents.
1965  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1966                        SourceLocation PointOfInstantiation = SourceLocation());
1967
1968  /// \brief Retrieve the (first) point of instantiation of a function template
1969  /// specialization or a member of a class template specialization.
1970  ///
1971  /// \returns the first point of instantiation, if this function was
1972  /// instantiated from a template; otherwise, returns an invalid source
1973  /// location.
1974  SourceLocation getPointOfInstantiation() const;
1975
1976  /// \brief Determine whether this is or was instantiated from an out-of-line
1977  /// definition of a member function.
1978  virtual bool isOutOfLine() const;
1979
1980  /// \brief Identify a memory copying or setting function.
1981  /// If the given function is a memory copy or setting function, returns
1982  /// the corresponding Builtin ID. If the function is not a memory function,
1983  /// returns 0.
1984  unsigned getMemoryFunctionKind() const;
1985
1986  // Implement isa/cast/dyncast/etc.
1987  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1988  static bool classofKind(Kind K) {
1989    return K >= firstFunction && K <= lastFunction;
1990  }
1991  static DeclContext *castToDeclContext(const FunctionDecl *D) {
1992    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1993  }
1994  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1995    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1996  }
1997
1998  friend class ASTDeclReader;
1999  friend class ASTDeclWriter;
2000};
2001
2002
2003/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2004/// represent a member of a struct/union/class.
2005class FieldDecl : public DeclaratorDecl {
2006  // FIXME: This can be packed into the bitfields in Decl.
2007  bool Mutable : 1;
2008  mutable unsigned CachedFieldIndex : 31;
2009
2010  /// \brief An InClassInitStyle value, and either a bit width expression (if
2011  /// the InClassInitStyle value is ICIS_NoInit), or a pointer to the in-class
2012  /// initializer for this field (otherwise).
2013  ///
2014  /// We can safely combine these two because in-class initializers are not
2015  /// permitted for bit-fields.
2016  ///
2017  /// If the InClassInitStyle is not ICIS_NoInit and the initializer is null,
2018  /// then this field has an in-class initializer which has not yet been parsed
2019  /// and attached.
2020  llvm::PointerIntPair<Expr *, 2, unsigned> InitializerOrBitWidth;
2021protected:
2022  FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2023            SourceLocation IdLoc, IdentifierInfo *Id,
2024            QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2025            InClassInitStyle InitStyle)
2026    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2027      Mutable(Mutable), CachedFieldIndex(0),
2028      InitializerOrBitWidth(BW, InitStyle) {
2029    assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2030  }
2031
2032public:
2033  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2034                           SourceLocation StartLoc, SourceLocation IdLoc,
2035                           IdentifierInfo *Id, QualType T,
2036                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2037                           InClassInitStyle InitStyle);
2038
2039  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2040
2041  /// getFieldIndex - Returns the index of this field within its record,
2042  /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2043  unsigned getFieldIndex() const;
2044
2045  /// isMutable - Determines whether this field is mutable (C++ only).
2046  bool isMutable() const { return Mutable; }
2047
2048  /// isBitfield - Determines whether this field is a bitfield.
2049  bool isBitField() const {
2050    return getInClassInitStyle() == ICIS_NoInit &&
2051           InitializerOrBitWidth.getPointer();
2052  }
2053
2054  /// @brief Determines whether this is an unnamed bitfield.
2055  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2056
2057  /// isAnonymousStructOrUnion - Determines whether this field is a
2058  /// representative for an anonymous struct or union. Such fields are
2059  /// unnamed and are implicitly generated by the implementation to
2060  /// store the data for the anonymous union or struct.
2061  bool isAnonymousStructOrUnion() const;
2062
2063  Expr *getBitWidth() const {
2064    return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2065  }
2066  unsigned getBitWidthValue(const ASTContext &Ctx) const;
2067
2068  /// setBitWidth - Set the bit-field width for this member.
2069  // Note: used by some clients (i.e., do not remove it).
2070  void setBitWidth(Expr *Width);
2071  /// removeBitWidth - Remove the bit-field width from this member.
2072  // Note: used by some clients (i.e., do not remove it).
2073  void removeBitWidth() {
2074    assert(isBitField() && "no bitfield width to remove");
2075    InitializerOrBitWidth.setPointer(0);
2076  }
2077
2078  /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2079  /// this field has.
2080  InClassInitStyle getInClassInitStyle() const {
2081    return static_cast<InClassInitStyle>(InitializerOrBitWidth.getInt());
2082  }
2083
2084  /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2085  /// initializer.
2086  bool hasInClassInitializer() const {
2087    return getInClassInitStyle() != ICIS_NoInit;
2088  }
2089  /// getInClassInitializer - Get the C++11 in-class initializer for this
2090  /// member, or null if one has not been set. If a valid declaration has an
2091  /// in-class initializer, but this returns null, then we have not parsed and
2092  /// attached it yet.
2093  Expr *getInClassInitializer() const {
2094    return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2095  }
2096  /// setInClassInitializer - Set the C++11 in-class initializer for this
2097  /// member.
2098  void setInClassInitializer(Expr *Init);
2099  /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2100  /// member.
2101  void removeInClassInitializer() {
2102    assert(hasInClassInitializer() && "no initializer to remove");
2103    InitializerOrBitWidth.setPointer(0);
2104    InitializerOrBitWidth.setInt(ICIS_NoInit);
2105  }
2106
2107  /// getParent - Returns the parent of this field declaration, which
2108  /// is the struct in which this method is defined.
2109  const RecordDecl *getParent() const {
2110    return cast<RecordDecl>(getDeclContext());
2111  }
2112
2113  RecordDecl *getParent() {
2114    return cast<RecordDecl>(getDeclContext());
2115  }
2116
2117  SourceRange getSourceRange() const LLVM_READONLY;
2118
2119  // Implement isa/cast/dyncast/etc.
2120  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2121  static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2122
2123  friend class ASTDeclReader;
2124  friend class ASTDeclWriter;
2125};
2126
2127/// EnumConstantDecl - An instance of this object exists for each enum constant
2128/// that is defined.  For example, in "enum X {a,b}", each of a/b are
2129/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2130/// TagType for the X EnumDecl.
2131class EnumConstantDecl : public ValueDecl {
2132  Stmt *Init; // an integer constant expression
2133  llvm::APSInt Val; // The value.
2134protected:
2135  EnumConstantDecl(DeclContext *DC, SourceLocation L,
2136                   IdentifierInfo *Id, QualType T, Expr *E,
2137                   const llvm::APSInt &V)
2138    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2139
2140public:
2141
2142  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2143                                  SourceLocation L, IdentifierInfo *Id,
2144                                  QualType T, Expr *E,
2145                                  const llvm::APSInt &V);
2146  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2147
2148  const Expr *getInitExpr() const { return (const Expr*) Init; }
2149  Expr *getInitExpr() { return (Expr*) Init; }
2150  const llvm::APSInt &getInitVal() const { return Val; }
2151
2152  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2153  void setInitVal(const llvm::APSInt &V) { Val = V; }
2154
2155  SourceRange getSourceRange() const LLVM_READONLY;
2156
2157  // Implement isa/cast/dyncast/etc.
2158  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2159  static bool classofKind(Kind K) { return K == EnumConstant; }
2160
2161  friend class StmtIteratorBase;
2162};
2163
2164/// IndirectFieldDecl - An instance of this class is created to represent a
2165/// field injected from an anonymous union/struct into the parent scope.
2166/// IndirectFieldDecl are always implicit.
2167class IndirectFieldDecl : public ValueDecl {
2168  virtual void anchor();
2169  NamedDecl **Chaining;
2170  unsigned ChainingSize;
2171
2172  IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2173                    DeclarationName N, QualType T,
2174                    NamedDecl **CH, unsigned CHS)
2175    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2176
2177public:
2178  static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2179                                   SourceLocation L, IdentifierInfo *Id,
2180                                   QualType T, NamedDecl **CH, unsigned CHS);
2181
2182  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2183
2184  typedef NamedDecl * const *chain_iterator;
2185  chain_iterator chain_begin() const { return Chaining; }
2186  chain_iterator chain_end() const  { return Chaining+ChainingSize; }
2187
2188  unsigned getChainingSize() const { return ChainingSize; }
2189
2190  FieldDecl *getAnonField() const {
2191    assert(ChainingSize >= 2);
2192    return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2193  }
2194
2195  VarDecl *getVarDecl() const {
2196    assert(ChainingSize >= 2);
2197    return dyn_cast<VarDecl>(*chain_begin());
2198  }
2199
2200  // Implement isa/cast/dyncast/etc.
2201  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2202  static bool classofKind(Kind K) { return K == IndirectField; }
2203  friend class ASTDeclReader;
2204};
2205
2206/// TypeDecl - Represents a declaration of a type.
2207///
2208class TypeDecl : public NamedDecl {
2209  virtual void anchor();
2210  /// TypeForDecl - This indicates the Type object that represents
2211  /// this TypeDecl.  It is a cache maintained by
2212  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2213  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2214  mutable const Type *TypeForDecl;
2215  /// LocStart - The start of the source range for this declaration.
2216  SourceLocation LocStart;
2217  friend class ASTContext;
2218  friend class DeclContext;
2219  friend class TagDecl;
2220  friend class TemplateTypeParmDecl;
2221  friend class TagType;
2222  friend class ASTReader;
2223
2224protected:
2225  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2226           SourceLocation StartL = SourceLocation())
2227    : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2228
2229public:
2230  // Low-level accessor. If you just want the type defined by this node,
2231  // check out ASTContext::getTypeDeclType or one of
2232  // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2233  // already know the specific kind of node this is.
2234  const Type *getTypeForDecl() const { return TypeForDecl; }
2235  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2236
2237  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2238  void setLocStart(SourceLocation L) { LocStart = L; }
2239  virtual SourceRange getSourceRange() const LLVM_READONLY {
2240    if (LocStart.isValid())
2241      return SourceRange(LocStart, getLocation());
2242    else
2243      return SourceRange(getLocation());
2244  }
2245
2246  // Implement isa/cast/dyncast/etc.
2247  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2248  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2249};
2250
2251
2252/// Base class for declarations which introduce a typedef-name.
2253class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2254  virtual void anchor();
2255  /// UnderlyingType - This is the type the typedef is set to.
2256  TypeSourceInfo *TInfo;
2257
2258protected:
2259  TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2260                  SourceLocation IdLoc, IdentifierInfo *Id,
2261                  TypeSourceInfo *TInfo)
2262    : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2263
2264  typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2265  virtual TypedefNameDecl *getNextRedeclaration() {
2266    return RedeclLink.getNext();
2267  }
2268  virtual TypedefNameDecl *getPreviousDeclImpl() {
2269    return getPreviousDecl();
2270  }
2271  virtual TypedefNameDecl *getMostRecentDeclImpl() {
2272    return getMostRecentDecl();
2273  }
2274
2275public:
2276  typedef redeclarable_base::redecl_iterator redecl_iterator;
2277  using redeclarable_base::redecls_begin;
2278  using redeclarable_base::redecls_end;
2279  using redeclarable_base::getPreviousDecl;
2280  using redeclarable_base::getMostRecentDecl;
2281
2282  TypeSourceInfo *getTypeSourceInfo() const {
2283    return TInfo;
2284  }
2285
2286  /// Retrieves the canonical declaration of this typedef-name.
2287  TypedefNameDecl *getCanonicalDecl() {
2288    return getFirstDeclaration();
2289  }
2290  const TypedefNameDecl *getCanonicalDecl() const {
2291    return getFirstDeclaration();
2292  }
2293
2294  QualType getUnderlyingType() const {
2295    return TInfo->getType();
2296  }
2297  void setTypeSourceInfo(TypeSourceInfo *newType) {
2298    TInfo = newType;
2299  }
2300
2301  // Implement isa/cast/dyncast/etc.
2302  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2303  static bool classofKind(Kind K) {
2304    return K >= firstTypedefName && K <= lastTypedefName;
2305  }
2306};
2307
2308/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2309/// type specifier.
2310class TypedefDecl : public TypedefNameDecl {
2311  TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2312              IdentifierInfo *Id, TypeSourceInfo *TInfo)
2313    : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2314
2315public:
2316  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2317                             SourceLocation StartLoc, SourceLocation IdLoc,
2318                             IdentifierInfo *Id, TypeSourceInfo *TInfo);
2319  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2320
2321  SourceRange getSourceRange() const LLVM_READONLY;
2322
2323  // Implement isa/cast/dyncast/etc.
2324  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2325  static bool classofKind(Kind K) { return K == Typedef; }
2326};
2327
2328/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2329/// alias-declaration.
2330class TypeAliasDecl : public TypedefNameDecl {
2331  TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2332                IdentifierInfo *Id, TypeSourceInfo *TInfo)
2333    : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2334
2335public:
2336  static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2337                               SourceLocation StartLoc, SourceLocation IdLoc,
2338                               IdentifierInfo *Id, TypeSourceInfo *TInfo);
2339  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2340
2341  SourceRange getSourceRange() const LLVM_READONLY;
2342
2343  // Implement isa/cast/dyncast/etc.
2344  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2345  static bool classofKind(Kind K) { return K == TypeAlias; }
2346};
2347
2348/// TagDecl - Represents the declaration of a struct/union/class/enum.
2349class TagDecl
2350  : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2351public:
2352  // This is really ugly.
2353  typedef TagTypeKind TagKind;
2354
2355private:
2356  // FIXME: This can be packed into the bitfields in Decl.
2357  /// TagDeclKind - The TagKind enum.
2358  unsigned TagDeclKind : 3;
2359
2360  /// IsCompleteDefinition - True if this is a definition ("struct foo
2361  /// {};"), false if it is a declaration ("struct foo;").  It is not
2362  /// a definition until the definition has been fully processed.
2363  bool IsCompleteDefinition : 1;
2364
2365protected:
2366  /// IsBeingDefined - True if this is currently being defined.
2367  bool IsBeingDefined : 1;
2368
2369private:
2370  /// IsEmbeddedInDeclarator - True if this tag declaration is
2371  /// "embedded" (i.e., defined or declared for the very first time)
2372  /// in the syntax of a declarator.
2373  bool IsEmbeddedInDeclarator : 1;
2374
2375  /// \brief True if this tag is free standing, e.g. "struct foo;".
2376  bool IsFreeStanding : 1;
2377
2378protected:
2379  // These are used by (and only defined for) EnumDecl.
2380  unsigned NumPositiveBits : 8;
2381  unsigned NumNegativeBits : 8;
2382
2383  /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2384  /// possible in C++11 mode.
2385  bool IsScoped : 1;
2386  /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2387  /// then this is true if the scoped enum was declared using the class
2388  /// tag, false if it was declared with the struct tag. No meaning is
2389  /// associated if this tag declaration is not a scoped enum.
2390  bool IsScopedUsingClassTag : 1;
2391
2392  /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2393  /// possible in C++11 or Microsoft extensions mode.
2394  bool IsFixed : 1;
2395
2396  /// \brief Indicates whether it is possible for declarations of this kind
2397  /// to have an out-of-date definition.
2398  ///
2399  /// This option is only enabled when modules are enabled.
2400  bool MayHaveOutOfDateDef : 1;
2401
2402private:
2403  SourceLocation RBraceLoc;
2404
2405  // A struct representing syntactic qualifier info,
2406  // to be used for the (uncommon) case of out-of-line declarations.
2407  typedef QualifierInfo ExtInfo;
2408
2409  /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2410  /// is qualified, it points to the qualifier info (nns and range);
2411  /// otherwise, if the tag declaration is anonymous and it is part of
2412  /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2413  /// otherwise, it is a null (TypedefNameDecl) pointer.
2414  llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2415
2416  bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2417  ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2418  const ExtInfo *getExtInfo() const {
2419    return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2420  }
2421
2422protected:
2423  TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2424          SourceLocation L, IdentifierInfo *Id,
2425          TagDecl *PrevDecl, SourceLocation StartL)
2426    : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2427      TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2428    assert((DK != Enum || TK == TTK_Enum) &&
2429           "EnumDecl not matched with TTK_Enum");
2430    TagDeclKind = TK;
2431    IsCompleteDefinition = false;
2432    IsBeingDefined = false;
2433    IsEmbeddedInDeclarator = false;
2434    IsFreeStanding = false;
2435    setPreviousDeclaration(PrevDecl);
2436  }
2437
2438  typedef Redeclarable<TagDecl> redeclarable_base;
2439  virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2440  virtual TagDecl *getPreviousDeclImpl() {
2441    return getPreviousDecl();
2442  }
2443  virtual TagDecl *getMostRecentDeclImpl() {
2444    return getMostRecentDecl();
2445  }
2446
2447  /// @brief Completes the definition of this tag declaration.
2448  ///
2449  /// This is a helper function for derived classes.
2450  void completeDefinition();
2451
2452public:
2453  typedef redeclarable_base::redecl_iterator redecl_iterator;
2454  using redeclarable_base::redecls_begin;
2455  using redeclarable_base::redecls_end;
2456  using redeclarable_base::getPreviousDecl;
2457  using redeclarable_base::getMostRecentDecl;
2458
2459  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2460  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2461
2462  /// getInnerLocStart - Return SourceLocation representing start of source
2463  /// range ignoring outer template declarations.
2464  SourceLocation getInnerLocStart() const { return getLocStart(); }
2465
2466  /// getOuterLocStart - Return SourceLocation representing start of source
2467  /// range taking into account any outer template declarations.
2468  SourceLocation getOuterLocStart() const;
2469  virtual SourceRange getSourceRange() const LLVM_READONLY;
2470
2471  virtual TagDecl* getCanonicalDecl();
2472  const TagDecl* getCanonicalDecl() const {
2473    return const_cast<TagDecl*>(this)->getCanonicalDecl();
2474  }
2475
2476  /// isThisDeclarationADefinition() - Return true if this declaration
2477  /// is a completion definintion of the type.  Provided for consistency.
2478  bool isThisDeclarationADefinition() const {
2479    return isCompleteDefinition();
2480  }
2481
2482  /// isCompleteDefinition - Return true if this decl has its body
2483  /// fully specified.
2484  bool isCompleteDefinition() const {
2485    return IsCompleteDefinition;
2486  }
2487
2488  /// isBeingDefined - Return true if this decl is currently being defined.
2489  bool isBeingDefined() const {
2490    return IsBeingDefined;
2491  }
2492
2493  bool isEmbeddedInDeclarator() const {
2494    return IsEmbeddedInDeclarator;
2495  }
2496  void setEmbeddedInDeclarator(bool isInDeclarator) {
2497    IsEmbeddedInDeclarator = isInDeclarator;
2498  }
2499
2500  bool isFreeStanding() const { return IsFreeStanding; }
2501  void setFreeStanding(bool isFreeStanding = true) {
2502    IsFreeStanding = isFreeStanding;
2503  }
2504
2505  /// \brief Whether this declaration declares a type that is
2506  /// dependent, i.e., a type that somehow depends on template
2507  /// parameters.
2508  bool isDependentType() const { return isDependentContext(); }
2509
2510  /// @brief Starts the definition of this tag declaration.
2511  ///
2512  /// This method should be invoked at the beginning of the definition
2513  /// of this tag declaration. It will set the tag type into a state
2514  /// where it is in the process of being defined.
2515  void startDefinition();
2516
2517  /// getDefinition - Returns the TagDecl that actually defines this
2518  ///  struct/union/class/enum.  When determining whether or not a
2519  ///  struct/union/class/enum has a definition, one should use this
2520  ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2521  ///  whether or not a specific TagDecl is defining declaration, not
2522  ///  whether or not the struct/union/class/enum type is defined.
2523  ///  This method returns NULL if there is no TagDecl that defines
2524  ///  the struct/union/class/enum.
2525  TagDecl *getDefinition() const;
2526
2527  void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2528
2529  // FIXME: Return StringRef;
2530  const char *getKindName() const {
2531    return TypeWithKeyword::getTagTypeKindName(getTagKind());
2532  }
2533
2534  TagKind getTagKind() const {
2535    return TagKind(TagDeclKind);
2536  }
2537
2538  void setTagKind(TagKind TK) { TagDeclKind = TK; }
2539
2540  bool isStruct() const { return getTagKind() == TTK_Struct; }
2541  bool isInterface() const { return getTagKind() == TTK_Interface; }
2542  bool isClass()  const { return getTagKind() == TTK_Class; }
2543  bool isUnion()  const { return getTagKind() == TTK_Union; }
2544  bool isEnum()   const { return getTagKind() == TTK_Enum; }
2545
2546  /// Is this tag type named, either directly or via being defined in
2547  /// a typedef of this type?
2548  ///
2549  /// C++11 [basic.link]p8:
2550  ///   A type is said to have linkage if and only if:
2551  ///     - it is a class or enumeration type that is named (or has a
2552  ///       name for linkage purposes) and the name has linkage; ...
2553  /// C++11 [dcl.typedef]p9:
2554  ///   If the typedef declaration defines an unnamed class (or enum),
2555  ///   the first typedef-name declared by the declaration to be that
2556  ///   class type (or enum type) is used to denote the class type (or
2557  ///   enum type) for linkage purposes only.
2558  ///
2559  /// C does not have an analogous rule, but the same concept is
2560  /// nonetheless useful in some places.
2561  bool hasNameForLinkage() const {
2562    return (getDeclName() || getTypedefNameForAnonDecl());
2563  }
2564
2565  TypedefNameDecl *getTypedefNameForAnonDecl() const {
2566    return hasExtInfo() ? 0 :
2567           TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2568  }
2569
2570  void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2571
2572  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2573  /// declaration, if it was present in the source.
2574  NestedNameSpecifier *getQualifier() const {
2575    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2576                        : 0;
2577  }
2578
2579  /// \brief Retrieve the nested-name-specifier (with source-location
2580  /// information) that qualifies the name of this declaration, if it was
2581  /// present in the source.
2582  NestedNameSpecifierLoc getQualifierLoc() const {
2583    return hasExtInfo() ? getExtInfo()->QualifierLoc
2584                        : NestedNameSpecifierLoc();
2585  }
2586
2587  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2588
2589  unsigned getNumTemplateParameterLists() const {
2590    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2591  }
2592  TemplateParameterList *getTemplateParameterList(unsigned i) const {
2593    assert(i < getNumTemplateParameterLists());
2594    return getExtInfo()->TemplParamLists[i];
2595  }
2596  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2597                                     TemplateParameterList **TPLists);
2598
2599  // Implement isa/cast/dyncast/etc.
2600  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2601  static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2602
2603  static DeclContext *castToDeclContext(const TagDecl *D) {
2604    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2605  }
2606  static TagDecl *castFromDeclContext(const DeclContext *DC) {
2607    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2608  }
2609
2610  friend class ASTDeclReader;
2611  friend class ASTDeclWriter;
2612};
2613
2614/// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
2615/// with a fixed underlying type, and in C we allow them to be forward-declared
2616/// with no underlying type as an extension.
2617class EnumDecl : public TagDecl {
2618  virtual void anchor();
2619  /// IntegerType - This represent the integer type that the enum corresponds
2620  /// to for code generation purposes.  Note that the enumerator constants may
2621  /// have a different type than this does.
2622  ///
2623  /// If the underlying integer type was explicitly stated in the source
2624  /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2625  /// was automatically deduced somehow, and this is a Type*.
2626  ///
2627  /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2628  /// some cases it won't.
2629  ///
2630  /// The underlying type of an enumeration never has any qualifiers, so
2631  /// we can get away with just storing a raw Type*, and thus save an
2632  /// extra pointer when TypeSourceInfo is needed.
2633
2634  llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2635
2636  /// PromotionType - The integer type that values of this type should
2637  /// promote to.  In C, enumerators are generally of an integer type
2638  /// directly, but gcc-style large enumerators (and all enumerators
2639  /// in C++) are of the enum type instead.
2640  QualType PromotionType;
2641
2642  /// \brief If this enumeration is an instantiation of a member enumeration
2643  /// of a class template specialization, this is the member specialization
2644  /// information.
2645  MemberSpecializationInfo *SpecializationInfo;
2646
2647  EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2648           IdentifierInfo *Id, EnumDecl *PrevDecl,
2649           bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2650    : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2651      SpecializationInfo(0) {
2652    assert(Scoped || !ScopedUsingClassTag);
2653    IntegerType = (const Type*)0;
2654    NumNegativeBits = 0;
2655    NumPositiveBits = 0;
2656    IsScoped = Scoped;
2657    IsScopedUsingClassTag = ScopedUsingClassTag;
2658    IsFixed = Fixed;
2659  }
2660
2661  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2662                                    TemplateSpecializationKind TSK);
2663public:
2664  EnumDecl *getCanonicalDecl() {
2665    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2666  }
2667  const EnumDecl *getCanonicalDecl() const {
2668    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2669  }
2670
2671  const EnumDecl *getPreviousDecl() const {
2672    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2673  }
2674  EnumDecl *getPreviousDecl() {
2675    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2676  }
2677
2678  const EnumDecl *getMostRecentDecl() const {
2679    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2680  }
2681  EnumDecl *getMostRecentDecl() {
2682    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2683  }
2684
2685  EnumDecl *getDefinition() const {
2686    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2687  }
2688
2689  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2690                          SourceLocation StartLoc, SourceLocation IdLoc,
2691                          IdentifierInfo *Id, EnumDecl *PrevDecl,
2692                          bool IsScoped, bool IsScopedUsingClassTag,
2693                          bool IsFixed);
2694  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2695
2696  /// completeDefinition - When created, the EnumDecl corresponds to a
2697  /// forward-declared enum. This method is used to mark the
2698  /// declaration as being defined; it's enumerators have already been
2699  /// added (via DeclContext::addDecl). NewType is the new underlying
2700  /// type of the enumeration type.
2701  void completeDefinition(QualType NewType,
2702                          QualType PromotionType,
2703                          unsigned NumPositiveBits,
2704                          unsigned NumNegativeBits);
2705
2706  // enumerator_iterator - Iterates through the enumerators of this
2707  // enumeration.
2708  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2709
2710  enumerator_iterator enumerator_begin() const {
2711    const EnumDecl *E = getDefinition();
2712    if (!E)
2713      E = this;
2714    return enumerator_iterator(E->decls_begin());
2715  }
2716
2717  enumerator_iterator enumerator_end() const {
2718    const EnumDecl *E = getDefinition();
2719    if (!E)
2720      E = this;
2721    return enumerator_iterator(E->decls_end());
2722  }
2723
2724  /// getPromotionType - Return the integer type that enumerators
2725  /// should promote to.
2726  QualType getPromotionType() const { return PromotionType; }
2727
2728  /// \brief Set the promotion type.
2729  void setPromotionType(QualType T) { PromotionType = T; }
2730
2731  /// getIntegerType - Return the integer type this enum decl corresponds to.
2732  /// This returns a null qualtype for an enum forward definition.
2733  QualType getIntegerType() const {
2734    if (!IntegerType)
2735      return QualType();
2736    if (const Type* T = IntegerType.dyn_cast<const Type*>())
2737      return QualType(T, 0);
2738    return IntegerType.get<TypeSourceInfo*>()->getType();
2739  }
2740
2741  /// \brief Set the underlying integer type.
2742  void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2743
2744  /// \brief Set the underlying integer type source info.
2745  void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2746
2747  /// \brief Return the type source info for the underlying integer type,
2748  /// if no type source info exists, return 0.
2749  TypeSourceInfo* getIntegerTypeSourceInfo() const {
2750    return IntegerType.dyn_cast<TypeSourceInfo*>();
2751  }
2752
2753  /// \brief Returns the width in bits required to store all the
2754  /// non-negative enumerators of this enum.
2755  unsigned getNumPositiveBits() const {
2756    return NumPositiveBits;
2757  }
2758  void setNumPositiveBits(unsigned Num) {
2759    NumPositiveBits = Num;
2760    assert(NumPositiveBits == Num && "can't store this bitcount");
2761  }
2762
2763  /// \brief Returns the width in bits required to store all the
2764  /// negative enumerators of this enum.  These widths include
2765  /// the rightmost leading 1;  that is:
2766  ///
2767  /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
2768  /// ------------------------     -------     -----------------
2769  ///                       -1     1111111                     1
2770  ///                      -10     1110110                     5
2771  ///                     -101     1001011                     8
2772  unsigned getNumNegativeBits() const {
2773    return NumNegativeBits;
2774  }
2775  void setNumNegativeBits(unsigned Num) {
2776    NumNegativeBits = Num;
2777  }
2778
2779  /// \brief Returns true if this is a C++0x scoped enumeration.
2780  bool isScoped() const {
2781    return IsScoped;
2782  }
2783
2784  /// \brief Returns true if this is a C++0x scoped enumeration.
2785  bool isScopedUsingClassTag() const {
2786    return IsScopedUsingClassTag;
2787  }
2788
2789  /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2790  /// type.
2791  bool isFixed() const {
2792    return IsFixed;
2793  }
2794
2795  /// \brief Returns true if this can be considered a complete type.
2796  bool isComplete() const {
2797    return isCompleteDefinition() || isFixed();
2798  }
2799
2800  /// \brief Returns the enumeration (declared within the template)
2801  /// from which this enumeration type was instantiated, or NULL if
2802  /// this enumeration was not instantiated from any template.
2803  EnumDecl *getInstantiatedFromMemberEnum() const;
2804
2805  /// \brief If this enumeration is a member of a specialization of a
2806  /// templated class, determine what kind of template specialization
2807  /// or instantiation this is.
2808  TemplateSpecializationKind getTemplateSpecializationKind() const;
2809
2810  /// \brief For an enumeration member that was instantiated from a member
2811  /// enumeration of a templated class, set the template specialiation kind.
2812  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2813                        SourceLocation PointOfInstantiation = SourceLocation());
2814
2815  /// \brief If this enumeration is an instantiation of a member enumeration of
2816  /// a class template specialization, retrieves the member specialization
2817  /// information.
2818  MemberSpecializationInfo *getMemberSpecializationInfo() const {
2819    return SpecializationInfo;
2820  }
2821
2822  /// \brief Specify that this enumeration is an instantiation of the
2823  /// member enumeration ED.
2824  void setInstantiationOfMemberEnum(EnumDecl *ED,
2825                                    TemplateSpecializationKind TSK) {
2826    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2827  }
2828
2829  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2830  static bool classofKind(Kind K) { return K == Enum; }
2831
2832  friend class ASTDeclReader;
2833};
2834
2835
2836/// RecordDecl - Represents a struct/union/class.  For example:
2837///   struct X;                  // Forward declaration, no "body".
2838///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
2839/// This decl will be marked invalid if *any* members are invalid.
2840///
2841class RecordDecl : public TagDecl {
2842  // FIXME: This can be packed into the bitfields in Decl.
2843  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2844  /// array member (e.g. int X[]) or if this union contains a struct that does.
2845  /// If so, this cannot be contained in arrays or other structs as a member.
2846  bool HasFlexibleArrayMember : 1;
2847
2848  /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2849  /// or union.
2850  bool AnonymousStructOrUnion : 1;
2851
2852  /// HasObjectMember - This is true if this struct has at least one member
2853  /// containing an Objective-C object pointer type.
2854  bool HasObjectMember : 1;
2855
2856  /// HasVolatileMember - This is true if struct has at least one member of
2857  /// 'volatile' type.
2858  bool HasVolatileMember : 1;
2859
2860  /// \brief Whether the field declarations of this record have been loaded
2861  /// from external storage. To avoid unnecessary deserialization of
2862  /// methods/nested types we allow deserialization of just the fields
2863  /// when needed.
2864  mutable bool LoadedFieldsFromExternalStorage : 1;
2865  friend class DeclContext;
2866
2867protected:
2868  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2869             SourceLocation StartLoc, SourceLocation IdLoc,
2870             IdentifierInfo *Id, RecordDecl *PrevDecl);
2871
2872public:
2873  static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2874                            SourceLocation StartLoc, SourceLocation IdLoc,
2875                            IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2876  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
2877
2878  const RecordDecl *getPreviousDecl() const {
2879    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2880  }
2881  RecordDecl *getPreviousDecl() {
2882    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2883  }
2884
2885  const RecordDecl *getMostRecentDecl() const {
2886    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2887  }
2888  RecordDecl *getMostRecentDecl() {
2889    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2890  }
2891
2892  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2893  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2894
2895  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2896  /// or union. To be an anonymous struct or union, it must have been
2897  /// declared without a name and there must be no objects of this
2898  /// type declared, e.g.,
2899  /// @code
2900  ///   union { int i; float f; };
2901  /// @endcode
2902  /// is an anonymous union but neither of the following are:
2903  /// @code
2904  ///  union X { int i; float f; };
2905  ///  union { int i; float f; } obj;
2906  /// @endcode
2907  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2908  void setAnonymousStructOrUnion(bool Anon) {
2909    AnonymousStructOrUnion = Anon;
2910  }
2911
2912  bool hasObjectMember() const { return HasObjectMember; }
2913  void setHasObjectMember (bool val) { HasObjectMember = val; }
2914
2915  bool hasVolatileMember() const { return HasVolatileMember; }
2916  void setHasVolatileMember (bool val) { HasVolatileMember = val; }
2917
2918  /// \brief Determines whether this declaration represents the
2919  /// injected class name.
2920  ///
2921  /// The injected class name in C++ is the name of the class that
2922  /// appears inside the class itself. For example:
2923  ///
2924  /// \code
2925  /// struct C {
2926  ///   // C is implicitly declared here as a synonym for the class name.
2927  /// };
2928  ///
2929  /// C::C c; // same as "C c;"
2930  /// \endcode
2931  bool isInjectedClassName() const;
2932
2933  /// getDefinition - Returns the RecordDecl that actually defines
2934  ///  this struct/union/class.  When determining whether or not a
2935  ///  struct/union/class is completely defined, one should use this
2936  ///  method as opposed to 'isCompleteDefinition'.
2937  ///  'isCompleteDefinition' indicates whether or not a specific
2938  ///  RecordDecl is a completed definition, not whether or not the
2939  ///  record type is defined.  This method returns NULL if there is
2940  ///  no RecordDecl that defines the struct/union/tag.
2941  RecordDecl *getDefinition() const {
2942    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2943  }
2944
2945  // Iterator access to field members. The field iterator only visits
2946  // the non-static data members of this class, ignoring any static
2947  // data members, functions, constructors, destructors, etc.
2948  typedef specific_decl_iterator<FieldDecl> field_iterator;
2949
2950  field_iterator field_begin() const;
2951
2952  field_iterator field_end() const {
2953    return field_iterator(decl_iterator());
2954  }
2955
2956  // field_empty - Whether there are any fields (non-static data
2957  // members) in this record.
2958  bool field_empty() const {
2959    return field_begin() == field_end();
2960  }
2961
2962  /// completeDefinition - Notes that the definition of this type is
2963  /// now complete.
2964  virtual void completeDefinition();
2965
2966  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2967  static bool classofKind(Kind K) {
2968    return K >= firstRecord && K <= lastRecord;
2969  }
2970
2971  /// isMsStrust - Get whether or not this is an ms_struct which can
2972  /// be turned on with an attribute, pragma, or -mms-bitfields
2973  /// commandline option.
2974  bool isMsStruct(const ASTContext &C) const;
2975
2976private:
2977  /// \brief Deserialize just the fields.
2978  void LoadFieldsFromExternalStorage() const;
2979};
2980
2981class FileScopeAsmDecl : public Decl {
2982  virtual void anchor();
2983  StringLiteral *AsmString;
2984  SourceLocation RParenLoc;
2985  FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
2986                   SourceLocation StartL, SourceLocation EndL)
2987    : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
2988public:
2989  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
2990                                  StringLiteral *Str, SourceLocation AsmLoc,
2991                                  SourceLocation RParenLoc);
2992
2993  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2994
2995  SourceLocation getAsmLoc() const { return getLocation(); }
2996  SourceLocation getRParenLoc() const { return RParenLoc; }
2997  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2998  SourceRange getSourceRange() const LLVM_READONLY {
2999    return SourceRange(getAsmLoc(), getRParenLoc());
3000  }
3001
3002  const StringLiteral *getAsmString() const { return AsmString; }
3003  StringLiteral *getAsmString() { return AsmString; }
3004  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3005
3006  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3007  static bool classofKind(Kind K) { return K == FileScopeAsm; }
3008};
3009
3010/// BlockDecl - This represents a block literal declaration, which is like an
3011/// unnamed FunctionDecl.  For example:
3012/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3013///
3014class BlockDecl : public Decl, public DeclContext {
3015public:
3016  /// A class which contains all the information about a particular
3017  /// captured value.
3018  class Capture {
3019    enum {
3020      flag_isByRef = 0x1,
3021      flag_isNested = 0x2
3022    };
3023
3024    /// The variable being captured.
3025    llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3026
3027    /// The copy expression, expressed in terms of a DeclRef (or
3028    /// BlockDeclRef) to the captured variable.  Only required if the
3029    /// variable has a C++ class type.
3030    Expr *CopyExpr;
3031
3032  public:
3033    Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3034      : VariableAndFlags(variable,
3035                  (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3036        CopyExpr(copy) {}
3037
3038    /// The variable being captured.
3039    VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3040
3041    /// Whether this is a "by ref" capture, i.e. a capture of a __block
3042    /// variable.
3043    bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3044
3045    /// Whether this is a nested capture, i.e. the variable captured
3046    /// is not from outside the immediately enclosing function/block.
3047    bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3048
3049    bool hasCopyExpr() const { return CopyExpr != 0; }
3050    Expr *getCopyExpr() const { return CopyExpr; }
3051    void setCopyExpr(Expr *e) { CopyExpr = e; }
3052  };
3053
3054private:
3055  // FIXME: This can be packed into the bitfields in Decl.
3056  bool IsVariadic : 1;
3057  bool CapturesCXXThis : 1;
3058  bool BlockMissingReturnType : 1;
3059  bool IsConversionFromLambda : 1;
3060  /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3061  /// parameters of this function.  This is null if a prototype or if there are
3062  /// no formals.
3063  ParmVarDecl **ParamInfo;
3064  unsigned NumParams;
3065
3066  Stmt *Body;
3067  TypeSourceInfo *SignatureAsWritten;
3068
3069  Capture *Captures;
3070  unsigned NumCaptures;
3071
3072protected:
3073  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3074    : Decl(Block, DC, CaretLoc), DeclContext(Block),
3075      IsVariadic(false), CapturesCXXThis(false),
3076      BlockMissingReturnType(true), IsConversionFromLambda(false),
3077      ParamInfo(0), NumParams(0), Body(0),
3078      SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
3079
3080public:
3081  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3082  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3083
3084  SourceLocation getCaretLocation() const { return getLocation(); }
3085
3086  bool isVariadic() const { return IsVariadic; }
3087  void setIsVariadic(bool value) { IsVariadic = value; }
3088
3089  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3090  Stmt *getBody() const { return (Stmt*) Body; }
3091  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3092
3093  void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3094  TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3095
3096  // Iterator access to formal parameters.
3097  unsigned param_size() const { return getNumParams(); }
3098  typedef ParmVarDecl **param_iterator;
3099  typedef ParmVarDecl * const *param_const_iterator;
3100
3101  bool param_empty() const { return NumParams == 0; }
3102  param_iterator param_begin()  { return ParamInfo; }
3103  param_iterator param_end()   { return ParamInfo+param_size(); }
3104
3105  param_const_iterator param_begin() const { return ParamInfo; }
3106  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
3107
3108  unsigned getNumParams() const { return NumParams; }
3109  const ParmVarDecl *getParamDecl(unsigned i) const {
3110    assert(i < getNumParams() && "Illegal param #");
3111    return ParamInfo[i];
3112  }
3113  ParmVarDecl *getParamDecl(unsigned i) {
3114    assert(i < getNumParams() && "Illegal param #");
3115    return ParamInfo[i];
3116  }
3117  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3118
3119  /// hasCaptures - True if this block (or its nested blocks) captures
3120  /// anything of local storage from its enclosing scopes.
3121  bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3122
3123  /// getNumCaptures - Returns the number of captured variables.
3124  /// Does not include an entry for 'this'.
3125  unsigned getNumCaptures() const { return NumCaptures; }
3126
3127  typedef const Capture *capture_iterator;
3128  typedef const Capture *capture_const_iterator;
3129  capture_iterator capture_begin() { return Captures; }
3130  capture_iterator capture_end() { return Captures + NumCaptures; }
3131  capture_const_iterator capture_begin() const { return Captures; }
3132  capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3133
3134  bool capturesCXXThis() const { return CapturesCXXThis; }
3135  bool blockMissingReturnType() const { return BlockMissingReturnType; }
3136  void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3137
3138  bool isConversionFromLambda() const { return IsConversionFromLambda; }
3139  void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3140
3141  bool capturesVariable(const VarDecl *var) const;
3142
3143  void setCaptures(ASTContext &Context,
3144                   const Capture *begin,
3145                   const Capture *end,
3146                   bool capturesCXXThis);
3147
3148  virtual SourceRange getSourceRange() const LLVM_READONLY;
3149
3150  // Implement isa/cast/dyncast/etc.
3151  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3152  static bool classofKind(Kind K) { return K == Block; }
3153  static DeclContext *castToDeclContext(const BlockDecl *D) {
3154    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3155  }
3156  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3157    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3158  }
3159};
3160
3161/// \brief Describes a module import declaration, which makes the contents
3162/// of the named module visible in the current translation unit.
3163///
3164/// An import declaration imports the named module (or submodule). For example:
3165/// \code
3166///   @import std.vector;
3167/// \endcode
3168///
3169/// Import declarations can also be implicitly generated from
3170/// \#include/\#import directives.
3171class ImportDecl : public Decl {
3172  /// \brief The imported module, along with a bit that indicates whether
3173  /// we have source-location information for each identifier in the module
3174  /// name.
3175  ///
3176  /// When the bit is false, we only have a single source location for the
3177  /// end of the import declaration.
3178  llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3179
3180  /// \brief The next import in the list of imports local to the translation
3181  /// unit being parsed (not loaded from an AST file).
3182  ImportDecl *NextLocalImport;
3183
3184  friend class ASTReader;
3185  friend class ASTDeclReader;
3186  friend class ASTContext;
3187
3188  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3189             ArrayRef<SourceLocation> IdentifierLocs);
3190
3191  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3192             SourceLocation EndLoc);
3193
3194  ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3195
3196public:
3197  /// \brief Create a new module import declaration.
3198  static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3199                            SourceLocation StartLoc, Module *Imported,
3200                            ArrayRef<SourceLocation> IdentifierLocs);
3201
3202  /// \brief Create a new module import declaration for an implicitly-generated
3203  /// import.
3204  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3205                                    SourceLocation StartLoc, Module *Imported,
3206                                    SourceLocation EndLoc);
3207
3208  /// \brief Create a new, deserialized module import declaration.
3209  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3210                                        unsigned NumLocations);
3211
3212  /// \brief Retrieve the module that was imported by the import declaration.
3213  Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3214
3215  /// \brief Retrieves the locations of each of the identifiers that make up
3216  /// the complete module name in the import declaration.
3217  ///
3218  /// This will return an empty array if the locations of the individual
3219  /// identifiers aren't available.
3220  ArrayRef<SourceLocation> getIdentifierLocs() const;
3221
3222  virtual SourceRange getSourceRange() const LLVM_READONLY;
3223
3224  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3225  static bool classofKind(Kind K) { return K == Import; }
3226};
3227
3228/// \brief Represents an empty-declaration.
3229class EmptyDecl : public Decl {
3230  virtual void anchor();
3231  EmptyDecl(DeclContext *DC, SourceLocation L)
3232    : Decl(Empty, DC, L) { }
3233
3234public:
3235  static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3236                           SourceLocation L);
3237  static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3238
3239  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3240  static bool classofKind(Kind K) { return K == Empty; }
3241};
3242
3243/// Insertion operator for diagnostics.  This allows sending NamedDecl's
3244/// into a diagnostic with <<.
3245inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3246                                           const NamedDecl* ND) {
3247  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3248                  DiagnosticsEngine::ak_nameddecl);
3249  return DB;
3250}
3251inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3252                                           const NamedDecl* ND) {
3253  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3254                  DiagnosticsEngine::ak_nameddecl);
3255  return PD;
3256}
3257
3258template<typename decl_type>
3259void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3260  // Note: This routine is implemented here because we need both NamedDecl
3261  // and Redeclarable to be defined.
3262
3263  decl_type *First;
3264
3265  if (PrevDecl) {
3266    // Point to previous. Make sure that this is actually the most recent
3267    // redeclaration, or we can build invalid chains. If the most recent
3268    // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3269    First = PrevDecl->getFirstDeclaration();
3270    assert(First->RedeclLink.NextIsLatest() && "Expected first");
3271    decl_type *MostRecent = First->RedeclLink.getNext();
3272    RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3273  } else {
3274    // Make this first.
3275    First = static_cast<decl_type*>(this);
3276  }
3277
3278  // First one will point to this one as latest.
3279  First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3280  assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3281         cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3282}
3283
3284// Inline function definitions.
3285
3286/// \brief Check if the given decl is complete.
3287///
3288/// We use this function to break a cycle between the inline definitions in
3289/// Type.h and Decl.h.
3290inline bool IsEnumDeclComplete(EnumDecl *ED) {
3291  return ED->isComplete();
3292}
3293
3294/// \brief Check if the given decl is scoped.
3295///
3296/// We use this function to break a cycle between the inline definitions in
3297/// Type.h and Decl.h.
3298inline bool IsEnumDeclScoped(EnumDecl *ED) {
3299  return ED->isScoped();
3300}
3301
3302}  // end namespace clang
3303
3304#endif
3305