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