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