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