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