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