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