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