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