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