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