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